Aliens

Wireguard配置教程

March 2, 2022

安装

1
sudo apt install wireguard

Server配置示例

1.生成公钥和私钥

1
2
3
wg genkey | sudo tee /etc/wireguard/private.key
sudo chmod go= /etc/wireguard/private.key
sudo cat /etc/wireguard/private.key | wg pubkey | sudo tee /etc/wireguard/public.key

2.打开端口转发

1
2
3
4
5
sudo vi /etc/sysctl.conf
----
net.ipv4.ip_forward=1
---
sudo sysctl -p

3.配置文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/etc/wireguard/wg0.conf
----------
[Interface]
Address = 10.0.0.1/24
#注意下面的eth0按需修改
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
ListenPort = 7456
PrivateKey = </etc/wireguard/private.key的内容>

[Peer]
PublicKey = <clinet public key>
AllowedIPs = 10.0.0.3/32

[Peer]
PublicKey = UKHyRkC/0nz18xxwG2j1ibaD7n3qBrXlDC5oFomyx0U=
AllowedIPs = 10.0.0.2/32

启动

1
sudo systemctl enable [email protected]

https://www.digitalocean.com/community/tutorials/how-to-set-up-wireguard-on-ubuntu-20-04 https://wiki.archlinux.org/title/WireGuard

Client配置

1
2
3
4
5
6
7
8
9
[Interface]
PrivateKey = KFmVIRLpxOT+ZHCg8eAKJ1T0a+iEWnhmeapeS9Psi3E=
Address = 10.0.0.3/24

[Peer]
#服务端的公钥
PublicKey = KsE/n/oVYjCZqc0Bo7vMmGkd5+RsNGO5k2X66aLNB3o=
AllowedIPs = 10.0.0.0/24
Endpoint = s.mypri.cloud:7456

Bypass Certain Ip

You could replace 0.0.0.0/0 and/or ::/0 in the AllowedIPs setting with a list of ranges that cover everything but the IP ranges you want to bypass.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from ipaddress import ip_network

start = '0.0.0.0/0'
exclude = ['8.8.8.8', '10.8.0.0/24']

result = [ip_network(start)]
for x in exclude:
    n = ip_network(x)
    new = []
    for y in result:
        if y.overlaps(n):
            new.extend(y.address_exclude(n))
        else:
            new.append(y)
    result = new

print(','.join(str(x) for x in sorted(result)))

https://www.reddit.com/r/WireGuard/comments/emjgp0/bypass_certain_ip_from_going_into_wireguard_tunnel/

Tips

reload config

1
wg syncconf wg0 <(wg-quick strip wg0)