ติดตั้ง WireGuard VPN สำหรับ admin access

เมื่อ VPS ขึ้น production แล้ว คุณคงไม่อยากเปิด admin UIs (Grafana, Netdata, internal tools) สู่ public internet WireGuard ช่วยให้คุณมี tunnel ส่วนตัวไปยัง VPS — มีแค่ client ที่มี key ถูกต้องที่เข้าถึงได้

ตั้ง Server

apt install -y wireguard

wg genkey | tee /etc/wireguard/server_private.key | wg pubkey > /etc/wireguard/server_public.key
chmod 600 /etc/wireguard/server_private.key

cat > /etc/wireguard/wg0.conf <<EOF
[Interface]
Address = 10.10.10.1/24
ListenPort = 51820
PrivateKey = $(cat /etc/wireguard/server_private.key)
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

[Peer]
PublicKey = <client_public_key>
AllowedIPs = 10.10.10.2/32
EOF

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p
systemctl enable --now wg-quick@wg0

ufw allow 51820/udp comment 'WireGuard'

ตั้ง Client (macOS, Linux, iOS, Android)

สำหรับแต่ละ client:

  1. สร้าง keys: wg genkey | tee private.key | wg pubkey > public.key
  2. ใส่ public key ของ client ใน /etc/wireguard/wg0.conf ใต้ [Peer] ใหม่
  3. Restart: systemctl restart wg-quick@wg0
  4. ส่ง config ให้ client:
[Interface]
PrivateKey = <client_private_key>
Address = 10.10.10.2/24
DNS = 1.1.1.1

[Peer]
PublicKey = <server_public_key>
Endpoint = <server_public_ip>:51820
AllowedIPs = 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 10.10.10.0/24
PersistentKeepalive = 25

AllowedIPs ควบคุมว่า traffic ไหนผ่าน VPN ranges ข้างบน route เฉพาะ private network traffic — การท่องเว็บปกติยังตรง

จำกัด admin UIs ให้เข้าถึงผ่าน VPN เท่านั้น

iptables -A INPUT -p tcp --dport 19999 ! -s 10.10.10.0/24 -j DROP

ทำไม WireGuard (ไม่ใช่ OpenVPN)?

  • เร็วกว่า: ~3× throughput บน hardware เดียวกัน
  • ง่ายกว่า: ~4,000 บรรทัดใน kernel vs OpenVPN ~100,000
  • Modern crypto: Curve25519, ChaCha20, Poly1305
  • Stealth: ไม่ตอบ unauthenticated packets — มองไม่เห็นจาก port scan

ข้อแลกเปลี่ยนเดียว: ไม่มี dynamic IP ในตัว ต้องใช้ wireguard-dynamic หรือ script เล็ก ๆ