2018-09-23
WireGuard安装笔记
在Google Cloud和Vultr的Debian系统测试通过,直接无脑执行下列代码
apt-get install libmnl-dev linux-headers-$(uname -r) build-essential make git
git clone https://git.zx2c4.com/WireGuard
cd WireGuard/src/
make
make install
ip link add dev wg0 type wireguard
umask 077
wg genkey > private
wg pubkey < private > public
cat public
wg set wg0 listen-port 51920 private-key ~/private peer <PEER_PUBLIC_KEY> allowed-ips 10.0.0.0/24 endpoint <OTHER_SERVER_IP>:51920
这里需要把<PEER_PUBLIC_KEY>、<OTHER_SERVER_IP>替换成对应的内容
ip link set up dev wg0
ip addr add 10.0.0.1/24 dev wg0
这样应该已经能够建立handshake了,注意网卡分配的地址和客户端的地址要在同一网段。
现在本地跟服务器已经在同一个内网上,可以彼此通信了。
但本地现在是无法通过服务器连接到外面的网络,如果需要通过服务器连接到外面的网络,要在服务器上设置流量转发和 NAT 才可以。
转发与 NAT
首先,检查下 ip 转发是否已开启:
sysctl net.ipv4.ip_forward
如果等于 1 说明已经开启,否则可以使用:
sysctl net.ipv4.ip_forward=1
来临时开启,如果想永久生效,需要编辑 /etc/sysctl.conf 文件,查找到 net.ipv4.ip_forward 这一行,把最前端的 # 号(注释)去掉,如果其值不为 1 的,改成 1。如果找不到,就把 net.ipv4.ip_forward=1 加在文件最下面。
然后使用命令 sysctl -p 来使其生效。
接下来检查下 iptables 里 filter 表的 FORWARD 链的 policy 是否为 ACCEPT:
iptables -t filter -L FORWARD
如果 policy 为 DROP,需要允许 wg0 接口才行:
iptables -t filter -A FORWARD -i wg0 -j ACCEPT
iptables -t filter -A FORWARD -o wg0 -m state –state RELATED,ESTABLISHED -j ACCEPT
然后看下 nat 表的 POSTROUTING 链里是否已经做了出口的 NAT 了(这里假设服务器上连接外网的接口是 eth0):
iptables -t nat -L POSTROUTING -v
如果还没有,使用以下命令加上:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PS:如果出口不是 eth0 接口的,把 eth0 换成正真的出口接口
在服务器设置好后,还要在本地加上路由,把流量转发到 wg0 接口上。
这个时候应该可以顺利的上网了。
参考:
https://www.vultr.com/docs/create-a-secure-connection-between-two-servers-using-wireguard-on-ubuntu
https://blog.mozcp.com/wireguard-usage/
https://wiki.archlinux.org/index.php/WireGuard
https://www.wireguard.com/quickstart/
标签:
转载注明:转自Mao
