LoginSignup
13
22

More than 3 years have passed since last update.

WireGuardを使って爆速でVPNトンネルを構築する

Last updated at Posted at 2020-11-12

せっかちな人向け

aptでWireGuardをインストールして、
Wireguard Config Generatorで設定を生成して、
systemctlでサービス化すれば完成!

はじめに

この記事ではVPSと自宅LAN内に設置したラズパイの間にトンネルを張ること目指す。
順調に進んだ場合10分程度で完了する。

環境

  • サーバー側
    • Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-52-generic x86_64)
  • クライアント側
    • Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-1021-raspi aarch64)

手順

WireGuardのインストール

サーバー側・クライアント側ともに同様にインストールする。

sudo apt update
sudo apt install wireguard

設定の生成

Wireguard Config Generatorを使うと簡単に設定を生成できる。
各項目を入力し、[Generate Config]をクリックすると設定が書き出される。
今回は下記の設定を使用する。

  • Listen Port
    • ポート設定
    • 今回はデフォルトの値(51820)を使用
  • Number of Clients
    • クライアントの数
    • 今回は1を指定
  • CIDR
    • 構築される仮想ネットワークが使用するIP
    • 今回はデフォルトの値(10.0.0.0/24)を使用
  • Client Allowed IPs
    • クライアント側から仮想ネットワーク上に流すIPの範囲
    • カンマ区切りで複数指定できる
    • 今回はサーバー側のIPアドレス(10.0.0.1/32)を指定
  • Endpoint (Optional)
    • [サーバーのグローバルIPアドレス]:[Listen Port]
    • IPv4でもIPv6でも良い
  • DNS (Optional)
    • 今回はいらない
    • クライアントの通信を全てサーバー経由にしたい場合は設定する必要がある
  • Post-Up rule, Post-Down rule
    • 今回はいらない
    • クライアントの通信を全てサーバー経由にしたい場合は設定する必要がある
  • Use Pre-Shared Keys (Enhanced Security)
    • 使うとよりセキュアになる
    • 今回は有効にする

設定の保存

サーバー側・クライアント側ともに生成された設定を /etc/wireguard/wg0.conf に書き込む。
それぞれの[Peer]の最後に PersistentKeepalive = 10 を追記し、常時接続となるようにする。
また、MTU値を調整すると接続が安定するので、[Interface]に MTU = 適切な値 を指定する。
とりあえず1350あたりを設定しておけば安定するはず(詳しくないので適当ですが許してください)。

最終的に下記のようになる。(PrivateKey, PublicKey, PresharedKeyはマスク済み)

/etc/wireguard/wg0.conf(サーバー側)
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
MTU = 1350

[Peer]
PublicKey = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
PresharedKey = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
AllowedIPs = 10.0.0.2/32
PersistentKeepalive = 10
/etc/wireguard/wg0.conf(クライアント側)
[Interface]
Address = 10.0.0.2/24
ListenPort = 51820
PrivateKey = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
MTU = 1350

[Peer]
PublicKey = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
PresharedKey = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=
AllowedIPs = 10.0.0.1/32
Endpoint = [サーバーのグローバルIPアドレス]:51820
PersistentKeepalive = 10

ポート開放

サーバー側のポートをudpを指定して開放する。

ufwの場合の例
sudo ufw allow 51820/udp
sudo ufw reload

デーモン化

サーバー側・クライアント側ともにsystemctlの設定を行い、起動時にトンネルを張るように設定する。

sudo systemctl start wg-quick@wg0
sudo systemctl enable wg-quick@wg0

疎通確認

サーバーからクライアント
ping -c 3 10.0.0.2
クライアントからサーバー
ping -c 3 10.0.0.1

おわり

WireGuardは非常にお手軽で素晴らしい。
Wireguard Config Generatorもお手軽で素晴らしい。

13
22
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
22