Skip to content

Instantly share code, notes, and snippets.

@CLCL
Last active September 26, 2022 18:21
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save CLCL/5742738 to your computer and use it in GitHub Desktop.
Save CLCL/5742738 to your computer and use it in GitHub Desktop.
L2TP/IPsec(AndroidやiPhoneからのVPN接続)を経路を用意すべくVPSにL2TP/IPsecサーバを設置するとき、ネットにある情報だとなかなかつながらないから、標準環境としてAWSのCentOS 6.3 x86_64 Release Media(ami-3fe8603e)の起動直後から最短距離で設定する方法をまとめた。

CentOS 6でとにかくL2TP/IPsecサーバ

  • AWSでEC2のインスタンスを借りる
  • 今回は東京リージョンのCentOS 6.3 x86_64 Release MediaのAIM(ami-3fe8603e)でインスタンスを建てる
  • Security Group: L2TP/IPsec(Inbound 22/TCP: SSH, 500/UDP: ISAKMP, 1701/UDP: L2TP, 4500/UDP: IPSec NAT Traversal)を許可
  • ec2-54-249-173-214.ap-northeast-1.compute.amazonaws.com(グローバルIPアドレス:54.249.173.214)にrootでログイン

SELinuxを無効にする

[root@ip-10-132-164-105 ~]# setenforce 0
[root@ip-10-132-164-105 ~]# sed -i -e 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

EPELリポジトリを入れる

ちなみに、EPELのデフォルト使用をOFFにしています。

[root@ip-10-132-164-105 ~]# rpm -ivh http://ftp-srv2.kddilabs.jp/Linux/distributions/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
[root@ip-10-132-164-105 ~]# sed -i -e 's/enabled=1/enabled=0/' /etc/yum.repos.d/epel.repo

IPsec(Openswan)、L2TP(xl2tpd)、lsof(IPsecの動作確認で使う)をインストール

EPELのデフォルト使用をOFFにしたので、EPELからインストールするxl2tpdの時はリポジトリを指定します。

[root@ip-10-132-164-105 ~]# yum -y install lsof openswan
[root@ip-10-132-164-105 ~]# yum -y --enablerepo=epel install xl2tpd

自サーバのIPアドレスを確認しておく

AWS EC2ならプライベートIPアドレスが付与される。さくらのVPSとか、GMOクラウドPublicとか、グローバルIPアドレスが付与されているサーバもあるよ。

[root@ip-10-132-164-105 ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 22:00:0A:84:A4:69
          inet addr:10.132.164.105  Bcast:10.132.164.127  Mask:255.255.255.192
          inet6 addr: fe80::2000:aff:fe84:a469/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:19392 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10875 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:27717894 (26.4 MiB)  TX bytes:809895 (790.9 KiB)
          Interrupt:247

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

この場合は、10.132.164.105 がサーバのIPアドレス。

xl2tpdの設定

[root@ip-10-132-164-105 ~]# cp -a /etc/xl2tpd/xl2tpd.conf /etc/xl2tpd/xl2tpd.conf.orig
[root@ip-10-132-164-105 ~]# vi /etc/xl2tpd/xl2tpd.conf
;
; This is a minimal sample xl2tpd configuration file for use
; with L2TP over IPsec.
;
; The idea is to provide an L2TP daemon to which remote Windows L2TP/IPsec
; clients connect. In this example, the internal (protected) network
; is 192.168.1.0/24.  A special IP range within this network is reserved
; for the remote clients: 192.168.1.128/25
; (i.e. 192.168.1.128 ... 192.168.1.254)
;
; The listen-addr parameter can be used if you want to bind the L2TP daemon
; to a specific IP address instead of to all interfaces. For instance,
; you could bind it to the interface of the internal LAN (e.g. 192.168.1.98
; in the example below). Yet another IP address (local ip, e.g. 192.168.1.99)
; will be used by xl2tpd as its address on pppX interfaces.


; IMPORTANT: always set listen-addr to a specific address, to work around a
; udpfromto bug!!!


[global]
; listen-addr = 192.168.1.98
listen-addr = 10.132.164.105
;
; requires openswan-2.5.18 or higher - Also does not yet work in combination
; with kernel mode l2tp as present in linux 2.6.23+
; ipsec saref = yes
; Use refinfo of 22 if using an SAref kernel patch based on openswan 2.6.35 or
;  when using any of the SAref kernel patches for kernels up to 2.6.35.
; ipsec refinfo = 30
;
; force userspace = yes
;
; debug tunnel = yes

[lns default]
ip range = 192.168.1.128-192.168.1.254
local ip = 192.168.1.99
; leave chap unspecified for maximum compatibility with windows, iOS, etc
require chap = yes
refuse pap = yes
require authentication = yes
name = LinuxVPNserver
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes

listen-addr に自サーバのIPアドレスを指定します。 ip range は接続してくる端末に振られるIPの範囲、local ip はサーバに割り当てられるIPアドレス。デフォルトでも通信できるが、好みや都合で変更してもよい。

pppd用xl2tpd設定

  • MTUは、ppp0のMTUになるが、実際にはネゴシエーションで小さくなったりするので(docomo 3Gなら1400)、あえてデフォルトの1410のまま
  • DNSは、デフォルト設定がGoogleのPublic DNS(8.8.8.8)になっているので、変更しなくても接続に影響はない。
  • DNSをあえて変更するなら、/etc/resolv.conf に書かれているDNSのIPアドレスにする。
[root@ip-10-132-164-105 ~]# cp -a /etc/ppp/options.xl2tpd /etc/ppp/options.xl2tpd.orig
[root@ip-10-132-164-105 ~]# vi /etc/ppp/options.xl2tpd
ipcp-accept-local
ipcp-accept-remote
ms-dns  8.8.8.8
# ms-dns  192.168.1.1
# ms-dns  192.168.1.3
# ms-wins 192.168.1.2
# ms-wins 192.168.1.4
#noccp # iPhoneからつなげるためコメントアウト
auth
crtscts
idle 1800
mtu 1410
mru 1410
nodefaultroute
debug
lock
proxyarp
connect-delay 5000
# To allow authentication against a Windows domain EXAMPLE, and require the
# user to be in a group "VPN Users". Requires the samba-winbind package
# require-mschap-v2
# plugin winbind.so
# ntlm_auth-helper '/usr/bin/ntlm_auth --helper-protocol=ntlm-server-1 --require-membership-of="EXAMPLE\\VPN Users"'
# You need to join the domain on the server, for example using samba:
# http://rootmanager.com/ubuntu-ipsec-l2tp-windows-domain-auth/setting-up-openswan-xl2tpd-with-native-windows-clients-lucid.html

name xl2tpd
refuse-pap
refuse-chap
refuse-mschap
require-mschap-v2
persist
logfile /var/log/xl2tpd.log

noccp をコメントアウトし、末尾7行追加します。

Openswan(IPsec)の設定

[root@ip-10-132-164-105 ~]# cp -a /etc/ipsec.conf /etc/ipsec.conf.orig
[root@ip-10-132-164-105 ~]# vi /etc/ipsec.conf
# /etc/ipsec.conf - Openswan IPsec configuration file
#
# Manual:     ipsec.conf.5
#
# Please place your own config files in /etc/ipsec.d/ ending in .conf

version 2.0     # conforms to second version of ipsec.conf specification

# basic configuration
config setup
        # Debug-logging controls:  "none" for (almost) none, "all" for lots.
        # klipsdebug=none
        # plutodebug="control parsing"
        # For Red Hat Enterprise Linux and Fedora, leave protostack=netkey
        protostack=netkey
        nat_traversal=yes
        virtual_private=
        oe=off
        # Enable this if you see "failed to find any available worker"
        # nhelpers=0

#You may put your configuration (.conf) file in the "/etc/ipsec.d/" and uncomment this.
#include /etc/ipsec.d/*.conf
include /etc/ipsec.d/*.conf

最後1行追加します(コメントアウトを解除でも可)。

IPsec用L2TP接続の設定

設定ファイル /etc/ipsec.d/l2tp-ipsec.conf を新規作成します。 rightsubnetにサーバのIPを指定する例をよく見ます。

ServersMan SIM 3G 100はグローバルIPを持つので問題ないのですが、接続元がプライベートネットワークの中にいる場合(WiMAXやauやソフトバンク、ServersMan SIM 3G 100でもモバイルルータで使用している場合など)、接続が出来ません……

なので、今回の設定のように、rightsubnet=0.0.0.0/0 と書くことで、NATトラバーサルに対応できます。

[root@ip-10-132-164-105 ~]# vi /etc/ipsec.d/l2tp-ipsec.conf
conn L2TP-PSK-NAT
    rightsubnet=0.0.0.0/0
    dpddelay=10
    dpdtimeout=20
    dpdaction=clear
    forceencaps=yes
    also=L2TP-PSK-noNAT

conn L2TP-PSK-noNAT
    authby=secret
    pfs=no
    auto=add
    keyingtries=3
    rekey=no

    ikelifetime=8h
    keylife=1h

    type=transport

    left=10.132.164.105
    leftprotoport=17/1701

    right=%any
    rightprotoport=17/%any

10.132.164.105 は自サーバのIPアドレス。

L2TP(PPP)接続用アカウント・パスワードの設定

ここで設定するアカウント・パスワードは、iPhone・AndroidのVPN(L2TPクライアント)で設定するアカウント名とパスワードになります。 次の工程で、事前共有鍵(シークレット・secrets)という文字列も設定しますので、間違わないように。 (つまり、 アカウント・パスワード・シークレットの3つの文字列が接続に必要

[root@ip-10-132-164-105 ~]# cp -a /etc/ppp/chap-secrets /etc/ppp/chap-secrets.orig
[root@ip-10-132-164-105 ~]# vi /etc/ppp/chap-secrets
# Secrets for authentication using CHAP
# client        server  secret                  IP addresses
"vpn-account" "xl2tpd" "vpnpassword" *

アカウントがvpn-account、パスワードがvpnpassword。シークレットは次で設定します。

IPsec用PSK(事前共有鍵)を設定

新規作成ファイル /etc/ipsec.d/default.secrets となります。 ここで設定するのが、事前共有鍵( __P__re- __S__hared __K__ey)−シークレット(secrets)です。

[root@ip-10-132-164-105 ~]# vi /etc/ipsec.d/default.secrets
: PSK "psksecrets"

シークレットはpsksecretsです。

ファイヤウォール(IP転送設定)の設定

iptablesでL2TP/IPsec接続に必要なポートの解放、IP MasqueradeやIP転送の設定をします。iptablesを使わないと、インターネットに出られません。

[root@ip-10-132-164-105 ~]# cp -a /etc/sysconfig/iptables /etc/sysconfig/iptables.orig
[root@ip-10-132-164-105 ~]# vi /etc/sysconfig/iptables
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT

# L2TP/IPsec
-A FORWARD -i ppp+ -j ACCEPT
-A FORWARD -o ppp+ -j ACCEPT
-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p esp -j ACCEPT
-A INPUT -p udp -m udp --dport 1701 -j ACCEPT
-A INPUT -p udp -m udp --dport 500 -j ACCEPT
-A INPUT -p udp -m udp --dport 4500 -j ACCEPT

-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

*nat
-A POSTROUTING -s 192.168.1.128/25 -j MASQUERADE
COMMIT

サービスの起動

[root@ip-10-132-164-105 ~]# /sbin/service iptables restart
[root@ip-10-132-164-105 ~]# /sbin/service xl2tpd start
[root@ip-10-132-164-105 ~]# /sbin/service ipsec start
[root@ip-10-132-164-105 ~]# /sbin/chkconfig xl2tpd on
[root@ip-10-132-164-105 ~]# /sbin/chkconfig ipsec on

xl2tpdとipsecの起動順番を逆にすると、Androidからは繋がるがiOSやMac OS Xからは繋がらない。その場合は、/sbin/service ipsec restartで回復する

Openswanの動作確認

Openswan(IPsec)動作確認用コマンドを実行します。

[root@ip-10-132-164-105 ~]# ipsec verify
Checking your system to see if IPsec got installed and started correctly:
Version check and ipsec on-path                                 [OK]
Linux Openswan U2.6.32/K2.6.32-279.el6.x86_64 (netkey)
Checking for IPsec support in kernel                            [OK]
 SAref kernel support                                           [N/A]
 NETKEY:  Testing for disabled ICMP send_redirects              [FAILED]

  Please disable /proc/sys/net/ipv4/conf/*/send_redirects
  or NETKEY will cause the sending of bogus ICMP redirects!

NETKEY detected, testing for disabled ICMP accept_redirects     [FAILED]

  Please disable /proc/sys/net/ipv4/conf/*/accept_redirects
  or NETKEY will accept bogus ICMP redirects!

Testing against enforced SElinux mode                           [OK]
Checking that pluto is running                                  [OK]
 Pluto listening for IKE on udp 500                             [OK]
 Pluto listening for NAT-T on udp 4500                          [OK]
Checking for 'ip' command                                       [OK]
Checking /bin/sh is not /bin/dash                               [OK]
Checking for 'iptables' command                                 [OK]
Opportunistic Encryption Support                                [DISABLED]

FAILEDが出ているので、このままではサービスが出来ない。 原因は、カーネルにIP転送を任せなくてはならないのだけれども、カーネルパラメータのデフォルト値ではIP転送が出来ない設定になっているから。 よって、カーネルパラメータを変更する。

カーネルパラメータ変更

[root@ip-10-132-164-105 ~]# vi /etc/sysctl.conf
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled.  See sysctl(8) and
# sysctl.conf(5) for more details.

# Controls IP packet forwarding
net.ipv4.ip_forward = 0

# Controls source route verification
net.ipv4.conf.default.rp_filter = 1

# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0

# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1

# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1

# Disable netfilter on bridges.
net.bridge.bridge-nf-call-ip6tables = 0
net.bridge.bridge-nf-call-iptables = 0
net.bridge.bridge-nf-call-arptables = 0

# Controls the default maxmimum size of a mesage queue
kernel.msgmnb = 65536

# Controls the maximum size of a message, in bytes
kernel.msgmax = 65536

# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736

# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296

net.ipv4.ip_forward = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.lo.accept_redirects = 0
net.ipv4.conf.lo.send_redirects = 0
net.ipv4.conf.eth0.accept_redirects = 0
net.ipv4.conf.eth0.send_redirects = 0

末尾に9行分追加します。

[root@ip-10-132-164-105 ~]# /sbin/sysctl -p

設定を読み込み有効にします。

Openswanの動作確認(再)

[root@ip-10-132-164-105 ~]# ipsec verify
Checking your system to see if IPsec got installed and started correctly:
Version check and ipsec on-path                                 [OK]
Linux Openswan U2.6.32/K2.6.32-279.el6.x86_64 (netkey)
Checking for IPsec support in kernel                            [OK]
 SAref kernel support                                           [N/A]
 NETKEY:  Testing for disabled ICMP send_redirects              [OK]
NETKEY detected, testing for disabled ICMP accept_redirects     [OK]
Testing against enforced SElinux mode                           [OK]
Checking that pluto is running                                  [OK]
 Pluto listening for IKE on udp 500                             [OK]
 Pluto listening for NAT-T on udp 4500                          [OK]
Checking for 'ip' command                                       [OK]
Checking /bin/sh is not /bin/dash                               [OK]
Checking for 'iptables' command                                 [OK]
Opportunistic Encryption Support                                [DISABLED]

設定完了

AndroidやiPhone、Mac OS Xから接続してみましょう。

  • iPad 3のWi-Fi(WiMAXルータ・プライベートIPアドレス付与)で接続確認済み。
  • Android 2.3のWi-Fi(WiMAXルータ経由・Wi2 300経由)/3G回線(ServersMan SIM 100経由)
  • Android 4.2.2(Nexus 7)のWi-Fi(WiMAXルータ経由・Wi2 300経由)
  • Mac OS X 10.6.8のWi-Fi(WiMAXルータ経由)

iPhoneからの接続

  • 設定ー一般ーネットワーク
  • VPNをクリックーVPN構成を追加...をクリック
  • L2TPの所
  • 説明: AWS-VPN
  • サーバ: 54.249.173.214
  • アカウント: vpn-account
  • RSA SecurID: オフ
  • パスワード: vpnpassword
  • シークレット: psksecret
  • すべての信号を送信: オン
  • プロキシ: オフ

--

  • (保存すると [AWS-VPN]が出来ているので、クリック)
  • VPNを[オン]にする

Andoroidからの接続

  • VPN接続設定前に、初回だけ認証情報ストレージのセキュリティ設定が必要です。
  • VPN名: AWS-VPN
  • VPNサーバの設定: 54.249.173.214
  • IPSec事前共有鍵の設定: psksecrets
  • L2TPセキュリティ保護: no
  • DNSサーチドメイン: (入力しない)

--

  • (戻って、 [AWS-VPN]をクリック)
  • ユーザ名: vpn-account
  • パスワード: vpnpassword
  • ユーザ名の保存: チェック
  • [接続]で、VPN接続

接続後の確認

  • Androidなら、ifconfigを確認できるアプリがあれば、ネットワークインターフェースとしてppp0が追加されています。
  • CentOS 6サーバ側では、ifconfigを実行すると、ネットワークインターフェースとしてpppX(Xは接続順に0から増えていく)が存在しています。L2TP接続が切れると、pppインターフェースはなくなります。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment