Featured image of post 如何配置WireGuard

如何配置WireGuard

WireGuard是由Jason A. Donenfeld开发的自由及开源加密VPN程序及协议,旨在获得比IPsec和OpenVPN更好的性能。

2020年3月,该软件的Linux版本达到了稳定的生产版本,并被纳入Linux5.6内核,并在一些Linux发行版中向后移植到早期的Linux内核。

更新系统软件包

1
apt update && apt upgrade

安装基础软件包

1
apt install -y wireguard iptables qrencode

创建配置文件目录

1
2
mkdir -p /etc/wireguard
chmod 700 /etc/wireguard

生成秘钥对

1
2
wg genkey | tee /etc/wireguard/服务器私钥.key | wg pubkey > /etc/wireguard/服务器公钥.key
wg genkey | tee /etc/wireguard/客户端私钥.key | wg pubkey > /etc/wireguard/客户端公钥.key

查看秘钥

服务器秘钥

1
cat /etc/wireguard/服务器私钥.key

客户端公钥

1
cat /etc/wireguard/客户端公钥.key

编辑服务器配置

1
vim /etc/wireguard/wg0.conf

写入以下内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[Interface]
Address = 10.0.0.1/24
ListenPort = 4444
PrivateKey = 服务器私钥

PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

[Peer]
PublicKey = 客户端公钥
AllowedIPs = 10.0.0.2/32

提示
[Interface]

  • ListenPort:监听端口可以改成自己喜欢的数字,0-65535之间
  • PrivateKey:填服务器私钥

[Peer]

  • PublicKey:填客户端公钥

启用ip转发

编辑 /etc/sysctl.conf 文件

1
vim /etc/sysctl.conf

找到#net.ipv4.ip_forward=1行,把前面的#号注释符删掉

1
net.ipv4.ip_forward=1

重新加载服务

1
sysctl -p

启动wireguard

1
wg-quick up wg0

设置开机自启

1
systemctl enable wg-quick@wg0

查看运行状态

1
wg show

客户端配置

查看客户端私钥

1
cat /etc/wireguard/客户端私钥.key

查看服务器公钥

1
cat /etc/wireguard/服务器公钥.key

创建一个客户端配置文件,例如client.conf

1
vim client.conf

写以下内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[Interface]
Address = 10.0.0.2/24
PrivateKey = 客户端私钥
DNS = 8.8.8.8

[Peer]
PublicKey = 服务器公钥
Endpoint = 服务器公网IP:4444
AllowedIPs = 0.0.0.0/0, ::/0
PersistentKeepalive = 25

提示
[Interface]

  • PrivateKey:填客户端私钥

[Peer]

  • PublicKey:填服务器公钥
  • Endpoint:填服务器ip:端口号

生成二维码

1
qrencode -t ansiutf8 < client.conf

在客户端导入配置

client.conf文件拷贝到客户端设备(如手机、电脑),使用WireGuard应用导入。

文章根据 CC BY-NC-SA 4.0 许可发布
使用 Hugo 构建,主题 StackJimmy 设计