WireGuard笔记
WireGuard securely encapsulates IP packets over UDP. You add a WireGuard interface, configure it with your private key and your peers' public keys, and then you send packets across it.
WireGuard works by adding a network interface (or multiple), like eth0
or wlan0
, called wg0
(or wg1
, wg2
, wg3
, etc). This network interface can then be configured normally using ifconfig(8)
or ip-address(8)
, with routes for it added and removed using route(8)
or ip-route(8)
, and so on with all the ordinary networking utilities. The specific WireGuard aspects of the interface are configured using the wg(8)
tool. This interface acts as a tunnel interface.
WireGuard associates tunnel IP addresses with public keys and remote endpoints. When the interface sends a packet to a peer, it does the following:
- This packet is meant for 192.168.30.8. Which peer is that? Let me look... Okay, it's for peer
ABCDEFGH
. (Or if it's not for any configured peer, drop the packet.) - Encrypt entire IP packet using peer
ABCDEFGH
's public key. - What is the remote endpoint of peer
ABCDEFGH
? Let me look... Okay, the endpoint is UDP port 53133 on host 216.58.211.110. - Send encrypted bytes from step 2 over the Internet to 216.58.211.110:53133 using UDP.
When the interface receives a packet, this happens:
- I just got a packet from UDP port 7361 on host 98.139.183.24. Let's decrypt it!
- It decrypted and authenticated properly for peer
LMNOPQRS
. Okay, let's remember that peerLMNOPQRS
's most recent Internet endpoint is 98.139.183.24:7361 using UDP. - Once decrypted, the plain-text packet is from 192.168.43.89. Is peer
LMNOPQRS
allowed to be sending us packets as 192.168.43.89? - If so, accept the packet on the interface. If not, drop it.
Behind the scenes there is much happening to provide proper privacy, authenticity, and perfect forward secrecy, using state-of-the-art cryptography.
WireGuard像普通以太网接口一样,以Linux内核模块的形式运行,支持任何类型的二层网络通信,例如 ARP、DHCP 和 ICMP,而不仅仅是 TCP/HTTP,但它不能发送原始的二层以太网帧。
中继服务器(Bounce Server)和普通的对等节点一样,它能够在 NAT
后面的 VPN 客户端之间充当中继服务器,可以将收到的任何 VPN 子网流量转发到正确的对等节点。
在 WireGuard 里,客户端和服务端基本是平等的,差别只是谁主动连接谁而已。双方都会监听一个 UDP 端口,谁主动连接,谁就是客户端。主动连接的客户端需要指定对端的公网地址和端口,被动连接的服务端不需要指定其他对等节点的地址和端口。如果客户端和服务端都位于 NAT 后面,需要加一个中继服务器,客户端和服务端都指定中继服务器作为对等节点,它们的通信流量会先进入中继服务器,然后再转发到对端。
WireGuard 使用加密的 UDP 报文来封装所有的数据,UDP 不保证数据包一定能送达,也不保证按顺序到达,但隧道内的 TCP 连接可以保证数据有效交付。