WireGuard 的搭建使用与配置

参考连接:https://fuckcloudnative.io/posts/wireguard-docs-practice/

  1. 快速开始
    配置 WireGuard 的大致流程如下:

安装
CentOS7
Ubuntu
MacOS
Windows
其他

Ubuntu ≥ 18.04

$ apt install wireguard

Ubuntu ≤ 16.04

$ add-apt-repository ppa:wireguard/wireguard
$ apt-get update
$ apt-get install wireguard
在中继服务器上开启 IP 地址转发:

$ echo “net.ipv4.ip_forward = 1” >> /etc/sysctl.conf
$ echo “net.ipv4.conf.all.proxy_arp = 1” >> /etc/sysctl.conf
$ sysctl -p /etc/sysctl.conf
添加 iptables 规则,允许本机的 NAT 转换:

$ iptables -A INPUT -m conntrack –ctstate RELATED,ESTABLISHED -j ACCEPT
$ iptables -A FORWARD -m conntrack –ctstate RELATED,ESTABLISHED -j ACCEPT
$ iptables -A FORWARD -i wg0 -o wg0 -m conntrack –ctstate NEW -j ACCEPT
$ iptables -t nat -A POSTROUTING -s 192.0.2.0/24 -o eth0 -j MASQUERADE
需要把 eth0 改成你实际使用的网卡接口名称。

编写配置文件
配置文件可以放在任何路径下,但必须通过绝对路径引用。默认路径是 /etc/wireguard/wg0.conf。

配置文件内容解析放到下一章节再讲。

一键安装
一键安装请参考这个项目:WireGuard installer

  1. 配置详解
    WireGuard 使用 INI 语法作为其配置文件格式。配置文件可以放在任何路径下,但必须通过绝对路径引用。默认路径是 /etc/wireguard/wg0.conf。

配置文件的命名形式必须为 ${WireGuard 接口的名称}.conf。通常情况下 WireGuard 接口名称以 wg 为前缀,并从 0 开始编号,但你也可以使用其他名称,只要符合正则表达式 ^[a-zA-Z0-9_=+.-]{1,15}$ 就行。

你可以选择使用 wg 命令来手动配置隧道,但一般建议使用 wg-quick,它提供了更强大和用户友好的配置体验,可以通过配置文件来管理配置。

下面是一个配置文件示例:

[Interface]

Name = node1.example.tld

Address = 192.0.2.3/32
ListenPort = 51820
PrivateKey = localPrivateKeyAbcAbcAbc=
DNS = 1.1.1.1,8.8.8.8
Table = 12345
MTU = 1500
PreUp = /bin/example arg1 arg2 %i
PostUp = /bin/example arg1 arg2 %i
PreDown = /bin/example arg1 arg2 %i
PostDown = /bin/example arg1 arg2 %i

[Peer]

Name = node2-node.example.tld

AllowedIPs = 192.0.2.1/24
Endpoint = node1.example.tld:51820
PublicKey = remotePublicKeyAbcAbcAbc=
PersistentKeepalive = 25
[Interface]

本地节点是客户端,只路由自身的流量,只暴露一个 IP。

[Interface]

Name = phone.example-vpn.dev

Address = 192.0.2.5/32
PrivateKey =