OpenVPN

提供: ArchWiki
ナビゲーションに移動 検索に移動

関連記事

この記事では、小規模な事業やプライベートでの利用に適している、OpenVPN の基本的なインストールと設定について説明します。詳しい情報は OpenVPN 2.4 man ページOpenVPN ドキュメント を見て下さい。OpenVPN は堅牢で高い柔軟性を持つ VPN デーモンです。SSL/TLS セキュリティ, Ethernet ブリッジ, プロキシNAT による TCPUDPトンネリングをサポートしています。さらに、動的 IP アドレスと DHCP をサポートしており、数百あるいは数千までのユーザーに対応し、主要な OS プラットフォームで動作します。

OpenVPN は OpenSSL ライブラリと密接に関係しており、OpenSSL の暗号機能を多数利用しています。事前共有鍵による慣用暗号 (Static Key モード) とクライアントとサーバーの証明書を用いる公開鍵暗号 (SSL/TLS モード) をサポートしています。さらに、暗号化を施さない TCP/UDP トンネルにも対応しています。

ほとんどのプラットフォームに存在する TUN/TAP 仮想ネットワークインターフェイスを使うように OpenVPN は設計されています。OpenVPN は IPSec の主要な機能の多くを提供しますがフットプリントは比較的軽量に抑えられます。OpenVPN は James Yonan によって書かれ GNU General Public License (GPL) の下で公開されています。

目次

インストール

サーバーモードとクライアントモードの両方を提供する openvpn パッケージをインストールしてください。

利用可能なフロントエンド:

  • NetworkManager OpenVPN — OpenVPN 用の NetworkManager VPN プラグイン。
https://wiki.gnome.org/Projects/NetworkManager/VPN || networkmanager-openvpn
  • QOpenVPN — systemd ベースのディストリビューション向けに PyQt で書かれたシンプルな OpenVPN GUI。
https://github.com/xmikos/qopenvpn || qopenvpn
  • eOVPN — OpenVPN の接続、管理、設定の更新を行うアプリケーション。
https://github.com/jkotra/eOVPN || eovpnAUR

カーネルの設定

OpenVPN は TUN/TAP のサポートを必要としますが、デフォルトカーネルでは既に設定済みです。自分でカーネルをビルドするときは、以下のように tun モジュールを有効にしてください:

Kernel config file
 Device Drivers
  --> Network device support
    [M] Universal TUN/TAP device driver support

詳しくはカーネルモジュールを読んで下さい。

第三者の VPN に接続

サードパーティによって提供されている VPN サービスに接続する場合、以下に書かれていることのほとんど(特にサーバーの設定に関する部分)は無視することができます。クライアントの設定ファイルにそって設定して、それから OpenVPN の起動まで飛んでください。プロバイダの証明書と説明書を使うべきです。他のプロバイダに適用できる例については Category:VPN プロバイダー を参照してください。Linux Containers で OpenVPN クライアント にも一般的な適用手順がありますが、OpenVPN クライアントプロセスをコンテナに分離することでさらに一歩進んだ手順になっています。

ノート: フリーの VPN プロバイダの多くは PPTP を提供しており、簡単に設定することが可能です。ただし、セキュアではありません

公開鍵基盤 (PKI) を最初から作成する

スクラッチから OpenVPN をセットアップする場合、公開鍵基盤 (PKI) を作成する必要があります。詳しくは Easy-RSA の記事に書かれています。必要な証明書・秘密鍵・関連ファイルが作成できたら、/etc/openvpn/server に以下のファイルが存在するはずです:

  • /etc/openvpn/server/ca.crt
  • /etc/openvpn/server/dh.pem
  • /etc/openvpn/server/servername.crt/etc/openvpn/server/servername.key
  • /etc/openvpn/server/ta.key

ベーシックな L3 IP ルーティング設定

ノート: 特に明示しないかぎり、この記事では以下の基本的な L3 IP ルーティング設定を使います。

OpenVPN は幅広い用途に使えるソフトウェアであり様々な設定ができます。マシンをサーバーとクライアントのどちらにでもできるので、サーバーとクライアントの区別は曖昧です。

v2.4 のリリースから、サーバーの設定は /etc/openvpn/server に保存され、クライアントの設定は /etc/openvpn/client に保存されるようになり、それぞれ別の systemd ユニット (openvpn-client@.serviceopenvpn-server@.service) を使うようになりました。

設定例

OpenVPN パッケージには様々な設定サンプルファイルが付属しています。以下の機能を持つベーシックな OpenVPN をセットアップしたい場合、サンプルのサーバーとクライアント設定ファイルを使用すると良いでしょう:

  • Public Key Infrastructure (PKI) を使って認証。
  • 仮想 TUN ネットワークインターフェイスを使用して VPN を作成 (OSI L3 IP ルーティング)。
  • UDP ポート 1194 でクライアントから接続 (OpenVPN の公式 IANA ポート番号)。
  • 仮想アドレスを 10.8.0.0/24 サブネットからクライアントに配布。

高度な設定例は公式の OpenVPN 2.4 man ページOpenVPN ドキュメント を読んでください。

サーバーの設定ファイル

ノート: サーバーまでの通り道にファイアウォールや NAT 変換ルーターがある場合、サーバー側で OpenVPN ポートを転送する必要があります。

サーバーのサンプル設定ファイルを /etc/openvpn/server/server.conf にコピー:

# cp /usr/share/openvpn/examples/server.conf /etc/openvpn/server/server.conf
/etc/openvpn/server/server.conf
ca ca.crt
cert servername.crt
key servername.key  # This file should be kept secret
dh dh.pem
.
tls-auth ta.key 0
.
user nobody
group nobody

サーバーの堅牢化

セキュリティが重要な場合、以下の設定を行うことを推奨します: 強固な暗号・認証方式、新しい tls 暗号だけを使うようにサーバーを設定。/etc/openvpn/server/server.conf に以下を追加してください:

/etc/openvpn/server/server.conf
...
cipher AES-256-CBC
auth SHA512
tls-version-min 1.2
tls-cipher TLS-DHE-RSA-WITH-AES-256-GCM-SHA384:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CBC-SHA:TLS-DHE-RSA-WITH-CAMELLIA-256-CBC-SHA:TLS-DHE-RSA-WITH-AES-128-CBC-SHA:TLS-DHE-RSA-WITH-CAMELLIA-128-CBC-SHA
...
ノート: .ovpn クライアントプロファイルには同じ cipher 行と auth 行を記述する必要があります (特に iOS と Android クライアントの場合)。

標準のポートやプロトコルを変更

パブリックネットワークやプライベートネットワークの管理者によってデフォルトポートやデフォルトプロトコルで OpenVPN 接続が許可されていない場合があります。通常の https/SSL トラフィックのように偽装することで解決できます。

/etc/openvpn/server/server.conf を以下のように設定してください:

/etc/openvpn/server/server.conf
...
port 443
proto tcp
...
ノート: .ovpn クライアントプロファイルには同じ port 行と proto 行を記述する必要があります。
TCP vs UDP

TCP と UDP には以下のような違いがあります。

TCP

  • いわゆる「ステートフルプロトコル」。
  • 誤り訂正による高い信頼性 (パケット応答を待機)。
  • UDP よりも低速。

UDP

  • いわゆる「ステートレスプロトコル」。
  • 誤り訂正が使われないため TCP よりも信頼性が低い。
  • TCP よりも高速。

クライアントの設定ファイル

クライアント設定ファイルのサンプルを /etc/openvpn/client/client.conf にコピー:

# cp /usr/share/openvpn/examples/client.conf /etc/openvpn/client/client.conf

以下を編集してください:

  • remote ディレクティブにはサーバーの完全修飾ドメイン名, (クライアントから名前解決できる) ホストネーム, IP アドレスのどれかを指定してください。
  • 特権を与えないようにするには usergroup ディレクティブをアンコメントします。
  • ca, cert, key パラメータは鍵と証明書のパス・名前に合わせてください。
  • SSL/TLS HMAC のハンドシェイクを有効にします。クライアントではパラメータを1にしてください。
/etc/openvpn/client/client.conf
remote elmer.acmecorp.org 1194
.
user nobody
group nobody
ca ca.crt
cert client.crt
key client.key
.
tls-auth ta.key 1

接続後に root 権限を落とす

設定ファイルで user nobodygroup nobody オプションを使うことで接続が確立した後 OpenVPN は権限を落とします。ただし、VPN が切断されたときにデーモンがネットワークルートを削除して再設定することができないという欠点があります。VPN 接続を使わずにトラフィックの転送を制限したい場合、ルートを残すのは望ましくありません。さらに、トンネルの起動時に OpenVPN サーバーがルートにアップデートをプッシュする可能性もあります。権限が落ちたクライアントではアップデートを実行することができずエラーを吐いて終了します。

ルートを管理するために手動で操作が必要があると思われるため、オプション user nobodygroup nobody は望ましくないように思われるかもしれません。しかし、セットアップに応じて、これらの状況を処理するための異なる方法があります。

  • ユニットのエラーの場合、ユニットを編集して [Service] セクションに Restart=on-failure を追加してください。ただし、これだけでは古いルートが削除されないため、再起動されたトンネルが正しくルーティングされません。
  • パッケージには /usr/lib/openvpn/plugins/openvpn-plugin-down-root.so が含まれています。これを使用して、openvpn が root 権限を持つプロセスをフォークし、メインプロセスから down シグナルを受信したときにカスタムスクリプトを実行するというタスクだけを持たせることができます。(README を参照)。

以下のリンク先の OpenVPN HowTo では、既存の nobody ではなく、専用の非特権ユーザー/グループを作成しています。これにより、デーモン間でユーザーを共有する際の潜在的なリスクを回避できるという利点があります。

  • The OpenVPN HowTo explains another way how to create an unprivileged user mode and wrapper script to have the routes restored automatically.
  • Further, it is possible to let OpenVPN start as a non-privileged user in the first place, without ever running as root, see this OpenVPN wiki HowTo.
ノート: The OpenVPN HowTos linked above create a dedicated non-privileged user/group, instead of the already existing nobody. The advantage is that this avoids potential risks when sharing a user among daemons.

証明書を暗号化された .p12 フォーマットに変換

ソフトウェアによってはパスワードで暗号化された .p12 ファイルで保存された VPN 証明書しか読み込まない場合があります。ファイルは以下のコマンドで生成することができます:

# openssl pkcs12 -export -inkey keys/bugs.key -in keys/bugs.crt -certfile keys/ca.crt -out keys/bugs.p12

OpenVPN 設定のテスト

サーバーで # openvpn /etc/openvpn/server/server.conf を実行して、クライアントで # openvpn /etc/openvpn/client/client.conf を実行してください。以下のような出力がされるはずです:

# openvpn /etc/openvpn/server/server.conf
Wed Dec 28 14:41:26 2011 OpenVPN 2.2.1 x86_64-unknown-linux-gnu [SSL] [LZO2] [EPOLL] [eurephia] built on Aug 13 2011
Wed Dec 28 14:41:26 2011 NOTE: OpenVPN 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables
Wed Dec 28 14:41:26 2011 Diffie-Hellman initialized with 2048 bit key
...
Wed Dec 28 14:41:54 2011 bugs/95.126.136.73:48904 MULTI: primary virtual IP for bugs/95.126.136.73:48904: 10.8.0.6
Wed Dec 28 14:41:57 2011 bugs/95.126.136.73:48904 PUSH: Received control message: 'PUSH_REQUEST'
Wed Dec 28 14:41:57 2011 bugs/95.126.136.73:48904 SENT CONTROL [bugs]: 'PUSH_REPLY,route 10.8.0.1,topology net30,ping 10,ping-restart 120,ifconfig 10.8.0.6 10.8.0.5' (status=1)
# openvpn /etc/openvpn/client/client.conf
Wed Dec 28 14:41:50 2011 OpenVPN 2.2.1 i686-pc-linux-gnu [SSL] [LZO2] [EPOLL] [eurephia] built on Aug 13 2011
Wed Dec 28 14:41:50 2011 NOTE: OpenVPN 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables
Wed Dec 28 14:41:50 2011 LZO compression initialized
...
Wed Dec 28 14:41:57 2011 GID set to nobody
Wed Dec 28 14:41:57 2011 UID set to nobody
Wed Dec 28 14:41:57 2011 Initialization Sequence Completed

サーバーで、tunX デバイスに割り当てられた IP アドレスを確認してください:

# ip addr show
...
40: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 100
    link/none
    inet 10.8.0.1 peer 10.8.0.2/32 scope global tun0

上記の場合、サーバーのトンネルの終末に割り当てられた IP アドレスは 10.8.0.1 です。

クライアントでも同じように確認してください:

# ip addr show
...
37: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 100
    link/none
    inet 10.8.0.6 peer 10.8.0.5/32 scope global tun0

クライアント側の IP アドレスは 10.8.0.6 と確認できます。

IP アドレスを確認したら ping を実行してみてください。

サーバー側:

# ping -c3 10.8.0.6
PING 10.8.0.6 (10.8.0.6) 56(84) bytes of data.
64 bytes from 10.8.0.6: icmp_req=1 ttl=64 time=238 ms
64 bytes from 10.8.0.6: icmp_req=2 ttl=64 time=237 ms
64 bytes from 10.8.0.6: icmp_req=3 ttl=64 time=205 ms

--- 10.8.0.6 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 205.862/227.266/238.788/15.160 ms

クライアント側:

# ping -c3 10.8.0.1
PING 10.8.0.1 (10.8.0.1) 56(84) bytes of data.
64 bytes from 10.8.0.1: icmp_req=1 ttl=64 time=158 ms
64 bytes from 10.8.0.1: icmp_req=2 ttl=64 time=158 ms
64 bytes from 10.8.0.1: icmp_req=3 ttl=64 time=157 ms

--- 10.8.0.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 157.426/158.278/158.940/0.711 ms
ノート: ファイアウォールを使っている場合、TUN デバイスの IP パケットがブロックされていないことを確認してください。

Fragment と MSS による MTU の設定

ノート: MTU を設定しなかった場合 ping や DNS などパケット数が少ない通信は上手く行きますが、ウェブブラウザなどはできません。

次は最大セグメントサイズ (MSS) の設定です。クライアントとサーバーの経路で最小の MTU を確認する必要があります。断片化を無効化してサーバーに ping することで確認できます:

# ping -c5 -M do -s 1500 elmer.acmecorp.org
PING elmer.acmecorp.org (99.88.77.66) 1500(1528) bytes of data.
From 1.2.3.4 (99.88.77.66) icmp_seq=1 Frag needed and DF set (mtu = 576)
From 1.2.3.4 (99.88.77.66) icmp_seq=1 Frag needed and DF set (mtu = 576)
From 1.2.3.4 (99.88.77.66) icmp_seq=1 Frag needed and DF set (mtu = 576)
From 1.2.3.4 (99.88.77.66) icmp_seq=1 Frag needed and DF set (mtu = 576)
From 1.2.3.4 (99.88.77.66) icmp_seq=1 Frag needed and DF set (mtu = 576)

--- core.myrelay.net ping statistics ---
0 packets transmitted, 0 received, +5 errors

上記の ICMP メッセージによれば MTU は 576 バイトです。UDP のオーバーヘッドのために UDP パケットを 576 バイト未満に断片化する必要があります。

# ping -c5 -M do -s 548 elmer.acmecorp.org
PING elmer.acmecorp.org (99.88.77.66) 548(576) bytes of data.
556 bytes from 99.88.77.66: icmp_seq=1 ttl=48 time=206 ms
556 bytes from 99.88.77.66: icmp_seq=2 ttl=48 time=224 ms
556 bytes from 99.88.77.66: icmp_seq=3 ttl=48 time=206 ms
556 bytes from 99.88.77.66: icmp_seq=4 ttl=48 time=207 ms
556 bytes from 99.88.77.66: icmp_seq=5 ttl=48 time=208 ms

--- myrelay.net ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4001ms
rtt min/avg/max/mdev = 206.027/210.603/224.158/6.832 ms

試行錯誤によりパケットを 548 バイトで断片化する必要があると確認できました。OpenVPN のクライアント設定ファイルを以下のように修正してください:

/etc/openvpn/client/client.conf
remote elmer.acmecorp.org 1194
...
fragment 548
mssfix 548
...

サーバーにも断片化について設定が必要です。サーバー側の設定では "mssfix" は不要なので注意してください:

ノート: 'fragment' ディレクティブをサポートしていないクライアント (例: OpenELEC, iOS アプリ) は 'fragment' ディレクティブを使用しているサーバーに接続できません。そのようなクライアントを使用する場合は、このセクションはスキップして下で説明している 'mtu-test' ディレクティブでクライアントを設定してください。
/etc/openvpn/server/server.conf
...
fragment 548
ノート: The following will add about 3 minutes to OpenVPN start time. It is advisable to configure the fragment size unless your client is a laptop that will be connecting over many different networks and the bottle neck is on the client side.

クライアントが VPN に接続するたびに OpenVPN でテストの ping を実行するように設定することもできます。クライアントはテストを実行していることを通知しない場合があり、テストが完了するまで接続が切れているかのように表示されることがあります。

/etc/openvpn/client/client.conf
remote elmer.acmecorp.org 1194
...
mtu-test
...
tls-auth ta.key 1

IPv6

IPv6 でサーバーに接続

OpenVPN でデュアルスタックを有効にするには、server.confclient.conf の両方で proto udpproto udp6 に変更してください。変更後、IPv4 と IPv6 の両方が有効になります。

トンネルで IPv6 を使用

トンネルで IPv6 を使えるようにするには、IPv6 プレフィックスを OpenVPN サーバーにルーティングする必要があります。ゲートウェイでスタティックルートを設定するか (固定ブロックが割り当てられている場合)、あるいは DHCPv6 クライアントを使って DHCPv6 プレフィックス委譲でプレフィックスを取得してください (詳しくは IPv6 プレフィックス委譲を参照)。アドレスブロック fc00::/7 からユニークなローカルアドレスを使うこともできます。どちらの方法もメリットとデメリットがあります:

  • Many ISPs only provide dynamically changing IPv6 prefixes. OpenVPN does not support prefix changes, so you need to change your server.conf every time the prefix is changed (Maybe can be automated with a script).
  • ULA addresses are not routed to the Internet, and setting up NAT is not as straightforward as with IPv4. So you cannot route the entire traffic over the tunnel. If you only want to connect two sites via IPv6, without the need to connect to the Internet over the tunnel, the ULA addresses may be easier to use.

プレフィックスを取得したら (/64 が推奨)、server.conf に以下を追加してください:

server-ipv6 2001:db8:0:123::/64

This is the IPv6 equivalent to the default 10.8.0.0/24 network of OpenVPN and needs to be taken from the DHCPv6 client. Or use for example fd00:1234::/64.

If you want to push a route to your home network (192.168.1.0/24 equivalent), also append:

push "route-ipv6 2001:db8:0:abc::/64"

OpenVPN does not yet include DHCPv6, so there is no method to e.g. push DNS server over IPv6. This needs to be done with IPv4. The OpenVPN Wiki provides some other configuration options.

OpenVPN の起動

手動起動

VPN 接続をトラブルシュートするときは、root で openvpn /etc/openvpn/client/client.conf を実行して手動でクライアントのデーモンを起動してください。同じように、サーバーもサーバーの設定ファイル (例: openvpn /etc/openvpn/server/server.conf) を使って起動できます。

ノート: openvpn /etc/openvpn/client/client.conf で動かない場合、cd /etc/openvpn/client; openvpn client.conf とするか、設定ファイル内のファイルへの参照をフルパスで記述すると起動します。

systemd サービスの設定

システムの起動時に OpenVPN サーバーを自動的に実行するには、該当するマシンで openvpn-server@<configuration>.service有効化してください。 クライアントの場合は、代わりに openvpn-client@configuration.service有効化してください。(<configuration>.conf 拡張子は要りません)。

例えば、クライアントの設定ファイルが /etc/openvpn/client/client.conf の場合、サービス名は openvpn-client@client.service です。また、サーバーの設定ファイルが /etc/openvpn/server/server.conf の場合、サービス名は openvpn-server@server.service となります。

ヒント: If openvpn-client@configuration.service units take a long time to start, it might be the network manager is not triggering the network-online.target systemd target at the right moment. For example, when using systemd-networkd, check that systemd-networkd-wait-online.service is properly configured.

NetworkManager で接続を開始

クライアント側で VPN トンネルを常時実行しない場合や特定の NetworkManager の接続だけで確立してほしい場合、/etc/NetworkManager/dispatcher.d/ にスクリプトを追加してください。以下の例では "Provider" が NetworkManager の接続名です:

/etc/NetworkManager/dispatcher.d/10-openvpn
#!/bin/bash

case "$2" in
  up)
    if [ "$CONNECTION_ID" == "Provider" ]; then
      systemctl start openvpn@client
    fi
  ;;
  down)
    systemctl stop openvpn@client
  ;;
esac

詳しくは NetworkManager#ネットワークサービスと NetworkManager dispatcher を見て下さい。

NetworkManager によるネイティブ VPN 設定

NetworkManagernetworkmanager-openvpn を使用した OpenVPN 管理をサポートしています。

ノート:
  • NetworkManagerはモバイル設定ファイル(通常 .ovpn で終わる)、すなわちインライン証明書と 1 つのファイルのみをサポートしています(Linux の設定は通常 userpass ファイルと分離された証明書を備えています)。
  • サポートされていないオプションのエラーメッセージは表示されません。使用されているオプションを確認するには、networkmanagerjournal を開いてください。

GUI configuration

In your desktop environment network settings (or nm-connection-editor). Click the plus sign to add a new connection and choose OpenVPN and manually enter the settings. You also can optionally import #The client configuration profile by selecting Import a saved VPN configuration... and selecting the appropriate file.

CLI configuration

For importing a configuration:

$ nmcli connection import type openvpn file file.ovpn

To do a manual configuration:

$ nmcli connection add type vpn vpn-type openvpn ...

See nm-settings-nmcli(5) § vpn setting for the detailed options.

Sync state with connection

NetworkManager supports syncing the VPN state with a インターフェース接続状態, i.e start the VPN together with the connection and bringing it down when the connection goes down.

To achieve this, open nm-connection-editor and select a network connection (not the VPN), then head to the General section, tick Automatically connect to VPN and select the appropriate config in the dropdown menu.

Automatically connect to VPN via CLI

List connections

nmcli connection
NAME     UUID                                  TYPE      DEVICE
zrh-003  d46e4a92-778e-4792-b085-e1f638ecb8e3  vpn       enp1s0
enp1s0   1715b889-3c47-3e21-a86f-94ce207297a9  ethernet  enp1s0
tun0     7405f329-255d-4b50-b98d-c2e865a443a4  tun       tun0

Copy UUID of VPN Connection you want to connect automatically (d46e4a92-778e-4792-b085-e1f638ecb8e3)

nmcli c edit enp1s0
nmcli> set connection.secondaries d46e4a92-778e-4792-b085-e1f638ecb8e3
nmcli> save persistent
Connection 'enp1s0' (1715b889-3c47-3e21-a86f-94ce207297a9) successfully updated.
systemctl restart NetworkManager

トラブルシューティング

証明書パスワードなし

If you get:

Warning: password for 'vpn.secrets.password' not given in 'passwd-file' and nmcli cannot ask without '--ask' option.
Error: Connection activation failed: No valid secrets

Even with

[vpn]
cert-pass-flags=0

You can add:

[vpn-secrets]
cert-pass=anything_you_want

全てのクライアントの通信をサーバーにルーティング

ノート: VPN サーバーを介してすべてのトラフィックをルーティングする場合、潜在的な落とし穴があります。詳細については、the OpenVPN documentation on this topic を参照してください。

デフォルトでは OpenVPN サーバーから直接送受信されたトラフィックしか VPN を通過しません。ウェブのトラフィックなど全てのトラフィックを VPN を通過させたい場合、まずはサーバーの設定ファイル (/etc/openvpn/server/server.conf) に以下を追加してください [1]:

push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 8.8.8.8"

8.8.8.8 は使用したい DNS の IP アドレスに変えてください。

サーバーに接続した後、DNS が反応しない場合は、シンプルな DNS フォワーダーとして BIND をインストールして OpenVPN サーバーの IP アドレスを DNS としてクライアントに送信してください。

設定ファイルが設定できたら、サーバーでパケットフォワーディングを有効化してください。さらに、サーバーのファイアウォールを設定して VPN の通信が通るようにします。以下では ufwiptables の設定方法を解説しています。

サーバーとは別の(プライベート)サブネットにもクライアントがアクセスできるようにしたい場合、push "route <address pool> <subnet>" オプションを使ってください:

push "route 172.10.142.0 255.255.255.0"
push "route 172.20.142.0 255.255.255.0"

ファイアウォールの設定

firewalld

デフォルトの1194番ポートを使用している場合は、openvpn サービスを有効にします。それ以外の場合は、別のポートで新しいサービスを作成します。

# firewall-cmd --zone=public --add-service openvpn

次にゾーンにマスカレードを追加します:

# firewall-cmd --zone=FedoraServer --add-masquerade

これらの変更を永続的にします:

# firewall-cmd --runtime-to-permanent

ufw

VPN 通信の ufw 設定を行うにはまず以下を /etc/default/ufw に追加してください:

/etc/default/ufw
DEFAULT_FORWARD_POLICY="ACCEPT"

そして /etc/ufw/before.rules を編集して以下のコードをヘッダーの後ろ、"*filter" 行の前に追加してください。IP やサブネットマスクは /etc/openvpn/server/server.conf に設定した値と同じ値に変更してください。以下の例ではアダプタ ID が一般的な eth0 ですが必要に応じて編集してください。

/etc/ufw/before.rules
# NAT (Network Address Translation) table rules
*nat
:POSTROUTING ACCEPT [0:0]

# Allow traffic from clients to eth0
-A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

# do not delete the "COMMIT" line or the NAT table rules above will not be processed
COMMIT

OpenVPN のポート 1194 を開く:

# ufw allow 1194

最後に、UFW をリロード:

# ufw reload

iptables

In order to allow VPN traffic through your iptables firewall of your server, first create an iptables rule for NAT forwarding [2] on the server, assuming the interface you want to forward to is named eth0:

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

If you have difficulty pinging the server through the VPN, you may need to add explicit rules to open up TUN/TAP interfaces to all traffic. If that is the case, do the following [3]:

警告: There are security implications for the following rules if you do not trust all clients which connect to the server. Refer to the OpenVPN documentation on this topic for more details.
iptables -A INPUT -i tun+ -j ACCEPT
iptables -A FORWARD -i tun+ -j ACCEPT
iptables -A INPUT -i tap+ -j ACCEPT
iptables -A FORWARD -i tap+ -j ACCEPT

Additionally be sure to accept connections from the OpenVPN port (default 1194) and through the physical interface.

設定ができたら iptables#iptables の設定と実行に書かれているように設定を永続化させてください。

If you have multiple tun or tap interfaces, or more than one VPN configuration, you can "pin" the name of your interface by specifying it in the OpenVPN config file, e.g. tun22 instead of tun. This is advantageous if you have different firewall rules for different interfaces or OpenVPN configurations.

VPN が落ちた時に漏洩を防止

The idea is simple: prevent all traffic through our default interface (enp3s0 for example) and only allow tun0. If the OpenVPN connection drops, your computer will lose its internet access and therefore, avoid your programs to continue connecting through an insecure network adapter.

Be sure to set up a script to restart OpenVPN if it goes down if you do not want to manually restart it.

ufw

# Default policies
ufw default deny incoming
ufw default deny outgoing

# Openvpn interface (adjust interface accordingly to your configuration)
ufw allow in on tun0
ufw allow out on tun0

# Local Network (adjust ip accordingly to your configuration)
ufw allow in on enp3s0 from 192.168.1.0/24
ufw allow out on enp3s0 to 192.168.1.0/24

# Openvpn (adjust port accordingly to your configuration)
ufw allow out on enp3s0 to any port 1194
ufw allow in on enp3s0 from any port 1194
警告: DNS won't work unless you run your own dns server like BIND

Otherwise, you will need to allow dns leak. Be sure to trust your dns server!

# DNS
ufw allow in from any to any port 53
ufw allow out from any to any port 53

vpnfailsafe

もしくは vpnfailsafe (vpnfailsafe-gitAUR) スクリプトをクライアントで使うことでも DNS 漏洩を防ぐことができ、インターネット宛の全てのトラフィックが VPN を通過するようにできます。VPN トンネルが落ちた場合、インターネットへのアクセスはできなくなりますが、VPN サーバーへの接続は可能です。スクリプトには update-resolv-conf の機能も含まれています。

L3 IPv4 ルーティング

このセクションでは L3 IPv4 ルーティングを使ってクライアント・サーバー LAN を互いに接続する方法を説明しています。

LAN のルーティングの要件

ホストが LAN と VPN で IPv4 パケットを転送できるようにするために、NIC と tun/tap デバイスでパケットを転送できるようにする必要があります。詳しい設定方法はインターネット共有#パケット転送の有効化を見て下さい。

ルーティングテーブル

By default, all IP packets on a LAN addressed to a different subnet get sent to the default gateway. If the LAN/VPN gateway is also the default gateway, there is no problem and the packets get properly forwarded. If not, the gateway has no way of knowing where to send the packets. There are a couple of solutions to this problem.

  • Add a static route to the default gateway routing the VPN subnet to the LAN/VPN gateway's IP address.
  • Add a static route on each host on the LAN that needs to send IP packets back to the VPN.
  • Use iptables' NAT feature on the LAN/VPN gateway to masquerade the incoming VPN IP packets.

サーバー LAN をクライアントに接続

The server is on a LAN using the 10.66.0.0/24 subnet. To inform the client about the available subnet, add a push directive to the server configuration file:

/etc/openvpn/server/server.conf
push "route 10.66.0.0 255.255.255.0"
ノート: To route more LANs from the server to the client, add more push directives to the server configuration file, but keep in mind that the server side LANs will need to know how to route to the client.

クライアント LAN をサーバーに接続

要件:

  • クライアント側で使用するサブネットは、サーバーや他のクライアントで使用されていないユニークなものである必要があります。この例では、クライアントの LAN に 192.168.4.0/24 を使用することにします。
  • 各クライアントの証明書は一意の Common Name を持ち、この場合は bugs とします。
  • サーバーは、設定ファイルで duplicate-cn ディレクティブを使用してはならない。
  • CCD フォルダは、サーバーの設定ファイルで定義されたユーザーとグループ(通常は nobody:nobody)でアクセス可能でなければならない。

サーバにクライアント設定ディレクトリを作成します。クライアントの common name と同じ名前のファイルが検索され、クライアントが接続したときにディレクティブが適用されます。

# mkdir -p /etc/openvpn/ccd

クライアントの設定ディレクトリに bugs というファイルを作成し、iroute 192.168.4.0 255.255.255.0 ディレクティブを含めます。これは、サーバに、どのサブネットがクライアントにルーティングされるべきかを伝えます。

/etc/openvpn/ccd/bugs
iroute 192.168.4.0 255.255.255.0

サーバ設定ファイルに client-config-dir と route 192.168.4.0 255.255.255.0 ディレクティブを追加します。これは、tun デバイスからサーバー LAN にルーティングされるべきサブネットをサーバーに伝えます。

/etc/openvpn/server/server.conf
client-config-dir ccd
route 192.168.4.0 255.255.255.0

サーバ LAN のマシンからクライアント LAN のマシンにアクセスする場合、クライアント側でパケット転送を有効にする必要があることを忘れないように(インターネット共有#パケット転送の有効化)。

ノート:
  • openVPN を systemd でデーモンとして動かしている場合、ccd ディレクトリへの絶対パスを指定する必要があるかもしれません。
  • クライアントからサーバへ、より多くの LAN をルーティングするには、適切な設定ファイルにさらに iroute と route ディレクティブを追加してください。

クライアントとサーバー両方の LAN を接続

Combine the two previous sections:

/etc/openvpn/server/server.conf
push "route 10.66.0.0 255.255.255.0"
...
client-config-dir ccd
route 192.168.4.0 255.255.255.0
/etc/openvpn/ccd/bugs
iroute 192.168.4.0 255.255.255.0
ノート: Remember to make sure that all the LANs or the needed hosts can route to all the destinations.

クライアントとクライアントの LAN を接続

デフォルトではクライアントは互いを認識できません。クライアント間やクライアントの LAN 間の IP パケットを許可するには、サーバーの設定ファイルに client-to-client ディレクティブを追加してください:

/etc/openvpn/server/server.conf
client-to-client

他のクライアントやクライアント LAN が特定のクライアント LAN を認識できるようにしたい場合、各クライアントのサブネットに対して push ディレクティブをサーバーの設定ファイルに追加してください (サーバーが利用可能なサブネットを他のクライアントに通知します):

/etc/openvpn/server/server.conf
client-to-client
push "route 192.168.4.0 255.255.255.0"
push "route 192.168.5.0 255.255.255.0"
...
ノート: As always, make sure that the routing is properly configured.

DNS

システムによって使われる DNS サーバーは /etc/resolv.conf に定義します。伝統的に、このファイルはシステムをネットワークに接続するプログラムによって扱われます (例: Wicd, NetworkManager など)。しかしながら、リモート側で名前解決ができるようにするには、OpenVPN がこのファイルを修正する必要があります。openresolv をインストールすることで、複数のプログラムが互いに干渉することなく resolv.conf を編集できるようになります。

先に進む前に、ネットワーク接続を再起動して resolv.conf の中に resolvconf によって生成されたという文言があること、そして DNS の解決が問題なく機能することを確認してください。openresolv を設定する必要はありません。ネットワークによって自動的に認識されて使用されます。

Linux の場合、OpenVPN は DNS のホスト情報を送信することができますが、外部プロセスがそれを扱うようになっています。/usr/share/openvpn/contrib/pull-resolv-conf/ に存在する client.upclient.down スクリプトを使用します。スクリプトを /etc/openvpn/client/ にインストールする方法はコメントを見てください。以下は resolvconf#接続後に root 権限を落とすのオプションを組み合わせてスクリプトを使って作成されたクライアント設定の抜粋です:

/etc/openvpn/client/clienttunnel.conf
user nobody
group nobody
# Optional, choose a suitable path to chroot into for your system
chroot /srv
script-security 2
up /etc/openvpn/client/client.up
plugin /usr/lib/openvpn/plugins/openvpn-plugin-down-root.so "/etc/openvpn/client/client.down tun0"

The pull-resolv-conf custom scripts

These scripts are maintained by OpenVPN. They are client.up and client.down, and they are packaged in /usr/share/openvpn/contrib/pull-resolv-conf/. The following is an excerpt of a resulting client configuration using the scripts in conjunction with the down-root plugin:

/etc/openvpn/client/clienttunnel.conf
user nobody
group nobody
# Optional, choose a suitable path to chroot into
chroot /srv
script-security 2
up /usr/share/openvpn/contrib/pull-resolv-conf/client.up 
plugin /usr/lib/openvpn/plugins/openvpn-plugin-down-root.so "/usr/share/openvpn/contrib/pull-resolv-conf/client.down tun0"

These scripts use the resolvconf command if present. Systemd-resolvconf and Openresolv both implement this command. See their wiki pages for more information on getting a working resolvconf implementation.

ノート: As of October 2019, systemd-resolvconf works as long as the systemd-resolved service is running. Openresolv will not work out of the box because client.up will only create private DNS server entries. These require extra configuration of openresolv to work. See man 8 resolvconf for more details on private DNS servers in openresolv.

If no implementation of resolvconf is present, client.up preserves the existing resolv.conf at /etc/resolv.conf.ovpnsave and writes a new one. This new one will not have any of the original DNS servers.

When editing these scripts, copy them somewhere else and edit them there, so that the changes do not get overwritten by the next openvpn package upgrade. /etc/openvpn/client is a pretty good place.

# cp /usr/share/openvpn/contrib/pull-resolv-conf/* /etc/openvpn/client
# $EDITOR /etc/openvpn/client/client.{up,down}
# # etc ...

update-resolv-conf スクリプト

パッケージに含まれているスクリプトのかわりとして openvpn-update-resolv-conf スクリプトを使うことができます。/etc/openvpn/update-resolv-conf などに保存して chmod で実行可能属性を付与してください。AUR の openvpn-update-resolv-conf-gitAUR パッケージでスクリプトをインストールすることもできます。

スクリプトをインストールしたら OpenVPN のクライアント設定ファイルに以下のような行を追加してください:

script-security 2
up /etc/openvpn/update-resolv-conf
down /etc/openvpn/update-resolv-conf

これで OpenVPN 接続を起動すると resolv.conf ファイルが正しく更新され、接続を終了すると通常の resolv.conf に戻ります。

ノート: When using openresolv with the -p or -x options in a script (as both the included client.up and update-resolv-conf scripts currently do), a DNS resolver like dnsmasq or unbound is required for openresolv to correctly update /etc/resolv.conf. In contrast, when using the default DNS resolution from libc the -p and -x options must be removed in order for /etc/resolv.conf to be correctly updated by openresolv. For example, if the script contains a command like resolvconf -p -a and the default DNS resolver from libc is being used, change the command in the script to be resolvconf -a .

update-systemd-resolved スクリプト

systemd-229 から、systemd-networkdsystemd-resolved.service には DBus を使ってリンクごとに DNS の設定を管理することができる API が用意されています。/etc/resolv.confsystemd-resolved によって管理されている場合、openresolv などのツールは上手く動かない場合があります。さらに、/etc/nsswitch.conf ファイルで dns のかわりに resolve を使っている場合は全く動作しません。update-systemd-resolved スクリプトは DBus を通して OpenVPN と systemd-resolved をリンクし DNS レコードを更新します。

スクリプトを /etc/openvpn にコピーして chmod で実行可能属性を付与するか、AUR パッケージでインストールして (openvpn-update-systemd-resolvedAUR)、OpenVPN のクライアント設定ファイルに以下の行を追加してください:

script-security 2
setenv PATH /usr/bin
up /etc/openvpn/update-systemd-resolved
down-pre /etc/openvpn/update-systemd-resolved

Override DNS servers using NetworkManager

By default networkmanager-openvpn plugin appends DNS servers provided by OpenVPN to /etc/resolv.conf.

To verify that the correct DNS server(s) are configured, see resolvectl status if systemd-resolved is in use, for other resolvers see Domain name resolution.

L2 Ethernet ブリッジ

次を参照: OpenVPN Bridge

Config ジェネレーター

警告: 自動化スクリプトを使用する前に、上記の手動設定を通過し、オプションと使用方法に関する知識を得ることを強くお勧めします。

ovpngen

ovpngenAUR パッケージは、Android および iOS 用の OpenVPN Connect アプリに適した統一ファイル形式で OpenVPN 互換のトンネルプロファイルを作成するシンプルなシェルスクリプトを提供します。

5 つのトークンを使ってスクリプトを呼び出すだけです。

  1. Server OpenVPN サーバーの完全修飾ドメイン名 (または IP アドレス)。
  2. CA 証明書へのフルパス。
  3. クライアント証明書へのフルパス
  4. クライアントの秘密鍵へのフルパス
  5. サーバーの TLS 共有秘密鍵へのフルパス。
  6. オプションでポート番号を指定します。
  7. オプションでプロトコル (udp または tcp) を指定します。

例:

# ovpngen example.org /etc/openvpn/server/ca.crt /etc/easy-rsa/pki/signed/client1.crt /etc/easy-rsa/pki/private/client1.key /etc/openvpn/server/ta.key > foo.ovpn

If the server is configured to use tls-crypt, as is suggested in #The server configuration file, manually edit the resulting foo.ovpn replacing <tls-auth> and </tls-auth> with <tls-crypt> and </tls-crypt>.

The resulting foo.ovpn can be edited if desired as the script does insert some commented lines. foo.ovpn will not automatically route all traffic through the VPN, so you may want to follow #Routing client traffic through the server to enable redirection.

The client expects this file to be located in /etc/openvpn/client/foo.conf. Note the change in file extension from 'ovpn' to 'conf' in this case.

ヒント: If the server.conf contains a specified cipher and/or auth line, it is highly recommended that users manually edit the generated .ovpn file adding matching lines for cipher and auth. Failure to do so may results in connection errors!

openvpn-unroot

ノート: If you intend to use a custom script, perhaps for configuring #DNS, you must add these scripts to your config before calling openvpn-unroot on it. Failing to do so will cause problems if the scripts require root permissions.

The steps necessary for OpenVPN to #Run as unprivileged user, can be performed automatically using openvpn-unroot (openvpn-unroot-gitAUR).

It automates the actions required for the OpenVPN howto by adapting it to systemd, and also working around the bug for persistent tun devices mentioned in the note.

トラブルシューティング

サスペンド後にクライアントデーモンが再起動しない

クライアントをスリープ状態にしてから復帰しても OpenVPN が再起動しないために切断してしまう場合、以下のファイルを作成してください:

/usr/lib/systemd/system-sleep/vpn.sh
#!/bin/sh
if [ "$1" == "pre" ]
then
  killall openvpn
fi

chmod a+x /usr/lib/systemd/system-sleep/vpn.sh に実行可能属性を付与してサービスを編集してください:

/etc/systemd/system/openvpn-client@.service.d/restart.conf
[Service]
Restart=always

しばらく通信しないと接続が切れる

データを通信していないと接続中と表示されているのに数秒で VPN 接続が切れて、データがトンネルで転送されない場合、サーバーの設定に keepalive ディレクティブを追加してみてください:

/etc/openvpn/server/server.conf
...
keepalive 10 120
...

上記の設定でサーバーは ping のようなメッセージを10秒ごとにクライアントに送信してトンネルを維持します。クライアントから120秒以上反応を得られなかった場合、サーバーはクライアントが切断されたと判断します。

ping の間隔を小さくすることでトンネルの安定性を上げることができますが、発生するトラフィックが増大します。接続環境によっては10秒以下に設定してみてください。

PID files not present

The default systemd service file for openvpn-client does not have the --writepid flag enabled, despite creating /run/openvpn-client. If this breaks a configuration (such as an i3bar VPN indicator), simply change openvpn-client@.service using a drop-in snippet:

[Service]
ExecStart=
ExecStart=/usr/sbin/openvpn --suppress-timestamps --nobind --config %i.conf --writepid /run/openvpn-client/%i.pid

Route configuration fails with systemd-networkd

When using systemd-networkd to manage network connections and attempting to tunnel all outgoing traffic through the VPN, OpenVPN may fail to add routes. This is a result of systemd-networkd attempting to manage the tun interface before OpenVPN finishes configuring the routes. When this happens, the following message will appear in the OpenVPN log.

openvpn[458]: RTNETLINK answers: Network is unreachable
openvpn[458]: ERROR: Linux route add command failed: external program exited with error status: 2

From systemd-233, systemd-networkd can be configured to ignore the tun connections and allow OpenVPN to manage them. To do this, create the following file:

/etc/systemd/network/90-tun-ignore.network
[Match]
Name=tun*

[Link]
Unmanaged=true

Restart systemd-networkd.service to apply the changes. To verify that the changes took effect, start the previously problematic OpenVPN connection and run networkctl. The output should have a line similar to the following:

7 tun0             none               routable    unmanaged

tls-crypt unwrap error: packet too short

This error shows up in the server log when a client that does not support tls-crypt, or a client that is misconfigured to use tls-auth while the server is configured to use tls-crypt, attempts to connect.

To support clients that do not support tls-crypt, replace tls-crypt ta.key with tls-auth ta.key 0 (the default) in server.conf. Also replace tls-crypt ta.key with tls-auth ta.key 1 (the default) in client.conf.

NetworkManager fails to connect using imported configuration

There is a known upstream bug [4][5][6] in conjunction with importing existing OpenVPN configurations (.ovpn files) under KDE via the GUI (plasma-nm not nm-connection-editor) that causes certain advanced options such as tls-crypt to be silently ignored. The created NetworkManager connection profile will therefore be incomplete and the connection ultimately fails.

Logs might reveal errors such as the following:

TLS Error: TLS handshake failed
TLS Error: TLS key negotiation failed to occur within 60 seconds (check your network connectivity)

A workaround is to resort to NetworkManager's command-line utility nmcli to import the connection profile as is shown in #CLI configuration.

OpenVPN connection fails after update to OpenSSL3

There exists an issue with PKCS#12 encoded user certificates/private key files (usually denoted by a .pfx or .p12 file ending) with OpenSSL3, c.f. also [7]. This leads to connections which worked perfectly before updating to OpenSSL3 not being able to connect with the following log messages produced (in this case via NetworkManager):

nm-openvpn[14025]: WARNING: No server certificate verification method has been enabled.  See https://openvpn.net/howto.html#mitm for more info.
nm-openvpn[14025]: NOTE: the current --script-security setting may allow this configuration to call user-defined scripts
nm-openvpn[14025]: OpenSSL: error:0308010C:digital envelope routines::unsupported
nm-openvpn[14025]: OpenSSL: error:11800071:PKCS12 routines::mac verify failure
nm-openvpn[14025]: Decoding PKCS12 failed. Probably wrong password or unsupported/legacy encryption
nm-openvpn[14025]: SIGUSR1[soft,private-key-password-failure] received, process restarting

The reason is that older versions of OpenSSL used algorithms, which are now deprecated, to encrypt the PKCS#12 files.

To solve this issue the PKCS#12 file must be re-encrypted with a non-legacy algorithm.

$ cd path/to/the/pfx-file
$ mv mykeys.pfx mykeys.pfx.bak
$ openssl pkcs12 -in mykeys.pfx.bak -out mykeys.pfx -aes256 -legacy

参照