wireguard MacOS 安裝筆記

首先安裝 xcode 工具

% xcode-select --install

為了要設定開機自動連 VPN 所以用 brew 安裝 wireguard

% brew install wireguard-tools

先用指令 建立 wireguard 的 public & private keys

% umask 077
% wg genkey | tee privatekey | wg pubkey > publickey

然後用上面的 keys 建立 wireguard 的 conf 檔案

% sudo mkdir -p /usr/local/etc/wireguard/
% sudo vi /usr/local/etc/wireguard/wg0.conf
[Interface]
PrivateKey = YBngW0d9S0ZsHSQtwG6AUck0XoQb2vx+O/0u23+JR1c= ### 剛剛產生的 private key
Address = 192.168.11.100/32

[Peer]
PublicKey = v7SbqmQqYZ9VolnlclkonSmgMEsBdNc5ARcoK/IdiWo= ### 遠端 server 的 public key
AllowedIPs = 10.10.10.0/24
Endpoint = 168.168.95.95:51820 ### VPN server 的 public ip address
PersistentKeepalive = 25

% sudo chmod 640 /usr/local/etc/wireguard/wg0.conf
% sudo chown -R root:wheel /usr/local/etc/wireguard

手動啟動一下 wireguard VPN

% sudo wg-quick up wg0

然後測試一下是否有正常連入 VPN

% sudo wg
interface: utun0
  public key: 0kLAq+YOPJd3wjkW1OScfjKox6BO1ZfQ9BKgpc+OLFs=
  private key: (hidden)
  listening port: 56405

peer: v7SbqmQqYZ9VolnlclkonSmgMEsBdNc5ARcoK/IdiWo=
  endpoint: 168.168.95.95.8:51820
  allowed ips: 10.10.10.0/24
  latest handshake: 1 minute, 20 seconds ago
  transfer: 9.25 KiB received, 7.96 KiB sent

看到上面的結果就連線成功。然後關閉 VPN

% sudo wg-quick down wg0
[+] Interface for wg0 is utun0
[#] rm -f /var/run/wireguard/utun0.sock
[#] rm -f /var/run/wireguard/wg0.name

開始建立每次開機就啟動的設定檔案

% sudo vi /Library/LaunchDaemons/com.wireguard.wg0.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.wireguard.wg0</string>
        <key>ProgramArguments</key>
        <array>
            <string>/opt/homebrew/bin/wg-quick</string>
            <string>up</string>
            <string>wg0</string>
        </array>
        <key>KeepAlive</key>
            <dict>
                <key>NetworkState</key>
                <true/>
            </dict>
        <key>RunAtLoad</key>
        <true/>
        <key>StandardErrorPath</key>
        <string>/opt/homebrew/var/log/wireguard.err</string>
        <key>EnvironmentVariables</key>
        <dict>
            <key>PATH</key>
            <string>/opt/homebrew/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
        </dict>
    </dict>
</plist>

然後設定每次開機都啟動

% sudo launchctl enable system/com.wireguard.wg0
% sudo launchctl bootstrap system /Library/LaunchDaemons/com.wireguard.wg0.plist

從新開機 然後用 sudo wg 指令驗證有沒有連線成功 : D