How to build VPN server(IPsec) for iPhone

Server side

environnement

  • OS: Amazon Linux 2
  • private IP: 10.0.0.1(bind at eth0)
  • public IP: 2.2.2.2(supposed, 2.2.2.2 is belong to France TELECOM)
  • network interface: eth0

step in detail

Show you the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# install software
yum -y install libreswan
# version is 3.23 with yum install, I will upgrade it to 4.5
rpm -ivh \
https://download.libreswan.org/binaries/rhel/7/x86_64/libreswan-4.5-1.el7.x86_64.rpm
# get the public IP address
PUBLIC_IP=$(dig @resolver1.opendns.com -t A -4 myip.opendns.com +short)
[ -z "$PUBLIC_IP" ] && PUBLIC_IP=$(wget -t 3 -T 15 -qO- http://ipv4.icanhazip.com)
printf '%s\n' "$PUBLIC_IP"
# config file generate
cat > /etc/ipsec.d/ipsec.conf <<EOF
conn setup
protostack=netkey
virtual-private=%v4:10.0.0.0/8,%v4:192.168.0.0/16,%v4:172.16.0.0/12,%v4:25.0.0.0/8,%v4:!10.231.247.0/24,%v4:!10.0.0.1/24
uniqueids=no

conn xauth-psk
authby=secret
pfs=no
auto=add
rekey=no
left=%defaultroute
leftsubnet=0.0.0.0/0
rightaddresspool=10.231.247.1-10.231.247.254
right=%any
modecfgdns=1.1.1.1,8.8.8.8
leftxauthserver=yes
rightxauthclient=yes
leftmodecfgserver=yes
rightmodecfgclient=yes
modecfgpull=yes
xauthby=file
ikev2=never
EOF

# main configuration file(/etc/ipsec.conf) modification
if ! grep -qs '^include /etc/ipsec\.d/\*\.conf$' /etc/ipsec.conf; then
echo >> /etc/ipsec.conf
echo 'include /etc/ipsec.d/*.conf' >> /etc/ipsec.conf
fi

# for xauth-psk
cat > /etc/ipsec.d/xauth.secrets <<EOF
10.0.0.1 %any : PSK "mypassword"
EOF

# to be sure that file /etc/ipsec.d/passwd exist
touch /etc/ipsec.d/passwd

# account generation
for i in {1..16}
do
password=$(openssl rand -base64 6)
pasw_enc=$(openssl passwd -1 "$password")
cat >> /etc/ipsec.d/passwd <<EOF
user${i}:$pasw_enc:xauth-psk
EOF

echo "user${i}:${password}"
done

# start service ipsec
ipsec start

# masquerate(configurate by iptables)
iptables -t nat -A POSTROUTING \
-s 10.231.247.0/24 \
-o eth0 -m policy \
--dir out --pol none \
-j MASQUERADE

Client side

iOS

  1. Settings→VPN→Add VPN Configuration…
  2. fill the form below:

    Type: IPsec
    Description: anything you like
    Server: 2.2.2.2
    Account: one of user[1..16]
    Password: see above
    Secret: mypassword

  3. tap “DONE”