setup-ipsec-vpn Documentation

Set up your own IPsec VPN server in just a few minutes, with IPsec/L2TP, Cisco IPsec and IKEv2. Supports Ubuntu, Debian, CentOS/RHEL, Alpine Linux and...

RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy setup-ipsec-vpn on any server, homelab, or cloud container platform.

File: README.md

English | 简体中文 | 繁體中文 | 日本語 | Русский

IPsec VPN Server Auto Setup Scripts

Set up your own IPsec VPN server in just a few minutes, with IPsec/L2TP, Cisco IPsec and IKEv2.

An IPsec VPN encrypts your network traffic, so that nobody between you and the VPN server can eavesdrop on your data as it travels via the Internet. This is especially useful when using unsecured networks, e.g. at coffee shops, airports or hotel rooms.

We will use Libreswan as the IPsec server, and xl2tpd as the L2TP provider.

Features:

  • Fully automated IPsec VPN server setup, no user input needed
  • Supports IKEv2 with strong and fast ciphers (e.g. AES-GCM)
  • Generates VPN profiles to auto-configure iOS, macOS and Android devices
  • Supports Windows, macOS, iOS, Android, Chrome OS and Linux as VPN clients
  • Includes helper scripts to manage VPN users and certificates

Also available:

Quick start

First, prepare your Linux server* with an install of a supported OS.

Use this one-liner to set up an IPsec VPN server:

bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh

Your VPN login details will be randomly generated, and displayed when finished.

[!TIP]
Optionally install WireGuard, OpenVPN and/or Headscale on the same server.

See the script in action (terminal recording).

Note: This recording is for demo purposes only. VPN credentials in this recording are NOT valid.

Click here if you are unable to download.

You may also use curl to download:

bash
curl -fsSL https://get.vpnsetup.net -o vpn.sh && sudo sh vpn.sh

Alternative setup URLs:

bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh

If you are unable to download, open vpnsetup.sh, then click the Raw button on the right. Press Ctrl/Cmd+A to select all, Ctrl/Cmd+C to copy, then paste into your favorite editor.

A pre-built Docker image is also available. For other options and client setup, read the sections below.

* A cloud server, virtual private server (VPS) or dedicated server.

Community

  • 📬 Subscribe for project updates (1–2 emails/month) — get free VPN and AI deployment guides (PDF)
  • 💬 Join the r/selfhostedstack community for discussions
  • ⭐ Star the repository if you find it useful — it helps others discover it

Requirements

A cloud server, virtual private server (VPS) or dedicated server, with an install of:

  • Ubuntu 26.04, 24.04 or 22.04
  • Debian 13, 12 or 11
  • CentOS Stream 10 or 9
  • Rocky Linux or AlmaLinux
  • Oracle Linux

Other supported Linux distributions.

  • Raspberry Pi OS (Raspbian)
  • Kali Linux
  • Alpine Linux
  • Red Hat Enterprise Linux (RHEL)

This also includes Linux VMs in public clouds, such as DigitalOcean, Vultr, Linode, OVH and Microsoft Azure. Public cloud users can also deploy using user data.

Quick deploy to:

 

» I want to run my own VPN but don't have a server for that

For servers with an external firewall (e.g. EC2/GCE), open UDP ports 500 and 4500 for the VPN.

A pre-built Docker image is also available. Advanced users can install on a Raspberry Pi. [1] [2]

[!WARNING]
DO NOT run these scripts on your PC or Mac! They should only be used on a server!

Installation

First, update your server with sudo apt-get update && sudo apt-get dist-upgrade (Ubuntu/Debian) or sudo yum update and reboot. This is optional, but recommended.

To install the VPN, please choose one of the following options:

Option 1: Have the script generate random VPN credentials for you (will be displayed when finished).

bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh

Option 2: Edit the script and provide your own VPN credentials.

bash
wget https://get.vpnsetup.net -O vpn.sh
nano -w vpn.sh
[Replace with your own values: YOUR_IPSEC_PSK, YOUR_USERNAME and YOUR_PASSWORD]
sudo sh vpn.sh

[!NOTE]
A secure IPsec PSK should consist of at least 20 random characters.

Option 3: Define your VPN credentials as environment variables.

bash
# All values MUST be placed inside 'single quotes'
# DO NOT use these special characters within values: \ " '
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_IPSEC_PSK='your_ipsec_pre_shared_key' \
VPN_USER='your_vpn_username' \
VPN_PASSWORD='your_vpn_password' \
sh vpn.sh

[!TIP]
Optionally install WireGuard, OpenVPN and/or Headscale on the same server. If your server runs CentOS Stream, Rocky Linux or AlmaLinux, first install OpenVPN/WireGuard, then install the IPsec VPN.

Click here if you are unable to download.

You may also use curl to download. For example:

bash
curl -fL https://get.vpnsetup.net -o vpn.sh
sudo sh vpn.sh

Alternative setup URLs:

bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh

If you are unable to download, open vpnsetup.sh, then click the Raw button on the right. Press Ctrl/Cmd+A to select all, Ctrl/Cmd+C to copy, then paste into your favorite editor.

I want to install the older Libreswan version 4.

It is generally recommended to use the latest Libreswan version 5, which is the default version in this project. However, if you want to install the older Libreswan version 4:

bash
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_SWAN_VER=4.15 sh vpn.sh

Note: If Libreswan version 5 is already installed, you may need to first Uninstall the VPN before installing Libreswan version 4. Alternatively, download the update script, edit it to specify SWAN_VER=4.15, then run the script.

Customize VPN options

Use alternative DNS servers

By default, clients are set to use Google Public DNS when the VPN is active. When installing the VPN, you may optionally specify custom DNS server(s) for all VPN modes. Example:

bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh

Use VPN_DNS_SRV1 to specify the primary DNS server, and VPN_DNS_SRV2 to specify the secondary DNS server (optional).

Below is a list of some popular public DNS providers for your reference.

Provider Primary DNS Secondary DNS Notes
Google Public DNS 8.8.8.8 8.8.4.4 Default in this project
Cloudflare 1.1.1.1 1.0.0.1 See also: Cloudflare for families
Quad9 9.9.9.9 149.112.112.112 Blocks malicious domains
OpenDNS 208.67.222.222 208.67.220.220 Blocks phishing domains, configurable.
CleanBrowsing 185.228.168.9 185.228.169.9 Domain filters available
NextDNS Varies Varies Ad blocking, free tier available. Learn more.
Control D Varies Varies Ad blocking, configurable. Learn more.

If you need to change DNS servers after VPN setup, see Advanced usage.

[!NOTE]
If IKEv2 is already set up on the server, the variables above have no effect for IKEv2 mode. In that case, to customize IKEv2 options such as DNS servers, you can first remove IKEv2, then set it up again using sudo ikev2.sh.

Customize IKEv2 options

When installing the VPN, advanced users can optionally customize IKEv2 options.

Option 1: Skip IKEv2 during VPN setup, then set up IKEv2 using custom options.

When installing the VPN, you can skip IKEv2 and only install the IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes:

bash
sudo VPN_SKIP_IKEV2=yes sh vpn.sh

(Optional) If you want to specify custom DNS server(s) for VPN clients, define VPN_DNS_SRV1 and optionally VPN_DNS_SRV2. See Use alternative DNS servers for details.

After that, run the IKEv2 helper script to set up IKEv2 interactively using custom options:

bash
sudo ikev2.sh

You can customize the following options: VPN server's DNS name, name and validity period of the first client, DNS server for VPN clients and whether to password protect client config files.

Note: The VPN_SKIP_IKEV2 variable has no effect if IKEv2 is already set up on the server. In that case, to customize IKEv2 options, you can first remove IKEv2, then set it up again using sudo ikev2.sh.

Option 2: Customize IKEv2 options using environment variables.

When installing the VPN, you can optionally specify a DNS name for the IKEv2 server address. The DNS name must be a fully qualified domain name (FQDN). Example:

bash
sudo VPN_DNS_NAME='vpn.example.com' sh vpn.sh

Similarly, you may specify a name for the first IKEv2 client. The default is vpnclient if not specified.

bash
sudo VPN_CLIENT_NAME='your_client_name' sh vpn.sh

By default, clients are set to use Google Public DNS when the VPN is active. You may specify custom DNS server(s) for all VPN modes. Example:

bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh

By default, no password is required when importing IKEv2 client configuration. You can choose to protect client config files using a random password.

bash
sudo VPN_PROTECT_CONFIG=yes sh vpn.sh

For reference: List of IKEv1 and IKEv2 parameters.

IKEv1 parameter* Default value Customize (env variable)**
Server address (DNS name) - No, but you can connect using a DNS name
Server address (public IP) Auto detect VPN_PUBLIC_IP
IPsec pre-shared key Auto generate VPN_IPSEC_PSK
VPN username vpnuser VPN_USER
VPN password Auto generate VPN_PASSWORD
DNS servers for clients Google Public DNS VPN_DNS_SRV1, VPN_DNS_SRV2
Skip IKEv2 setup no VPN_SKIP_IKEV2=yes

* These IKEv1 parameters are for IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes.
** Define these as environment variables when running vpn(setup).sh.

IKEv2 parameter* Default value Customize (env variable)** Customize (interactive)***
Server address (DNS name) - VPN_DNS_NAME ✅
Server address (public IP) Auto detect VPN_PUBLIC_IP ✅
Name of first client vpnclient VPN_CLIENT_NAME ✅
DNS servers for clients Google Public DNS VPN_DNS_SRV1, VPN_DNS_SRV2 ✅
Protect client config files no VPN_PROTECT_CONFIG=yes ✅
Enable/Disable MOBIKE Enable if supported ❌ ✅
Client cert validity 10 years (120 months) VPN_CLIENT_VALIDITY**** ✅
CA & server cert validity 10 years (120 months) ❌ ❌
CA certificate name IKEv2 VPN CA ❌ ❌
Certificate key size 3072 bits ❌ ❌

* These IKEv2 parameters are for IKEv2 mode.
** Define these as environment variables when running vpn(setup).sh, or when setting up IKEv2 in auto mode (sudo ikev2.sh --auto).
*** Can be customized during interactive IKEv2 setup (sudo ikev2.sh). Refer to option 1 above.
**** Use VPN_CLIENT_VALIDITY to specify the client cert validity period in months. Must be an integer between 1 and 120.

In addition to these parameters, advanced users can also customize VPN subnets during VPN setup.

Next steps

Read this in other languages: English, 简体中文, 繁體中文, 日本語, Русский.

Get your computer or device to use the VPN. Please refer to:

Configure IKEv2 VPN Clients (recommended)

Configure IPsec/L2TP VPN Clients

Configure IPsec/XAuth ("Cisco IPsec") VPN Clients

Read :book: VPN book to access extra content.

Enjoy your very own VPN! :sparkles::tada::rocket::sparkles:

Important notes

Windows users: For IPsec/L2TP mode, a one-time registry change is required if the VPN server or client is behind NAT (e.g. home router).

The same VPN account can be used by your multiple devices. However, due to an IPsec/L2TP limitation, if you wish to connect multiple devices from behind the same NAT (e.g. home router), you must use IKEv2 or IPsec/XAuth mode. To view or update VPN user accounts, see Manage VPN users.

For servers with an external firewall (e.g. EC2/GCE), open UDP ports 500 and 4500 for the VPN. Aliyun users, see #433.

Clients are set to use Google Public DNS when the VPN is active. If another DNS provider is preferred, see Advanced usage.

Using kernel support could improve IPsec/L2TP performance. It is available on all supported OS. Ubuntu users should install the linux-modules-extra-$(uname -r) package and run service xl2tpd restart.

The scripts will backup existing config files before making changes, with .old-date-time suffix.

Upgrade Libreswan

Use this one-liner to update Libreswan (changelog | announce) on your VPN server.

bash
wget https://get.vpnsetup.net/upg -O vpnup.sh && sudo sh vpnup.sh

Click here if you are unable to download.

You may also use curl to download:

bash
curl -fsSL https://get.vpnsetup.net/upg -o vpnup.sh && sudo sh vpnup.sh

Alternative update URLs:

bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/extras/vpnupgrade.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/extras/vpnupgrade.sh

If you are unable to download, open vpnupgrade.sh, then click the Raw button on the right. Press Ctrl/Cmd+A to select all, Ctrl/Cmd+C to copy, then paste into your favorite editor.

The latest supported Libreswan version is 5.3.2. Check installed version: ipsec --version.

Note: xl2tpd can be updated using your system's package manager, such as apt-get on Ubuntu/Debian.

Manage VPN users

See Manage VPN users.

Advanced usage

See Advanced usage.

Uninstall the VPN

To uninstall IPsec VPN, run the helper script:

[!CAUTION]
This helper script will remove IPsec VPN from your server. All VPN configuration will be permanently deleted, and Libreswan and xl2tpd will be removed. This cannot be undone!

bash
wget https://get.vpnsetup.net/unst -O unst.sh && sudo bash unst.sh

Click here if you are unable to download.

You may also use curl to download:

bash
curl -fsSL https://get.vpnsetup.net/unst -o unst.sh && sudo bash unst.sh

Alternative script URLs:

bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/extras/vpnuninstall.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/extras/vpnuninstall.sh

For more information, see Uninstall the VPN.

Feedback & Questions

License

Copyright (C) 2014-2026 Lin Song
Based on the work of Thomas Sarlandie (Copyright 2012)


This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License
Attribution required: please include my name in any derivative and let me know how you have improved it!


File: docs/advanced-usage.md

English | 中文

Advanced Usage

Use alternative DNS servers

By default, clients are set to use Google Public DNS when the VPN is active. If another DNS provider is preferred, you may replace 8.8.8.8 and 8.8.4.4 in these files: /etc/ppp/options.xl2tpd, /etc/ipsec.conf and /etc/ipsec.d/ikev2.conf (if exists). Then run service ipsec restart and service xl2tpd restart.

Below is a list of some popular public DNS providers for your reference.

Provider Primary DNS Secondary DNS Notes
Google Public DNS 8.8.8.8 8.8.4.4 Default in this project
Cloudflare 1.1.1.1 1.0.0.1 See also: Cloudflare for families
Quad9 9.9.9.9 149.112.112.112 Blocks malicious domains
OpenDNS 208.67.222.222 208.67.220.220 Blocks phishing domains, configurable.
CleanBrowsing 185.228.168.9 185.228.169.9 Domain filters available
NextDNS Varies Varies Ad blocking, free tier available. Learn more.
Control D Varies Varies Ad blocking, configurable. Learn more.

Advanced users can define VPN_DNS_SRV1 and optionally VPN_DNS_SRV2 when running the VPN setup script. For more details, see Customize VPN options.

It is possible to set different DNS server(s) for specific IKEv2 client(s). For this use case, please refer to #1562.

If your use case requires redirecting DNS traffic to another server using IPTables rules, see #1565.

In certain circumstances, you may want VPN clients to use the specified DNS server(s) only for resolving internal domain name(s), and use their locally configured DNS servers to resolve all other domain names. This can be configured using the modecfgdomains option, e.g. modecfgdomains="internal.example.com, home". Add this option to section conn ikev2-cp in /etc/ipsec.d/ikev2.conf for IKEv2, and to section conn xauth-psk in /etc/ipsec.conf for IPsec/XAuth ("Cisco IPsec"). Then run service ipsec restart. IPsec/L2TP mode does not support this option.

DNS name and server IP changes

For IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes, you may use a DNS name (e.g. vpn.example.com) instead of an IP address to connect to the VPN server, without additional configuration. In addition, the VPN should generally continue to work after server IP changes, such as after restoring a snapshot to a new server with a different IP, although a reboot may be required.

For IKEv2 mode, if you want the VPN to continue to work after server IP changes, read this section. Alternatively, you may specify a DNS name for the IKEv2 server address when setting up IKEv2. The DNS name must be a fully qualified domain name (FQDN). Example:

text
sudo VPN_DNS_NAME='vpn.example.com' ikev2.sh --auto

Alternatively, you may customize IKEv2 options by running the helper script without the --auto parameter.

IKEv2-only VPN

Using Libreswan 4.2 or newer, advanced users can enable IKEv2-only mode on the VPN server. With IKEv2-only mode enabled, VPN clients can only connect to the VPN server using IKEv2. All IKEv1 connections (including IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes) will be dropped.

To enable IKEv2-only mode, first install the VPN server and set up IKEv2 using instructions in the README. Then run the helper script and follow the prompts.

bash
wget https://get.vpnsetup.net/ikev2only -O ikev2only.sh
sudo bash ikev2only.sh

To disable IKEv2-only mode, run the helper script again and select the appropriate option.

Alternatively, you may manually enable IKEv2-only mode.

Alternatively, you may manually enable IKEv2-only mode. First check Libreswan version using ipsec --version, and update Libreswan if needed. Then edit /etc/ipsec.conf on the VPN server. Replace ikev1-policy=accept with ikev1-policy=drop. If the line does not exist, append ikev1-policy=drop to the end of the config setup section, indented by two spaces. Save the file and run service ipsec restart. When finished, you can run ipsec status to verify that only the ikev2-cp connection is enabled.

Enable IKEv2 perfect forward secrecy

By default, IKEv2 Child SAs derive keying material from the existing IKE SA without a new Diffie-Hellman exchange (pfs=no). Enabling perfect forward secrecy (PFS) causes each Child SA rekey to perform a fresh DH exchange, so that a future compromise of the server's private key cannot decrypt previously recorded sessions.

Note: The IKE SA already proposes ECP-256 as its first preference (aes_gcm_c_256-hmac_sha2_256-ecp_256), and all modern clients negotiate it, so session keys are already independent of the server's long-term private key for those clients. Enabling PFS for Child SAs is an incremental hardening step, not a critical gap.

Client compatibility: All modern clients support PFS. However, macOS and iOS clients require re-export and re-import of the .mobileconfig profile with EnablePFS set to 1 (see below). Windows clients require a connection update. RouterOS users must change pfs-group=none to pfs-group=ecp256 in their IKEv2 profile. Android and Linux strongSwan clients require no changes. Windows 7 IKEv2 clients do not support ECP PFS groups and will fail to connect if PFS is enabled on the server.

To enable PFS on the server, edit /etc/ipsec.d/ikev2.conf and change pfs=no to pfs=yes in the conn ikev2-cp section, then restart the IPsec service:

bash
sudo sed -i 's/pfs=no/pfs=yes/' /etc/ipsec.d/ikev2.conf
sudo service ipsec restart

Docker users: Open a Bash shell inside the container, run the sed command above, then exit and run docker restart ipsec-vpn-server.

After enabling PFS, the following client configurations must be updated:

  • macOS / iOS: Re-export the client .mobileconfig using sudo ikev2.sh --exportclient <name>, then edit the exported file to enable PFS:
    bash
    sed -i '/EnablePFS/{n;s/0/1/;}' <name>.mobileconfig
    Re-import the updated file on your device.
  • Windows: In an elevated PowerShell window, run Set-VpnConnection -Name "Your VPN Name" -PfsGroup ECP256 (replace with your actual VPN connection name), then reconnect the VPN.
  • RouterOS (MikroTik): In the IKEv2 peer profile, change pfs-group=none to pfs-group=ecp256.

Android and Linux strongSwan clients require no changes; PFS is auto-negotiated.

To revert to the default (PFS disabled):

bash
sudo sed -i 's/pfs=yes/pfs=no/' /etc/ipsec.d/ikev2.conf
sudo service ipsec restart

Internal VPN IPs and traffic

When connecting using IPsec/L2TP mode, the VPN server has internal IP 192.168.42.1 within the VPN subnet 192.168.42.0/24. Clients are assigned internal IPs from 192.168.42.10 to 192.168.42.250. To check which IP is assigned to a client, view the connection status on the VPN client.

When connecting using IPsec/XAuth ("Cisco IPsec") or IKEv2 mode, the VPN server does NOT have an internal IP within the VPN subnet 192.168.43.0/24. Clients are assigned internal IPs from 192.168.43.10 to 192.168.43.250.

You may use these internal VPN IPs for communication. However, note that the IPs assigned to VPN clients are dynamic, and firewalls on client devices may block such traffic.

Advanced users may optionally assign static IPs to VPN clients. Expand for details.

IPsec/L2TP mode: Assign static IPs to VPN clients

The example below ONLY applies to IPsec/L2TP mode. Commands must be run as root.

  1. First, create a new VPN user for each VPN client that you want to assign a static IP to. Refer to Manage VPN Users. Helper scripts are included for convenience.

  2. Edit /etc/xl2tpd/xl2tpd.conf on the VPN server. Replace ip range = 192.168.42.10-192.168.42.250 with e.g. ip range = 192.168.42.100-192.168.42.250. This reduces the pool of auto-assigned IP addresses, so that more IPs are available to assign to clients as static IPs.

  3. Edit /etc/ppp/chap-secrets on the VPN server. For example, if the file contains:

    text
    "username1"  l2tpd  "password1"  *
    "username2"  l2tpd  "password2"  *
    "username3"  l2tpd  "password3"  *

    Let's assume that you want to assign static IP 192.168.42.2 to VPN user username2, assign static IP 192.168.42.3 to VPN user username3, while keeping username1 unchanged (auto-assign from the pool). After editing, the file should look like:

    text
    "username1"  l2tpd  "password1"  *
    "username2"  l2tpd  "password2"  192.168.42.2
    "username3"  l2tpd  "password3"  192.168.42.3

    Note: The assigned static IP(s) must be from the subnet 192.168.42.0/24, and must NOT be from the pool of auto-assigned IPs (see ip range above). In addition, 192.168.42.1 is reserved for the VPN server itself. In the example above, you can only assign static IP(s) from the range 192.168.42.2-192.168.42.99.

  4. (Important) Restart the xl2tpd service:

    text
    service xl2tpd restart

IPsec/XAuth ("Cisco IPsec") mode: Assign static IPs to VPN clients

The example below ONLY applies to IPsec/XAuth ("Cisco IPsec") mode. Commands must be run as root.

  1. First, create a new VPN user for each VPN client that you want to assign a static IP to. Refer to Manage VPN Users. Helper scripts are included for convenience.

  2. Edit /etc/ipsec.conf on the VPN server. Replace rightaddresspool=192.168.43.10-192.168.43.250 with e.g. rightaddresspool=192.168.43.100-192.168.43.250. This reduces the pool of auto-assigned IP addresses, so that more IPs are available to assign to clients as static IPs.

  3. Edit /etc/ipsec.d/ikev2.conf on the VPN server (if exists). Replace rightaddresspool=192.168.43.10-192.168.43.250 with the same value as the previous step.

  4. Edit /etc/ipsec.d/passwd on the VPN server. For example, if the file contains:

    text
    username1:password1hashed:xauth-psk
    username2:password2hashed:xauth-psk
    username3:password3hashed:xauth-psk

    Let's assume that you want to assign static IP 192.168.43.2 to VPN user username2, assign static IP 192.168.43.3 to VPN user username3, while keeping username1 unchanged (auto-assign from the pool). After editing, the file should look like:

    text
    username1:password1hashed:xauth-psk
    username2:password2hashed:xauth-psk:192.168.42.2
    username3:password3hashed:xauth-psk:192.168.42.3

    Note: The assigned static IP(s) must be from the subnet 192.168.43.0/24, and must NOT be from the pool of auto-assigned IPs (see rightaddresspool above). In the example above, you can only assign static IP(s) from the range 192.168.43.1-192.168.43.99.

  5. (Important) Restart the IPsec service:

    text
    service ipsec restart

IKEv2 mode: Assign static IPs to VPN clients

The example below ONLY applies to IKEv2 mode. Commands must be run as root.

  1. First, create a new IKEv2 client certificate for each client that you want to assign a static IP to, and write down the name of each IKEv2 client. Refer to Add a client certificate.

  2. Edit /etc/ipsec.d/ikev2.conf on the VPN server. Replace rightaddresspool=192.168.43.10-192.168.43.250 with e.g. rightaddresspool=192.168.43.100-192.168.43.250. This reduces the pool of auto-assigned IP addresses, so that more IPs are available to assign to clients as static IPs.

  3. Edit /etc/ipsec.conf on the VPN server. Replace rightaddresspool=192.168.43.10-192.168.43.250 with the same value as the previous step.

  4. Edit /etc/ipsec.d/ikev2.conf on the VPN server again. For example, if the file contains:

    text
    conn ikev2-cp
      left=%defaultroute
      ... ...

    Let's assume that you want to assign static IP 192.168.43.4 to IKEv2 client client1, assign static IP 192.168.43.5 to client client2, while keeping other clients unchanged (auto-assign from the pool). After editing, the file should look like:

    text
    conn ikev2-cp
      left=%defaultroute
      ... ...
    
    conn ikev2-shared
      # COPY everything from the ikev2-cp section, EXCEPT FOR:
      # rightid, rightaddresspool, auto=add
    
    conn client1
      rightid=@client1
      rightaddresspool=192.168.43.4-192.168.43.4
      auto=add
      also=ikev2-shared
    
    conn client2
      rightid=@client2
      rightaddresspool=192.168.43.5-192.168.43.5
      auto=add
      also=ikev2-shared

    Note: Add a new conn section for each client that you want to assign a static IP to. You must add a @ prefix to the client name for rightid=. The client name must exactly match the name you specified when adding the client certificate. The assigned static IP(s) must be from the subnet 192.168.43.0/24, and must NOT be from the pool of auto-assigned IPs (see rightaddresspool above). In the example above, you can only assign static IP(s) from the range 192.168.43.1-192.168.43.99.

    Note: For Windows 7/8/10/11 and RouterOS clients, you must use a different syntax for rightid=. For example, if the client name is client1, set rightid="CN=client1, O=IKEv2 VPN" in the example above.

  5. (Important) Restart the IPsec service:

    text
    service ipsec restart

Client-to-client traffic is allowed by default. If you want to disallow client-to-client traffic, run the following commands on the VPN server. Add them to /etc/rc.local to persist after reboot.

text
iptables -I FORWARD 2 -i ppp+ -o ppp+ -s 192.168.42.0/24 -d 192.168.42.0/24 -j DROP
iptables -I FORWARD 3 -s 192.168.43.0/24 -d 192.168.43.0/24 -j DROP
iptables -I FORWARD 4 -i ppp+ -d 192.168.43.0/24 -j DROP
iptables -I FORWARD 5 -s 192.168.43.0/24 -o ppp+ -j DROP

Specify VPN server's public IP

On servers with multiple public IP addresses, advanced users can specify a public IP for the VPN server using variable VPN_PUBLIC_IP. For example, if the server has IPs 192.0.2.1 and 192.0.2.2, and you want the VPN server to use 192.0.2.2:

text
sudo VPN_PUBLIC_IP=192.0.2.2 sh vpn.sh

Note that this variable has no effect for IKEv2 mode, if IKEv2 is already set up on the server. In this case, you may remove IKEv2 and set it up again using custom options. Refer to Set up IKEv2 using helper script.

Additional configuration may be required if you want VPN clients to use the specified public IP as their "outgoing IP" when the VPN connection is active, and the specified IP is NOT the main IP (or default route) on the server. In this case, you may need to change IPTables rules on the server. To persist after reboot, you can add these commands to /etc/rc.local.

Continuing with the example above, if you want the "outgoing IP" to be 192.0.2.2:

text
# Get default network interface name
netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
# Remove MASQUERADE rules
iptables -t nat -D POSTROUTING -s 192.168.43.0/24 -o "$netif" -m policy --dir out --pol none -j MASQUERADE
iptables -t nat -D POSTROUTING -s 192.168.42.0/24 -o "$netif" -j MASQUERADE
# Add SNAT rules
iptables -t nat -I POSTROUTING -s 192.168.43.0/24 -o "$netif" -m policy --dir out --pol none -j SNAT --to 192.0.2.2
iptables -t nat -I POSTROUTING -s 192.168.42.0/24 -o "$netif" -j SNAT --to 192.0.2.2

Note: The method above only applies if the VPN server's default network interface maps to multiple public IPs. This method may not work if the server has multiple network interfaces, each with a different public IP.

To check the "outgoing IP" for a connected VPN client, you may open a browser on the client and look up the IP address on Google.

Customize VPN subnets

By default, IPsec/L2TP VPN clients will use internal VPN subnet 192.168.42.0/24, while IPsec/XAuth ("Cisco IPsec") and IKEv2 VPN clients will use internal VPN subnet 192.168.43.0/24. For more details, see Internal VPN IPs and traffic.

For most use cases, it is NOT necessary and NOT recommended to customize these subnets. If your use case requires it, however, you may specify custom subnet(s) when installing the VPN.

Important: You may only specify custom subnets during initial VPN install. If the IPsec VPN is already installed, you must first uninstall the VPN, then specify custom subnets and re-install. Otherwise, the VPN may stop working.

text
# Example: Specify custom VPN subnet for IPsec/L2TP mode
# Note: All three variables must be specified.
sudo VPN_L2TP_NET=10.1.0.0/16 \
VPN_L2TP_LOCAL=10.1.0.1 \
VPN_L2TP_POOL=10.1.0.10-10.1.254.254 \
sh vpn.sh
text
# Example: Specify custom VPN subnet for IPsec/XAuth and IKEv2 modes
# Note: Both variables must be specified.
sudo VPN_XAUTH_NET=10.2.0.0/16 \
VPN_XAUTH_POOL=10.2.0.10-10.2.254.254 \
sh vpn.sh

In the examples above, VPN_L2TP_LOCAL is the VPN server's internal IP for IPsec/L2TP mode. VPN_L2TP_POOL and VPN_XAUTH_POOL are the pools of auto-assigned IP addresses for VPN clients.

IPv6 support

If your VPN server has a public (global unicast) IPv6 address and the requirements below are met, IPv6 support for IKEv2 clients is automatically enabled during VPN setup. No manual configuration is needed.

Note: IPv6 works without additional configuration when using the strongSwan VPN client on Android. For Windows and macOS clients, follow the platform-specific steps below. iOS clients do not currently support routing IPv6 traffic through the IKEv2 VPN; you may instead use OpenVPN or WireGuard.

Windows: Route IPv6 traffic through the VPN

If you used the ikev2_config_import.cmd script to import IKEv2 configuration, you can answer y when prompted to automatically add IPv6 routes. Otherwise, run the following commands once in a PowerShell window to route IPv6 traffic through the VPN. Replace IKEv2 VPN X.X.X.X with the actual name of your VPN connection. When finished, reconnect to the IKEv2 VPN.

powershell
Add-VpnConnectionRoute -ConnectionName "IKEv2 VPN X.X.X.X" -DestinationPrefix ::/1
Add-VpnConnectionRoute -ConnectionName "IKEv2 VPN X.X.X.X" -DestinationPrefix 8000::/1

macOS: Route IPv6 traffic through the VPN

After connecting to the IKEv2 VPN, run the following command in Terminal to route IPv6 traffic through the VPN. This command must be run each time you connect. The route is automatically removed when you disconnect from the VPN. The interface is usually ipsec0; if you have multiple VPN connections active it may be ipsec1, etc. Run ifconfig | grep ipsec to confirm.

text
sudo route -n add -inet6 default -interface ipsec0

When IPv6 is enabled, IKEv2 VPN clients receive both an IPv4 address from the 192.168.43.0/24 pool and an IPv6 address from the fddd:500:500:500::/64 pool. The VPN server masquerades IPv6 traffic from the client pool through the server's own IPv6 address, giving VPN clients full IPv6 internet access through the tunnel.

Requirements:

  • The VPN server must have a routable global unicast IPv6 address (i.e., an address starting with 2 or 3). Link-local (fe80::/10) and ULA (fc00::/7) addresses are not sufficient.
  • Libreswan 5.0 or newer (the VPN setup scripts use 5.x by default).
  • IPv6 is only supported for IKEv2 mode. IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes do not support IPv6.

To verify that IPv6 is working, connect to the VPN using IKEv2 and check your IPv6 address, e.g. using test-ipv6.com.

You may optionally specify a custom IPv6 pool subnet when installing the VPN. The subnet must be a /64 from the ULA range (fddd::/16 is recommended).

text
# Example: Specify custom IPv6 pool subnet for IKEv2 mode
sudo VPN_IP6_NET=fddd:1234:5678:9012::/64 \
sh vpn.sh

Note: The VPN_IP6_NET variable may only be specified during initial VPN install.

Port forwarding to VPN clients

In certain circumstances, you may want to forward port(s) on the VPN server to a connected VPN client. This can be done by adding IPTables rules on the VPN server.

Warning: Port forwarding will expose port(s) on the VPN client to the entire Internet, which could be a security risk! This is NOT recommended, unless your use case requires it.

Note: The internal VPN IPs assigned to VPN clients are dynamic, and firewalls on client devices may block forwarded traffic. To assign static IPs to VPN clients, see Internal VPN IPs and traffic. To check which IP is assigned to a client, view the connection status on the VPN client.

Example 1: Forward TCP port 443 on the VPN server to the IPsec/L2TP client at 192.168.42.10.

text
# Get default network interface name
netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
iptables -I FORWARD 2 -i "$netif" -o ppp+ -p tcp --dport 443 -j ACCEPT
iptables -t nat -A PREROUTING -i "$netif" -p tcp --dport 443 -j DNAT --to 192.168.42.10

Example 2: Forward UDP port 123 on the VPN server to the IKEv2 (or IPsec/XAuth) client at 192.168.43.10.

text
# Get default network interface name
netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
iptables -I FORWARD 2 -i "$netif" -d 192.168.43.0/24 -p udp --dport 123 -j ACCEPT
iptables -t nat -A PREROUTING -i "$netif" ! -s 192.168.43.0/24 -p udp --dport 123 -j DNAT --to 192.168.43.10

If you want the rules to persist after reboot, you may add these commands to /etc/rc.local. To remove the added IPTables rules, run the commands again, but replace -I FORWARD 2 with -D FORWARD, and replace -A PREROUTING with -D PREROUTING.

Split tunneling

With split tunneling, VPN clients will only send traffic for specific destination subnet(s) through the VPN tunnel. Other traffic will NOT go through the VPN tunnel. This allows you to gain secure access to a network through your VPN, without routing all your client's traffic through the VPN. Split tunneling has some limitations, and is not supported by all VPN clients.

Advanced users can optionally enable split tunneling for the IPsec/XAuth ("Cisco IPsec") and/or IKEv2 modes. Expand for details. IPsec/L2TP mode does not support this feature (except on Windows, see below).

IPsec/XAuth ("Cisco IPsec") mode: Enable split tunneling

The example below ONLY applies to IPsec/XAuth ("Cisco IPsec") mode. Commands must be run as root.

  1. Edit /etc/ipsec.conf on the VPN server. In the section conn xauth-psk, replace leftsubnet=0.0.0.0/0 with the subnet(s) you want VPN clients to send traffic through the VPN tunnel. For example:
    For a single subnet:
    text
    leftsubnet=10.123.123.0/24
    For multiple subnets (use leftsubnets instead):
    text
    leftsubnets="10.123.123.0/24,10.100.0.0/16"
  2. (Important) Restart the IPsec service:
    text
    service ipsec restart

IKEv2 mode: Enable split tunneling

The example below ONLY applies to IKEv2 mode. Commands must be run as root.

  1. Edit /etc/ipsec.d/ikev2.conf on the VPN server. In the section conn ikev2-cp, replace leftsubnet=0.0.0.0/0 with the subnet(s) you want VPN clients to send traffic through the VPN tunnel. For example:
    For a single subnet:
    text
    leftsubnet=10.123.123.0/24
    For multiple subnets (use leftsubnets instead):
    text
    leftsubnets="10.123.123.0/24,10.100.0.0/16"
  2. (Important) Restart the IPsec service:
    text
    service ipsec restart

Note: Advanced users can set a different split tunneling configuration for specific IKEv2 client(s). Refer to section Internal VPN IPs and traffic and expand "IKEv2 mode: Assign static IPs to VPN clients". Based on the example in that section, you may add the leftsubnet=... option to the conn section of the specific IKEv2 client, then restart the IPsec service.

Alternatively, Windows users can enable split tunneling by manually adding routes:

  1. Right-click on the wireless/network icon in your system tray.
  2. Windows 11: Select Network and Internet settings, then on the page that opens, click Advanced network settings. Click More network adapter options.
    Windows 10: Select Open Network & Internet settings, then on the page that opens, click Network and Sharing Center. On the left, click Change adapter settings.
    Windows 8/7: Select Open Network and Sharing Center. On the left, click Change adapter settings.
  3. Right-click on the new VPN connection, and choose Properties.
  4. Click the Network tab. Select Internet Protocol Version 4 (TCP/IPv4), then click Properties.
  5. Click Advanced. Uncheck Use default gateway on remote network.
  6. Click OK to close the Properties window.
  7. (Important) Disconnect the VPN, then re-connect.
  8. Assume that the subnet you want VPN clients to send traffic through the VPN tunnel is 10.123.123.0/24. Open an elevated command prompt and run one of the following commands:
    For IKEv2 and IPsec/XAuth ("Cisco IPsec") modes:
    text
    route add -p 10.123.123.0 mask 255.255.255.0 192.168.43.1
    For IPsec/L2TP mode:
    text
    route add -p 10.123.123.0 mask 255.255.255.0 192.168.42.1
  9. When finished, VPN clients will send traffic through the VPN tunnel for the specified subnet only. Other traffic will bypass the VPN.

Access VPN server's subnet

After connecting to the VPN, VPN clients can generally access services running on other devices that are within the same local subnet as the VPN server, without additional configuration. For example, if the VPN server's local subnet is 192.168.0.0/24, and an Nginx server is running on IP 192.168.0.2, VPN clients can use IP 192.168.0.2 to access the Nginx server.

Please note, additional configuration is required if the VPN server has multiple network interfaces (e.g. eth0 and eth1), and you want VPN clients to access the local subnet behind the network interface that is NOT for Internet access. In this scenario, you must run the following commands to add IPTables rules. To persist after reboot, you may add these commands to /etc/rc.local.

bash
# Replace eth1 with the name of the network interface
# on the VPN server that you want VPN clients to access
netif=eth1
iptables -I FORWARD 2 -i "$netif" -o ppp+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -I FORWARD 2 -i ppp+ -o "$netif" -j ACCEPT
iptables -I FORWARD 2 -i "$netif" -d 192.168.43.0/24 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -I FORWARD 2 -s 192.168.43.0/24 -o "$netif" -j ACCEPT
iptables -t nat -I POSTROUTING -s 192.168.43.0/24 -o "$netif" -m policy --dir out --pol none -j MASQUERADE
iptables -t nat -I POSTROUTING -s 192.168.42.0/24 -o "$netif" -j MASQUERADE

Access VPN clients from server's subnet

In certain circumstances, you may need to access services on VPN clients from other devices that are on the same local subnet as the VPN server. This can be done using the following steps.

Assume that the VPN server IP is 10.1.0.2, and the IP of the device from which you want to access VPN clients is 10.1.0.3.

  1. Add IPTables rules on the VPN server to allow this traffic. For example:
    text
    # Get default network interface name
    netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
    iptables -I FORWARD 2 -i "$netif" -o ppp+ -s 10.1.0.3 -j ACCEPT
    iptables -I FORWARD 2 -i "$netif" -d 192.168.43.0/24 -s 10.1.0.3 -j ACCEPT
  2. Add routing rules on the device you want to access VPN clients. For example:
    text
    # Replace eth0 with the network interface name of the device's local subnet
    route add -net 192.168.42.0 netmask 255.255.255.0 gw 10.1.0.2 dev eth0
    route add -net 192.168.43.0 netmask 255.255.255.0 gw 10.1.0.2 dev eth0

Learn more about internal VPN IPs in Internal VPN IPs and traffic.

Modify IPTables rules

If you want to modify IPTables rules after install, edit /etc/iptables.rules and/or /etc/iptables/rules.v4 (Ubuntu/Debian), or /etc/sysconfig/iptables (CentOS/RHEL). Then reboot your server.

If IPv6 support is enabled, the corresponding ip6tables rules are saved in /etc/ip6tables.rules and /etc/iptables/rules.v6 (Ubuntu/Debian), or /etc/sysconfig/ip6tables (CentOS/RHEL).

Note: If your server runs CentOS Linux (or similar), and firewalld was active during VPN setup, nftables may be configured. In this case, edit /etc/sysconfig/nftables.conf instead of /etc/sysconfig/iptables.

Deploy Google BBR congestion control

After the VPN server is set up, the performance can be improved by deploying the Google BBR congestion control algorithm.

This is usually done by modifying the configuration file /etc/sysctl.conf. However, some Linux distributions may additionally require updates to the Linux kernel.

For detailed deployment methods, please refer to this document.

License

Copyright (C) 2021-2026 Lin Song


This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License
Attribution required: please include my name in any derivative and let me know how you have improved it!


File: docs/advanced-usage-zh.md

English | 中文

高级用法

使用其他的 DNS 服务器

在 VPN 已连接时,客户端默认配置为使用 Google Public DNS。如果偏好其它的域名解析服务,你可以编辑以下文件:/etc/ppp/options.xl2tpd, /etc/ipsec.conf 和 /etc/ipsec.d/ikev2.conf(如果存在),并替换 8.8.8.8 和 8.8.4.4。然后运行 service ipsec restart 和 service xl2tpd restart。

以下是一些流行的公共 DNS 提供商的列表,供你参考。

提供商 主 DNS 辅助 DNS 注释
Google Public DNS 8.8.8.8 8.8.4.4 本项目默认
Cloudflare 1.1.1.1 1.0.0.1 另见:Cloudflare for families
Quad9 9.9.9.9 149.112.112.112 阻止恶意域
OpenDNS 208.67.222.222 208.67.220.220 阻止网络钓鱼域,可配置。
CleanBrowsing 185.228.168.9 185.228.169.9 域过滤器可用
NextDNS 按需选择 按需选择 广告拦截,免费套餐可用。了解更多。
Control D 按需选择 按需选择 广告拦截,可配置。了解更多。

高级用户可以在运行 VPN 安装脚本时定义 VPN_DNS_SRV1 和 VPN_DNS_SRV2(可选)。有关更多详细信息,请参见自定义 VPN 选项。

你可以为特定的 IKEv2 客户端设置不同的 DNS 服务器。对于此用例,请参见 #1562。

如果你的用例需要使用 IPTables 规则将 DNS 流量重定向到另一台服务器,请参见 #1565。

在某些情况下,你可能希望 VPN 客户端仅使用指定的 DNS 服务器来解析内部域名,并使用其本地配置的 DNS 服务器来解析所有其他域名。这可以使用 modecfgdomains 选项进行配置,例如 modecfgdomains="internal.example.com, home"。对于 IKEv2,将此选项添加到 /etc/ipsec.d/ikev2.conf 中的 conn ikev2-cp 小节。对于 IPsec/XAuth ("Cisco IPsec"),将此选项添加到 /etc/ipsec.conf 中的 conn xauth-psk 小节。然后运行 service ipsec restart。IPsec/L2TP 模式不支持此选项。

域名和更改服务器 IP

对于 IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式,你可以在不需要额外配置的情况下使用一个域名(比如 vpn.example.com)而不是 IP 地址连接到 VPN 服务器。另外,一般来说,在服务器的 IP 更改后,比如在恢复一个映像到具有不同 IP 的新服务器后,VPN 会继续正常工作,虽然可能需要重启服务器。

对于 IKEv2 模式,如果你想要 VPN 在服务器的 IP 更改后继续正常工作,参见这一小节。或者,你也可以在配置 IKEv2 时指定一个域名作为 IKEv2 服务器地址。该域名必须是一个全称域名(FQDN)。示例如下:

text
sudo VPN_DNS_NAME='vpn.example.com' ikev2.sh --auto

另外,你也可以自定义 IKEv2 选项,通过在运行辅助脚本时去掉 --auto 参数来实现。

仅限 IKEv2 的 VPN

使用 Libreswan 4.2 或更新版本,高级用户可以为 VPN 服务器启用仅限 IKEv2 模式。当启用该模式时,VPN 客户端仅能使用 IKEv2 连接到 VPN 服务器。所有的 IKEv1 连接(包括 IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式)将被丢弃。

要启用仅限 IKEv2 模式,首先按照自述文件中的说明安装 VPN 服务器并且配置 IKEv2。然后运行辅助脚本并按提示操作。

bash
wget https://get.vpnsetup.net/ikev2only -O ikev2only.sh
sudo bash ikev2only.sh

要禁用仅限 IKEv2 模式,再次运行辅助脚本并选择适当的选项。

另外,你也可以手动启用仅限 IKEv2 模式。

另外,你也可以手动启用仅限 IKEv2 模式。首先使用 ipsec --version 命令检查 Libreswan 版本,并更新 Libreswan(如果需要)。然后编辑 VPN 服务器上的 /etc/ipsec.conf。将 ikev1-policy=accept 替换为 ikev1-policy=drop。如果该行不存在,则在 config setup 小节的末尾添加 ikev1-policy=drop,开头必须空两格。保存文件并运行 service ipsec restart。在完成后,你可以使用 ipsec status 命令来验证仅启用了 ikev2-cp 连接。

启用 IKEv2 前向保密

默认情况下,IKEv2 子安全关联(Child SA)从现有 IKE SA 派生密钥材料,不进行新的 Diffie-Hellman 交换(pfs=no)。启用前向保密(PFS)后,每次子 SA 重新生成密钥时都会执行新的 DH 交换,从而确保即使服务器私钥在将来遭到泄露,攻击者也无法解密之前录制的会话。

注: IKE SA 已将 ECP-256(aes_gcm_c_256-hmac_sha2_256-ecp_256)作为首选提案,所有现代客户端均会协商使用,因此这些客户端的会话密钥已与长期密钥材料独立。为子 SA 启用 PFS 是一项渐进式安全加固措施,而非关键漏洞修复。

客户端兼容性: 所有现代客户端均支持 PFS。但是,macOS 和 iOS 客户端需要重新导出并导入已将 EnablePFS 设为 1 的 .mobileconfig 配置文件(详见下文)。Windows 客户端需要更新连接配置。RouterOS 用户需将 IKEv2 配置文件中的 pfs-group=none 改为 pfs-group=ecp256。Android 和 Linux strongSwan 客户端无需更改。Windows 7 IKEv2 客户端不支持 ECP PFS 组,若服务器启用 PFS,将无法连接。

要在服务器上启用 PFS,请编辑 /etc/ipsec.d/ikev2.conf,将 conn ikev2-cp 部分中的 pfs=no 改为 pfs=yes,然后重启 IPsec 服务:

bash
sudo sed -i 's/pfs=no/pfs=yes/' /etc/ipsec.d/ikev2.conf
sudo service ipsec restart

Docker 用户: 请先在容器内打开 Bash shell,运行上述 sed 命令,然后 exit 并运行 docker restart ipsec-vpn-server。

启用 PFS 后,需要更新以下客户端配置:

  • macOS / iOS: 使用 sudo ikev2.sh --exportclient <名称> 重新导出客户端 .mobileconfig 文件,然后编辑导出的文件以启用 PFS:
    bash
    sed -i '/EnablePFS/{n;s/0/1/;}' <名称>.mobileconfig
    在设备上重新导入更新后的文件。
  • Windows: 在提升权限的 PowerShell 窗口中运行 Set-VpnConnection -Name "你的VPN名称" -PfsGroup ECP256(替换为实际的 VPN 连接名称),然后重新连接 VPN。
  • RouterOS (MikroTik): 在 IKEv2 对等配置文件中,将 pfs-group=none 改为 pfs-group=ecp256。

Android 和 Linux strongSwan 客户端无需更改,PFS 会自动协商。

要恢复默认设置(禁用 PFS):

bash
sudo sed -i 's/pfs=yes/pfs=no/' /etc/ipsec.d/ikev2.conf
sudo service ipsec restart

VPN 内网 IP 和流量

在使用 IPsec/L2TP 模式连接时,VPN 服务器在虚拟网络 192.168.42.0/24 内具有内网 IP 192.168.42.1。为客户端分配的内网 IP 在这个范围内:192.168.42.10 到 192.168.42.250。要找到为特定的客户端分配的 IP,可以查看该 VPN 客户端上的连接状态。

在使用 IPsec/XAuth ("Cisco IPsec") 或 IKEv2 模式连接时,VPN 服务器在虚拟网络 192.168.43.0/24 内 没有 内网 IP。为客户端分配的内网 IP 在这个范围内:192.168.43.10 到 192.168.43.250。

你可以使用这些 VPN 内网 IP 进行通信。但是请注意,为 VPN 客户端分配的 IP 是动态的,而且客户端设备上的防火墙可能会阻止这些流量。

高级用户可以将静态 IP 分配给 VPN 客户端。这是可选的。展开以查看详细信息。

IPsec/L2TP 模式:为 VPN 客户端分配静态 IP

下面的示例 仅适用于 IPsec/L2TP 模式。这些命令必须用 root 账户运行。

  1. 首先为要分配静态 IP 的每个 VPN 客户端创建一个新的 VPN 用户。参见管理 VPN 用户。该文档包含辅助脚本,以方便管理 VPN 用户。

  2. 编辑 VPN 服务器上的 /etc/xl2tpd/xl2tpd.conf。将 ip range = 192.168.42.10-192.168.42.250 替换为比如 ip range = 192.168.42.100-192.168.42.250。这样可以缩小自动分配的 IP 地址池,从而使更多的 IP 可以作为静态 IP 分配给客户端。

  3. 编辑 VPN 服务器上的 /etc/ppp/chap-secrets。例如,如果文件内容是:

    text
    "username1"  l2tpd  "password1"  *
    "username2"  l2tpd  "password2"  *
    "username3"  l2tpd  "password3"  *

    假设你要为 VPN 用户 username2 分配静态 IP 192.168.42.2,为 VPN 用户 username3 分配静态 IP 192.168.42.3,同时保持 username1 不变(从池中自动分配)。在编辑完成后,文件内容应该如下所示:

    text
    "username1"  l2tpd  "password1"  *
    "username2"  l2tpd  "password2"  192.168.42.2
    "username3"  l2tpd  "password3"  192.168.42.3

    注: 分配的静态 IP 必须来自子网 192.168.42.0/24,并且必须 不是 来自自动分配的 IP 地址池(参见上面的 ip range)。另外,192.168.42.1 保留给 VPN 服务器本身使用。在上面的示例中,你只能分配 192.168.42.2-192.168.42.99 范围内的静态 IP。

  4. (重要) 重启 xl2tpd 服务:

    text
    service xl2tpd restart

IPsec/XAuth ("Cisco IPsec") 模式:为 VPN 客户端分配静态 IP

下面的示例 仅适用于 IPsec/XAuth ("Cisco IPsec") 模式。这些命令必须用 root 账户运行。

  1. 首先为要分配静态 IP 的每个 VPN 客户端创建一个新的 VPN 用户。参见管理 VPN 用户。该文档包含辅助脚本,以方便管理 VPN 用户。

  2. 编辑 VPN 服务器上的 /etc/ipsec.conf。将 rightaddresspool=192.168.43.10-192.168.43.250 替换为比如 rightaddresspool=192.168.43.100-192.168.43.250。这样可以缩小自动分配的 IP 地址池,从而使更多的 IP 可以作为静态 IP 分配给客户端。

  3. 编辑 VPN 服务器上的 /etc/ipsec.d/ikev2.conf(如果存在)。将 rightaddresspool=192.168.43.10-192.168.43.250 替换为与上一步 相同的值。

  4. 编辑 VPN 服务器上的 /etc/ipsec.d/passwd。例如,如果文件内容是:

    text
    username1:password1hashed:xauth-psk
    username2:password2hashed:xauth-psk
    username3:password3hashed:xauth-psk

    假设你要为 VPN 用户 username2 分配静态 IP 192.168.43.2,为 VPN 用户 username3 分配静态 IP 192.168.43.3,同时保持 username1 不变(从池中自动分配)。在编辑完成后,文件内容应该如下所示:

    text
    username1:password1hashed:xauth-psk
    username2:password2hashed:xauth-psk:192.168.42.2
    username3:password3hashed:xauth-psk:192.168.42.3

    注: 分配的静态 IP 必须来自子网 192.168.43.0/24,并且必须 不是 来自自动分配的 IP 地址池(参见上面的 rightaddresspool)。在上面的示例中,你只能分配 192.168.43.1-192.168.43.99 范围内的静态 IP。

  5. (重要) 重启 IPsec 服务:

    text
    service ipsec restart

IKEv2 模式:为 VPN 客户端分配静态 IP

下面的示例 仅适用于 IKEv2 模式。这些命令必须用 root 账户运行。

  1. 首先为要分配静态 IP 的每个客户端创建一个新的 IKEv2 客户端证书,并且在纸上记下每个客户端的名称。参见添加客户端证书。

  2. 编辑 VPN 服务器上的 /etc/ipsec.d/ikev2.conf。将 rightaddresspool=192.168.43.10-192.168.43.250 替换为比如 rightaddresspool=192.168.43.100-192.168.43.250。这样可以缩小自动分配的 IP 地址池,从而使更多的 IP 可以作为静态 IP 分配给客户端。

  3. 编辑 VPN 服务器上的 /etc/ipsec.conf。将 rightaddresspool=192.168.43.10-192.168.43.250 替换为与上一步 相同的值。

  4. 再次编辑 VPN 服务器上的 /etc/ipsec.d/ikev2.conf。例如,如果文件内容是:

    text
    conn ikev2-cp
      left=%defaultroute
      ... ...

    假设你要为 IKEv2 客户端 client1 分配静态 IP 192.168.43.4,为客户端 client2 分配静态 IP 192.168.43.5,同时保持其它客户端不变(从池中自动分配)。在编辑完成后,文件内容应该如下所示:

    text
    conn ikev2-cp
      left=%defaultroute
      ... ...
    
    conn ikev2-shared
      # 复制/粘贴 ikev2-cp 小节中 *除了下面三项之外* 的所有内容
      # rightid, rightaddresspool, auto=add
    
    conn client1
      rightid=@client1
      rightaddresspool=192.168.43.4-192.168.43.4
      auto=add
      also=ikev2-shared
    
    conn client2
      rightid=@client2
      rightaddresspool=192.168.43.5-192.168.43.5
      auto=add
      also=ikev2-shared

    注: 为要分配静态 IP 的每个客户端添加一个新的 conn 小节。rightid= 右边的客户端名称必须添加 @ 前缀。该客户端名称必须与你在添加客户端证书时指定的名称完全一致。分配的静态 IP 必须来自子网 192.168.43.0/24,并且必须 不是 来自自动分配的 IP 地址池(参见上面的 rightaddresspool)。在上面的示例中,你只能分配 192.168.43.1-192.168.43.99 范围内的静态 IP。

    注: 对于 Windows 7/8/10/11 和 RouterOS 客户端,你必须对 rightid= 使用不同的语法。例如,如果客户端名称为 client1,则在上面的示例中设置 rightid="CN=client1, O=IKEv2 VPN"。

  5. (重要) 重启 IPsec 服务:

    text
    service ipsec restart

在默认配置下,允许客户端之间的流量。如果你想要 不允许 客户端之间的流量,可以在 VPN 服务器上运行以下命令。将它们添加到 /etc/rc.local 以便在重启后继续有效。

text
iptables -I FORWARD 2 -i ppp+ -o ppp+ -s 192.168.42.0/24 -d 192.168.42.0/24 -j DROP
iptables -I FORWARD 3 -s 192.168.43.0/24 -d 192.168.43.0/24 -j DROP
iptables -I FORWARD 4 -i ppp+ -d 192.168.43.0/24 -j DROP
iptables -I FORWARD 5 -s 192.168.43.0/24 -o ppp+ -j DROP

指定 VPN 服务器的公有 IP

在具有多个公有 IP 地址的服务器上,高级用户可以使用变量 VPN_PUBLIC_IP 为 VPN 服务器指定一个公有 IP。例如,如果服务器的 IP 为 192.0.2.1 和 192.0.2.2,并且你想要 VPN 服务器使用 192.0.2.2:

text
sudo VPN_PUBLIC_IP=192.0.2.2 sh vpn.sh

请注意,如果在服务器上已经配置了 IKEv2,则此变量对 IKEv2 模式无效。在这种情况下,你可以移除 IKEv2 并使用自定义选项重新配置它。参见使用辅助脚本配置 IKEv2。

如果你想要 VPN 客户端在 VPN 连接处于活动状态时使用指定的公有 IP 作为其 "出站 IP",并且指定的 IP 不是 服务器上的主 IP(或默认路由),则可能需要额外的配置。在这种情况下,你可能需要更改服务器上的 IPTables 规则。如果要在重启后继续有效,你可以将这些命令添加到 /etc/rc.local。

继续上面的例子,如果你希望 "出站 IP" 为 192.0.2.2:

text
# 获取默认网络接口名称
netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
# 移除 MASQUERADE 规则
iptables -t nat -D POSTROUTING -s 192.168.43.0/24 -o "$netif" -m policy --dir out --pol none -j MASQUERADE
iptables -t nat -D POSTROUTING -s 192.168.42.0/24 -o "$netif" -j MASQUERADE
# 添加 SNAT 规则
iptables -t nat -I POSTROUTING -s 192.168.43.0/24 -o "$netif" -m policy --dir out --pol none -j SNAT --to 192.0.2.2
iptables -t nat -I POSTROUTING -s 192.168.42.0/24 -o "$netif" -j SNAT --to 192.0.2.2

注: 以上方法仅适用于服务器的默认网络接口对应多个公有 IP 的情况。如果服务器有多个网络接口,对应不同的公有 IP,则此方法无效。

要检查一个已连接的 VPN 客户端的 "出站 IP",你可以在该客户端上打开浏览器并到这里检测 IP 地址。

自定义 VPN 子网

默认情况下,IPsec/L2TP VPN 客户端将使用内部 VPN 子网 192.168.42.0/24,而 IPsec/XAuth ("Cisco IPsec") 和 IKEv2 VPN 客户端将使用内部 VPN 子网 192.168.43.0/24。有关更多详细信息,请参见 VPN 内网 IP 和流量。

对于大多数用例,没有必要也 不建议 自定义这些子网。但是,如果你的用例需要它,你可以在安装 VPN 时指定自定义子网。

重要: 你只能在 初始 VPN 安装时 指定自定义子网。如果 IPsec VPN 已安装,你 必须 首先卸载 VPN,然后指定自定义子网并重新安装。否则,VPN 可能会停止工作。

text
# 示例:为 IPsec/L2TP 模式指定自定义 VPN 子网
# 注:必须指定所有三个变量。
sudo VPN_L2TP_NET=10.1.0.0/16 \
VPN_L2TP_LOCAL=10.1.0.1 \
VPN_L2TP_POOL=10.1.0.10-10.1.254.254 \
sh vpn.sh
text
# 示例:为 IPsec/XAuth 和 IKEv2 模式指定自定义 VPN 子网
# 注:必须指定以下两个变量。
sudo VPN_XAUTH_NET=10.2.0.0/16 \
VPN_XAUTH_POOL=10.2.0.10-10.2.254.254 \
sh vpn.sh

在上面的例子中,VPN_L2TP_LOCAL 是在 IPsec/L2TP 模式下的 VPN 服务器的内网 IP。VPN_L2TP_POOL 和 VPN_XAUTH_POOL 是为 VPN 客户端自动分配的 IP 地址池。

IPv6 支持

如果你的 VPN 服务器拥有公共(全局单播)IPv6 地址并且满足以下要求,IKEv2 客户端的 IPv6 支持将在 VPN 安装时自动启用,无需手动配置。

注: 在 Android 上使用 strongSwan VPN 客户端时,IPv6 无需额外配置即可正常工作。对于 Windows 和 macOS 客户端,请按照以下平台特定步骤进行配置。iOS 客户端目前不支持通过 IKEv2 VPN 路由 IPv6 流量;你可以改用 OpenVPN 或 WireGuard。

Windows:通过 VPN 路由 IPv6 流量

如果你使用了 ikev2_config_import.cmd 脚本导入 IKEv2 配置,可以在提示时输入 y 以自动添加 IPv6 路由。否则,你需要在 PowerShell 窗口中运行以下命令一次,以通过 VPN 路由 IPv6 流量。将 IKEv2 VPN X.X.X.X 替换为你的 VPN 连接的实际名称。完成后,重新连接到 IKEv2 VPN。

powershell
Add-VpnConnectionRoute -ConnectionName "IKEv2 VPN X.X.X.X" -DestinationPrefix ::/1
Add-VpnConnectionRoute -ConnectionName "IKEv2 VPN X.X.X.X" -DestinationPrefix 8000::/1

macOS:通过 VPN 路由 IPv6 流量

连接到 IKEv2 VPN 后,需要在终端中运行以下命令以通过 VPN 路由 IPv6 流量。每次连接后都需要运行此命令。断开 VPN 时,该路由将自动删除。接口通常为 ipsec0;如果同时有多个 VPN 连接处于活动状态,可能为 ipsec1 等,运行 ifconfig | grep ipsec 确认。

text
sudo route -n add -inet6 default -interface ipsec0

启用 IPv6 后,IKEv2 VPN 客户端将同时获得来自 192.168.43.0/24 地址池的 IPv4 地址和来自 fddd:500:500:500::/64 地址池的 IPv6 地址。VPN 服务器通过将客户端地址池的 IPv6 流量伪装(NAT)为服务器自身的 IPv6 地址,从而使 VPN 客户端能够通过该隧道获得完整的 IPv6 互联网访问。

要求:

  • VPN 服务器必须拥有可路由的全局单播 IPv6 地址(即以 2 或 3 开头的地址)。链路本地地址 (fe80::/10) 和 ULA 地址 (fc00::/7) 不满足要求。
  • Libreswan 5.0 或更新版本(VPN 安装脚本默认使用 5.x)。
  • IPv6 仅支持 IKEv2 模式。IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式不支持 IPv6。

要验证 IPv6 是否正常工作,请使用 IKEv2 连接到 VPN,然后检查你的 IPv6 地址,例如使用 test-ipv6.com。

你可以在安装 VPN 时选择指定自定义 IPv6 地址池子网,这是可选的。该子网必须是 /64 ULA 范围内的子网(推荐使用 fddd::/16)。

text
# 示例:为 IKEv2 模式指定自定义 IPv6 地址池子网
sudo VPN_IP6_NET=fddd:1234:5678:9012::/64 \
sh vpn.sh

注: VPN_IP6_NET 变量只能在初始 VPN 安装时指定。

转发端口到 VPN 客户端

在某些情况下,你可能想要将 VPN 服务器上的端口转发到一个已连接的 VPN 客户端。这可以通过在 VPN 服务器上添加 IPTables 规则来实现。

警告: 端口转发会将 VPN 客户端上的端口暴露给整个因特网,这可能会带来安全风险!不建议这样做,除非你的用例需要它。

注: 为 VPN 客户端分配的内网 IP 是动态的,而且客户端设备上的防火墙可能会阻止转发的流量。如果要将静态 IP 分配给 VPN 客户端,请参见 VPN 内网 IP 和流量。要找到为特定的客户端分配的 IP,可以查看该 VPN 客户端上的连接状态。

示例 1:将 VPN 服务器上的 TCP 端口 443 转发到位于 192.168.42.10 的 IPsec/L2TP 客户端。

text
# 获取默认网络接口名称
netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
iptables -I FORWARD 2 -i "$netif" -o ppp+ -p tcp --dport 443 -j ACCEPT
iptables -t nat -A PREROUTING -i "$netif" -p tcp --dport 443 -j DNAT --to 192.168.42.10

示例 2:将 VPN 服务器上的 UDP 端口 123 转发到位于 192.168.43.10 的 IKEv2(或 IPsec/XAuth)客户端。

text
# 获取默认网络接口名称
netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
iptables -I FORWARD 2 -i "$netif" -d 192.168.43.0/24 -p udp --dport 123 -j ACCEPT
iptables -t nat -A PREROUTING -i "$netif" ! -s 192.168.43.0/24 -p udp --dport 123 -j DNAT --to 192.168.43.10

如果你想要这些规则在重启后仍然有效,可以将这些命令添加到 /etc/rc.local。要删除添加的 IPTables 规则,请再次运行这些命令,但是将 -I FORWARD 2 替换为 -D FORWARD,并且将 -A PREROUTING 替换为 -D PREROUTING。

VPN 分流

在启用 VPN 分流 (split tunneling) 时,VPN 客户端将仅通过 VPN 隧道发送特定目标子网的流量。其他流量 不会 通过 VPN 隧道。这允许你通过 VPN 安全访问指定的网络,而无需通过 VPN 发送所有客户端的流量。VPN 分流有一些局限性,而且并非所有的 VPN 客户端都支持。

高级用户可以为 IPsec/XAuth ("Cisco IPsec") 和/或 IKEv2 模式启用 VPN 分流。这是可选的。展开查看详情。IPsec/L2TP 模式不支持此功能(Windows 除外,见下文)。

IPsec/XAuth ("Cisco IPsec") 模式:启用 VPN 分流 (split tunneling)

下面的示例 仅适用于 IPsec/XAuth ("Cisco IPsec") 模式。这些命令必须用 root 账户运行。

  1. 编辑 VPN 服务器上的 /etc/ipsec.conf。在 conn xauth-psk 小节中,将 leftsubnet=0.0.0.0/0 替换为你想要 VPN 客户端通过 VPN 隧道发送流量的子网。例如:
    对于单个子网:
    text
    leftsubnet=10.123.123.0/24
    对于多个子网(使用 leftsubnets):
    text
    leftsubnets="10.123.123.0/24,10.100.0.0/16"
  2. (重要) 重启 IPsec 服务:
    text
    service ipsec restart

IKEv2 模式:启用 VPN 分流 (split tunneling)

下面的示例 仅适用于 IKEv2 模式。这些命令必须用 root 账户运行。

  1. 编辑 VPN 服务器上的 /etc/ipsec.d/ikev2.conf。在 conn ikev2-cp 小节中,将 leftsubnet=0.0.0.0/0 替换为你想要 VPN 客户端通过 VPN 隧道发送流量的子网。例如:
    对于单个子网:
    text
    leftsubnet=10.123.123.0/24
    对于多个子网(使用 leftsubnets):
    text
    leftsubnets="10.123.123.0/24,10.100.0.0/16"
  2. (重要) 重启 IPsec 服务:
    text
    service ipsec restart

注: 高级用户可以为特定的 IKEv2 客户端设置不同的 VPN 分流配置。请参见 VPN 内网 IP 和流量部分并展开 "IKEv2 模式:为 VPN 客户端分配静态 IP"。在该部分中的示例的基础上,你可以将 leftsubnet=... 选项添加到特定 IKEv2 客户端的 conn 小节,然后重启 IPsec 服务。

另外,Windows 用户也可以通过手动添加路由的方式启用 VPN 分流:

  1. 右键单击系统托盘中的无线/网络图标。
  2. Windows 11: 选择 网络和 Internet 设置,然后在打开的页面中单击 高级网络设置。单击 更多网络适配器选项。
    Windows 10: 选择 打开"网络和 Internet"设置,然后在打开的页面中单击 网络和共享中心。单击左侧的 更改适配器设置。
    Windows 8/7: 选择 打开网络和共享中心。单击左侧的 更改适配器设置。
  3. 右键单击新的 VPN 连接,并选择 属性。
  4. 单击 网络 选项卡,选择 Internet Protocol Version 4 (TCP/IPv4),然后单击 属性。
  5. 单击 高级,然后取消选中 在远程网络上使用默认网关。
  6. 单击 确定 以关闭 属性 对话框。
  7. (重要) 断开 VPN 连接,然后重新连接。
  8. 假设你想要 VPN 客户端通过 VPN 隧道发送流量的子网是 10.123.123.0/24。打开提升权限命令提示符并运行以下命令之一。
    对于 IKEv2 和 IPsec/XAuth ("Cisco IPsec") 模式:
    text
    route add -p 10.123.123.0 mask 255.255.255.0 192.168.43.1
    对于 IPsec/L2TP 模式:
    text
    route add -p 10.123.123.0 mask 255.255.255.0 192.168.42.1
  9. 完成后,VPN 客户端将通过 VPN 隧道仅发送指定子网的流量。其他流量将绕过 VPN。

访问 VPN 服务器的网段

连接到 VPN 后,VPN 客户端通常可以访问与 VPN 服务器位于同一本地子网内的其他设备上运行的服务,而无需进行其他配置。例如,如果 VPN 服务器的本地子网为 192.168.0.0/24,并且一个 Nginx 服务器在 IP 192.168.0.2 上运行,则 VPN 客户端可以使用 IP 192.168.0.2来访问 Nginx 服务器。

请注意,如果 VPN 服务器具有多个网络接口(例如 eth0 和 eth1),并且你想要 VPN 客户端访问服务器上 不用于 Internet 访问的网络接口后面的本地子网,则需要进行额外的配置。在此情形下,你必须运行以下命令来添加 IPTables 规则。为了在重启后仍然有效,你可以将这些命令添加到 /etc/rc.local。

bash
# 将 eth1 替换为 VPN 服务器上你想要客户端访问的网络接口名称
netif=eth1
iptables -I FORWARD 2 -i "$netif" -o ppp+ -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -I FORWARD 2 -i ppp+ -o "$netif" -j ACCEPT
iptables -I FORWARD 2 -i "$netif" -d 192.168.43.0/24 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -I FORWARD 2 -s 192.168.43.0/24 -o "$netif" -j ACCEPT
iptables -t nat -I POSTROUTING -s 192.168.43.0/24 -o "$netif" -m policy --dir out --pol none -j MASQUERADE
iptables -t nat -I POSTROUTING -s 192.168.42.0/24 -o "$netif" -j MASQUERADE

VPN 服务器网段访问 VPN 客户端

在某些情况下,你可能需要从 VPN 服务器位于同一本地子网内的其他设备访问 VPN 客户端上的服务。这可以通过以下几个步骤实现。

假设 VPN 服务器 IP 是 10.1.0.2,你想要访问 VPN 客户端的设备的 IP 是 10.1.0.3。

  1. 在 VPN 服务器上添加 IPTables 规则以允许该流量。例如:
    text
    # 获取默认网络接口名称
    netif=$(ip -4 route list 0/0 | grep -m 1 -Po '(?<=dev )(\S+)')
    iptables -I FORWARD 2 -i "$netif" -o ppp+ -s 10.1.0.3 -j ACCEPT
    iptables -I FORWARD 2 -i "$netif" -d 192.168.43.0/24 -s 10.1.0.3 -j ACCEPT
  2. 在你想要访问 VPN 客户端的设备上添加路由规则。例如:
    text
    # 将 eth0 替换为设备的本地子网的网络接口名称
    route add -net 192.168.42.0 netmask 255.255.255.0 gw 10.1.0.2 dev eth0
    route add -net 192.168.43.0 netmask 255.255.255.0 gw 10.1.0.2 dev eth0

在 VPN 内网 IP 和流量小节了解 VPN 内网 IP 的更多信息。

更改 IPTables 规则

如果你想要在安装后更改 IPTables 规则,请编辑 /etc/iptables.rules 和/或 /etc/iptables/rules.v4 (Ubuntu/Debian),或者 /etc/sysconfig/iptables (CentOS/RHEL)。然后重启服务器。

如果启用了 IPv6 支持,相应的 ip6tables 规则将保存在 /etc/ip6tables.rules 和 /etc/iptables/rules.v6 (Ubuntu/Debian),或者 /etc/sysconfig/ip6tables (CentOS/RHEL)。

注: 如果你的服务器运行 CentOS Linux(或类似系统),并且在安装 VPN 时 firewalld 处于活动状态,则可能已配置 nftables。在这种情况下,编辑 /etc/sysconfig/nftables.conf 而不是 /etc/sysconfig/iptables。

部署 Google BBR 拥塞控制

VPN 服务器搭建完成后,可以通过部署 Google BBR 拥塞控制算法提升性能。

这通常只需要在配置文件 /etc/sysctl.conf 中插入设定即可完成。但是部分 Linux 发行版可能需要额外更新 Linux 内核。

详细的部署方法,可以参考这篇文档。

授权协议

版权所有 (C) 2021-2026 Lin Song


这个项目是以知识共享署名-相同方式共享3.0 许可协议授权。
必须署名: 请包括我的名字在任何衍生产品,并且让我知道你是如何改善它的!


File: docs/bbr.md

English | 中文

Advanced usage: Deploy Google BBR congestion control algorithm

Google BBR is a congestion control algorithm that could significantly increase server throughput and reduce latency.

Google BBR has been built into Linux kernel 4.9 and higher, but needs to be manually turned on.

To learn more about the Google BBR algorithm, see this official blog or this official repository.

Prepare

You can check the current Linux kernel version with the command uname -r. When the version is greater than or equal to 4.9, you can deploy BBR directly by referring to the instructions below.

Generally speaking, the kernel versions of Ubuntu 18.04+, Debian 10+, CentOS 8+ and RHEL 8+ are greater than 4.9. But for Amazon Linux 2, you need to update the kernel in the following ways before deploying Google BBR.

Amazon Linux 2

Amazon Linux 2 provides newer versions of the verified Linux kernel, which can be installed from the Extras repository.

  1. Install kernel-ng from the Extras repository
    bash
    sudo amazon-linux-extras install kernel-ng
  2. Update packages
    bash
    sudo yum update
  3. Restart the system
    bash
    sudo reboot
  4. Check the Linux kernel version
    bash
    uname -r

Deploy Google BBR

In this section, we will start Google BBR by modifying the configuration file.

  1. Backup /etc/sysctl.conf
    bash
    sudo cp /etc/sysctl.conf /etc/sysctl.conf.backup
  2. Modify /etc/sysctl.conf
    bash
    sudo vim /etc/sysctl.conf
    Add the following lines to the file
    text
    net.core.default_qdisc = fq
    net.ipv4.tcp_congestion_control = bbr
  3. Enable Google BBR
    First, check your server's kernel version using uname -r.
    For kernel versions >= 4.20, apply sysctl settings:
    bash
    sudo sysctl -p
    For kernel versions < 4.20, you must reboot the server:
    bash
    sudo reboot
  4. Check Google BBR status
    bash
    sudo sysctl net.ipv4.tcp_available_congestion_control
    # net.ipv4.tcp_available_congestion_control = reno cubic bbr
    sudo sysctl -n net.ipv4.tcp_congestion_control
    # bbr
    lsmod | grep bbr
    # tcp_bbr  16384  0

Document author

Copyright (C) 2022 Leo Liu
Translated by Lin Song


File: docs/bbr-zh.md

English | 中文

高级用法:部署 Google BBR 拥塞控制算法

Google BBR是一种拥塞控制算法,它能够显著提升服务器吞吐率并降低延迟。

Google BBR已经被内置于Linux内核4.9及更高版本中,但是需要手动开启。

关于Google BBR算法,可以在这篇官方博客或者这个官方库中找到更多信息。

准备

可以通过命令 uname -r 来查看当前Linux内核版本。版本大于等于4.9时,可以直接参照下方的说明部署BBR。

通常而言,Ubuntu 18.04+, Debian 10+,CentOS 8+及RHEL 8+的内核版本都大于4.9。但是对于Amazon Linux 2,需要通过以下的方式更新内核之后才能部署Google BBR。

Amazon Linux 2

Amazon Linux 2提供过经过验证的新版Linux内核,并可以通过启用预置的Extras库安装。

  1. 从Extras库安装 kernel-ng
    bash
    sudo amazon-linux-extras install kernel-ng
  2. 更新包
    bash
    sudo yum update
  3. 重启系统
    bash
    sudo reboot
  4. 检查Linux内核版本
    bash
    uname -r

部署 Google BBR

在这个部分,我们将通过修改配置文件启动Google BBR。

  1. 备份 /etc/sysctl.conf
    bash
    sudo cp /etc/sysctl.conf /etc/sysctl.conf.backup
  2. 修改 /etc/sysctl.conf
    bash
    sudo vim /etc/sysctl.conf
    在文件中增加以下行
    text
    net.core.default_qdisc = fq
    net.ipv4.tcp_congestion_control = bbr
  3. 启用Google BBR
    首先使用 uname -r 检查你的服务器的内核版本。
    对于内核版本 >= 4.20,应用 sysctl 设置:
    bash
    sudo sysctl -p
    对于内核版本 < 4.20,你必须重启服务器:
    bash
    sudo reboot
  4. 检查Google BBR状态
    bash
    sudo sysctl net.ipv4.tcp_available_congestion_control
    # net.ipv4.tcp_available_congestion_control = reno cubic bbr
    sudo sysctl -n net.ipv4.tcp_congestion_control
    # bbr
    lsmod | grep bbr
    # tcp_bbr  16384  0

文档作者

版权所有 (C) 2022 Leo Liu


File: docs/clients.md

English | 中文

Configure IPsec/L2TP VPN Clients

After setting up your own VPN server, follow these steps to configure your devices. IPsec/L2TP is natively supported by Android, iOS, OS X, and Windows. There is no additional software to install. Setup should only take a few minutes. In case you are unable to connect, first check to make sure the VPN credentials were entered correctly.


Windows

You may also connect using IKEv2 mode (recommended).

Windows 11

  1. Right-click on the wireless/network icon in your system tray.
  2. Select Network and Internet settings, then on the page that opens, click VPN.
  3. Click the Add VPN button.
  4. Select Windows (built-in) in the VPN provider drop-down menu.
  5. Enter anything you like in the Connection name field.
  6. Enter Your VPN Server IP in the Server name or address field.
  7. Select L2TP/IPsec with pre-shared key in the VPN type drop-down menu.
  8. Enter Your VPN IPsec PSK in the Pre-shared key field.
  9. Enter Your VPN Username in the User name field.
  10. Enter Your VPN Password in the Password field.
  11. Check the Remember my sign-in info checkbox.
  12. Click Save to save the VPN connection details.

Note: This one-time registry change is required if the VPN server and/or client is behind NAT (e.g. home router).

To connect to the VPN: Click the Connect button, or click on the wireless/network icon in your system tray, click VPN, then select the new VPN entry and click Connect. If prompted, enter Your VPN Username and Password, then click OK. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Windows 10 and 8

  1. Right-click on the wireless/network icon in your system tray.
  2. Select Open Network & Internet settings, then on the page that opens, click Network and Sharing Center.
  3. Click Set up a new connection or network.
  4. Select Connect to a workplace and click Next.
  5. Click Use my Internet connection (VPN).
  6. Enter Your VPN Server IP in the Internet address field.
  7. Enter anything you like in the Destination name field, and then click Create.
  8. Return to Network and Sharing Center. On the left, click Change adapter settings.
  9. Right-click on the new VPN entry and choose Properties.
  10. Click the Security tab. Select "Layer 2 Tunneling Protocol with IPsec (L2TP/IPSec)" for the Type of VPN.
  11. Click Allow these protocols. Check the "Challenge Handshake Authentication Protocol (CHAP)" and "Microsoft CHAP Version 2 (MS-CHAP v2)" checkboxes.
  12. Click the Advanced settings button.
  13. Select Use preshared key for authentication and enter Your VPN IPsec PSK for the Key.
  14. Click OK to close the Advanced settings.
  15. Click OK to save the VPN connection details.

Note: This one-time registry change is required if the VPN server and/or client is behind NAT (e.g. home router).

To connect to the VPN: Click on the wireless/network icon in your system tray, select the new VPN entry, and click Connect. If prompted, enter Your VPN Username and Password, then click OK. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Alternatively, instead of following the steps above, you may create the VPN connection using these Windows PowerShell commands. Replace Your VPN Server IP and Your VPN IPsec PSK with your own values, enclosed in single quotes:

console
# Disable persistent command history
Set-PSReadlineOption –HistorySaveStyle SaveNothing
# Create VPN connection
Add-VpnConnection -Name 'My IPsec VPN' -ServerAddress 'Your VPN Server IP' `
  -L2tpPsk 'Your VPN IPsec PSK' -TunnelType L2tp -EncryptionLevel Required `
  -AuthenticationMethod Chap,MSChapv2 -Force -RememberCredential -PassThru
# Ignore the data encryption warning (data is encrypted in the IPsec tunnel)

Windows 7, Vista and XP

  1. Click on the Start Menu and go to the Control Panel.
  2. Go to the Network and Internet section.
  3. Click Network and Sharing Center.
  4. Click Set up a new connection or network.
  5. Select Connect to a workplace and click Next.
  6. Click Use my Internet connection (VPN).
  7. Enter Your VPN Server IP in the Internet address field.
  8. Enter anything you like in the Destination name field.
  9. Check the Don't connect now; just set it up so I can connect later checkbox.
  10. Click Next.
  11. Enter Your VPN Username in the User name field.
  12. Enter Your VPN Password in the Password field.
  13. Check the Remember this password checkbox.
  14. Click Create, and then Close.
  15. Return to Network and Sharing Center. On the left, click Change adapter settings.
  16. Right-click on the new VPN entry and choose Properties.
  17. Click the Options tab and uncheck Include Windows logon domain.
  18. Click the Security tab. Select "Layer 2 Tunneling Protocol with IPsec (L2TP/IPSec)" for the Type of VPN.
  19. Click Allow these protocols. Check the "Challenge Handshake Authentication Protocol (CHAP)" and "Microsoft CHAP Version 2 (MS-CHAP v2)" checkboxes.
  20. Click the Advanced settings button.
  21. Select Use preshared key for authentication and enter Your VPN IPsec PSK for the Key.
  22. Click OK to close the Advanced settings.
  23. Click OK to save the VPN connection details.

Note: This one-time registry change is required if the VPN server and/or client is behind NAT (e.g. home router).

To connect to the VPN: Click on the wireless/network icon in your system tray, select the new VPN entry, and click Connect. If prompted, enter Your VPN Username and Password, then click OK. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

OS X (macOS)

macOS 13 (Ventura) and newer

You may also connect using IKEv2 (recommended) or IPsec/XAuth mode.

  1. Open System Settings and go to the Network section.
  2. Click VPN on the right hand side of the window.
  3. Click the Add VPN Configuration drop-down menu and select L2TP over IPSec.
  4. In the window that opens, enter anything you like for the Display name.
  5. Leave Configuration as Default.
  6. Enter Your VPN Server IP for the Server address.
  7. Enter Your VPN Username for the Account name.
  8. Select Password from the User authentication drop-down menu.
  9. Enter Your VPN Password for the Password.
  10. Select Shared secret from the Machine authentication drop-down menu.
  11. Enter Your VPN IPsec PSK for the Shared secret.
  12. Leave the Group name field blank.
  13. (Important before you click create) Click the Options tab, and make sure the Send all traffic over VPN connection toggle is ON.
  14. (Important before you click create) Click the TCP/IP tab, and select Link-local only from the Configure IPv6 drop-down menu.
  15. Click Create to save the VPN configuration.
  16. To show VPN status in your menu bar and for shortcut access, go to the Control Center section of System Settings. Scroll to the bottom and select Show in Menu Bar from the VPN drop-down menu.

To connect to the VPN: Use the menu bar icon, or go to the VPN section of System Settings and toggle the switch for your VPN configuration. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

macOS 12 (Monterey) and older

You may also connect using IKEv2 (recommended) or IPsec/XAuth mode.

  1. Open System Preferences and go to the Network section.
  2. Click the + button in the lower-left corner of the window.
  3. Select VPN from the Interface drop-down menu.
  4. Select L2TP over IPSec from the VPN Type drop-down menu.
  5. Enter anything you like for the Service Name.
  6. Click Create.
  7. Enter Your VPN Server IP for the Server Address.
  8. Enter Your VPN Username for the Account Name.
  9. Click the Authentication Settings button.
  10. In the User Authentication section, select the Password radio button and enter Your VPN Password.
  11. In the Machine Authentication section, select the Shared Secret radio button and enter Your VPN IPsec PSK.
  12. Click OK.
  13. Check the Show VPN status in menu bar checkbox.
  14. (Important) Click the Advanced button and make sure the Send all traffic over VPN connection checkbox is checked.
  15. (Important) Click the TCP/IP tab, and make sure Link-local only is selected in the Configure IPv6 section.
  16. Click OK to close the Advanced settings, and then click Apply to save the VPN connection information.

To connect to the VPN: Use the menu bar icon, or go to the Network section of System Preferences, select the VPN and choose Connect. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Android

Important: Android users should instead connect using IKEv2 mode (recommended), which is more secure. Android 12+ only supports IKEv2 mode. The native VPN client in Android uses the less secure modp1024 (DH group 2) for the IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes.

If you still want to connect using IPsec/L2TP mode, you must first edit /etc/ipsec.conf on the VPN server. Find the line ike=... and append ,aes256-sha2;modp1024,aes128-sha1;modp1024 at the end. Save the file and run service ipsec restart.

Docker users: Add VPN_ENABLE_MODP1024=yes to your env file, then re-create the Docker container.

After that, follow the steps below on your Android device:

  1. Launch the Settings application.
  2. Tap "Network & internet". Or, if using Android 7 or earlier, tap More... in the Wireless & networks section.
  3. Tap VPN.
  4. Tap Add VPN Profile or the + icon at top-right of screen.
  5. Enter anything you like in the Name field.
  6. Select L2TP/IPSec PSK in the Type drop-down menu.
  7. Enter Your VPN Server IP in the Server address field.
  8. Leave the L2TP secret field blank.
  9. Leave the IPSec identifier field blank.
  10. Enter Your VPN IPsec PSK in the IPSec pre-shared key field.
  11. Tap Save.
  12. Tap the new VPN connection.
  13. Enter Your VPN Username in the Username field.
  14. Enter Your VPN Password in the Password field.
  15. Check the Save account information checkbox.
  16. Tap Connect.

Once connected, you will see a VPN icon in the notification bar. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

iOS

You may also connect using IKEv2 (recommended) or IPsec/XAuth mode.

  1. Go to Settings -> General -> VPN.
  2. Tap Add VPN Configuration....
  3. Tap Type. Select L2TP and go back.
  4. Tap Description and enter anything you like.
  5. Tap Server and enter Your VPN Server IP.
  6. Tap Account and enter Your VPN Username.
  7. Tap Password and enter Your VPN Password.
  8. Tap Secret and enter Your VPN IPsec PSK.
  9. Make sure the Send All Traffic switch is ON.
  10. Tap Done.
  11. Slide the VPN switch ON.

Once connected, you will see a VPN icon in the status bar. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Chrome OS

You may also connect using IKEv2 mode (recommended).

  1. Go to Settings -> Network.
  2. Click Add connection, then click Add built-in VPN.
  3. Enter anything you like for the Service name.
  4. Select L2TP/IPsec in the Provider type drop-down menu.
  5. Enter Your VPN Server IP for the Server hostname.
  6. Select Pre-shared key in the Authentication type drop-down menu.
  7. Enter Your VPN Username for the Username.
  8. Enter Your VPN Password for the Password.
  9. Enter Your VPN IPsec PSK for the Pre-shared key.
  10. Leave other fields blank.
  11. Enable Save identity and password.
  12. Click Connect.

Once connected, you will see a VPN icon overlay on the network status icon. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Linux

You may also connect using IKEv2 mode (recommended).

Ubuntu Linux

Ubuntu 18.04 (and newer) users can install the network-manager-l2tp-gnome package using apt, then configure the IPsec/L2TP VPN client using the GUI.

  1. Go to Settings -> Network -> VPN. Click the + button.
  2. Select Layer 2 Tunneling Protocol (L2TP).
  3. Enter anything you like in the Name field.
  4. Enter Your VPN Server IP for the Gateway.
  5. Enter Your VPN Username for the User name.
  6. Right-click the ? in the Password field, select Store the password only for this user.
  7. Enter Your VPN Password for the Password.
  8. Leave the NT Domain field blank.
  9. Click the IPsec Settings... button.
  10. Check the Enable IPsec tunnel to L2TP host checkbox.
  11. Leave the Gateway ID field blank.
  12. Enter Your VPN IPsec PSK for the Pre-shared key.
  13. Expand the Advanced section.
  14. Enter aes128-sha1-modp2048 for the Phase1 Algorithms.
  15. Enter aes128-sha1 for the Phase2 Algorithms.
  16. Click OK, then click Add to save the VPN connection information.
  17. Turn the VPN switch ON.

If you get an error when trying to connect, try this fix.

Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

Fedora and CentOS

Fedora 28 (and newer) and CentOS 8/7 users can connect using IPsec/XAuth mode.

Other Linux

First check here to see if the network-manager-l2tp and network-manager-l2tp-gnome packages are available for your Linux distribution. If yes, install them (select strongSwan) and follow the instructions above. Alternatively, you may configure Linux VPN clients using the command line.

Configure Linux VPN clients using the command line

Advanced users can configure Linux VPN clients using the command line. Alternatively, you may connect using IKEv2 mode (recommended), or configure using the GUI. Instructions below are inspired by the work of Peter Sanford. Commands must be run as root on your VPN client.

To set up the VPN client, first install the following packages:

bash
# Ubuntu and Debian
apt-get update
apt-get install strongswan xl2tpd net-tools

# Fedora
yum install strongswan xl2tpd net-tools

# CentOS
yum install epel-release
yum --enablerepo=epel install strongswan xl2tpd net-tools

Create VPN variables (replace with actual values):

bash
VPN_SERVER_IP='your_vpn_server_ip'
VPN_IPSEC_PSK='your_ipsec_pre_shared_key'
VPN_USER='your_vpn_username'
VPN_PASSWORD='your_vpn_password'

Configure strongSwan:

bash
cat > /etc/ipsec.conf <<EOF
# ipsec.conf - strongSwan IPsec configuration file

conn myvpn
  auto=add
  keyexchange=ikev1
  authby=secret
  type=transport
  left=%defaultroute
  leftprotoport=17/1701
  rightprotoport=17/1701
  right=$VPN_SERVER_IP
  ike=aes128-sha1-modp2048
  esp=aes128-sha1
EOF

cat > /etc/ipsec.secrets <<EOF
: PSK "$VPN_IPSEC_PSK"
EOF

chmod 600 /etc/ipsec.secrets

# For CentOS and Fedora ONLY
mv /etc/strongswan/ipsec.conf /etc/strongswan/ipsec.conf.old 2>/dev/null
mv /etc/strongswan/ipsec.secrets /etc/strongswan/ipsec.secrets.old 2>/dev/null
ln -s /etc/ipsec.conf /etc/strongswan/ipsec.conf
ln -s /etc/ipsec.secrets /etc/strongswan/ipsec.secrets

Configure xl2tpd:

bash
cat > /etc/xl2tpd/xl2tpd.conf <<EOF
[lac myvpn]
lns = $VPN_SERVER_IP
ppp debug = yes
pppoptfile = /etc/ppp/options.l2tpd.client
length bit = yes
EOF

cat > /etc/ppp/options.l2tpd.client <<EOF
ipcp-accept-local
ipcp-accept-remote
refuse-eap
require-chap
noccp
noauth
mtu 1280
mru 1280
noipdefault
defaultroute
usepeerdns
connect-delay 5000
name "$VPN_USER"
password "$VPN_PASSWORD"
EOF

chmod 600 /etc/ppp/options.l2tpd.client

The VPN client setup is now complete. Follow the steps below to connect.

Note: You must repeat all steps below every time you try to connect to the VPN.

Create xl2tpd control file:

bash
mkdir -p /var/run/xl2tpd
touch /var/run/xl2tpd/l2tp-control

Restart services:

bash
service strongswan restart

# For Ubuntu, if strongswan service not found
ipsec restart

service xl2tpd restart

Start the IPsec connection:

bash
# Ubuntu and Debian
ipsec up myvpn

# CentOS and Fedora
strongswan up myvpn

Start the L2TP connection:

bash
echo "c myvpn" > /var/run/xl2tpd/l2tp-control

Run ifconfig and check the output. You should now see a new interface ppp0.

Check your existing default route:

bash
ip route

Find this line in the output: default via X.X.X.X .... Write down this gateway IP for use in the two commands below.

Exclude your VPN server's public IP from the new default route (replace with actual value):

bash
route add YOUR_VPN_SERVER_PUBLIC_IP gw X.X.X.X

If your VPN client is a remote server, you must also exclude your Local PC's public IP from the new default route, to prevent your SSH session from being disconnected (replace with actual value):

bash
route add YOUR_LOCAL_PC_PUBLIC_IP gw X.X.X.X

Add a new default route to start routing traffic via the VPN server:

bash
route add default dev ppp0

The VPN connection is now complete. Verify that your traffic is being routed properly:

bash
wget -qO- http://ipv4.icanhazip.com; echo

The above command should return Your VPN Server IP.

To stop routing traffic via the VPN server:

bash
route del default dev ppp0

To disconnect:

bash
# Ubuntu and Debian
echo "d myvpn" > /var/run/xl2tpd/l2tp-control
ipsec down myvpn

# CentOS and Fedora
echo "d myvpn" > /var/run/xl2tpd/l2tp-control
strongswan down myvpn

IKEv1 troubleshooting

Read this in other languages: English, 中文.

See also: IKEv2 troubleshooting and Advanced usage.

Check logs and VPN status

Commands below must be run as root (or using sudo).

First, restart services on the VPN server:

bash
service ipsec restart
service xl2tpd restart

Docker users: Run docker restart ipsec-vpn-server.

Then reboot your VPN client device, and retry the connection. If still unable to connect, try removing and recreating the VPN connection. Make sure that the VPN server address and VPN credentials are entered correctly.

For servers with an external firewall (e.g. EC2/GCE), open UDP ports 500 and 4500 for the VPN.

Check the Libreswan (IPsec) and xl2tpd logs for errors:

bash
# Ubuntu & Debian
grep pluto /var/log/auth.log
grep xl2tpd /var/log/syslog

# CentOS/RHEL, Rocky Linux, AlmaLinux & Oracle Linux
grep pluto /var/log/secure
grep xl2tpd /var/log/messages

# Alpine Linux
grep pluto /var/log/messages
grep xl2tpd /var/log/messages

If Libreswan logs errors such as Protocol not supported (errno 93) or Adding IPsec SA failed, see IPsec SA errors.

Check the status of the IPsec VPN server:

bash
ipsec status

Show currently established VPN connections:

bash
ipsec trafficstatus

Windows error 809

Error 809: The network connection between your computer and the VPN server could not be established because the remote server is not responding. This could be because one of the network devices (e.g, firewalls, NAT, routers, etc) between your computer and the remote server is not configured to allow VPN connections. Please contact your Administrator or your service provider to determine which device may be causing the problem.

Note: The registry change below is only required if you use IPsec/L2TP mode to connect to the VPN. It is NOT required for the IKEv2 and IPsec/XAuth modes.

To fix this error, a one-time registry change is required because the VPN server and/or client is behind NAT (e.g. home router). Download and import the .reg file below, or run the following from an elevated command prompt. You must reboot your PC when finished.

  • For Windows Vista, 7, 8, 10 and 11 (download .reg file)

    console
    REG ADD HKLM\SYSTEM\CurrentControlSet\Services\PolicyAgent /v AssumeUDPEncapsulationContextOnSendRule /t REG_DWORD /d 0x2 /f
  • For Windows XP ONLY (download .reg file)

    console
    REG ADD HKLM\SYSTEM\CurrentControlSet\Services\IPSec /v AssumeUDPEncapsulationContextOnSendRule /t REG_DWORD /d 0x2 /f

Although uncommon, some Windows systems disable IPsec encryption, causing the connection to fail. To re-enable it, run the following command and reboot your PC.

  • For Windows XP, Vista, 7, 8, 10 and 11 (download .reg file)

    console
    REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RasMan\Parameters /v ProhibitIpSec /t REG_DWORD /d 0x0 /f

Windows error 789 or 691

Error 789: The L2TP connection attempt failed because the security layer encountered a processing error during initial negotiations with the remote computer.

Error 691: The remote connection was denied because the user name and password combination you provided is not recognized, or the selected authentication protocol is not permitted on the remote access server.

For error 789, click here for troubleshooting information. For error 691, you may try removing and recreating the VPN connection, by following the instructions in this document. Make sure that the VPN credentials are entered correctly.

Windows error 628 or 766

Error 628: The connection was terminated by the remote computer before it could be completed.

Error 766: A certificate could not be found. Connections that use the L2TP protocol over IPSec require the installation of a machine certificate, also known as a computer certificate.

To fix these errors, please follow these steps:

  1. Right-click on the wireless/network icon in your system tray.
  2. Windows 11: Select Network and Internet settings, then on the page that opens, click Advanced network settings. Click More network adapter options.
    Windows 10: Select Open Network & Internet settings, then on the page that opens, click Network and Sharing Center. On the left, click Change adapter settings.
    Windows 8/7: Select Open Network and Sharing Center. On the left, click Change adapter settings.
  3. Right-click on the new VPN connection, and choose Properties.
  4. Click the Security tab. Select "Layer 2 Tunneling Protocol with IPsec (L2TP/IPSec)" for Type of VPN.
  5. Click Allow these protocols. Check the "Challenge Handshake Authentication Protocol (CHAP)" and "Microsoft CHAP Version 2 (MS-CHAP v2)" checkboxes.
  6. Click the Advanced settings button.
  7. Select Use preshared key for authentication and enter Your VPN IPsec PSK for the Key.
  8. Click OK to close the Advanced settings.
  9. Click OK to save the VPN connection details.

Windows 10 connecting

If using Windows 10 and the VPN is stuck on "connecting" for more than a few minutes, try these steps:

  1. Right-click on the wireless/network icon in your system tray.
  2. Select Open Network & Internet settings, then on the page that opens, click VPN on the left.
  3. Select the new VPN entry, then click Connect. If prompted, enter Your VPN Username and Password, then click OK.

Windows 10/11 upgrades

After upgrading Windows 10/11 version (e.g. from 21H2 to 22H2), you may need to re-apply the fix above for Windows Error 809 and reboot.

Windows DNS leaks and IPv6

Windows 8, 10 and 11 use "smart multi-homed name resolution" by default, which may cause "DNS leaks" when using the native IPsec VPN client if your DNS servers on the Internet adapter are from the local network segment. To fix, you may either disable smart multi-homed name resolution, or configure your Internet adapter to use DNS servers outside your local network (e.g. 8.8.8.8 and 8.8.4.4). When finished, reboot your PC.

In addition, if your computer has IPv6 enabled, all IPv6 traffic (including DNS queries) will bypass the VPN. Learn how to disable IPv6 in Windows.

If you need IPv6 support through the VPN, try IKEv2 mode (see IPv6 support, requires a VPN server with a public IPv6 address), or try OpenVPN or WireGuard.

Android/Linux MTU/MSS issues

Some Android devices and Linux systems have MTU/MSS issues, that they are able to connect to the VPN using IPsec/XAuth ("Cisco IPsec") or IKEv2 mode, but cannot open websites. If you encounter this problem, try running the following commands on the VPN server. If successful, you may add these commands to /etc/rc.local to persist after reboot.

text
iptables -t mangle -A FORWARD -m policy --pol ipsec --dir in \
  -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 \
  -j TCPMSS --set-mss 1360
iptables -t mangle -A FORWARD -m policy --pol ipsec --dir out \
  -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 \
  -j TCPMSS --set-mss 1360

echo 1 > /proc/sys/net/ipv4/ip_no_pmtu_disc

Docker users: Instead of running the commands above, you may apply this fix by adding VPN_ANDROID_MTU_FIX=yes to your env file, then re-create the Docker container.

Reference: [1].

macOS send traffic over VPN

OS X (macOS) users: If you can successfully connect using IPsec/L2TP mode, but your public IP does not show Your VPN Server IP, read the macOS section above and complete these steps. Save VPN configuration and re-connect.

For macOS 13 (Ventura) and newer:

  1. Click the Options tab, and make sure the Send all traffic over VPN connection toggle is ON.
  2. Click the TCP/IP tab, and select Link-local only from the Configure IPv6 drop-down menu.

For macOS 12 (Monterey) and older:

  1. Click the Advanced button and make sure the Send all traffic over VPN connection checkbox is checked.
  2. Click the TCP/IP tab, and make sure Link-local only is selected in the Configure IPv6 section.

After trying the steps above, if your computer is still not sending traffic over the VPN, check the service order. From the main network preferences screen, select "set service order" in the cog drop down under the list of connections. Drag the VPN connection to the top.

iOS/Android sleep mode

To save battery, iOS devices (iPhone/iPad) will automatically disconnect Wi-Fi shortly after the screen turns off (sleep mode). As a result, the IPsec VPN disconnects. This behavior is by design and cannot be configured.

If you need the VPN to auto-reconnect when the device wakes up, you may connect using IKEv2 mode (recommended) and enable the "VPN On Demand" feature. Alternatively, you may try OpenVPN instead, which has support for options such as "Reconnect on Wakeup" and "Seamless Tunnel".


Android devices may also disconnect Wi-Fi after entering sleep mode. You may try enabling the "Always-on VPN" option to stay connected. Learn more here.

Debian kernel

Debian users: Run uname -r to check your server's Linux kernel version. If it contains the word "cloud", and /dev/ppp is missing, then the kernel lacks ppp support and cannot use IPsec/L2TP mode. The VPN setup scripts try to detect this and show a warning. In this case, you may instead use IKEv2 or IPsec/XAuth mode to connect to the VPN.

To fix the issue with IPsec/L2TP mode, you may switch to the standard Linux kernel by installing e.g. the linux-image-amd64 package. Then update the default kernel in GRUB and reboot your server.

License

Note: This license applies to this document only.

Copyright (C) 2016-2026 Lin Song
Inspired by the work of Joshua Lund

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.


File: docs/clients-xauth.md

English | 中文

Configure IPsec/XAuth VPN Clients

After setting up your own VPN server, follow these steps to configure your devices. IPsec/XAuth ("Cisco IPsec") is natively supported by Android, iOS and OS X. There is no additional software to install. Windows users can use the free Shrew Soft client. In case you are unable to connect, first check to make sure the VPN credentials were entered correctly.

IPsec/XAuth mode is also called "Cisco IPsec". This mode is generally faster than IPsec/L2TP with less overhead.


Windows

You may also connect using IKEv2 (recommended) or IPsec/L2TP mode. No additional software is required.

  1. Download and install the free Shrew Soft VPN client. When prompted during install, select Standard Edition.
    Note: This VPN client does NOT support Windows 10/11.
  2. Click Start Menu -> All Programs -> ShrewSoft VPN Client -> VPN Access Manager
  3. Click the Add (+) button on toolbar.
  4. Enter Your VPN Server IP in the Host Name or IP Address field.
  5. Click the Authentication tab. Select Mutual PSK + XAuth from the Authentication Method drop-down menu.
  6. Under the Local Identity sub-tab, select IP Address from the Identification Type drop-down menu.
  7. Click the Credentials sub-tab. Enter Your VPN IPsec PSK in the Pre Shared Key field.
  8. Click the Phase 1 tab. Select main from the Exchange Type drop-down menu.
  9. Click the Phase 2 tab. Select sha1 from the HMAC Algorithm drop-down menu.
  10. Click Save to save the VPN connection details.
  11. Select the new VPN connection. Click the Connect button on toolbar.
  12. Enter Your VPN Username in the Username field.
  13. Enter Your VPN Password in the Password field.
  14. Click Connect.

Once connected, you will see tunnel enabled in the VPN Connect status window. Click the "Network" tab, and confirm that Established - 1 is displayed under "Security Associations". You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

OS X (macOS)

macOS 13 (Ventura) and newer

You may also connect using IKEv2 (recommended) or IPsec/L2TP mode.

  1. Open System Settings and go to the Network section.
  2. Click VPN on the right hand side of the window.
  3. Click the Add VPN Configuration drop-down menu and select Cisco IPSec.
  4. In the window that opens, enter anything you like for the Display name.
  5. Enter Your VPN Server IP for the Server address.
  6. Enter Your VPN Username for the Account name.
  7. Enter Your VPN Password for the Password.
  8. Select Shared secret from the Type drop-down menu.
  9. Enter Your VPN IPsec PSK for the Shared secret.
  10. Leave the Group name field blank.
  11. Click Create to save the VPN configuration.
  12. To show VPN status in your menu bar and for shortcut access, go to the Control Center section of System Settings. Scroll to the bottom and select Show in Menu Bar from the VPN drop-down menu.

To connect to the VPN: Use the menu bar icon, or go to the VPN section of System Settings and toggle the switch for your VPN configuration. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

macOS 12 (Monterey) and older

You may also connect using IKEv2 (recommended) or IPsec/L2TP mode.

  1. Open System Preferences and go to the Network section.
  2. Click the + button in the lower-left corner of the window.
  3. Select VPN from the Interface drop-down menu.
  4. Select Cisco IPSec from the VPN Type drop-down menu.
  5. Enter anything you like for the Service Name.
  6. Click Create.
  7. Enter Your VPN Server IP for the Server Address.
  8. Enter Your VPN Username for the Account Name.
  9. Enter Your VPN Password for the Password.
  10. Click the Authentication Settings button.
  11. In the Machine Authentication section, select the Shared Secret radio button and enter Your VPN IPsec PSK.
  12. Leave the Group Name field blank.
  13. Click OK.
  14. Check the Show VPN status in menu bar checkbox.
  15. Click Apply to save the VPN connection information.

To connect to the VPN: Use the menu bar icon, or go to the Network section of System Preferences, select the VPN and choose Connect. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Android

Important: Android users should instead connect using IKEv2 mode (recommended), which is more secure. Android 12+ only supports IKEv2 mode. The native VPN client in Android uses the less secure modp1024 (DH group 2) for the IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes.

If you still want to connect using IPsec/XAuth mode, you must first edit /etc/ipsec.conf on the VPN server. Find the line ike=... and append ,aes256-sha2;modp1024,aes128-sha1;modp1024 at the end. Save the file and run service ipsec restart.

Docker users: Add VPN_ENABLE_MODP1024=yes to your env file, then re-create the Docker container.

After that, follow the steps below on your Android device:

  1. Launch the Settings application.
  2. Tap "Network & internet". Or, if using Android 7 or earlier, tap More... in the Wireless & networks section.
  3. Tap VPN.
  4. Tap Add VPN Profile or the + icon at top-right of screen.
  5. Enter anything you like in the Name field.
  6. Select IPSec Xauth PSK in the Type drop-down menu.
  7. Enter Your VPN Server IP in the Server address field.
  8. Leave the IPSec identifier field blank.
  9. Enter Your VPN IPsec PSK in the IPSec pre-shared key field.
  10. Tap Save.
  11. Tap the new VPN connection.
  12. Enter Your VPN Username in the Username field.
  13. Enter Your VPN Password in the Password field.
  14. Check the Save account information checkbox.
  15. Tap Connect.

Once connected, you will see a VPN icon in the notification bar. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

iOS

You may also connect using IKEv2 (recommended) or IPsec/L2TP mode.

  1. Go to Settings -> General -> VPN.
  2. Tap Add VPN Configuration....
  3. Tap Type. Select IPSec and go back.
  4. Tap Description and enter anything you like.
  5. Tap Server and enter Your VPN Server IP.
  6. Tap Account and enter Your VPN Username.
  7. Tap Password and enter Your VPN Password.
  8. Leave the Group Name field blank.
  9. Tap Secret and enter Your VPN IPsec PSK.
  10. Tap Done.
  11. Slide the VPN switch ON.

Once connected, you will see a VPN icon in the status bar. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Linux

You may also connect using IKEv2 mode (recommended).

Fedora and CentOS

Fedora 28 (and newer) and CentOS 8/7 users can install the NetworkManager-libreswan-gnome package using yum, then configure the IPsec/XAuth VPN client using the GUI.

  1. Go to Settings -> Network -> VPN. Click the + button.
  2. Select IPsec based VPN.
  3. Enter anything you like in the Name field.
  4. Enter Your VPN Server IP for the Gateway.
  5. Select IKEv1 (XAUTH) in the Type drop-down menu.
  6. Enter Your VPN Username for the User name.
  7. Right-click the ? in the User password field, select Store the password only for this user.
  8. Enter Your VPN Password for the User password.
  9. Leave the Group name field blank.
  10. Right-click the ? in the Secret field, select Store the password only for this user.
  11. Enter Your VPN IPsec PSK for the Secret.
  12. Leave the Remote ID field blank.
  13. Click Add to save the VPN connection information.
  14. Turn the VPN switch ON.

Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

Other Linux

Other Linux users can connect using IPsec/L2TP mode.

License

Note: This license applies to this document only.

Copyright (C) 2016-2026 Lin Song
Inspired by the work of Joshua Lund

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.


File: docs/clients-xauth-zh.md

English | 中文

配置 IPsec/XAuth VPN 客户端

在成功搭建自己的 VPN 服务器之后,按照下面的步骤来配置你的设备。IPsec/XAuth ("Cisco IPsec") 在 Android, iOS 和 OS X 上均受支持,无需安装额外的软件。Windows 用户可以使用免费的 Shrew Soft 客户端。如果无法连接,请首先检查是否输入了正确的 VPN 登录凭证。

IPsec/XAuth 模式也称为 "Cisco IPsec"。该模式通常能够比 IPsec/L2TP 更高效地传输数据(较低的额外开销)。


Windows

你也可以使用 IKEv2(推荐)或者 IPsec/L2TP 模式连接。无需安装额外的软件。

  1. 下载并安装免费的 Shrew Soft VPN 客户端。在安装时请选择 Standard Edition。
    注: 该 VPN 客户端 不支持 Windows 10/11。
  2. 单击开始菜单 -> 所有程序 -> ShrewSoft VPN Client -> VPN Access Manager
  3. 单击工具栏中的 Add (+) 按钮。
  4. 在 Host Name or IP Address 字段中输入你的 VPN 服务器 IP。
  5. 单击 Authentication 选项卡,从 Authentication Method 下拉菜单中选择 Mutual PSK + XAuth。
  6. 在 Local Identity 子选项卡中,从 Identification Type 下拉菜单中选择 IP Address。
  7. 单击 Credentials 子选项卡,并在 Pre Shared Key 字段中输入你的 VPN IPsec PSK。
  8. 单击 Phase 1 选项卡,从 Exchange Type 下拉菜单中选择 main。
  9. 单击 Phase 2 选项卡,从 HMAC Algorithm 下拉菜单中选择 sha1。
  10. 单击 Save 保存 VPN 连接的详细信息。
  11. 选择新添加的 VPN 连接。单击工具栏中的 Connect 按钮。
  12. 在 Username 字段中输入你的 VPN 用户名。
  13. 在 Password 字段中输入你的 VPN 密码。
  14. 单击 Connect。

连接成功后,你会在 VPN Connect 状态窗口中看到 tunnel enabled 字样。单击 "Network" 选项卡,并确认 Established - 1 显示在 "Security Associations" 下面。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

OS X (macOS)

macOS 13 (Ventura) 及以上

你也可以使用 IKEv2(推荐)或者 IPsec/L2TP 模式连接。

  1. 打开系统设置并转到网络部分。
  2. 在窗口右方单击 VPN。
  3. 从 添加VPN配置 下拉菜单选择 Cisco IPSec。
  4. 在打开的窗口中的 显示名称 字段中输入任意内容。
  5. 在 服务器地址 字段中输入你的 VPN 服务器 IP。
  6. 在 帐户名称 字段中输入你的 VPN 用户名。
  7. 在 密码 字段中输入你的 VPN 密码。
  8. 从 类型 下拉菜单选择 共享密钥。
  9. 在 共享密钥 字段中输入你的 VPN IPsec PSK。
  10. 保持 群组名称 字段空白。
  11. 单击 创建 保存 VPN 连接信息。
  12. 如果要在菜单栏显示 VPN 状态并快速访问相关设置,你可以转到系统设置的控制中心部分,滚动到页面底部并在 VPN 下拉菜单选择 在菜单栏中显示。

要连接到 VPN:使用菜单栏中的图标,或者打开系统设置的 VPN 部分并启用 VPN 连接。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

macOS 12 (Monterey) 及以下

你也可以使用 IKEv2(推荐)或者 IPsec/L2TP 模式连接。

  1. 打开系统偏好设置并转到网络部分。
  2. 在窗口左下角单击 + 按钮。
  3. 从 接口 下拉菜单选择 VPN。
  4. 从 VPN类型 下拉菜单选择 Cisco IPSec。
  5. 在 服务名称 字段中输入任意内容。
  6. 单击 创建。
  7. 在 服务器地址 字段中输入你的 VPN 服务器 IP。
  8. 在 帐户名称 字段中输入你的 VPN 用户名。
  9. 在 密码 字段中输入你的 VPN 密码。
  10. 单击 认证设置 按钮。
  11. 在 机器认证 部分,选择 共享的密钥 单选按钮,然后输入你的 VPN IPsec PSK。
  12. 保持 群组名称 字段空白。
  13. 单击 好。
  14. 选中 在菜单栏中显示 VPN 状态 复选框。
  15. 单击 应用 保存 VPN 连接信息。

要连接到 VPN:使用菜单栏中的图标,或者打开系统偏好设置的网络部分,选择 VPN 并单击 连接。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

Android

重要: Android 用户应该使用更安全的 IKEv2 模式连接(推荐)。Android 12+ 仅支持 IKEv2 模式。Android 系统自带的 VPN 客户端对 IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式使用安全性较低的 modp1024 (DH group 2)。

如果你仍然想用 IPsec/XAuth 模式连接,你必须首先编辑 VPN 服务器上的 /etc/ipsec.conf 并在 ike=... 一行的末尾加上 ,aes256-sha2;modp1024,aes128-sha1;modp1024 字样。保存文件并运行 service ipsec restart。

Docker 用户:在你的 env 文件中添加 VPN_ENABLE_MODP1024=yes,然后重新创建 Docker 容器。

然后在你的 Android 设备上进行以下步骤:

  1. 启动 设置 应用程序。
  2. 单击 网络和互联网。或者,如果你使用 Android 7 或更早版本,在 无线和网络 部分单击 更多...。
  3. 单击 VPN。
  4. 单击 添加VPN配置文件 或窗口右上角的 +。
  5. 在 名称 字段中输入任意内容。
  6. 在 类型 下拉菜单选择 IPSec Xauth PSK。
  7. 在 服务器地址 字段中输入你的 VPN 服务器 IP。
  8. 保持 IPSec 标识符 字段空白。
  9. 在 IPSec 预共享密钥 字段中输入你的 VPN IPsec PSK。
  10. 单击 保存。
  11. 单击新的VPN连接。
  12. 在 用户名 字段中输入你的 VPN 用户名。
  13. 在 密码 字段中输入你的 VPN 密码。
  14. 选中 保存帐户信息 复选框。
  15. 单击 连接。

连接成功后,会在通知栏显示图标。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

iOS

你也可以使用 IKEv2(推荐)或者 IPsec/L2TP 模式连接。

  1. 进入设置 -> 通用 -> VPN。
  2. 单击 添加VPN配置...。
  3. 单击 类型 。选择 IPSec 并返回。
  4. 在 描述 字段中输入任意内容。
  5. 在 服务器 字段中输入你的 VPN 服务器 IP。
  6. 在 帐户 字段中输入你的 VPN 用户名。
  7. 在 密码 字段中输入你的 VPN 密码。
  8. 保持 群组名称 字段空白。
  9. 在 密钥 字段中输入你的 VPN IPsec PSK。
  10. 单击右上角的 完成。
  11. 启用 VPN 连接。

连接成功后,会在通知栏显示图标。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

Linux

你也可以使用 IKEv2 模式连接(推荐)。

Fedora 和 CentOS

Fedora 28 (和更新版本)和 CentOS 8/7 用户可以使用 yum 安装 NetworkManager-libreswan-gnome 软件包,然后通过 GUI 配置 IPsec/XAuth VPN 客户端。

  1. 进入 Settings -> Network -> VPN。单击 + 按钮。
  2. 选择 IPsec based VPN。
  3. 在 Name 字段中输入任意内容。
  4. 在 Gateway 字段中输入你的 VPN 服务器 IP。
  5. 在 Type 下拉菜单选择 IKEv1 (XAUTH)。
  6. 在 User name 字段中输入你的 VPN 用户名。
  7. 右键单击 User password 字段中的 ?,选择 Store the password only for this user。
  8. 在 User password 字段中输入你的 VPN 密码。
  9. 保持 Group name 字段空白。
  10. 右键单击 Secret 字段中的 ?,选择 Store the password only for this user。
  11. 在 Secret 字段中输入你的 VPN IPsec PSK。
  12. 保持 Remote ID 字段空白。
  13. 单击 Add 保存 VPN 连接信息。
  14. 启用 VPN 连接。

连接成功后,你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

其它 Linux

其它 Linux 版本用户可以使用 IPsec/L2TP 模式连接。

授权协议

注: 这个协议仅适用于本文档。

版权所有 (C) 2016-2026 Lin Song
受到 Joshua Lund 的工作的启发

本程序为自由软件,在自由软件联盟发布的 GNU 通用公共许可协议的约束下,你可以对其进行再发布及修改。协议版本为第三版或(随你)更新的版本。

我们希望发布的这款程序有用,但不保证,甚至不保证它有经济价值和适合特定用途。详情参见GNU通用公共许可协议。


File: docs/clients-zh.md

English | 中文

配置 IPsec/L2TP VPN 客户端

在成功搭建自己的 VPN 服务器之后,按照下面的步骤来配置你的设备。IPsec/L2TP 在 Android, iOS, OS X 和 Windows 上均受支持,无需安装额外的软件。设置过程通常只需要几分钟。如果无法连接,请首先检查是否输入了正确的 VPN 登录凭证。


Windows

你也可以使用 IKEv2 模式连接(推荐)。

Windows 11

  1. 右键单击系统托盘中的无线/网络图标。
  2. 选择 网络和 Internet 设置,然后在打开的页面中单击 VPN。
  3. 单击 添加 VPN 按钮。
  4. 从 VPN 提供商 下拉菜单选择 Windows (内置)。
  5. 在 连接名称 字段中输入任意内容。
  6. 在 服务器名称或地址 字段中输入你的 VPN 服务器 IP。
  7. 从 VPN 类型 下拉菜单选择 使用预共享密钥的 L2TP/IPsec。
  8. 在 预共享密钥 字段中输入你的 VPN IPsec PSK。
  9. 在 用户名 字段中输入你的 VPN 用户名。
  10. 在 密码 字段中输入你的 VPN 密码。
  11. 选中 记住我的登录信息 复选框。
  12. 单击 保存 保存 VPN 连接的详细信息。

注: 在首次连接之前需要修改一次注册表,以解决 VPN 服务器 和/或 客户端与 NAT (比如家用路由器)的兼容问题。

要连接到 VPN:单击 连接 按钮,或者单击系统托盘中的无线/网络图标,单击 VPN,然后选择新的 VPN 连接并单击 连接。如果出现提示,在登录窗口中输入 你的 VPN 用户名 和 密码 ,并单击 确定。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

Windows 10 and 8

  1. 右键单击系统托盘中的无线/网络图标。
  2. 选择 打开"网络和 Internet"设置,然后在打开的页面中单击 网络和共享中心。
  3. 单击 设置新的连接或网络。
  4. 选择 连接到工作区,然后单击 下一步。
  5. 单击 使用我的Internet连接 (VPN)。
  6. 在 Internet地址 字段中输入你的 VPN 服务器 IP。
  7. 在 目标名称 字段中输入任意内容。单击 创建。
  8. 返回 网络和共享中心。单击左侧的 更改适配器设置。
  9. 右键单击新创建的 VPN 连接,并选择 属性。
  10. 单击 安全 选项卡,从 VPN 类型 下拉菜单中选择 "使用 IPsec 的第 2 层隧道协议 (L2TP/IPSec)"。
  11. 单击 允许使用这些协议。选中 "质询握手身份验证协议 (CHAP)" 和 "Microsoft CHAP 版本 2 (MS-CHAP v2)" 复选框。
  12. 单击 高级设置 按钮。
  13. 单击 使用预共享密钥作身份验证 并在 密钥 字段中输入你的 VPN IPsec PSK。
  14. 单击 确定 关闭 高级设置。
  15. 单击 确定 保存 VPN 连接的详细信息。

注: 在首次连接之前需要修改一次注册表,以解决 VPN 服务器 和/或 客户端与 NAT (比如家用路由器)的兼容问题。

要连接到 VPN:单击系统托盘中的无线/网络图标,选择新的 VPN 连接,然后单击 连接。如果出现提示,在登录窗口中输入 你的 VPN 用户名 和 密码 ,并单击 确定。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

另外,除了按照以上步骤操作,你也可以运行下面的 Windows PowerShell 命令来创建 VPN 连接。将 你的 VPN 服务器 IP 和 你的 VPN IPsec PSK 换成你自己的值,用单引号括起来:

console
# 不保存命令行历史记录
Set-PSReadlineOption –HistorySaveStyle SaveNothing
# 创建 VPN 连接
Add-VpnConnection -Name 'My IPsec VPN' -ServerAddress '你的 VPN 服务器 IP' `
  -L2tpPsk '你的 VPN IPsec PSK' -TunnelType L2tp -EncryptionLevel Required `
  -AuthenticationMethod Chap,MSChapv2 -Force -RememberCredential -PassThru
# 忽略 data encryption 警告(数据在 IPsec 隧道中已被加密)

Windows 7, Vista and XP

  1. 单击开始菜单,选择控制面板。
  2. 进入 网络和Internet 部分。
  3. 单击 网络和共享中心。
  4. 单击 设置新的连接或网络。
  5. 选择 连接到工作区,然后单击 下一步。
  6. 单击 使用我的Internet连接 (VPN)。
  7. 在 Internet地址 字段中输入你的 VPN 服务器 IP。
  8. 在 目标名称 字段中输入任意内容。
  9. 选中 现在不连接;仅进行设置以便稍后连接 复选框。
  10. 单击 下一步。
  11. 在 用户名 字段中输入你的 VPN 用户名。
  12. 在 密码 字段中输入你的 VPN 密码。
  13. 选中 记住此密码 复选框。
  14. 单击 创建,然后单击 关闭 按钮。
  15. 返回 网络和共享中心。单击左侧的 更改适配器设置。
  16. 右键单击新创建的 VPN 连接,并选择 属性。
  17. 单击 选项 选项卡,取消选中 包括Windows登录域 复选框。
  18. 单击 安全 选项卡,从 VPN 类型 下拉菜单中选择 "使用 IPsec 的第 2 层隧道协议 (L2TP/IPSec)"。
  19. 单击 允许使用这些协议。选中 "质询握手身份验证协议 (CHAP)" 和 "Microsoft CHAP 版本 2 (MS-CHAP v2)" 复选框。
  20. 单击 高级设置 按钮。
  21. 单击 使用预共享密钥作身份验证 并在 密钥 字段中输入你的 VPN IPsec PSK。
  22. 单击 确定 关闭 高级设置。
  23. 单击 确定 保存 VPN 连接的详细信息。

注: 在首次连接之前需要修改一次注册表,以解决 VPN 服务器 和/或 客户端与 NAT (比如家用路由器)的兼容问题。

要连接到 VPN:单击系统托盘中的无线/网络图标,选择新的 VPN 连接,然后单击 连接。如果出现提示,在登录窗口中输入 你的 VPN 用户名 和 密码 ,并单击 确定。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

OS X (macOS)

macOS 13 (Ventura) 及以上

你也可以使用 IKEv2(推荐)或者 IPsec/XAuth 模式连接。

  1. 打开系统设置并转到网络部分。
  2. 在窗口右方单击 VPN。
  3. 从 添加VPN配置 下拉菜单选择 L2TP/IPSec。
  4. 在打开的窗口中的 显示名称 字段中输入任意内容。
  5. 保持 配置 为 默认。
  6. 在 服务器地址 字段中输入你的 VPN 服务器 IP。
  7. 在 帐户名称 字段中输入你的 VPN 用户名。
  8. 从 用户认证 下拉菜单选择 密码。
  9. 在 密码 字段中输入你的 VPN 密码。
  10. 从 机器认证 下拉菜单选择 共享密钥。
  11. 在 共享密钥 字段中输入你的 VPN IPsec PSK。
  12. 保持 群组名称 字段空白。
  13. (重要) 单击 选项 选项卡,并启用 通过VPN连接发送所有流量。
  14. (重要) 单击 TCP/IP 选项卡,然后在 配置IPv6 下拉菜单选择 仅本地链接。
  15. 单击 创建 保存 VPN 连接信息。
  16. 如果要在菜单栏显示 VPN 状态并快速访问相关设置,你可以转到系统设置的控制中心部分,滚动到页面底部并在 VPN 下拉菜单选择 在菜单栏中显示。

要连接到 VPN:使用菜单栏中的图标,或者打开系统设置的 VPN 部分并启用 VPN 连接。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

macOS 12 (Monterey) 及以下

你也可以使用 IKEv2(推荐)或者 IPsec/XAuth 模式连接。

  1. 打开系统偏好设置并转到网络部分。
  2. 在窗口左下角单击 + 按钮。
  3. 从 接口 下拉菜单选择 VPN。
  4. 从 VPN类型 下拉菜单选择 IPSec 上的 L2TP。
  5. 在 服务名称 字段中输入任意内容。
  6. 单击 创建。
  7. 在 服务器地址 字段中输入你的 VPN 服务器 IP。
  8. 在 帐户名称 字段中输入你的 VPN 用户名。
  9. 单击 认证设置 按钮。
  10. 在 用户认证 部分,选择 密码 单选按钮,然后输入你的 VPN 密码。
  11. 在 机器认证 部分,选择 共享的密钥 单选按钮,然后输入你的 VPN IPsec PSK。
  12. 保持 群组名称 字段空白。
  13. 单击 好。
  14. 选中 在菜单栏中显示 VPN 状态 复选框。
  15. (重要) 单击 高级 按钮,并选中 通过VPN连接发送所有通信 复选框。
  16. (重要) 单击 TCP/IP 选项卡,并在 配置IPv6 部分中选择 仅本地链接。
  17. 单击 好 关闭高级设置,然后单击 应用 保存 VPN 连接信息。

要连接到 VPN:使用菜单栏中的图标,或者打开系统偏好设置的网络部分,选择 VPN 并单击 连接。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

Android

重要: Android 用户应该使用更安全的 IKEv2 模式连接(推荐)。Android 12+ 仅支持 IKEv2 模式。Android 系统自带的 VPN 客户端对 IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式使用安全性较低的 modp1024 (DH group 2)。

如果你仍然想用 IPsec/L2TP 模式连接,你必须首先编辑 VPN 服务器上的 /etc/ipsec.conf 并在 ike=... 一行的末尾加上 ,aes256-sha2;modp1024,aes128-sha1;modp1024 字样。保存文件并运行 service ipsec restart。

Docker 用户:在你的 env 文件中添加 VPN_ENABLE_MODP1024=yes,然后重新创建 Docker 容器。

然后在你的 Android 设备上进行以下步骤:

  1. 启动 设置 应用程序。
  2. 单击 网络和互联网。或者,如果你使用 Android 7 或更早版本,在 无线和网络 部分单击 更多...。
  3. 单击 VPN。
  4. 单击 添加VPN配置文件 或窗口右上角的 +。
  5. 在 名称 字段中输入任意内容。
  6. 在 类型 下拉菜单选择 L2TP/IPSec PSK。
  7. 在 服务器地址 字段中输入你的 VPN 服务器 IP。
  8. 保持 L2TP 密钥 字段空白。
  9. 保持 IPSec 标识符 字段空白。
  10. 在 IPSec 预共享密钥 字段中输入你的 VPN IPsec PSK。
  11. 单击 保存。
  12. 单击新的VPN连接。
  13. 在 用户名 字段中输入你的 VPN 用户名。
  14. 在 密码 字段中输入你的 VPN 密码。
  15. 选中 保存帐户信息 复选框。
  16. 单击 连接。

连接成功后,会在通知栏显示图标。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

iOS

你也可以使用 IKEv2(推荐)或者 IPsec/XAuth 模式连接。

  1. 进入设置 -> 通用 -> VPN。
  2. 单击 添加VPN配置...。
  3. 单击 类型 。选择 L2TP 并返回。
  4. 在 描述 字段中输入任意内容。
  5. 在 服务器 字段中输入你的 VPN 服务器 IP。
  6. 在 帐户 字段中输入你的 VPN 用户名。
  7. 在 密码 字段中输入你的 VPN 密码。
  8. 在 密钥 字段中输入你的 VPN IPsec PSK。
  9. 启用 发送所有流量 选项。
  10. 单击右上角的 完成。
  11. 启用 VPN 连接。

连接成功后,会在通知栏显示图标。最后你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

Chrome OS

你也可以使用 IKEv2 模式连接(推荐)。

  1. 进入设置 -> 网络。
  2. 单击 添加连接,然后单击 添加内置 VPN。
  3. 在 服务名称 字段中输入任意内容。
  4. 在 提供商类型 下拉菜单选择 L2TP/IPsec。
  5. 在 服务器主机名 字段中输入你的 VPN 服务器 IP。
  6. 在 身份验证类型 下拉菜单选择 预共享密钥。
  7. 在 用户名 字段中输入你的 VPN 用户名。
  8. 在 密码 字段中输入你的 VPN 密码。
  9. 在 预共享密钥 字段中输入你的 VPN IPsec PSK。
  10. 保持其他字段空白。
  11. 启用 保存身份信息和密码。
  12. 单击 连接。

连接成功后,网络状态图标上会出现 VPN 指示。你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

如果在连接过程中遇到错误,请参见故障排除。

Linux

你也可以使用 IKEv2 模式连接(推荐)。

Ubuntu Linux

Ubuntu 18.04 和更新版本用户可以使用 apt 安装 network-manager-l2tp-gnome 软件包,然后通过 GUI 配置 IPsec/L2TP VPN 客户端。

  1. 进入 Settings -> Network -> VPN。单击 + 按钮。
  2. 选择 Layer 2 Tunneling Protocol (L2TP)。
  3. 在 Name 字段中输入任意内容。
  4. 在 Gateway 字段中输入你的 VPN 服务器 IP。
  5. 在 User name 字段中输入你的 VPN 用户名。
  6. 右键单击 Password 字段中的 ?,选择 Store the password only for this user。
  7. 在 Password 字段中输入你的 VPN 密码。
  8. 保持 NT Domain 字段空白。
  9. 单击 IPsec Settings... 按钮。
  10. 选中 Enable IPsec tunnel to L2TP host 复选框。
  11. 保持 Gateway ID 字段空白。
  12. 在 Pre-shared key 字段中输入你的 VPN IPsec PSK。
  13. 展开 Advanced 部分。
  14. 在 Phase1 Algorithms 字段中输入 aes128-sha1-modp2048。
  15. 在 Phase2 Algorithms 字段中输入 aes128-sha1。
  16. 单击 OK,然后单击 Add 保存 VPN 连接信息。
  17. 启用 VPN 连接。

如果在连接过程中遇到错误,请尝试这个解决方案。

连接成功后,你可以到这里检测你的 IP 地址,应该显示为你的 VPN 服务器 IP。

Fedora 和 CentOS

Fedora 28(和更新版本)和 CentOS 8/7 用户可以使用 IPsec/XAuth 模式连接。

其它 Linux

首先看这里以确认 network-manager-l2tp 和 network-manager-l2tp-gnome 软件包是否在你的 Linux 版本上可用。如果可用,安装它们(选择使用 strongSwan)并参见上面的说明。另外,你也可以使用命令行配置 Linux VPN 客户端。

使用命令行配置 Linux VPN 客户端

高级用户可以使用命令行配置 Linux VPN 客户端。另外,你也可以使用 IKEv2 模式连接(推荐),或者使用图形界面配置。以下说明受到 Peter Sanford 的工作的启发。这些命令必须在你的 VPN 客户端上使用 root 账户运行。

要配置 VPN 客户端,首先安装以下软件包:

bash
# Ubuntu and Debian
apt-get update
apt-get install strongswan xl2tpd net-tools

# Fedora
yum install strongswan xl2tpd net-tools

# CentOS
yum install epel-release
yum --enablerepo=epel install strongswan xl2tpd net-tools

创建 VPN 变量(替换为你自己的值):

bash
VPN_SERVER_IP='你的VPN服务器IP'
VPN_IPSEC_PSK='你的IPsec预共享密钥'
VPN_USER='你的VPN用户名'
VPN_PASSWORD='你的VPN密码'

配置 strongSwan:

bash
cat > /etc/ipsec.conf <<EOF
# ipsec.conf - strongSwan IPsec configuration file

conn myvpn
  auto=add
  keyexchange=ikev1
  authby=secret
  type=transport
  left=%defaultroute
  leftprotoport=17/1701
  rightprotoport=17/1701
  right=$VPN_SERVER_IP
  ike=aes128-sha1-modp2048
  esp=aes128-sha1
EOF

cat > /etc/ipsec.secrets <<EOF
: PSK "$VPN_IPSEC_PSK"
EOF

chmod 600 /etc/ipsec.secrets

# For CentOS and Fedora ONLY
mv /etc/strongswan/ipsec.conf /etc/strongswan/ipsec.conf.old 2>/dev/null
mv /etc/strongswan/ipsec.secrets /etc/strongswan/ipsec.secrets.old 2>/dev/null
ln -s /etc/ipsec.conf /etc/strongswan/ipsec.conf
ln -s /etc/ipsec.secrets /etc/strongswan/ipsec.secrets

配置 xl2tpd:

bash
cat > /etc/xl2tpd/xl2tpd.conf <<EOF
[lac myvpn]
lns = $VPN_SERVER_IP
ppp debug = yes
pppoptfile = /etc/ppp/options.l2tpd.client
length bit = yes
EOF

cat > /etc/ppp/options.l2tpd.client <<EOF
ipcp-accept-local
ipcp-accept-remote
refuse-eap
require-chap
noccp
noauth
mtu 1280
mru 1280
noipdefault
defaultroute
usepeerdns
connect-delay 5000
name "$VPN_USER"
password "$VPN_PASSWORD"
EOF

chmod 600 /etc/ppp/options.l2tpd.client

至此 VPN 客户端配置已完成。按照下面的步骤进行连接。

注: 当你每次尝试连接到 VPN 时,必须重复下面的所有步骤。

创建 xl2tpd 控制文件:

bash
mkdir -p /var/run/xl2tpd
touch /var/run/xl2tpd/l2tp-control

重启服务:

bash
service strongswan restart

# 适用于 Ubuntu,如果 strongswan 服务不存在
ipsec restart

service xl2tpd restart

开始 IPsec 连接:

bash
# Ubuntu and Debian
ipsec up myvpn

# CentOS and Fedora
strongswan up myvpn

开始 L2TP 连接:

bash
echo "c myvpn" > /var/run/xl2tpd/l2tp-control

运行 ifconfig 并且检查输出。现在你应该看到一个新的网络接口 ppp0。

检查你现有的默认路由:

bash
ip route

在输出中查找以下行: default via X.X.X.X ...。记下这个网关 IP,并且在下面的两个命令中使用。

从新的默认路由中排除你的 VPN 服务器的公有 IP(替换为你自己的值):

bash
route add 你的VPN服务器的公有IP gw X.X.X.X

如果你的 VPN 客户端是一个远程服务器,则必须从新的默认路由中排除你的本地电脑的公有 IP,以避免 SSH 会话被断开(替换为实际值):

bash
route add 你的本地电脑的公有IP gw X.X.X.X

添加一个新的默认路由,并且开始通过 VPN 服务器发送数据:

bash
route add default dev ppp0

至此 VPN 连接已成功完成。检查 VPN 是否正常工作:

bash
wget -qO- http://ipv4.icanhazip.com; echo

以上命令应该返回 你的 VPN 服务器 IP。

要停止通过 VPN 服务器发送数据:

bash
route del default dev ppp0

要断开连接:

bash
# Ubuntu and Debian
echo "d myvpn" > /var/run/xl2tpd/l2tp-control
ipsec down myvpn

# CentOS and Fedora
echo "d myvpn" > /var/run/xl2tpd/l2tp-control
strongswan down myvpn

IKEv1 故障排除

其他语言版本: English, 中文。

另见: IKEv2 故障排除和高级用法。

检查日志及 VPN 状态

以下命令需要使用 root 账户(或者 sudo)运行。

首先,重启 VPN 服务器上的相关服务:

bash
service ipsec restart
service xl2tpd restart

Docker 用户: 运行 docker restart ipsec-vpn-server。

然后重启你的 VPN 客户端设备,并重试连接。如果仍然无法连接,可以尝试删除并重新创建 VPN 连接。请确保输入了正确的 VPN 服务器地址和 VPN 登录凭证。

对于有外部防火墙的服务器(比如 EC2/GCE),请为 VPN 打开 UDP 端口 500 和 4500。

检查 Libreswan (IPsec) 和 xl2tpd 日志是否有错误:

bash
# Ubuntu & Debian
grep pluto /var/log/auth.log
grep xl2tpd /var/log/syslog

# CentOS/RHEL, Rocky Linux, AlmaLinux & Oracle Linux
grep pluto /var/log/secure
grep xl2tpd /var/log/messages

# Alpine Linux
grep pluto /var/log/messages
grep xl2tpd /var/log/messages

如果 Libreswan 日志中出现 Protocol not supported (errno 93) 或 Adding IPsec SA failed 等错误,请参见 IPsec SA 错误。

检查 IPsec VPN 服务器状态:

bash
ipsec status

查看当前已建立的 VPN 连接:

bash
ipsec trafficstatus

Windows 错误 809

错误 809:无法建立计算机与 VPN 服务器之间的网络连接,因为远程服务器未响应。这可能是因为未将计算机与远程服务器之间的某种网络设备(如防火墙、NAT、路由器等)配置为允许 VPN 连接。请与管理员或服务提供商联系以确定哪种设备可能产生此问题。

注: 仅当你使用 IPsec/L2TP 模式连接到 VPN 时,才需要进行下面的注册表更改。对于 IKEv2 和 IPsec/XAuth 模式,不需要 进行此更改。

要解决此错误,在首次连接之前需要修改一次注册表,以解决 VPN 服务器 和/或 客户端与 NAT (比如家用路由器)的兼容问题。请下载并导入下面的 .reg 文件,或者打开提升权限命令提示符并运行以下命令。完成后必须重启计算机。

  • 适用于 Windows Vista, 7, 8, 10 和 11 (下载 .reg 文件)

    console
    REG ADD HKLM\SYSTEM\CurrentControlSet\Services\PolicyAgent /v AssumeUDPEncapsulationContextOnSendRule /t REG_DWORD /d 0x2 /f
  • 仅适用于 Windows XP (下载 .reg 文件)

    console
    REG ADD HKLM\SYSTEM\CurrentControlSet\Services\IPSec /v AssumeUDPEncapsulationContextOnSendRule /t REG_DWORD /d 0x2 /f

另外,某些个别的 Windows 系统配置禁用了 IPsec 加密,此时也会导致连接失败。要重新启用它,可以运行以下命令并重启。

  • 适用于 Windows XP, Vista, 7, 8, 10 和 11 (下载 .reg 文件)

    console
    REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RasMan\Parameters /v ProhibitIpSec /t REG_DWORD /d 0x0 /f

Windows 错误 789 或 691

错误 789:L2TP 连接尝试失败,因为安全层在初始化与远程计算机的协商时遇到一个处理错误。

错误 691:由于指定的用户名和/或密码无效而拒绝连接。下列条件可能会导致此情况:用户名和/或密码键入错误...

对于错误 789,点击这里查看故障排除信息。对于错误 691,你可以尝试删除并重新创建 VPN 连接,按照本文档中的步骤操作。请确保输入了正确的 VPN 登录凭证。

Windows 错误 628 或 766

错误 628:在连接完成前,连接被远程计算机终止。

错误 766:找不到证书。使用通过 IPSec 的 L2TP 协议的连接要求安装一个机器证书。它也叫做计算机证书。

要解决这些错误,请按以下步骤操作:

  1. 右键单击系统托盘中的无线/网络图标。
  2. Windows 11: 选择 网络和 Internet 设置,然后在打开的页面中单击 高级网络设置。单击 更多网络适配器选项。
    Windows 10: 选择 打开"网络和 Internet"设置,然后在打开的页面中单击 网络和共享中心。单击左侧的 更改适配器设置。
    Windows 8/7: 选择 打开网络和共享中心。单击左侧的 更改适配器设置。
  3. 右键单击新的 VPN 连接,并选择 属性。
  4. 单击 安全 选项卡,从 VPN 类型 下拉菜单中选择 "使用 IPsec 的第 2 层隧道协议 (L2TP/IPSec)"。
  5. 单击 允许使用这些协议。选中 "质询握手身份验证协议 (CHAP)" 和 "Microsoft CHAP 版本 2 (MS-CHAP v2)" 复选框。
  6. 单击 高级设置 按钮。
  7. 单击 使用预共享密钥作身份验证 并在 密钥 字段中输入你的 VPN IPsec PSK。
  8. 单击 确定 关闭 高级设置。
  9. 单击 确定 保存 VPN 连接的详细信息。

Windows 10 正在连接

如果你使用 Windows 10 并且 VPN 卡在 "正在连接" 状态超过几分钟,尝试以下步骤:

  1. 右键单击系统托盘中的无线/网络图标。
  2. 选择 打开"网络和 Internet"设置,然后在打开的页面中单击左侧的 VPN。
  3. 选择新的 VPN 连接,然后单击 连接。如果出现提示,在登录窗口中输入 你的 VPN 用户名 和 密码 ,并单击 确定。

Windows 10/11 升级

在升级 Windows 10/11 版本之后(比如从 21H2 到 22H2),你可能需要重新按照 Windows 错误 809 中的步骤修改注册表并重启。

Windows DNS 泄漏和 IPv6

Windows 8, 10 和 11 默认使用 "smart multi-homed name resolution" (智能多宿主名称解析)。如果你的因特网适配器的 DNS 服务器在本地网段上,在使用 Windows 自带的 IPsec VPN 客户端时可能会导致 "DNS 泄漏"。要解决这个问题,你可以禁用智能多宿主名称解析,或者配置你的因特网适配器以使用在你的本地网段之外的 DNS 服务器(比如 8.8.8.8 和 8.8.4.4)。在完成后重启计算机。

另外,如果你的计算机启用了 IPv6,所有的 IPv6 流量(包括 DNS 请求)都将绕过 VPN。要在 Windows 上禁用 IPv6,请看这里。

如果你需要支持 IPv6 的 VPN,请尝试 IKEv2 模式(参见 IPv6 支持,需要具有公共 IPv6 地址的 VPN 服务器),或者尝试 OpenVPN 或 WireGuard。

Android/Linux MTU/MSS 问题

某些 Android 设备和 Linux 系统有 MTU/MSS 问题,表现为使用 IPsec/XAuth ("Cisco IPsec") 或者 IKEv2 模式可以连接到 VPN 但是无法打开网站。如果你遇到该问题,尝试在 VPN 服务器上运行以下命令。如果成功解决,你可以将这些命令添加到 /etc/rc.local 以使它们重启后继续有效。

text
iptables -t mangle -A FORWARD -m policy --pol ipsec --dir in \
  -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 \
  -j TCPMSS --set-mss 1360
iptables -t mangle -A FORWARD -m policy --pol ipsec --dir out \
  -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 \
  -j TCPMSS --set-mss 1360

echo 1 > /proc/sys/net/ipv4/ip_no_pmtu_disc

Docker 用户: 要修复这个问题,不需要运行以上命令。你可以在你的 env 文件中添加 VPN_ANDROID_MTU_FIX=yes,然后重新创建 Docker 容器。

参考链接:[1]。

macOS 通过 VPN 发送通信

OS X (macOS) 用户:如果可以成功地使用 IPsec/L2TP 模式连接,但是你的公有 IP 没有显示为 你的 VPN 服务器 IP,请阅读上面的 macOS 部分并完成以下步骤。保存 VPN 配置然后重新连接。

对于 macOS 13 (Ventura) 及以上:

  1. 单击 选项 选项卡,并启用 通过VPN连接发送所有流量。
  2. 单击 TCP/IP 选项卡,然后在 配置IPv6 下拉菜单选择 仅本地链接。

对于 macOS 12 (Monterey) 及以下:

  1. 单击 高级 按钮,并选中 通过VPN连接发送所有通信 复选框。
  2. 单击 TCP/IP 选项卡,并在 配置IPv6 部分中选择 仅本地链接。

如果在尝试上面步骤之后,你的计算机仍然不能通过 VPN 连接发送通信,检查一下服务顺序。进入系统偏好设置中的网络部分,单击左侧连接列表下方的齿轮按钮,选择 "设定服务顺序"。然后将 VPN 连接拖动到顶端。

iOS/Android 睡眠模式

为了节约电池,iOS 设备 (iPhone/iPad) 在屏幕变黑(睡眠模式)之后会自动断开 Wi-Fi 连接。这会导致 IPsec VPN 断开。该行为是被故意设计的并且不能被配置。

如果需要 VPN 在设备唤醒后自动重连,你可以使用 IKEv2 模式连接(推荐)并启用 "VPN On Demand" 功能。或者你也可以另外尝试使用 OpenVPN,它支持一些选项比如 "Reconnect on Wakeup" 和 "Seamless Tunnel"。


Android 设备在进入睡眠模式后也会断开 Wi-Fi 连接。你可以尝试打开 "始终开启 VPN" 选项以保持连接。详情请看这里。

Debian 内核

Debian 用户:运行 uname -r 检查你的服务器的 Linux 内核版本。如果它包含 cloud 字样,并且 /dev/ppp 不存在,则该内核缺少 ppp 支持从而不能使用 IPsec/L2TP 模式。VPN 安装脚本会尝试检测此情形并显示警告。在这种情况下,你可以另外使用 IKEv2 或者 IPsec/XAuth 模式连接到 VPN。

要解决 IPsec/L2TP 模式的问题,你可以换用标准的 Linux 内核,通过安装比如 linux-image-amd64 软件包来实现。然后更新 GRUB 的内核默认值并重启服务器。

授权协议

注: 这个协议仅适用于本文档。

版权所有 (C) 2016-2026 Lin Song
受到 Joshua Lund 的工作的启发

本程序为自由软件,在自由软件联盟发布的 GNU 通用公共许可协议的约束下,你可以对其进行再发布及修改。协议版本为第三版或(随你)更新的版本。

我们希望发布的这款程序有用,但不保证,甚至不保证它有经济价值和适合特定用途。详情参见GNU通用公共许可协议。


File: docs/ikev2-howto.md

English | 中文

Guide: How to Set Up and Use IKEv2 VPN

Introduction

Modern operating systems support the IKEv2 standard. Internet Key Exchange (IKE or IKEv2) is the protocol used to set up a Security Association (SA) in the IPsec protocol suite. Compared to IKE version 1, IKEv2 contains improvements such as Standard Mobility support through MOBIKE, and improved reliability.

Libreswan can authenticate IKEv2 clients on the basis of X.509 Machine Certificates using RSA signatures. This method does not require an IPsec PSK, username or password. It can be used with Windows, macOS, iOS, Android, Chrome OS, Linux and RouterOS.

By default, IKEv2 is automatically set up when running the VPN setup script. If you want to learn more about setting up IKEv2, see Set up IKEv2 using helper script. Docker users, see Configure and use IKEv2 VPN.

Configure IKEv2 VPN clients

Note: To add or export IKEv2 clients, run sudo ikev2.sh. Use -h to show usage. Client config files can be safely deleted after import.

Learn how to change the IKEv2 server address.

In certain circumstances, you may need to change the IKEv2 server address. For example, to switch to use a DNS name, or after server IP changes. Learn more in this section.

Windows 7, 8, 10 and 11

Auto-import configuration

Screencast: IKEv2 Auto Import Configuration on Windows

Windows 8, 10 and 11+ users can automatically import IKEv2 configuration:

  1. Securely transfer the generated .p12 file to your computer.
  2. Right-click on ikev2_config_import.cmd and save this helper script to the same folder as the .p12 file.
  3. Right-click on the saved script, select Properties. Click on Unblock at the bottom, then click on OK.
  4. Right-click on the saved script, select Run as administrator and follow the prompts.

To connect to the VPN: Click on the wireless/network icon in your system tray, select the new VPN entry, and click Connect. Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Note: If you reinstalled the VPN server, you may want to first remove existing IKEv2 client and CA certificates, then follow the steps above to import the new .p12 file. This helps make sure that Windows uses the correct client certificate when connecting to the VPN. See "Remove the IKEv2 VPN connection" below for more details.

Manually import configuration

[Supporters] Screencast: IKEv2 Manually Import Configuration on Windows

Alternatively, Windows 7, 8, 10 and 11+ users can manually import IKEv2 configuration:

  1. Securely transfer the generated .p12 file to your computer, then import it into the certificate store.

    To import the .p12 file, run the following from an elevated command prompt:

    console
    # Import .p12 file (replace with your own value)
    certutil -f -importpfx "\path\to\your\file.p12" NoExport

    Note: If there is no password for client config files, press Enter to continue, or if manually importing the .p12 file, leave the password field blank.

    Alternatively, you can manually import the .p12 file. Make sure that the client cert is placed in "Personal -> Certificates", and the CA cert is placed in "Trusted Root Certification Authorities -> Certificates".

  2. On the Windows computer, add a new IKEv2 VPN connection.

    For Windows 8, 10 and 11+, it is recommended to create the VPN connection using the following commands from a command prompt, for improved security and performance.

    console
    # Create VPN connection (replace server address with your own value)
    powershell -command ^"Add-VpnConnection -ServerAddress 'Your VPN Server IP (or DNS name)' ^
      -Name 'My IKEv2 VPN' -TunnelType IKEv2 -AuthenticationMethod MachineCertificate ^
      -EncryptionLevel Required -PassThru^"
    # Set IPsec configuration
    powershell -command ^"Set-VpnConnectionIPsecConfiguration -ConnectionName 'My IKEv2 VPN' ^
      -AuthenticationTransformConstants GCMAES128 -CipherTransformConstants GCMAES128 ^
      -EncryptionMethod AES256 -IntegrityCheckMethod SHA256 -PfsGroup None ^
      -DHGroup Group14 -PassThru -Force^"

    Windows 7 does not support these commands, you can manually create the VPN connection.

    Note: The server address you specify must exactly match the server address in the output of the IKEv2 helper script. For example, if you specified the server's DNS name during IKEv2 setup, you must enter the DNS name in the Internet address field.

  3. This step is required if you manually created the VPN connection.

    Enable stronger ciphers for IKEv2 with a one-time registry change. Download and import the .reg file below, or run the following from an elevated command prompt. Read more here.

    • For Windows 7, 8, 10 and 11 (download .reg file)

      console
      REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RasMan\Parameters /v NegotiateDH2048_AES256 /t REG_DWORD /d 0x1 /f

To connect to the VPN: Click on the wireless/network icon in your system tray, select the new VPN entry, and click Connect. Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Remove the IKEv2 VPN connection.

Using the following steps, you can remove the VPN connection and optionally restore the computer to the status before IKEv2 configuration import.

  1. Remove the added VPN connection in Windows Settings -> Network -> VPN. Windows 7 users can remove the VPN connection in Network and Sharing Center -> Change adapter settings.

  2. (Optional) Remove IKEv2 certificates.

    1. Windows 8, 10 and 11: Press Win+R and enter certlm.msc, or search for certlm.msc in the Start Menu. Open Certificates - Local Computer.
      Windows 7: Press Win+R and enter mmc, or search for mmc in the Start Menu. Open Management Console. Open File - Add/Remove Snap-In. Select to add Certificates and in the window that opens, select Computer account -> Local Computer. Click on Finish -> OK to save the settings.

    2. Go to Certificates -> Personal -> Certificates and delete the IKEv2 client certificate. The name of the certificate is the same as the IKEv2 client name you specified (default: vpnclient). The certificate was issued by IKEv2 VPN CA.

    3. Go to Certificates -> Trusted Root Certification Authorities -> Certificates and delete the IKEv2 VPN CA certificate. The certificate was issued to IKEv2 VPN CA by IKEv2 VPN CA. Before deleting, make sure that there are no other certificate(s) issued by IKEv2 VPN CA in Certificates -> Personal -> Certificates.

  3. (Optional. For users who manually created the VPN connection) Restore registry settings. Note that you should backup the registry before editing.

    1. Press Win+R, or search for regedit in the Start Menu. Open Registry Editor.

    2. Go to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Rasman\Parameters and delete the item with name NegotiateDH2048_AES256, if it exists.

OS X (macOS)

[Supporters] Screencast: IKEv2 Import Configuration and Connect on macOS

First, securely transfer the generated .mobileconfig file to your Mac, then double-click and follow the prompts to import as a macOS profile. If your Mac runs macOS Big Sur or newer, open System Preferences and go to the Profiles section to finish importing. For macOS Ventura and newer, open System Settings and search for Profiles. When finished, check to make sure "IKEv2 VPN" is listed under System Preferences -> Profiles.

To connect to the VPN:

  1. Open System Preferences and go to the Network section.
  2. Select the VPN connection with Your VPN Server IP (or DNS name).
  3. Check the Show VPN status in menu bar checkbox. For macOS Ventura and newer, this setting can be configured in System Settings -> Control Center -> Menu Bar Only section.
  4. Click Connect, or slide the VPN switch ON.

(Optional feature) Enable VPN On Demand to automatically start a VPN connection when your Mac is on Wi-Fi. To enable, check the Connect on demand checkbox for the VPN connection, and click Apply. To find this setting on macOS Ventura and newer, click on the "i" icon on the right of the VPN connection.

You can customize VPN On Demand rules to exclude certain Wi-Fi networks (such as your home network). For more information, see the chapter "Guide: Customize IKEv2 VPN On Demand rules for macOS and iOS" in :book: Book: Set Up Your Own IPsec VPN, OpenVPN and WireGuard Server.

If you manually set up IKEv2 without using the helper script, click here for instructions.

First, securely transfer the generated .p12 file to your Mac, then double-click to import into the login keychain in Keychain Access. Next, double-click on the imported IKEv2 VPN CA certificate, expand Trust and select Always Trust from the IP Security (IPsec) drop-down menu. Close the dialog using the red "X" on the top-left corner. When prompted, use Touch ID or enter your password and click "Update Settings".

When finished, check to make sure both the new client certificate and IKEv2 VPN CA are listed under the Certificates category of login keychain.

  1. Open System Preferences and go to the Network section.
  2. Click the + button in the lower-left corner of the window.
  3. Select VPN from the Interface drop-down menu.
  4. Select IKEv2 from the VPN Type drop-down menu.
  5. Enter anything you like for the Service Name.
  6. Click Create.
  7. Enter Your VPN Server IP (or DNS name) for the Server Address.
    Note: If you specified the server's DNS name (instead of its IP address) during IKEv2 setup, you must enter the DNS name in the Server Address and Remote ID fields.
  8. Enter Your VPN Server IP (or DNS name) for the Remote ID.
  9. Enter Your VPN client name in the Local ID field.
    Note: This must match exactly the client name you specified during IKEv2 setup. Same as the first part of your .p12 filename.
  10. Click the Authentication Settings... button.
  11. Select None from the Authentication Settings drop-down menu.
  12. Select the Certificate radio button, then select the new client certificate.
  13. Click OK.
  14. Check the Show VPN status in menu bar checkbox.
  15. Click Apply to save the VPN connection information.
  16. Click Connect.

Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Note: macOS 14 (Sonoma) has a minor issue that may cause IKEv2 VPN to disconnect and reconnect once every 24-48 minutes. Other macOS versions are not affected. For more details and a workaround, see macOS Sonoma clients reconnect.

Remove the IKEv2 VPN connection.

To remove the IKEv2 VPN connection, open System Preferences -> Profiles and remove the IKEv2 VPN profile you added.

iOS

[Supporters] Screencast: IKEv2 Import Configuration and Connect on iOS (iPhone & iPad)

First, securely transfer the generated .mobileconfig file to your iOS device, then import it as an iOS profile. To transfer the file, you may use:

  1. AirDrop, or
  2. Upload to your device (any App folder) using File Sharing, then open the "Files" App on your iOS device, move the uploaded file to the "On My iPhone" folder. After that, tap the file and go to the "Settings" App to import, or
  3. Host the file on a secure website of yours, then download and import it in Mobile Safari.

When finished, check to make sure "IKEv2 VPN" is listed under Settings -> General -> VPN & Device Management or Profile(s).

To connect to the VPN:

  1. Go to Settings -> VPN. Select the VPN connection with Your VPN Server IP (or DNS name).
  2. Slide the VPN switch ON.

(Optional feature) Enable VPN On Demand to automatically start a VPN connection when your iOS device is on Wi-Fi. To enable, tap the "i" icon on the right of the VPN connection, and enable Connect On Demand.

You can customize VPN On Demand rules to exclude certain Wi-Fi networks (such as your home network). For more information, see the chapter "Guide: Customize IKEv2 VPN On Demand rules for macOS and iOS" in :book: Book: Set Up Your Own IPsec VPN, OpenVPN and WireGuard Server.

Customize VPN On Demand rules: Connect on Wi-Fi and cellular networks.

The default VPN On Demand configuration only starts a VPN connection on Wi-Fi networks, but not on cellular networks. If you want the VPN to connect on both Wi-Fi and cellular networks:

  1. Edit /opt/src/ikev2.sh on the VPN server. Find the lines:
    text
    <dict>
        <key>InterfaceTypeMatch</key>
        <string>Cellular</string>
        <key>Action</key>
        <string>Disconnect</string>
      </dict>
    and replace "Disconnect" with "Connect":
    text
    <dict>
        <key>InterfaceTypeMatch</key>
        <string>Cellular</string>
        <key>Action</key>
        <string>Connect</string>
      </dict>
  2. Save the file, then run sudo ikev2.sh to export updated client config files for your iOS device(s).
  3. Remove the previously imported VPN profile from your iOS device(s), then import the new .mobileconfig file(s) from step 2.

If you manually set up IKEv2 without using the helper script, click here for instructions.

First, securely transfer the generated ca.cer and .p12 files to your iOS device, then import them one by one as iOS profiles. To transfer the files, you may use:

  1. AirDrop, or
  2. Upload to your device (any App folder) using File Sharing, then open the "Files" App on your iOS device, move the uploaded files to the "On My iPhone" folder. After that, tap each file and go to the "Settings" App to import, or
  3. Host the files on a secure website of yours, then download and import them in Mobile Safari.

When finished, check to make sure both the new client certificate and IKEv2 VPN CA are listed under Settings -> General -> VPN & Device Management or Profile(s).

  1. Go to Settings -> General -> VPN & Device Management -> VPN.
  2. Tap Add VPN Configuration....
  3. Tap Type. Select IKEv2 and go back.
  4. Tap Description and enter anything you like.
  5. Tap Server and enter Your VPN Server IP (or DNS name).
    Note: If you specified the server's DNS name (instead of its IP address) during IKEv2 setup, you must enter the DNS name in the Server and Remote ID fields.
  6. Tap Remote ID and enter Your VPN Server IP (or DNS name).
  7. Enter Your VPN client name in the Local ID field.
    Note: This must match exactly the client name you specified during IKEv2 setup. Same as the first part of your .p12 filename.
  8. Tap User Authentication. Select None and go back.
  9. Make sure the Use Certificate switch is ON.
  10. Tap Certificate. Select the new client certificate and go back.
  11. Tap Done.
  12. Slide the VPN switch ON.

Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Remove the IKEv2 VPN connection.

To remove the IKEv2 VPN connection, open Settings -> General -> VPN & Device Management or Profile(s) and remove the IKEv2 VPN profile you added.

Android

Using strongSwan VPN client

[Supporters] Screencast: Connect using Android strongSwan VPN Client

Android users can connect using strongSwan VPN client (recommended).

  1. Securely transfer the generated .sswan file to your Android device.
  2. Install strongSwan VPN Client from Google Play, F-Droid or strongSwan download server.
  3. Launch the strongSwan VPN client.
  4. Tap the "more options" menu on top right, then tap Import VPN profile.
  5. Choose the .sswan file you transferred from the VPN server.
    Note: To find the .sswan file, tap the three-line menu button, then browse to the location you saved the file.
  6. On the "Import VPN profile" screen, tap IMPORT CERTIFICATE FROM VPN PROFILE, and follow the prompts.
  7. On the "Choose certificate" screen, select the new client certificate, then tap Select.
  8. Tap IMPORT.
  9. Tap the new VPN profile to connect.

(Optional feature) You can choose to enable the "Always-on VPN" feature on Android. Launch the Settings app, go to Network & internet -> Advanced -> VPN, click the gear icon on the right of "strongSwan VPN Client", then enable the Always-on VPN and Block connections without VPN options.

If your device runs Android 6.0 or older, click here for additional instructions.

If your device runs Android 6.0 (Marshmallow) or older, in order to connect using the strongSwan VPN client, you must make the following change on the VPN server: Edit /etc/ipsec.d/ikev2.conf on the server. Append authby=rsa-sha1 to the end of the conn ikev2-cp section, indented by two spaces. Save the file and run service ipsec restart.

If you manually set up IKEv2 without using the helper script, click here for instructions.

Android 10 and newer:

  1. Securely transfer the generated .p12 file to your Android device.
  2. Install strongSwan VPN Client from Google Play, F-Droid or strongSwan download server.
  3. Launch the Settings application.
  4. Go to Security -> Advanced -> Encryption & credentials.
  5. Tap Install a certificate.
  6. Tap VPN & app user certificate.
  7. Choose the .p12 file you transferred from the VPN server, and follow the prompts.
    Note: To find the .p12 file, tap the three-line menu button, then browse to the location you saved the file.
  8. Launch the strongSwan VPN client and tap Add VPN Profile.
  9. Enter Your VPN Server IP (or DNS name) in the Server field.
    Note: If you specified the server's DNS name (instead of its IP address) during IKEv2 setup, you must enter the DNS name in the Server field.
  10. Select IKEv2 Certificate from the VPN Type drop-down menu.
  11. Tap Select user certificate, select the new client certificate and confirm.
  12. (Important) Tap Show advanced settings. Scroll down, find and enable the Use RSA/PSS signatures option.
  13. Save the new VPN connection, then tap to connect.

Android 4 to 9:

  1. Securely transfer the generated .p12 file to your Android device.
  2. Install strongSwan VPN Client from Google Play, F-Droid or strongSwan download server.
  3. Launch the strongSwan VPN client and tap Add VPN Profile.
  4. Enter Your VPN Server IP (or DNS name) in the Server field.
    Note: If you specified the server's DNS name (instead of its IP address) during IKEv2 setup, you must enter the DNS name in the Server field.
  5. Select IKEv2 Certificate from the VPN Type drop-down menu.
  6. Tap Select user certificate, then tap Install certificate.
  7. Choose the .p12 file you transferred from the VPN server, and follow the prompts.
    Note: To find the .p12 file, tap the three-line menu button, then browse to the location you saved the file.
  8. (Important) Tap Show advanced settings. Scroll down, find and enable the Use RSA/PSS signatures option.
  9. Save the new VPN connection, then tap to connect.

Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Using native IKEv2 client

[Supporters] Screencast: Connect using Native VPN Client on Android 11+

Android 11+ users can also connect using the native IKEv2 client.

  1. Securely transfer the generated .p12 file to your Android device.
  2. Launch the Settings application.
  3. Go to Security -> Advanced -> Encryption & credentials.
  4. Tap Install a certificate.
  5. Tap VPN & app user certificate.
  6. Choose the .p12 file you transferred from the VPN server.
    Note: To find the .p12 file, tap the three-line menu button, then browse to the location you saved the file.
  7. Enter a name for the certificate, then tap OK.
  8. Go to Settings -> Network & internet -> VPN, then tap the "+" button.
  9. Enter a name for the VPN profile.
  10. Select IKEv2/IPSec RSA from the Type drop-down menu.
  11. Enter Your VPN Server IP (or DNS name) in the Server address field.
    Note: This must exactly match the server address in the output of the IKEv2 helper script.
  12. Enter anything you like for the IPSec identifier.
    Note: This field should not be required. It is a bug in Android.
  13. Select the certificate you imported from the IPSec user certificate drop-down menu.
  14. Select the certificate you imported from the IPSec CA certificate drop-down menu.
  15. Select (receive from server) from the IPSec server certificate drop-down menu.
  16. Tap Save. Then tap the new VPN connection and tap Connect.

Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

Chrome OS

First, on your VPN server, export the CA certificate as ca.cer:

bash
sudo certutil -L -d sql:/etc/ipsec.d -n "IKEv2 VPN CA" -a -o ca.cer

Securely transfer the generated .p12 and ca.cer files to your Chrome OS device.

Install user and CA certificates:

  1. Open a new tab in Google Chrome.
  2. In the address bar, enter chrome://settings/certificates
  3. (Important) Click Import and Bind, not Import.
  4. In the box that opens, choose the .p12 file you transferred from the VPN server and select Open.
  5. Click OK if the certificate does not have a password. Otherwise, enter the certificate's password.
  6. Click the Authorities tab. Then click Import.
  7. In the box that opens, select All files in the drop-down menu at the bottom left.
  8. Choose the ca.cer file you transferred from the VPN server and select Open.
  9. Keep the default options and click OK.

Add a new VPN connection:

  1. Go to Settings -> Network.
  2. Click Add connection, then click Add built-in VPN.
  3. Enter anything you like for the Service name.
  4. Select IPsec (IKEv2) in the Provider type drop-down menu.
  5. Enter Your VPN Server IP (or DNS name) for the Server hostname.
  6. Select User certificate in the Authentication type drop-down menu.
  7. Select IKEv2 VPN CA [IKEv2 VPN CA] in the Server CA certificate drop-down menu.
  8. Select IKEv2 VPN CA [client name] in the User certificate drop-down menu.
  9. Leave other fields blank.
  10. Enable Save identity and password.
  11. Click Connect.

Once connected, you will see a VPN icon overlay on the network status icon. You can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

(Optional feature) You can choose to enable the "Always-on VPN" feature on Chrome OS. To manage this setting, go to Settings -> Network, then click VPN.

If you get an error when trying to connect, see Troubleshooting.

Linux

Before configuring Linux VPN clients, you must make the following change on the VPN server: Edit /etc/ipsec.d/ikev2.conf on the server. Append authby=rsa-sha1 to the end of the conn ikev2-cp section, indented by two spaces. Save the file and run service ipsec restart.

To configure your Linux computer to connect to IKEv2 as a VPN client, first install the strongSwan plugin for NetworkManager:

Ubuntu and Debian

bash
sudo apt-get update
sudo apt-get install network-manager-strongswan

Arch Linux

bash
sudo pacman -Syu  # upgrade all packages
sudo pacman -S networkmanager-strongswan

Fedora

For KDE Plasma/LXQt users:

bash
sudo dnf install NetworkManager-strongswan-gnome plasma-nm-strongswan

Other DEs:

bash
sudo dnf install NetworkManager-strongswan-gnome

CentOS

bash
sudo yum install epel-release
sudo yum --enablerepo=epel install NetworkManager-strongswan-gnome

Next, securely transfer the generated .p12 file from the VPN server to your Linux computer. After that, extract the CA certificate, client certificate and private key. Replace vpnclient.p12 in the example below with the name of your .p12 file.

bash
# Example: Extract CA certificate, client certificate and private key.
#          You may delete the .p12 file when finished.
# Note: You may need to enter the import password, which can be found
#       in the output of the IKEv2 helper script. If the output does not
#       contain an import password, press Enter to continue.
# Note: If using OpenSSL 3.x (run "openssl version" to check),
#       append "-legacy" to the 3 commands below.
openssl pkcs12 -in vpnclient.p12 -cacerts -nokeys -out ca.cer
openssl pkcs12 -in vpnclient.p12 -clcerts -nokeys -out client.cer
openssl pkcs12 -in vpnclient.p12 -nocerts -nodes  -out client.key
rm vpnclient.p12

# (Important) Protect certificate and private key files
# Note: This step is optional, but strongly recommended.
sudo chown root:root ca.cer client.cer client.key
sudo chmod 600 ca.cer client.cer client.key

[!IMPORTANT]

Fedora and its derivatives require a few extra steps to setup due to their default security policies.

For Fedora/Nobara 39+ clients:

1. Enable SHA1 Support

Fedora 39+ disables SHA-1 cryptographic support by default. Since this VPN setup uses SHA-1 for certificate generation, you need to re-enable it system-wide. Run the following command:

text
sudo update-crypto-policies --set DEFAULT:SHA1

Reboot your system after running this command.

2. Set Secure File Ownership

Fedora systems require that certificate and key files be owned by root. You can set the correct ownership using the chown command.

text
sudo chown root:root ca.cer client.cer client.key

3. Create System Directories

Create the official directories where the strongSwan service looks for certificates and private keys.

text
sudo mkdir -p /etc/ipsec.d/{certs,private}

4. Move Files into Place

Move the certificate and key files from your current location into the newly created system directories.

text
# Move certificates
sudo mv /path/to/ca.cer /path/to/client.cer /etc/ipsec.d/certs/

# Move private key
sudo mv /path/to/client.key /etc/ipsec.d/private/

5. Apply SELinux Contexts (If SELinux is Active)

This command updates the security context of the files, ensuring they are correctly labeled for use by the VPN service. It will only run if SELinux is enabled on your system (à la Fedora).

bash
bash -c '
# Check if SELinux is enabled and apply contexts if necessary
if command -v sestatus >/dev/null 2>&1 && sestatus | grep -q "SELinux status:.*enabled"; then
   sudo restorecon -R -v /etc/ipsec.d/
   echo "SELinux contexts applied successfully. Proceed to step 6."
else
   echo "SELinux not active or not found - skipping context restoration. Proceed to step 6."
fi'

6. Continue to NetworkManager Setup

You are now ready to configure the connection using the graphical editor. Open it with:

text
sudo nm-connection-editor

Proceed with the general Linux instructions below. When prompted to select certificate and key files during setup, use the files you just transferred to /etc/ipsec.d/. (Press Ctrl+L in the file picker to type the full paths directly.)

The paths, for your convenience, are:

/etc/ipsec.d/certs/ & /etc/ipsec.d/private/

You can then set up and enable the VPN connection:

  1. Go to Settings -> Network -> VPN. Click the + button.
  2. Select IPsec/IKEv2 (strongswan).
  3. Enter anything you like in the Name field.
  4. In the Gateway (Server) section, enter Your VPN Server IP (or DNS name) for the Address.
  5. Select the ca.cer file for the Certificate.
  6. In the Client section, select Certificate(/private key) in the Authentication drop-down menu.
  7. Select Certificate/private key in the Certificate drop-down menu (if exists).
  8. Select the client.cer file for the Certificate (file).
  9. Select the client.key file for the Private key.
  10. In the Options section, check the Request an inner IP address checkbox.
  11. In the Cipher proposals (Algorithms) section, check the Enable custom proposals checkbox.
  12. Leave the IKE field blank.
  13. Enter aes128gcm16 in the ESP field.
  14. Click Add to save the VPN connection information.
  15. Turn the VPN switch ON.

[!TIP]
If you're using the KDE Plasma desktop, you might encounter issues when configuring the VPN through the graphical System Settings. To ensure a smooth setup, we recommend launching the dedicated connection editor instead by running sudo nm-connection-editor in a terminal.

Alternatively, you may connect using the command line. See #1399, #1007 and #1789 for example steps. If you encounter error Could not find source connection, edit /etc/netplan/01-netcfg.yaml and replace renderer: networkd with renderer: NetworkManager, then run sudo netplan apply. If using nmcli to connect to the VPN, run sudo nmcli c up VPN. To disconnect: sudo nmcli c down VPN.

Once connected, you can verify that your traffic is being routed properly by looking up your IP address on Google. It should say "Your public IP address is Your VPN Server IP".

If you get an error when trying to connect, see Troubleshooting.

RouterOS

Note: These steps were contributed by @Unix-User. It is recommended to run terminal commands via an SSH connection, e.g. via Putty.

  1. Securely transfer the generated .p12 file to your computer.

    Click to see screencast.

  2. In WinBox, go to System > certificates > import. Import the .p12 certificate file twice (yes, import the same file two times!). Verify in your certificates panel. You will see 2 files, the one that is marked KT is the key.

    Click to see screencast.

    Or you can use terminal instead (empty passphrase):

    bash
    [admin@MikroTik] > /certificate/import file-name=mikrotik.p12
    passphrase:
    
      certificates-imported: 2
      private-keys-imported: 0
             files-imported: 1
        decryption-failures: 0
      keys-with-no-certificate: 0
    
    [admin@MikroTik] > /certificate/import file-name=mikrotik.p12
    passphrase:
    
         certificates-imported: 0
         private-keys-imported: 1
                files-imported: 1
           decryption-failures: 0
      keys-with-no-certificate: 0
  3. Run these commands in terminal. Replace the following with your own values.
    YOUR_VPN_SERVER_IP_OR_DNS_NAME is your VPN server IP or DNS name.
    IMPORTED_CERTIFICATE is the name of the certificate from step 2 above, e.g. vpnclient.p12_0
    (the one flagged with KT - Priv. Key Trusted - if not flagged as KT, import certificate again).
    THESE_ADDRESSES_GO_THROUGH_VPN are the local network addresses that you want to browse through the VPN.
    Assuming that your local network behind RouterOS is 192.168.0.0/24, you can use 192.168.0.0/24
    for the entire network, or use 192.168.0.10 for just one device, and so on.

    bash
    /ip firewall address-list add address=THESE_ADDRESSES_GO_THROUGH_VPN list=local
    /ip ipsec mode-config add name=ike2-rw responder=no src-address-list=local
    /ip ipsec policy group add name=ike2-rw
    /ip ipsec profile add name=ike2-rw
    /ip ipsec peer add address=YOUR_VPN_SERVER_IP_OR_DNS_NAME exchange-mode=ike2 \
        name=ike2-rw-client profile=ike2-rw
    /ip ipsec proposal add name=ike2-rw pfs-group=none
    /ip ipsec identity add auth-method=digital-signature certificate=IMPORTED_CERTIFICATE \
        generate-policy=port-strict mode-config=ike2-rw \
        peer=ike2-rw-client policy-template-group=ike2-rw
    /ip ipsec policy add group=ike2-rw proposal=ike2-rw template=yes
  4. For more information, see #1112.

tested on
mar/02/2022 12:52:57 by RouterOS 6.48
RouterBOARD 941-2nD

IKEv2 troubleshooting

Read this in other languages: English, 中文.

See also: Check logs and VPN status, IKEv1 troubleshooting and Advanced usage.

Cannot connect to the VPN server

First, make sure that the VPN server address specified on your VPN client device exactly matches the server address in the output of the IKEv2 helper script. For example, you cannot use a DNS name to connect if it was not specified when setting up IKEv2. To change the IKEv2 server address, read this section.

For servers with an external firewall (e.g. EC2/GCE), open UDP ports 500 and 4500 for the VPN. Aliyun users, see #433.

Check logs and VPN status for errors. If you encounter retransmission related errors and are unable to connect, there may be network issues between the VPN client and server. If you are connecting from mainland China, consider switching to alternative solutions other than IPsec VPN.

IPsec SA errors

If Libreswan logs errors such as Protocol not supported (errno 93), Requested type not found, Adding IPsec SA failed, or XFRM_MSG_DELPOLICY, the server may have ESP kernel support disabled.

This has been reported on RHEL 10-based systems where a security mitigation disables esp4 or esp6 in modprobe configuration, for example /etc/modprobe.d/dirtyfrag.conf. IPsec VPN requires ESP support. Update your kernel/security packages or follow your distribution's guidance before changing these settings, then restart IPsec or re-run the VPN setup script.

Ubuntu 20.04 cannot import client config

If you installed the IPsec VPN before 2024-04-10, and your VPN server runs Ubuntu Linux version 20.04, you may have encountered an issue where newly generated client configuration files (.mobileconfig) fail to import on iOS or macOS device(s) with errors like "incorrect password". This could be caused by updates to libnss3 related packages on Ubuntu 20.04, which required some changes (25670f3) in the IKEv2 script.

To fix this issue, first update the IKEv2 script on your server to the latest version using these instructions. After that, run sudo ikev2.sh and select "export" to re-create the client configuration files.

macOS Sonoma clients reconnect

macOS 14 (Sonoma) has a minor issue that may cause IKEv2 VPN to disconnect and reconnect once every 24-48 minutes. Other macOS versions are not affected. First check your macOS version. To work around this issue, follow the steps below.

Note: If you installed IPsec VPN after December 10, 2023, no action is required because the following fixes are already included.

  1. Edit /etc/ipsec.d/ikev2.conf on the VPN server. Find the line:
    text
    ike=aes256-sha2,aes128-sha2,aes256-sha1,aes128-sha1
    and replace it with the following:
    text
    ike=aes_gcm_c_256-hmac_sha2_256-ecp_256,aes256-sha2,aes128-sha2,aes256-sha1,aes128-sha1
    Note: Docker users should first open a Bash shell inside the container.
  2. Save the file and run service ipsec restart. Docker users: After step 4 below, exit the container and run docker restart ipsec-vpn-server.
  3. Edit /opt/src/ikev2.sh on the VPN server. Find and replace the following sections with these new values:
    text
    <key>ChildSecurityAssociationParameters</key>
      <dict>
        <key>DiffieHellmanGroup</key>
        19
        <key>EncryptionAlgorithm</key>
        <string>AES-256-GCM</string>
        <key>LifeTimeInMinutes</key>
        1410
      </dict>
    text
    <key>IKESecurityAssociationParameters</key>
      <dict>
        <key>DiffieHellmanGroup</key>
        19
        <key>EncryptionAlgorithm</key>
        <string>AES-256-GCM</string>
        <key>IntegrityAlgorithm</key>
        <string>SHA2-256</string>
        <key>LifeTimeInMinutes</key>
        1410
      </dict>
  4. Run sudo ikev2.sh to export (or add) updated client config files for each macOS device you have.
  5. Remove the previously imported IKEv2 profile (if any) from your macOS device(s), then import the updated .mobileconfig file(s). See Configure IKEv2 VPN clients. Docker users, see Configure and use IKEv2 VPN.

Unable to connect multiple IKEv2 clients

To connect multiple IKEv2 clients from behind the same NAT (e.g. home router) at the same time, you will need to generate a unique certificate for each client. Otherwise, you could encounter the issue where a later connected client affects the VPN connection of an existing client, which may lose Internet access.

To generate certificates for additional IKEv2 clients, run the helper script with the --addclient option. To customize client options, run the script without arguments.

bash
sudo ikev2.sh --addclient [client name]

IKE authentication credentials are unacceptable

If you encounter this error, make sure that the VPN server address specified on your VPN client device exactly matches the server address in the output of the IKEv2 helper script. For example, you cannot use a DNS name to connect if it was not specified when setting up IKEv2. To change the IKEv2 server address, read this section.

Policy match error

To fix this error, you will need to enable stronger ciphers for IKEv2 with a one-time registry change. Download and import the .reg file below, or run the following from an elevated command prompt.

console
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RasMan\Parameters /v NegotiateDH2048_AES256 /t REG_DWORD /d 0x1 /f

Parameter is incorrect

If you encounter "Error 87: The parameter is incorrect" when trying to connect using IKEv2 mode, try the solutions in this issue, more specifically, step 2 "reset device manager adapters".

Cannot open websites after connecting to IKEv2

If your VPN client device cannot open websites after successfully connecting to IKEv2, try the following fixes:

  1. Some cloud providers, such as Google Cloud, set a lower MTU by default. This could cause network issues with IKEv2 VPN clients. To fix, try setting the MTU to 1500 on the VPN server:

    bash
    # Replace ens4 with the network interface name on your server
    sudo ifconfig ens4 mtu 1500

    This setting does not persist after a reboot. To change the MTU size permanently, refer to relevant articles on the web.

  2. If your Android or Linux VPN client can connect using IKEv2 mode, but cannot open websites, try the fix in Android/Linux MTU/MSS issues.

  3. Windows VPN clients may not use the DNS servers specified by IKEv2 after connecting, if the client's configured DNS servers on the Internet adapter are from the local network segment. This can be fixed by manually entering DNS servers such as Google Public DNS (8.8.8.8, 8.8.4.4) in network interface properties -> TCP/IPv4. For more information, see Windows DNS leaks and IPv6.

Windows 10 connecting

If using Windows 10 and the VPN is stuck on "connecting" for more than a few minutes, try these steps:

  1. Right-click on the wireless/network icon in your system tray.
  2. Select Open Network & Internet settings, then on the page that opens, click VPN on the left.
  3. Select the new VPN entry, then click Connect.

Other known issues

The built-in VPN client in Windows may not support IKEv2 fragmentation (this feature requires Windows 10 v1803 or newer). On some networks, this can cause the connection to fail or have other issues. You may instead try the IPsec/L2TP or IPsec/XAuth mode.

Manage IKEv2 clients

List existing clients

To list the names of existing IKEv2 clients, run the helper script with the --listclients option. Use option -h to show usage.

bash
sudo ikev2.sh --listclients

Add a client certificate

To generate certificates for additional IKEv2 clients, run the helper script with the --addclient option. To customize client options, run the script without arguments.

bash
sudo ikev2.sh --addclient [client name]

Alternatively, you may manually add a client certificate. Refer to step 4 in this section.

Export configuration for an existing client

By default, the IKEv2 helper script exports client configuration after running. If later you want to export an existing client, you may use:

bash
sudo ikev2.sh --exportclient [client name]

Delete a client certificate

Important: Deleting a client certificate from the IPsec database WILL NOT prevent VPN client(s) from connecting using that certificate! For this use case, you MUST revoke the client certificate instead of deleting it.

First, read the important note above. Then click here for instructions.

Warning: The client certificate and private key will be permanently deleted. This cannot be undone!

To delete an existing client:

bash
sudo ikev2.sh --deleteclient [client name]

Alternatively, you can manually delete a client certificate.

  1. List certificates in the IPsec database:

    bash
    certutil -L -d sql:/etc/ipsec.d

    Example output:

    text
    Certificate Nickname                               Trust Attributes
                                                       SSL,S/MIME,JAR/XPI
    
    IKEv2 VPN CA                                       CTu,u,u
    ($PUBLIC_IP)                                       u,u,u
    vpnclient                                          u,u,u
  2. Delete the client certificate and private key. Replace "Nickname" below with the nickname of the client certificate you want to delete, e.g. vpnclient.

    bash
    certutil -F -d sql:/etc/ipsec.d -n "Nickname"
    certutil -D -d sql:/etc/ipsec.d -n "Nickname" 2>/dev/null
  3. (Optional) Delete the previously generated client configuration files (.p12, .mobileconfig and .sswan files) for this VPN client, if any.

Revoke a client certificate

In certain circumstances, you may need to revoke a previously generated VPN client certificate.

To revoke an existing client:

bash
sudo ikev2.sh --revokeclient [client name]

Alternatively, you can manually revoke a client certificate.

Alternatively, you can manually revoke a client certificate. This can be done using crlutil. See example steps below, commands must be run as root.

  1. Check the database, and identify the nickname of the client certificate you want to revoke.

    bash
    certutil -L -d sql:/etc/ipsec.d
    text
    Certificate Nickname                               Trust Attributes
                                                       SSL,S/MIME,JAR/XPI
    
    IKEv2 VPN CA                                       CTu,u,u
    ($PUBLIC_IP)                                       u,u,u
    vpnclient-to-revoke                                u,u,u

    In this example, we will revoke the certificate with nickname vpnclient-to-revoke, issued by IKEv2 VPN CA.

  2. Find the serial number of this client certificate.

    bash
    certutil -L -d sql:/etc/ipsec.d -n "vpnclient-to-revoke"
    text
    Certificate:
        Data:
            Version: 3 (0x2)
            Serial Number:
                00:cd:69:ff:74
    ... ...

    From the output, we see that the serial number is CD69FF74 in hexadecimal, which is 3446275956 in decimal. It will be used in the next steps.

  3. Create a new Certificate Revocation List (CRL). You only need to do this once for each CA.

    bash
    if ! crlutil -L -d sql:/etc/ipsec.d -n "IKEv2 VPN CA" 2>/dev/null; then
      crlutil -G -d sql:/etc/ipsec.d -n "IKEv2 VPN CA" -c /dev/null
    fi
    text
    CRL Info:
    :
        Version: 2 (0x1)
        Signature Algorithm: PKCS #1 SHA-256 With RSA Encryption
        Issuer: "O=IKEv2 VPN,CN=IKEv2 VPN CA"
        This Update: Sat Jun 06 22:00:00 2020
        CRL Extensions:
  4. Add the client certificate you want to revoke to the CRL. Here we specify the certificate's serial number in decimal, and the revocation time in GeneralizedTime format (YYYYMMDDhhmmssZ) in UTC.

    bash
    crlutil -M -d sql:/etc/ipsec.d -n "IKEv2 VPN CA" <<EOF
    addcert 3446275956 20200606220100Z
    EOF
    text
    CRL Info:
    :
        Version: 2 (0x1)
        Signature Algorithm: PKCS #1 SHA-256 With RSA Encryption
        Issuer: "O=IKEv2 VPN,CN=IKEv2 VPN CA"
        This Update: Sat Jun 06 22:02:00 2020
        Entry 1 (0x1):
            Serial Number:
                00:cd:69:ff:74
            Revocation Date: Sat Jun 06 22:01:00 2020
        CRL Extensions:

    Note: If you want to remove a certificate from the CRL, replace addcert 3446275956 20200606220100Z above with rmcert 3446275956. For other crlutil usage, read here.

  5. Finally, let Libreswan re-read the updated CRL.

    bash
    ipsec crls

Change IKEv2 server address

In certain circumstances, you may need to change the IKEv2 server address after setup. For example, to switch to use a DNS name, or after server IP changes. Note that the server address you specify on VPN client devices must exactly match the server address in the output of the IKEv2 helper script. Otherwise, devices may be unable to connect.

To change the server address, run the helper script and follow the prompts.

bash
wget https://get.vpnsetup.net/ikev2addr -O ikev2addr.sh
sudo bash ikev2addr.sh

Important: After running this script, you must manually update the server address (and remote ID, if applicable) on any existing IKEv2 client devices. For iOS clients, you'll need to run sudo ikev2.sh to export the updated client config file and import it to the iOS device.

Update IKEv2 helper script

The IKEv2 helper script is updated from time to time for bug fixes and improvements (commit log). When a newer version is available, you may optionally update the IKEv2 helper script on your server. Note that these commands will overwrite any existing ikev2.sh.

bash
wget https://get.vpnsetup.net/ikev2 -O /opt/src/ikev2.sh
chmod +x /opt/src/ikev2.sh && ln -s /opt/src/ikev2.sh /usr/bin 2>/dev/null

Set up IKEv2 using helper script

Note: By default, IKEv2 is automatically set up when running the VPN setup script. You may skip this section and continue to configure IKEv2 VPN clients.

Important: Before continuing, you should have successfully set up your own VPN server. Docker users, see Configure and use IKEv2 VPN.

Use this helper script to automatically set up IKEv2 on the VPN server:

bash
# Set up IKEv2 using default options
sudo ikev2.sh --auto
# Alternatively, you may customize IKEv2 options
sudo ikev2.sh

Note: If IKEv2 is already set up, but you want to customize IKEv2 options, first remove IKEv2, then set it up again using sudo ikev2.sh.

When finished, continue to configure IKEv2 VPN clients. Advanced users can optionally enable IKEv2-only mode.

Error: "sudo: ikev2.sh: command not found".

This is normal if you used an older version of the VPN setup script. First, download the IKEv2 helper script:

bash
wget https://get.vpnsetup.net/ikev2 -O /opt/src/ikev2.sh
chmod +x /opt/src/ikev2.sh && ln -s /opt/src/ikev2.sh /usr/bin

Then run the script using the instructions above.

You may optionally specify a DNS name, client name and/or custom DNS servers.

When running IKEv2 setup in auto mode, advanced users can optionally specify a DNS name for the IKEv2 server address. The DNS name must be a fully qualified domain name (FQDN). Example:

bash
sudo VPN_DNS_NAME='vpn.example.com' ikev2.sh --auto

Similarly, you may specify a name for the first IKEv2 client. The default is vpnclient if not specified.

bash
sudo VPN_CLIENT_NAME='your_client_name' ikev2.sh --auto

By default, IKEv2 clients are set to use Google Public DNS when the VPN is active. You may specify custom DNS server(s) for IKEv2. Example:

bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 ikev2.sh --auto

By default, no password is required when importing IKEv2 client configuration. You can choose to protect client config files using a random password.

bash
sudo VPN_PROTECT_CONFIG=yes ikev2.sh --auto

View usage information for the IKEv2 script.

text
Usage: bash ikev2.sh [options]

Options:
  --auto                        run IKEv2 setup in auto mode using default options (for initial setup only)
  --addclient [client name]     add a new client using default options
  --exportclient [client name]  export configuration for an existing client
  --listclients                 list the names of existing clients
  --revokeclient [client name]  revoke an existing client
  --deleteclient [client name]  delete an existing client
  --removeikev2                 remove IKEv2 and delete all certificates and keys from the IPsec database
  -y, --yes                     assume "yes" as answer to prompts when revoking/deleting a client or removing IKEv2
  -h, --help                    show this help message and exit

To customize IKEv2 or client options, run this script without arguments.

Manually set up IKEv2

As an alternative to using the helper script, advanced users can manually set up IKEv2 on the VPN server. Before continuing, it is recommended to update Libreswan to the latest version.

The following example shows how to manually configure IKEv2 with Libreswan. Commands below must be run as root.

View example steps for manually configuring IKEv2 with Libreswan.

  1. Find the VPN server's public IP, save it to a variable and check.

    bash
    PUBLIC_IP=$(dig @resolver1.opendns.com -t A -4 myip.opendns.com +short)
    [ -z "$PUBLIC_IP" ] && PUBLIC_IP=$(wget -t 2 -T 10 -qO- http://ipv4.icanhazip.com)
    printf '%s\n' "$PUBLIC_IP"

    Check to make sure the output matches the server's public IP. This variable is required in the steps below.

    Note: Alternatively, you may specify the server's DNS name here. e.g. PUBLIC_IP=myvpn.example.com.

  2. Add a new IKEv2 connection:

    bash
    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

    Note: If you specified the server's DNS name (instead of its IP address) in step 1 above, you must replace leftid=$PUBLIC_IP in the command below with leftid=@$PUBLIC_IP.

    bash
    cat > /etc/ipsec.d/ikev2.conf <<EOF
    
    conn ikev2-cp
      left=%defaultroute
      leftcert=$PUBLIC_IP
      leftid=$PUBLIC_IP
      leftsendcert=always
      leftsubnet=0.0.0.0/0
      leftrsasigkey=%cert
      right=%any
      rightid=%fromcert
      rightaddresspool=192.168.43.10-192.168.43.250
      rightca=%same
      rightrsasigkey=%cert
      narrowing=yes
      dpddelay=30
      retransmit-timeout=300s
      auto=add
      ikev2=insist
      rekey=no
      pfs=no
      ike=aes_gcm_c_256-hmac_sha2_256-ecp_256,aes256-sha2,aes128-sha2,aes256-sha1,aes128-sha1
      phase2alg=aes_gcm-null,aes128-sha1,aes256-sha1,aes128-sha2,aes256-sha2
      ikelifetime=24h
      salifetime=24h
    EOF

    We need to add a few more lines to that file. First check your Libreswan version, then run one of the following commands:

    bash
    ipsec --version

    For Libreswan 3.23 and newer:

    bash
    cat >> /etc/ipsec.d/ikev2.conf <<EOF
      modecfgdns="8.8.8.8 8.8.4.4"
      encapsulation=yes
      mobike=no
    EOF

    Note: The MOBIKE IKEv2 extension allows VPN clients to change network attachment points, e.g. switch between mobile data and Wi-Fi and keep the IPsec tunnel up on the new IP. If your server (or Docker host) is NOT running Ubuntu Linux, and you wish to enable MOBIKE support, replace mobike=no with mobike=yes in the command above. DO NOT enable this option on Ubuntu systems or Raspberry Pis.

    For Libreswan 3.19-3.22:

    bash
    cat >> /etc/ipsec.d/ikev2.conf <<EOF
      modecfgdns1=8.8.8.8
      modecfgdns2=8.8.4.4
      encapsulation=yes
    EOF

    For Libreswan 3.18 and older:

    bash
    cat >> /etc/ipsec.d/ikev2.conf <<EOF
      modecfgdns1=8.8.8.8
      modecfgdns2=8.8.4.4
      forceencaps=yes
    EOF
  3. Generate Certificate Authority (CA) and VPN server certificates.

    Note: Specify the certificate validity period (in months) with "-v". e.g. "-v 120".

    Generate CA certificate:

    bash
    certutil -z <(head -c 1024 /dev/urandom) \
      -S -x -n "IKEv2 VPN CA" \
      -s "O=IKEv2 VPN,CN=IKEv2 VPN CA" \
      -k rsa -g 3072 -v 120 \
      -d sql:/etc/ipsec.d -t "CT,," -2
    text
    Generating key.  This may take a few moments...
    
    Is this a CA certificate [y/N]?
    y
    Enter the path length constraint, enter to skip [<0 for unlimited path]: >
    Is this a critical extension [y/N]?
    N

    Generate VPN server certificate:

    Note: If you specified the server's DNS name (instead of its IP address) in step 1 above, you must replace --extSAN "ip:$PUBLIC_IP,dns:$PUBLIC_IP" in the command below with --extSAN "dns:$PUBLIC_IP".

    bash
    certutil -z <(head -c 1024 /dev/urandom) \
      -S -c "IKEv2 VPN CA" -n "$PUBLIC_IP" \
      -s "O=IKEv2 VPN,CN=$PUBLIC_IP" \
      -k rsa -g 3072 -v 120 \
      -d sql:/etc/ipsec.d -t ",," \
      --keyUsage digitalSignature,keyEncipherment \
      --extKeyUsage serverAuth \
      --extSAN "ip:$PUBLIC_IP,dns:$PUBLIC_IP"
    text
    Generating key.  This may take a few moments...
  4. Generate client certificate(s), then export the .p12 file that contains the client certificate, private key, and CA certificate.

    Note: You may repeat this step to generate certificates for additional VPN clients, but make sure to replace every vpnclient with vpnclient2, etc. To connect multiple IKEv2 clients from behind the same NAT (e.g. home router) at the same time, you will need to generate a unique certificate for each client.

    Generate client certificate:

    bash
    certutil -z <(head -c 1024 /dev/urandom) \
      -S -c "IKEv2 VPN CA" -n "vpnclient" \
      -s "O=IKEv2 VPN,CN=vpnclient" \
      -k rsa -g 3072 -v 120 \
      -d sql:/etc/ipsec.d -t ",," \
      --keyUsage digitalSignature,keyEncipherment \
      --extKeyUsage serverAuth,clientAuth -8 "vpnclient"
    text
    Generating key.  This may take a few moments...

    Export .p12 file:

    bash
    pk12util -d sql:/etc/ipsec.d -n "vpnclient" -o vpnclient.p12
    text
    Enter password for PKCS12 file:
    Re-enter password:
    pk12util: PKCS12 EXPORT SUCCESSFUL

    Enter a secure password to protect the exported .p12 file (when importing into an iOS or macOS device, this password cannot be empty).

  5. (For iOS clients) Export the CA certificate as ca.cer:

    bash
    certutil -L -d sql:/etc/ipsec.d -n "IKEv2 VPN CA" -a -o ca.cer
  6. The database should now contain:

    bash
    certutil -L -d sql:/etc/ipsec.d
    text
    Certificate Nickname                               Trust Attributes
                                                       SSL,S/MIME,JAR/XPI
    
    IKEv2 VPN CA                                       CTu,u,u
    ($PUBLIC_IP)                                       u,u,u
    vpnclient                                          u,u,u

    Note: To display a certificate, use certutil -L -d sql:/etc/ipsec.d -n "Nickname". To revoke a client certificate, follow these steps. For other certutil usage, read here.

  7. (Important) Restart the IPsec service:

    bash
    service ipsec restart

Before continuing, you must restart the IPsec service. The IKEv2 setup on the VPN server is now complete. Follow instructions to configure VPN clients.

Remove IKEv2

If you want to remove IKEv2 from the VPN server, but keep the IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes (if installed), run the helper script. Warning: All IKEv2 configuration including certificates and keys will be permanently deleted. This cannot be undone!

bash
sudo ikev2.sh --removeikev2

After removing IKEv2, if you want to set it up again, refer to this section.

Alternatively, you can manually remove IKEv2.

To manually remove IKEv2 from the VPN server, but keep the IPsec/L2TP and IPsec/XAuth ("Cisco IPsec") modes, follow these steps. Commands must be run as root.

Warning: All IKEv2 configuration including certificates and keys will be permanently deleted. This cannot be undone!

  1. Rename (or delete) the IKEv2 config file:

    bash
    mv /etc/ipsec.d/ikev2.conf /etc/ipsec.d/ikev2.conf.bak

    Note: If you used an older version (before 2020-05-31) of the IKEv2 helper script or instructions, file /etc/ipsec.d/ikev2.conf may not exist. In this case, please instead remove the conn ikev2-cp section from file /etc/ipsec.conf.

  2. (Important) Restart the IPsec service:

    bash
    service ipsec restart
  3. List certificates in the IPsec database:

    bash
    certutil -L -d sql:/etc/ipsec.d

    Example output:

    text
    Certificate Nickname                               Trust Attributes
                                                       SSL,S/MIME,JAR/XPI
    
    IKEv2 VPN CA                                       CTu,u,u
    ($PUBLIC_IP)                                       u,u,u
    vpnclient                                          u,u,u
  4. Delete the Certificate Revocation List (CRL), if any:

    bash
    crlutil -D -d sql:/etc/ipsec.d -n "IKEv2 VPN CA" 2>/dev/null
  5. Delete certificates and keys. Replace "Nickname" below with each certificate's nickname. Repeat these commands for each certificate. When finished, list certificates in the IPsec database again, and confirm that the list is empty.

    bash
    certutil -F -d sql:/etc/ipsec.d -n "Nickname"
    certutil -D -d sql:/etc/ipsec.d -n "Nickname" 2>/dev/null

References

License

Copyright (C) 2016-2026 Lin Song


This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License
Attribution required: please include my name in any derivative and let me know how you have improved it!