raspberry pi 4 で openvpn サーバを構築

投稿者:

raspberry pi に openvpn をインストールしてリモート接続できるようにしてみた、というのは、よくある話だとは思うが、多少工夫をしてみた話。

背景

これまで openvpn を使ったリモート接続環境を大学の研究室などに提供していた。

特徴としては、小型のPCをLANに設置し、ファイアウォールの外側にあるサーバ経由でLANにブリッジ接続できるという点だ。要はファイアウォールを越えてLANに接続させる。そういった接続を黙認している大学の研究室ではいまだに使われていた。研究室にあるマシン(おそらくかなり高価、特殊なPC)にログインしたり、大学内からしか使えないWEBサイトをリモートからアクセスしたりするのに使うそうだ。

しかし、凝った構成のためか、最近の mac os 環境でつながらなくなってしまって、たまに使っていた自分自身も困ってしまった。

10年ほど前に構築したもので、サーバやクライアントソフトのアップデートができなくなってしまった。なんせ、サーバは、FreeBSD 8.4 で、間にIPアドレスを変換したり、セキュリティチェックをしたりするソフトが挟まっている。管理用の WEBサイトは、セキュリティを考慮して、サーバをいくつかに分割した作りで、Perl や C で書かれていて、読み解くにはソースコードを読むしかなくメンテナンスするには時間がかかりそうだった。また、クライアント側もファイアウォールが https しか通らない環境を考慮して、stunnel 上に openvpn を通す設計だった。

お客さんは2グループしかいない(苦笑)ものの、VPN環境は使いたいということだったので、これまで使っていたサーバ類は一切捨てることに決めて、openvpn や tunnelblick だけで接続でき、なおかつ、自作のプログラムは使わないで標準設定だけで使える方法を模索した。

構成

まず、小型なものが良いだろうと思い、冒頭の写真のように raspberry pi 4 をケースに入れたものとした。なかなか可愛い。ネジも要らないし、ケースに入れるのが簡単。自分用にも1個買っとけばよかった。

これに ubuntu 20.04 LTS をインストールしたものにした。

openvpn のブリッジ接続(tap)はLANに直接接続しているように見えるのでとてもわかりやすいのだが、DHCPやDNSの設定が非常に難しい。場合によっては、DHCPサーバ(一般にはルータ)の設定を変更する必要がある。

なので、ブリッジ接続は諦めて、IPトンネル接続(tun)を使うことにした。難点としては、

  • 例えば研究室LANに自宅からアクセスする場合、研究室LANと自宅LANのネットワークアドレスが同じだと研究室LANのPCに接続できない。その場合は、自宅LAN(研究室LANでもよいが)のネットワークアドレスを変える必要がある。
  • IP ルーティングではトンネル上に bonjour(mdns) が飛ばないので、例えば NAS などには固定IPアドレスでアクセスするしかない。

などがあるが、 ヒアリングしたところ、特に不便も無いだろうと思い、この構成とした。

DNS 設定はリモート環境のDNSを参照したい(リモート環境だけでしか見えないホスト名があるかもしれないので)。接続時に push することができるのだが、ルータが提示する DNS アドレスを渡すのは複雑そうだ。なので、openvpn サーバ自身を dns サーバにして、tun に付くアドレスを push することにした。dns サーバは、dnsmasq が使えるかと思ったが、systemd が127.0.0.53 に立てている dns サーバと競合するのか、うまく起動させられなかった。dnsproxy というパッケージがあったので、ちょっと古めかなと思いつつもこのパッケージを使用した。参照するDNSサーバを127.0.0.53にすればよい。

ファイアウォールを越える設定が必要になるのだが、中継用サーバとして、ファイアウォールの外側にサーバを立てて、このサーバと openvpn サーバ間を ssh の reverse port forward(-R オプション)で openvpn に転送する方式とした。autossh を使えば常時 ssh トンネルを張っておくことができる。中継用サーバの設定は、sshd の設定を数行変更するだけなので、それほど手間はかからないだろう。(私はAWS の t3.nano/t4g.nanoを使用した)

設定ファイルなど

まず、ca.crt やプライベートキーなどを作る必要があるが、easyrsa3 を使った。easyrsa2 に比べて非常に使いやすい。。。以下のような感じで簡単に作れるだろう。

easyrsa init-pki
easyrsa build-ca nopass
easyrsa build-server-full 何か名称 nopass
easyrsa build-client-full 何か名称 nopass
easyrsa gen-dh
easyrsa gen-crl

本当はパスワードはつけたほうが良い(nopass を指定しない)と思う。

ここから設定ファイルを作らないといけないが、私は python script を作って、設定ファイルを生成できるようにした。openvpn の設定ファイルをテンプレート(jinja) にしておいて、証明書・鍵ファイル名、サーバ名を埋めむようにすればよい。

設定ファイル一式を利用者に何かの方法(ここが一番考慮すべきだが)で渡してインストールしてもらう。Windows であれば、設定ファイル一式を c:¥users¥ログインid¥Openvpn¥config にコピー、MacOS であれば、設定ファイルを Tunnelblick にドラッグアンドドロップするだけで良いようだ。

参考

Amazon: raspbery pi4

RS components: ケース

設定など

中継サーバ上の /etc/sshd/sshd_config

GatewayPorts yes

raspberry pi 上の設定

必要なパッケージのインストール

apt install openvpn
apt install autossh
apt install dnsproxy
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
apt install iptables-persistent

autossh設定

https://gist.github.com/ttimasdf/ef739670ac5d627981c5695adf4c8f98 を参考

/etc/default/autossh@aws

# Options for autossh@host1.service
# Place it at /etc/default

# Save all your credential/user/port related config in ~/.ssh/config is strongly
# Leave hostname here only
TARGET_HOST=中継サーバのIPアドレス、または、DNS名

# -L LOCALPORT:IP_ON_EXAMPLE_COM:PORT_ON_EXAMPLE_COM
# can set multiple forwardings here
FORWARDS=-R 0.0.0.0:1194:localhost:1194

# === Settings below for ADVANCED users only ===

SSH_OPTIONS=-o "ServerAliveInterval=10" -o "ServerAliveCountMax=3"
AUTOSSH_PORT=0
AUTOSSH_GATETIME=0

TARGET_HOSTは自分のものに変える。

/etc/systemd/system/autossh@.service

[Unit]
Description=Keeps an ssh tunnel to %I open
After=network-online.target ssh.service

[Service]
User=direct
# no monitoring
Environment="AUTOSSH_PORT=0"
# Disable gatetime behaviour
Environment="AUTOSSH_GATETIME=0"
EnvironmentFile=/etc/default/autossh@%i
RestartSec=3
Restart=always

# -NT Just open the connection and do nothing (not interactive, no tty alloc)
# use /usr/bin/ssh instead of autossh is good as well
ExecStart=/usr/bin/autossh -NT -o "ExitOnForwardFailure=yes" $SSH_OPTIONS ${TARGET_HOST} $FORWARDS
TimeoutStopSec=10

[Install]
WantedBy=multi-user.target

上記の設定では direct というユーザで接続する。中継サーバ、rasberry pi 両方に direct というユーザを作り、一度、ssh 接続しておくこと。

systemctl enable autossh@aws

/etc/sysctl.conf

net.ipv4.ip_forward=1

/etc/dnsproxy.conf

#
# Authoritative server
#
authoritative           127.0.0.53
authoritative-port      53              # It's port. Defaults to 53.
authoritative-timeout   10              # Seconds to wait for answers.

#
# Recursive resolver
#
recursive               127.0.0.53
recursive-port          53              # It's port. Defaults to 53.
recursive-timeout       90              # Seconds to wait for answers.

#
# Local address and port of dnsproxy
#
listen 10.8.0.1
port 53

#
# Security features
#
chroot /var/spool/dnsproxy
user dnsproxy

#
# Internal networks (allowed to do recursive queries)
#
#internal 192.168.168.0/24      # Our internal network
#internal 192.168.169.0/24      # Friendly neighbours
#internal 127.0.0.1

設定ファイル等

  1. /etc/openvpn/server に設定ファイル一式をコピーする。
  2. systemctl enable openvpn-server@名称

設定ファイル生成スクリプト

gen-openvpn-config.py(雑なスクリプトで申し訳ない。)

なにかドメイン名のところは、適当に編集。

なにかID.なにかドメイン名にサーバがあり、

easyrsa なにかID-server nopass
easyrsa なにかID-001 nopass

のようにして鍵・証明書を作る前提。適当に工夫を。

#!/usr/bin/env python3
import os.path
import subprocess
import os
import glob
import shutil
from jinja2 import Template

ta_key = 'ta.key'
config_dir = 'openvpn'
common_list = ['ta.key', 'pki/ca.crt', 'pki/dh.pem']
server_config_list = ['pki/crl.pem']

server_config="""#################################################
# Sample OpenVPN 2.0 config file for            #
# multi-client server.                          #
#                                               #
# This file is for the server side              #
# of a many-clients <-> one-server              #
# OpenVPN configuration.                        #
#                                               #
# OpenVPN also supports                         #
# single-machine <-> single-machine             #
# configurations (See the Examples page         #
# on the web site for more info).               #
#                                               #
# This config should work on Windows            #
# or Linux/BSD systems.  Remember on            #
# Windows to quote pathnames and use            #
# double backslashes, e.g.:                     #
# "C:\\Program Files\\OpenVPN\\config\\foo.key" #
#                                               #
# Comments are preceded with '#' or ';'         #
#################################################

# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d

# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one.  You will need to
# open up this port on your firewall.
port 1194

# TCP or UDP server?
proto tcp
;proto udp

# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one.  On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap

# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key).  Each client
# and the server must have their own cert and
# key file.  The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys.  Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca {{ca_crt}}
cert {{server_crt}}
key {{server_key}}  # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh2048.pem 2048
dh dh.pem

# Network topology
# Should be subnet (addressing via IP)
# unless Windows clients v2.0.9 and lower have to
# be supported (then net30, i.e. a /30 per client)
# Defaults to net30 (not recommended)
;topology subnet

# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0

# Maintain a record of client <-> virtual IP address
# associations in this file.  If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt

# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface.  Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0.  Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients.  Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses.  You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge

# Push routes to the client to allow it
# to reach other private subnets behind
# the server.  Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
;push "route 192.168.10.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"

# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).

# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
#   iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN.  This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.

# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
#   ifconfig-push 10.9.0.1 10.9.0.2

# Suppose that you want to enable different
# firewall access policies for different groups
# of clients.  There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
#     group, and firewall the TUN/TAP interface
#     for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
#     modify the firewall in response to access
#     from different clients.  See man
#     page for more info on learn-address script.
;learn-address ./script

# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
push "redirect-gateway def1 bypass-dhcp"

# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses.  CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"
push "dhcp-option DNS 10.8.0.1"

# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
;client-to-client

# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names.  This is recommended
# only for testing purposes.  For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn

# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120

# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#   openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
tls-auth ta.key 0 # This file is secret

# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
# Note that v2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
cipher AES-256-CBC

# Enable compression on the VPN link and push the
# option to the client (v2.4+ only, for earlier
# versions see below)
;compress lz4-v2
;push "compress lz4-v2"

# For compression compatible with older clients use comp-lzo
# If you enable it here, you must also
# enable it in the client config file.
;comp-lzo

# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100

# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody
;group nobody

# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun

# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log

# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it.  Use one
# or the other (but not both).
;log         openvpn.log
;log-append  openvpn.log

# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3

# Silence repeating messages.  At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20

# Notify the client that when the server restarts so it
# can automatically reconnect.
;explicit-exit-notify 1

crl-verify crl.pem
"""

client_config="""##############################################
# Sample client-side OpenVPN 2.0 config file #
# for connecting to multi-client server.     #
#                                            #
# This configuration can be used by multiple #
# clients, however each client should have   #
# its own cert and key files.                #
#                                            #
# On Windows, you might want to rename this  #
# file so it has a .ovpn extension           #
##############################################

# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client

# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel
# if you have more than one.  On XP SP2,
# you may need to disable the firewall
# for the TAP adapter.
;dev-node MyTap

# Are we connecting to a TCP or
# UDP server?  Use the same setting as
# on the server.
proto tcp
;proto udp

# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
remote {{server}} 1194
;remote my-server-2 1194

# Choose a random host from the remote
# list for load-balancing.  Otherwise
# try hosts in the order specified.
;remote-random

# Keep trying indefinitely to resolve the
# host name of the OpenVPN server.  Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite

# Most clients don't need to bind to
# a specific local port number.
nobind

# Downgrade privileges after initialization (non-Windows only)
;user nobody
;group nobody

# Try to preserve some state across restarts.
persist-key
persist-tun

# If you are connecting through an
# HTTP proxy to reach the actual OpenVPN
# server, put the proxy server/IP and
# port number here.  See the man page
# if your proxy server requires
# authentication.
;http-proxy-retry # retry on connection failures
;http-proxy [proxy server] [proxy port #]

# Wireless networks often produce a lot
# of duplicate packets.  Set this flag
# to silence duplicate packet warnings.
;mute-replay-warnings

# SSL/TLS parms.
# See the server config file for more
# description.  It's best to use
# a separate .crt/.key file pair
# for each client.  A single ca
# file can be used for all clients.
ca {{ca_crt}}
cert {{client_crt}}
key {{client_key}}

# Verify server certificate by checking that the
# certicate has the correct key usage set.
# This is an important precaution to protect against
# a potential attack discussed here:
#  http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the keyUsage set to
#   digitalSignature, keyEncipherment
# and the extendedKeyUsage to
#   serverAuth
# EasyRSA can do this for you.
remote-cert-tls server

# If a tls-auth key is used on the server
# then every client must also have the key.
tls-auth ta.key 1

# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
# Note that v2.4 client/server will automatically
# negotiate AES-256-GCM in TLS mode.
# See also the ncp-cipher option in the manpage
cipher AES-256-CBC

# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
#comp-lzo

# Set log file verbosity.
verb 3

# Silence repeating messages
;mute 20
"""

def copyfiles(file_list, dstdir):
    for f in file_list:
        bn = os.path.basename(f)
        shutil.copyfile(f, os.path.join(dstdir, bn))

def main():
    if not os.path.exists(ta_key):
        subprocess.run(['openvpn', '--genkey', '--secret', ta_key])
    if not os.path.exists(config_dir):
        os.mkdir(config_dir)
    ca_name = os.path.basename(os.getcwd())
    for crt in glob.glob('pki/issued/*.crt'):
        (bn, ext) = os.path.splitext(crt)
        fn = os.path.basename(bn)
        kn = bn.split('-')[-1]
        cdir = os.path.join(config_dir, fn)
        #cdir = os.path.join(config_dir, kn)
        if not os.path.exists(cdir):
            os.mkdir(cdir)
        copyfiles(common_list, cdir)
        copyfiles([crt], cdir)
        copyfiles([os.path.join('pki/private', fn + '.key')], cdir)
        if kn == 'server':
            copyfiles(server_config_list, cdir)
            conf = os.path.join(cdir, fn + '.conf') # for ubuntu server systemd
            with open(conf, 'wt') as conffp:
                template = Template(server_config)
                conffp.write(template.render(ca_crt='ca.crt', server_crt = fn + '.crt', server_key = fn + '.key'))
        else:
            conf = os.path.join(cdir, fn + '.ovpn')
            with open(conf, 'wt') as conffp:
                template = Template(client_config)
                conffp.write(template.render(ca_crt='ca.crt', client_crt = fn + '.crt', client_key = fn + '.key', server=ca_name + '.なにかドメイン名'))

if __name__ == '__main__':
    main()