Setup Wireguard on Ubuntu 20.04

Chanming
Aug 6, 2020
#! /bin/bash

echo "开放端口号(8058):"
read wg_port_input

if [[ $wg_port_input -lt 1 || $wg_port_input -gt 65535 ]]   # checks that the input is within the desired range
 then
    echo "Input outside acceptable range."
    echo "Use default 8058."
    wg_port=8058
 else
    echo "端口号: "$wg_port_input
    wg_port=$wg_port_input
fi

echo "客户端数量(1):"
read num_client_input
if [[ $num_client_input -lt 1 ]]   # checks that the input is within the desired range
 then
    echo "Input outside acceptable range."
    echo "Use default 1."
    num_client=1
 else
    echo "客户端数量: "$num_client_input
    num_client=$num_client_input
fi

config_dir="$HOME/.wireguard/"

mkdir -p "$config_dir"
cd "$config_dir" || {
    echo "切换目录失败,程序退出"
    exit
}
# 生成服务端私钥和公钥
wg genkey | tee server_priv | wg pubkey > server_pub
chmod 600 server_priv

# 检索网络配置
interface=$(ip -o -4 route show to default | awk '{print $5}')
ip=$(ip -4 addr show "$interface" | grep -oP '(?<=inet\s)\d+(\.\d+){3}')

# 生成服务端配置文件
cat >wg0.conf <<EOL
[Interface]
PrivateKey = $(cat server_priv)
Address = 10.10.10.1
ListenPort = $wg_port
PostUp   = iptables -A FORWARD -i %i -j ACCEPT; iptables -t nat -A POSTROUTING -o $interface -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -o $interface -j MASQUERADE
EOL

# 生成客户端私钥与公钥
for no in $(seq 1 1 ${num_client})
do
    wg genkey | tee client_priv_$no | wg pubkey >client_pub_$no
    chmod 600 client_priv_$no
    echo "[Peer]
PublicKey = $(cat client_pub_${no})
AllowedIPs = 10.10.10.${no}/32
" >> wg0.conf

    # 生成客户端配置文件
    cat >client${no}.conf <<EOL
[Interface]
PrivateKey = $(cat client_priv_${no})
Address = 10.10.10.${no}
DNS = 208.67.222.222  # use open dns server

[Peer]
PublicKey = $(cat server_pub)
Endpoint = $ip:$wg_port
AllowedIPs = 0.0.0.0/0
EOL

done

# 复制配置文件并启动
sudo cp wg0.conf /etc/wireguard/ || {
    echo "复制失败,请检查/etc/wireguard目录或wg0.conf是否已经存在"
    exit
}
sudo wg-quick up wg0 || {
    echo "启动wireguard失败,请检查/etc/wireguard/wg0.conf是否存在错误"
    exit
}
# 启动wireguard服务, 开机自启
sudo systemctl enable wg-quick@wg0
# 开启ipv4流量转发
sudo echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
# 使sysctl设置生效
sudo sysctl -p

# 显示客户端配置文件
for no in $(seq 1 1 ${num_client})
do
    echo "----------以下是客户端"${no}"的配置文件,请保存并在客户端中使用----------"
    cat client${no}.conf
done

Todos

Further add clients to existing configurations.

Reference

How to set up WireGuard VPN server on Ubuntu 20.04 @ ServerSide UP 安装和配置wireguard @ segmentfault WireGuard介绍及客户端配置使用教程 @ 敲敲幸福的门,怎样更好呢? Ubuntu 20.04 set up WireGuard VPN server @ nixCraft