メンターを任されたエンジニアのブログ

ある日メンターを任された3流エンジニアのブログ

OpenVPNのインストール - その2 サーバ設定

hatman62.hatenablog.com

ubuntu公式だとTLS認証を有効化する手順が含まれていません。
ので、その設定を含めつつ、公式ドキュメントに則って手順を書いていきたいと思います。

大体1時間くらいで終わる、、、はず。

サーバのインストール

ターミナルから以下のコマンドを実行

$ sudo apt-get install openvpn easy-rsa

公開鍵暗号基盤(PKI)のセットアップ

  1. 自前の認証局(CA)で証明書を作成
  2. その証明書を使って鍵を作成

てな感じ。

オレオレ認証局の設定

というわけで、認証局をセットアップしていきます
※ rootユーザで実施

# mkdir /etc/openvpn/easy-rsa/
# cp -r /usr/share/easy-rsa/* /etc/openvpn/easy-rsa/

変数ファイルを修正

# cd /etc/openvpn/easy-rsa/
# cp -p vars vars.bk
# vi /etc/openvpn/easy-rsa/vars
# # 64-68行目を編集
# # 編集した差分を表示
# diff vars.bk vars
64,68c64,68
< export KEY_COUNTRY="US"
< export KEY_PROVINCE="CA"
< export KEY_CITY="SanFrancisco"
< export KEY_ORG="Fort-Funston"
< export KEY_EMAIL="me@myhost.mydomain"
---
> export KEY_COUNTRY="JP"              # <- 国
> export KEY_PROVINCE="Tokyo"          # <- 都道府県
> export KEY_CITY="CITY-NAME"          # <- 区市町村名
> export KEY_ORG="hogehoge.com"        # <- ドメイン名
> export KEY_EMAIL="example@hoge.com"  # <- メールアドレス

CA証明書と鍵を作成

# cd /etc/openvpn/easy-rsa/
# source vars
# ./clean-all
# ./build-ca
(略 とりあずEnterキー押下していればOK)
# ./build-key-server myservername

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:password #←パスワードを入力(空でもOKらしい)
(略 とりあずEnterキー押下していればOK)
Certificate is to be certified until Jul  4 13:25:38 2026 GMT (3650 days)
Sign the certificate? [y/n]:y # <- yを入力


1 out of 1 certificate requests certified, commit? [y/n]y # <- yを入力
Write out database with 1 new entries
Data Base Updated

# ./build-dh
(ちょっと時間かかる)

# cd keys
# openvpn --genkey --secret ta.key
# cp myservername.crt myservername.key ca.crt dh2048.pem ta.key /etc/openvpn/

クライアント用の証明書を作成

# cd /etc/openvpn/easy-rsa/
# source vars
# ./build-key client1
(build-key-serverの時と同じ)

この時作成される証明書とか諸々はクライアント側にコピーしておく。

※クライアント証明書とキーはコピー後に削除すること
※CA証明書(ca.crt)、TLS証明書(ta.key)は削除しないでね

# cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/
# gzip -d /etc/openvpn/server.conf.gz
# vi /etc/openvpn/server.conf
(数字は行数)
 77 # (see "pkcs12" directive in man page).
 78 ca ca.crt
 79 cert myservername.crt
 80 key myservername.key  # This file should be kept secret
 81
 82 # Diffie hellman parameters.
 83 # Generate your own with:
 84 #   openssl dhparam -out dh2048.pem 2048
 85 dh dh2048.pem

243 # on the server and '1' on the clients.
244 tls-auth ta.key 0 # This file is secret

IP forwardingを有効化するため、/etc/sysctl.confの以下のコメントアウトを外す

#net.ipv4.ip_forward=1

外したら、再起動

sysctl -p /etc/sysctl.conf

確認してみる

# sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1

OpenVPNを起動する

# service openvpn@server start

@の後ろは設定ファイルの名前らしく、今回の場合、servrer.confなので、@serverをつけている

次回はクライアント側の設定について。