Showing preview only (727K chars total). Download the full file or copy to clipboard to get everything.
Repository: hwdsl2/setup-ipsec-vpn
Branch: master
Commit: dac31b87874f
Files: 59
Total size: 700.9 KB
Directory structure:
gitextract_z3qo90ab/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── 00-bug-report.md
│ │ ├── 10-bug-report-zh.md
│ │ ├── 20-enhancement-request.md
│ │ └── 30-enhancement-request-zh.md
│ └── workflows/
│ ├── check_urls.yml
│ ├── cron.yml
│ ├── main.yml
│ ├── shellcheck.yml
│ ├── test_set_1.yml
│ └── test_set_2.yml
├── LICENSE.md
├── README-ja.md
├── README-ru.md
├── README-zh-Hant.md
├── README-zh.md
├── README.md
├── aws/
│ ├── README-zh.md
│ ├── README.md
│ └── cloudformation-template-ipsec.json
├── azure/
│ ├── README-zh.md
│ ├── README.md
│ ├── azuredeploy.json
│ ├── azuredeploy.parameters.json
│ └── install.sh
├── docs/
│ ├── advanced-usage-zh.md
│ ├── advanced-usage.md
│ ├── bbr-zh.md
│ ├── bbr.md
│ ├── clients-xauth-zh.md
│ ├── clients-xauth.md
│ ├── clients-zh.md
│ ├── clients.md
│ ├── ikev2-howto-zh.md
│ ├── ikev2-howto.md
│ ├── manage-users-zh.md
│ ├── manage-users.md
│ ├── uninstall-zh.md
│ ├── uninstall.md
│ ├── vpn-book-ja.md
│ ├── vpn-book-zh-Hant.md
│ ├── vpn-book-zh.md
│ └── vpn-book.md
├── extras/
│ ├── add_vpn_user.sh
│ ├── del_vpn_user.sh
│ ├── ikev2changeaddr.sh
│ ├── ikev2onlymode.sh
│ ├── ikev2setup.sh
│ ├── update_vpn_users.sh
│ ├── vpnuninstall.sh
│ ├── vpnupgrade.sh
│ ├── vpnupgrade_alpine.sh
│ ├── vpnupgrade_amzn.sh
│ ├── vpnupgrade_centos.sh
│ └── vpnupgrade_ubuntu.sh
├── vpnsetup.sh
├── vpnsetup_alpine.sh
├── vpnsetup_amzn.sh
├── vpnsetup_centos.sh
└── vpnsetup_ubuntu.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/00-bug-report.md
================================================
---
name: Bug report
about: Tell us about a problem you are experiencing
title: ''
labels: ''
assignees: ''
---
**Checklist**
- [ ] I read the [README](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README.md)
- [ ] I read the [Important notes](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README.md#important-notes)
- [ ] I followed instructions to [configure VPN clients](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README.md#next-steps)
- [ ] I checked [IKEv1 troubleshooting](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients.md#ikev1-troubleshooting), [IKEv2 troubleshooting](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/ikev2-howto.md#ikev2-troubleshooting) and [VPN status](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients.md#check-logs-and-vpn-status)
- [ ] I searched existing [Issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue)
- [ ] This bug is about the VPN setup scripts, and not IPsec VPN itself
<!---
If you found a reproducible bug for the IPsec VPN, open a bug report at https://github.com/libreswan/libreswan. Ask VPN-related questions on the [Libreswan](https://lists.libreswan.org) or [strongSwan](https://lists.strongswan.org) users mailing list, or search e.g. [Stack Overflow](https://stackoverflow.com/questions/tagged/vpn).
--->
**Describe the issue**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. ...
2. ...
**Expected behavior**
A clear and concise description of what you expected to happen.
**Logs**
[Check logs and VPN status](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients.md#check-logs-and-vpn-status), and add error logs to help explain the problem, if applicable.
**Server (please complete the following information)**
- OS: [e.g. Debian 11]
- Hosting provider (if applicable): [e.g. GCP, AWS]
**Client (please complete the following information)**
- Device: [e.g. iPhone 12]
- OS: [e.g. iOS 15]
- VPN mode: [IPsec/L2TP, IPsec/XAuth ("Cisco IPsec") or IKEv2]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/10-bug-report-zh.md
================================================
---
name: 错误报告
about: 请使用这个模板来提交 bug
title: ''
labels: ''
assignees: ''
---
**任务列表**
- [ ] 我已阅读[自述文件](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README-zh.md)
- [ ] 我已阅读[重要提示](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README-zh.md#重要提示)
- [ ] 我已按照说明[配置 VPN 客户端](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README-zh.md#下一步)
- [ ] 我检查了 [IKEv1 故障排除](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients-zh.md#ikev1-故障排除),[IKEv2 故障排除](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/ikev2-howto-zh.md#ikev2-故障排除)以及 [VPN 状态](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients-zh.md#检查日志及-vpn-状态)
- [ ] 我搜索了已有的 [Issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue)
- [ ] 这个 bug 是关于 VPN 安装脚本,而不是 IPsec VPN 本身
<!---
如果你发现了 IPsec VPN 的一个可重复的程序漏洞,请在 https://github.com/libreswan/libreswan 提交一个错误报告。VPN 的相关问题可在 [Libreswan](https://lists.libreswan.org) 或 [strongSwan](https://lists.strongswan.org) 用户邮件列表提问,或者搜索比如 [Stack Overflow](https://stackoverflow.com/questions/tagged/vpn) 等网站。
--->
**问题描述**
使用清楚简明的语言描述这个 bug。
**重现步骤**
重现该 bug 的步骤:
1. ...
2. ...
**期待的正确结果**
简要地描述你期望的正确结果。
**日志**
[检查日志及 VPN 状态](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients-zh.md#检查日志及-vpn-状态),并添加错误日志以帮助解释该问题(如果适用)。
**服务器信息(请填写以下信息)**
- 操作系统: [比如 Debian 11]
- 服务提供商(如果适用): [比如 GCP, AWS]
**客户端信息(请填写以下信息)**
- 设备: [比如 iPhone 12]
- 操作系统: [比如 iOS 15]
- VPN 模式: [IPsec/L2TP, IPsec/XAuth ("Cisco IPsec") 或 IKEv2]
**其它信息**
添加关于该 bug 的其它信息。
================================================
FILE: .github/ISSUE_TEMPLATE/20-enhancement-request.md
================================================
---
name: Enhancement request
about: Suggest an improvement for this project
title: ''
labels: ''
assignees: ''
---
**Checklist**
- [ ] I searched existing [Issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue), and did not find a similar enhancement request
- [ ] This enhancement request is about the VPN setup scripts, and not IPsec VPN itself
- [ ] I read the [README](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README.md)
- [ ] I read the [Important notes](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README.md#important-notes)
- [ ] I followed instructions to [configure VPN clients](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README.md#next-steps)
- [ ] I checked [IKEv1 troubleshooting](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients.md#ikev1-troubleshooting), [IKEv2 troubleshooting](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/ikev2-howto.md#ikev2-troubleshooting) and [VPN status](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients.md#check-logs-and-vpn-status)
**Describe the enhancement request**
A clear and concise description of your enhancement request.
**Is your enhancement request related to a problem? Please describe.**
(If applicable) A clear and concise description of what the problem is.
**Additional context**
Add any other context about the enhancement request here.
================================================
FILE: .github/ISSUE_TEMPLATE/30-enhancement-request-zh.md
================================================
---
name: 改进建议
about: 请使用这个模板来提交改进建议
title: ''
labels: ''
assignees: ''
---
**任务列表**
- [ ] 我搜索了已有的 [Issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue),没有找到类似的改进建议
- [ ] 这个改进建议是关于 VPN 安装脚本,而不是 IPsec VPN 本身
- [ ] 我已阅读[自述文件](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README-zh.md)
- [ ] 我已阅读[重要提示](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README-zh.md#重要提示)
- [ ] 我已按照说明[配置 VPN 客户端](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/README-zh.md#下一步)
- [ ] 我检查了 [IKEv1 故障排除](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients-zh.md#ikev1-故障排除),[IKEv2 故障排除](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/ikev2-howto-zh.md#ikev2-故障排除)以及 [VPN 状态](https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients-zh.md#检查日志及-vpn-状态)
**描述改进建议**
使用清楚简明的语言描述你的改进建议。
**你的改进建议与遇到的问题有关吗?请描述。**
(如果适用)清楚,简洁地说明问题所在。
**其它信息**
添加关于该改进建议的其它信息。
================================================
FILE: .github/workflows/check_urls.yml
================================================
#
# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>
#
# This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
# Unported License: http://creativecommons.org/licenses/by-sa/3.0/
#
# Attribution required: please include my name in any derivative and let me
# know how you have improved it!
name: check_urls
on: workflow_call
jobs:
check_urls:
runs-on: ubuntu-24.04
if: github.repository_owner == 'hwdsl2'
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- name: Check
run: |
cd "$GITHUB_WORKSPACE"
mkdir workdir
cd workdir
set -ex
export DEBIAN_FRONTEND=noninteractive
sudo apt-get -yqq update
sudo apt-get -yqq install wget
wg="wget -t 3 -T 30 -nv -O"
sl="sleep 1"
gi="https://raw.githubusercontent.com/hwdsl2/setup-ipsec-vpn/master"
gh="https://github.com/hwdsl2/setup-ipsec-vpn/raw/master"
$wg vpnsetup.sh "$gi/vpnsetup.sh"; $sl
$wg vpnsetup_centos.sh "$gi/vpnsetup_centos.sh"; $sl
$wg vpnsetup_amzn.sh "$gi/vpnsetup_amzn.sh"; $sl
$wg vpnsetup_ubuntu.sh "$gi/vpnsetup_ubuntu.sh"; $sl
$wg vpnsetup_alpine.sh "$gi/vpnsetup_alpine.sh"; $sl
$wg ikev2setup.sh "$gi/extras/ikev2setup.sh"; $sl
$wg vpnupgrade.sh "$gi/extras/vpnupgrade.sh"; $sl
$wg vpnupgrade_centos.sh "$gi/extras/vpnupgrade_centos.sh"; $sl
$wg vpnupgrade_amzn.sh "$gi/extras/vpnupgrade_amzn.sh"; $sl
$wg vpnupgrade_ubuntu.sh "$gi/extras/vpnupgrade_ubuntu.sh"; $sl
$wg vpnupgrade_alpine.sh "$gi/extras/vpnupgrade_alpine.sh"; $sl
$wg vpnuninstall.sh "$gi/extras/vpnuninstall.sh"; $sl
$wg add_vpn_user.sh "$gi/extras/add_vpn_user.sh"; $sl
$wg del_vpn_user.sh "$gi/extras/del_vpn_user.sh"; $sl
$wg update_vpn_users.sh "$gi/extras/update_vpn_users.sh"; $sl
$wg ikev2changeaddr.sh "$gi/extras/ikev2changeaddr.sh"; $sl
$wg ikev2onlymode.sh "$gi/extras/ikev2onlymode.sh"; $sl
$wg vpnsetup2.sh "$gh/vpnsetup.sh"; $sl
$wg vpnsetup_centos2.sh "$gh/vpnsetup_centos.sh"; $sl
$wg vpnsetup_amzn2.sh "$gh/vpnsetup_amzn.sh"; $sl
$wg vpnsetup_ubuntu2.sh "$gh/vpnsetup_ubuntu.sh"; $sl
$wg vpnsetup_alpine2.sh "$gh/vpnsetup_alpine.sh"; $sl
$wg ikev2setup2.sh "$gh/extras/ikev2setup.sh"; $sl
$wg vpnupgrade2.sh "$gh/extras/vpnupgrade.sh"; $sl
$wg vpnupgrade_centos2.sh "$gh/extras/vpnupgrade_centos.sh"; $sl
$wg vpnupgrade_amzn2.sh "$gh/extras/vpnupgrade_amzn.sh"; $sl
$wg vpnupgrade_ubuntu2.sh "$gh/extras/vpnupgrade_ubuntu.sh"; $sl
$wg vpnupgrade_alpine2.sh "$gh/extras/vpnupgrade_alpine.sh"; $sl
$wg vpnuninstall2.sh "$gh/extras/vpnuninstall.sh"; $sl
$wg add_vpn_user2.sh "$gh/extras/add_vpn_user.sh"; $sl
$wg del_vpn_user2.sh "$gh/extras/del_vpn_user.sh"; $sl
$wg update_vpn_users2.sh "$gh/extras/update_vpn_users.sh"; $sl
$wg ikev2changeaddr2.sh "$gh/extras/ikev2changeaddr.sh"; $sl
$wg ikev2onlymode2.sh "$gh/extras/ikev2onlymode.sh"
diff vpnsetup.sh ../vpnsetup.sh
diff vpnsetup_centos.sh ../vpnsetup_centos.sh
diff vpnsetup_amzn.sh ../vpnsetup_amzn.sh
diff vpnsetup_ubuntu.sh ../vpnsetup_ubuntu.sh
diff vpnsetup_alpine.sh ../vpnsetup_alpine.sh
diff ikev2setup.sh ../extras/ikev2setup.sh
diff vpnupgrade.sh ../extras/vpnupgrade.sh
diff vpnupgrade_centos.sh ../extras/vpnupgrade_centos.sh
diff vpnupgrade_amzn.sh ../extras/vpnupgrade_amzn.sh
diff vpnupgrade_ubuntu.sh ../extras/vpnupgrade_ubuntu.sh
diff vpnupgrade_alpine.sh ../extras/vpnupgrade_alpine.sh
diff vpnuninstall.sh ../extras/vpnuninstall.sh
diff add_vpn_user.sh ../extras/add_vpn_user.sh
diff del_vpn_user.sh ../extras/del_vpn_user.sh
diff update_vpn_users.sh ../extras/update_vpn_users.sh
diff ikev2changeaddr.sh ../extras/ikev2changeaddr.sh
diff ikev2onlymode.sh ../extras/ikev2onlymode.sh
diff vpnsetup2.sh ../vpnsetup.sh
diff vpnsetup_centos2.sh ../vpnsetup_centos.sh
diff vpnsetup_amzn2.sh ../vpnsetup_amzn.sh
diff vpnsetup_ubuntu2.sh ../vpnsetup_ubuntu.sh
diff vpnsetup_alpine2.sh ../vpnsetup_alpine.sh
diff ikev2setup2.sh ../extras/ikev2setup.sh
diff vpnupgrade2.sh ../extras/vpnupgrade.sh
diff vpnupgrade_centos2.sh ../extras/vpnupgrade_centos.sh
diff vpnupgrade_amzn2.sh ../extras/vpnupgrade_amzn.sh
diff vpnupgrade_ubuntu2.sh ../extras/vpnupgrade_ubuntu.sh
diff vpnupgrade_alpine2.sh ../extras/vpnupgrade_alpine.sh
diff vpnuninstall2.sh ../extras/vpnuninstall.sh
diff add_vpn_user2.sh ../extras/add_vpn_user.sh
diff del_vpn_user2.sh ../extras/del_vpn_user.sh
diff update_vpn_users2.sh ../extras/update_vpn_users.sh
diff ikev2changeaddr2.sh ../extras/ikev2changeaddr.sh
diff ikev2onlymode2.sh ../extras/ikev2onlymode.sh
================================================
FILE: .github/workflows/cron.yml
================================================
#
# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>
#
# This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
# Unported License: http://creativecommons.org/licenses/by-sa/3.0/
#
# Attribution required: please include my name in any derivative and let me
# know how you have improved it!
name: build cron
on:
schedule:
- cron: '25 2 * * 0,4'
jobs:
check_urls:
if: github.repository_owner == 'hwdsl2'
uses: ./.github/workflows/check_urls.yml
test_set_1:
needs: check_urls
uses: ./.github/workflows/test_set_1.yml
test_set_2:
needs: check_urls
uses: ./.github/workflows/test_set_2.yml
================================================
FILE: .github/workflows/main.yml
================================================
#
# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>
#
# This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
# Unported License: http://creativecommons.org/licenses/by-sa/3.0/
#
# Attribution required: please include my name in any derivative and let me
# know how you have improved it!
name: build
on:
push:
branches: [master]
paths:
- '**.sh'
- '.github/workflows/main.yml'
- '.github/workflows/shellcheck.yml'
- '.github/workflows/test_set_1.yml'
- '.github/workflows/test_set_2.yml'
jobs:
shellcheck:
if: github.repository_owner == 'hwdsl2'
uses: ./.github/workflows/shellcheck.yml
test_set_1:
needs: shellcheck
uses: ./.github/workflows/test_set_1.yml
test_set_2:
needs: shellcheck
uses: ./.github/workflows/test_set_2.yml
================================================
FILE: .github/workflows/shellcheck.yml
================================================
#
# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>
#
# This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
# Unported License: http://creativecommons.org/licenses/by-sa/3.0/
#
# Attribution required: please include my name in any derivative and let me
# know how you have improved it!
name: shellcheck
on: workflow_call
jobs:
shellcheck:
runs-on: ubuntu-24.04
if: github.repository_owner == 'hwdsl2'
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- name: Check
run: |
if [ ! -x /usr/bin/shellcheck ]; then
export DEBIAN_FRONTEND=noninteractive
sudo apt-get -yqq update
sudo apt-get -yqq install shellcheck
fi
cd "$GITHUB_WORKSPACE"
pwd
ls -ld vpnsetup.sh
export SHELLCHECK_OPTS="-e SC1090,SC1091"
shellcheck --version
shopt -s globstar
ls -ld -- **/*.sh
shellcheck **/*.sh
================================================
FILE: .github/workflows/test_set_1.yml
================================================
#
# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>
#
# This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
# Unported License: http://creativecommons.org/licenses/by-sa/3.0/
#
# Attribution required: please include my name in any derivative and let me
# know how you have improved it!
name: test_set_1
on: workflow_call
jobs:
test_set_1:
runs-on: ubuntu-22.04
if: github.repository_owner == 'hwdsl2'
strategy:
matrix:
os_version: ["centos:10s", "centos:9s", "rockylinux:8", "almalinux:10", "almalinux:9", "almalinux:8", "oraclelinux:10", "oraclelinux:9", "oraclelinux:8"]
fail-fast: false
env:
OS_VERSION: ${{ matrix.os_version }}
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- name: Build
run: |
mkdir -p "$GITHUB_WORKSPACE/testing/${OS_VERSION//:}"
cd "$GITHUB_WORKSPACE/testing/${OS_VERSION//:}"
mkdir -p scripts/extras
ls -ld "$GITHUB_WORKSPACE/vpnsetup.sh"
cp -f "$GITHUB_WORKSPACE"/*.sh scripts/
cp -f "$GITHUB_WORKSPACE"/extras/*.sh scripts/extras/
cat > run.sh <<'EOF'
#!/bin/bash
set -eEx
log1=/var/log/secure
log2=/var/log/messages
trap 'catch $? $LINENO' ERR
catch() {
echo "Error $1 occurred on line $2."
cat -n -- "$0" | tail -n+"$(($2 - 3))" | head -n7
exit 1
}
restart_ipsec() {
if [ -f /etc/oracle-release ]; then
sleep 3
fi
systemctl restart ipsec
if grep -qs -i stream /etc/redhat-release \
&& grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
sleep 5
return 0
fi
echo "Waiting for IPsec to restart."
count=0
while ! grep -q "pluto\[$(cat /var/run/pluto/pluto.pid)\]: listening for IKE messages" "$log1"; do
[ "$count" -ge "30" ] && { echo "IPsec failed to start."; exit 1; }
count=$((count+1))
printf '%s' '.'
sleep 0.5
done
echo
}
restart_fail2ban() {
rm -f /var/log/fail2ban.log
systemctl restart fail2ban
echo "Waiting for Fail2ban to restart."
count=0
while ! grep -qs -E "Jail '(sshd?|ssh-iptables)' started" /var/log/fail2ban.log; do
[ "$count" -ge "30" ] && { echo "Fail2ban failed to start."; exit 1; }
count=$((count+1))
printf '%s' '.'
sleep 0.5
done
echo
}
cd /opt/src
if grep -qs -i rocky /etc/redhat-release; then
yum -y -q update
fi
yum -y -q install wget rsyslog
if grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
if grep -qs -i rocky /etc/redhat-release \
|| grep -qs -i alma /etc/redhat-release; then
yum -y -q install diffutils
fi
fi
if ! grep -qs -i stream /etc/redhat-release \
|| ! grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
systemctl start rsyslog
fi
cp -f /opt/src/scripts/vpnsetup.sh .
cp -f /opt/src/scripts/extras/vpnuninstall.sh ./vpnunst.sh
sed -i -e '/curl /a sed -i "/swan_ver_latest=/s/^/#/" "$tmpdir/vpn.sh"' \
-e '/curl /a sed -i \x27/status=0/a sed -i "/swan_ver_latest=/s/^/#/" /opt/src/ikev2.sh\x27 "$tmpdir/vpn.sh"' \
vpnsetup.sh
sh vpnsetup.sh
systemctl restart xl2tpd
restart_ipsec
if ! grep -qsE 'release (9|1[0-9])' /etc/oracle-release; then
if ! grep -qs -i stream /etc/redhat-release \
|| ! grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
restart_fail2ban
cat /var/log/fail2ban.log
fi
fi
netstat -anpu | grep pluto
netstat -anpu | grep xl2tpd
if grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
nft list ruleset
nft list ruleset | grep -q '192\.168\.42\.0/24'
nft list ruleset | grep -q '192\.168\.43\.0/24'
else
iptables -nvL
iptables -nvL | grep -q 'ppp+'
iptables -nvL | grep -q '192\.168\.43\.0/24'
iptables -nvL -t nat
iptables -nvL -t nat | grep -q '192\.168\.42\.0/24'
iptables -nvL -t nat | grep -q '192\.168\.43\.0/24'
fi
if ! grep -qs -i stream /etc/redhat-release \
|| ! grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
grep pluto "$log1"
grep xl2tpd "$log2"
fi
ipsec status
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
ls -ld /etc/ipsec.d/vpnclient.mobileconfig
ls -ld /etc/ipsec.d/vpnclient.sswan
ls -ld /etc/ipsec.d/vpnclient.p12
ls -l /usr/bin/ikev2.sh
ls -l /usr/bin/addvpnuser.sh
ls -l /usr/bin/delvpnuser.sh
ls -l /opt/src/ikev2.sh
ls -l /opt/src/addvpnuser.sh
ls -l /opt/src/delvpnuser.sh
bash vpnunst.sh <<ANSWERS
y
ANSWERS
rm -f /etc/ipsec.d/vpnclient*
if grep -qs -i stream /etc/redhat-release \
|| grep -qsE 'release (8|9|1[0-9])' /etc/oracle-release; then
mkdir /etc/xl2tpd
fi
if grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
if grep -qs -i rocky /etc/redhat-release \
|| grep -qs -i alma /etc/redhat-release; then
mkdir /etc/xl2tpd
fi
fi
cp -f /opt/src/scripts/vpnsetup_centos.sh ./vpnsetup.sh
sed -i -e '/swan_ver_latest=/s/^/#/' \
-e '/status=0/a sed -i "/swan_ver_latest=/s/^/#/" /opt/src/ikev2.sh' \
vpnsetup.sh
bash vpnsetup.sh
VPN_IPSEC_PSK='your_ipsec_pre_shared_key' \
VPN_USER='your_vpn_username' \
VPN_PASSWORD='your_vpn_password' \
VPN_DNS_SRV1='1.1.1.1' \
VPN_DNS_SRV2='1.0.0.1' \
bash vpnsetup.sh
systemctl restart xl2tpd
restart_ipsec
netstat -anpu | grep pluto
netstat -anpu | grep xl2tpd
if grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
nft list ruleset
nft list ruleset | grep -q '192\.168\.42\.0/24'
nft list ruleset | grep -q '192\.168\.43\.0/24'
else
iptables -nvL
iptables -nvL | grep -q 'ppp+'
iptables -nvL | grep -q '192\.168\.43\.0/24'
iptables -nvL -t nat
iptables -nvL -t nat | grep -q '192\.168\.42\.0/24'
iptables -nvL -t nat | grep -q '192\.168\.43\.0/24'
fi
ipsec status
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
grep -q "your_ipsec_pre_shared_key" /etc/ipsec.secrets
grep -q "your_vpn_username" /etc/ppp/chap-secrets
grep -q "your_vpn_password" /etc/ppp/chap-secrets
grep -q "your_vpn_username" /etc/ipsec.d/passwd
grep -q 'modecfgdns="1.1.1.1 1.0.0.1"' /etc/ipsec.conf
grep -q 'ms-dns 1.1.1.1' /etc/ppp/options.xl2tpd
grep -q 'ms-dns 1.0.0.1' /etc/ppp/options.xl2tpd
ls -ld /etc/ipsec.d/vpnclient.mobileconfig
ls -ld /etc/ipsec.d/vpnclient.sswan
ls -ld /etc/ipsec.d/vpnclient.p12
ls -l /usr/bin/ikev2.sh
ls -l /usr/bin/addvpnuser.sh
ls -l /usr/bin/delvpnuser.sh
ls -l /opt/src/ikev2.sh
ls -l /opt/src/addvpnuser.sh
ls -l /opt/src/delvpnuser.sh
rm -f /usr/bin/ikev2.sh /opt/src/ikev2.sh
rm -f /etc/ipsec.d/vpnclient*
cp -f /opt/src/scripts/extras/ikev2setup.sh ./ikev2.sh # hwdsl2
sed -i '/swan_ver_latest=/s/^/#/' ikev2.sh
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
bash ikev2.sh <<ANSWERS
ANSWERS
grep -q 'modecfgdns="8.8.8.8 8.8.4.4"' /etc/ipsec.d/ikev2.conf
ls -ld /etc/ipsec.d/vpnclient.mobileconfig
ls -ld /etc/ipsec.d/vpnclient.sswan
ls -ld /etc/ipsec.d/vpnclient.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient.p12 | grep AES-256 && exit 1
restart_ipsec
if ! grep -qs -i stream /etc/redhat-release \
|| ! grep -qsE 'release (9|1[0-9])' /etc/redhat-release; then
grep pluto "$log1" | tail -n 20
fi
ipsec status | grep -q ikev2-cp
bash ikev2.sh <<ANSWERS
1
invalidclient:
vpnclient
vpnclient2
ANSWERS
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
rm -f /etc/ipsec.d/vpnclient2*
bash ikev2.sh <<ANSWERS
2
nonexistclient
vpnclient2
ANSWERS
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
bash ikev2.sh <<ANSWERS
3
ANSWERS
bash ikev2.sh <<ANSWERS | grep -i "2 clients"
3
ANSWERS
bash ikev2.sh <<ANSWERS
4
nonexistclient
vpnclient2
y
ANSWERS
bash ikev2.sh <<ANSWERS 2>&1 | grep -i "abort"
4
vpnclient2
ANSWERS
bash ikev2.sh <<ANSWERS
5
vpnclient2
y
ANSWERS
bash ikev2.sh <<ANSWERS | grep -i "1 client"
3
ANSWERS
bash ikev2.sh <<ANSWERS 2>&1 | grep -i "abort"
2
vpnclient2
ANSWERS
bash ikev2.sh <<ANSWERS
100
7
ANSWERS
bash ikev2.sh <<ANSWERS 2>&1 | grep -i "abort"
6
ANSWERS
bash ikev2.sh <<ANSWERS
6
y
ANSWERS
restart_ipsec
ls -ld /etc/ipsec.d/ikev2.conf && exit 1
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp && exit 1
certutil -L -d sql:/etc/ipsec.d
rm -f /etc/ipsec.d/vpnclient*
VPN_DNS_SRV1=invaliddns \
bash ikev2.sh --auto 2>&1 | grep -i "invalid"
sed -i '/^include /d' /etc/ipsec.conf
VPN_CLIENT_NAME=vpnclient1 \
VPN_DNS_NAME=vpn.example.com \
VPN_DNS_SRV1=1.1.1.1 \
VPN_DNS_SRV2=1.0.0.1 \
bash ikev2.sh --auto
grep -q 'leftid=@vpn.example.com' /etc/ipsec.d/ikev2.conf
grep -q 'modecfgdns="1.1.1.1 1.0.0.1"' /etc/ipsec.d/ikev2.conf
ls -ld /etc/ipsec.d/vpnclient1.mobileconfig
ls -ld /etc/ipsec.d/vpnclient1.sswan
ls -ld /etc/ipsec.d/vpnclient1.p12
grep -q 'vpn.example.com' /etc/ipsec.d/vpnclient1.mobileconfig
grep -q 'vpn.example.com' /etc/ipsec.d/vpnclient1.sswan
restart_ipsec
ipsec status | grep -q ikev2-cp
bash ikev2.sh --addclient invalidclient: 2>&1 | grep -i "invalid"
bash ikev2.sh --addclient vpnclient1 2>&1 | grep -i "already exists"
bash ikev2.sh --addclient vpnclient2
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
bash ikev2.sh --exportclient nonexistclient 2>&1 | grep -i "does not exist"
rm -f /etc/ipsec.d/vpnclient2*
bash ikev2.sh --exportclient vpnclient2
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
bash ikev2.sh --addclient vpnclient2 --exportclient vpnclient2 2>&1 | grep -i "invalid"
bash ikev2.sh --listclients | grep "vpnclient1 \+valid"
bash ikev2.sh --listclients | grep "vpnclient2 \+valid"
bash ikev2.sh --listclients | grep "2 clients"
bash ikev2.sh --revokeclient nonexistclient 2>&1 | grep -i "does not exist"
bash ikev2.sh --revokeclient vpnclient2 <<ANSWERS
y
ANSWERS
bash ikev2.sh --listclients | grep "vpnclient2 \+revoked"
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig && exit 1
ls -ld /etc/ipsec.d/vpnclient2.sswan && exit 1
ls -ld /etc/ipsec.d/vpnclient2.p12 && exit 1
bash ikev2.sh --revokeclient vpnclient2 2>&1 | grep -i "already been revoked"
bash ikev2.sh --exportclient vpnclient2 2>&1 | grep -i "revoked"
bash ikev2.sh --deleteclient nonexistclient 2>&1 | grep -i "does not exist"
bash ikev2.sh --deleteclient vpnclient1 <<ANSWERS
y
ANSWERS
bash ikev2.sh --listclients | grep "1 client"
ls -ld /etc/ipsec.d/vpnclient1.mobileconfig && exit 1
ls -ld /etc/ipsec.d/vpnclient1.sswan && exit 1
ls -ld /etc/ipsec.d/vpnclient1.p12 && exit 1
bash ikev2.sh -h 2>&1 | grep -i "usage:"
bash ikev2.sh --invalidoption 2>&1 | grep -i "usage:"
bash ikev2.sh --removeikev2 --exportclient vpnclient1 2>&1 | grep -i "invalid"
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
rm -f /etc/ipsec.d/vpnclient*
bash ikev2.sh <<ANSWERS
y
invalidfqdn
vpn.example.com
y
invaliddns
1.1.1.1
invaliddns
1.0.0.1
y
ANSWERS
grep -q 'leftid=@vpn.example.com' /etc/ipsec.d/ikev2.conf
grep -q 'modecfgdns="1.1.1.1 1.0.0.1"' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
config_file="/etc/ipsec.d/.vpnconfig"
p12_pw=$(grep -s '^IKEV2_CONFIG_PASSWORD=.\+' "$config_file" | tail -n 1 | cut -f2- -d= | sed -e "s/^'//" -e "s/'$//")
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient.p12
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient.p12 | grep AES-256 && exit 1
bash ikev2.sh --addclient vpnclient2
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
bash ikev2.sh --exportclient vpnclient2
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
grep -qs '^IKEV2_CONFIG_PASSWORD=.\+' "$config_file" && exit 1
restart_ipsec
bash ikev2.sh <<ANSWERS
invalidip
1.2.3.4
invalidclient:
vpnclient1
1000
12
y
1.1.1.1
ANSWERS
grep -q 'leftid=1.2.3.4' /etc/ipsec.d/ikev2.conf
grep -q 'modecfgdns=1.1.1.1' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
VPN_DNS_SRV1=1.1.1.1 \
bash ikev2.sh --auto
grep -q 'modecfgdns=1.1.1.1' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
bash ikev2.sh --auto
grep -qs '^IKEV2_CONFIG_PASSWORD=.\+' "$config_file" && exit 1
grep -q 'modecfgdns="8.8.8.8 8.8.4.4"' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
cp -f /opt/src/scripts/extras/vpnupgrade.sh ./vpnup.sh
sed -i '/curl /a sed -i "/swan_ver_latest=/s/^/#/" "$tmpdir/vpnup.sh"' vpnup.sh
ver=5.2
sed -i "s/^SWAN_VER=.*/SWAN_VER=$ver/" vpnup.sh
bash vpnup.sh <<ANSWERS
ANSWERS
restart_ipsec
ipsec --version | grep "$ver"
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
cp -f /opt/src/scripts/extras/vpnupgrade_centos.sh ./vpnup.sh
sed -i '/swan_ver_latest=/s/^/#/' vpnup.sh
ver=5.3
bash vpnup.sh <<ANSWERS
ANSWERS
restart_ipsec
ipsec --version | grep "$ver"
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
ls -ld /etc/ipsec.d/ikev2.conf && exit 1
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp && exit 1
certutil -L -d sql:/etc/ipsec.d
exit 0
EOF
if [ "$OS_VERSION" = "centos:9s" ]; then
echo "FROM quay.io/centos/centos:stream9" > Dockerfile
elif [ "$OS_VERSION" = "centos:10s" ]; then
echo "FROM quay.io/centos/centos:stream10" > Dockerfile
else
echo "FROM $OS_VERSION" > Dockerfile
fi
cat >> Dockerfile <<'EOF'
ENV container=docker
WORKDIR /opt/src
EOF
if [ "$OS_VERSION" = "centos:9s" ] || [ "$OS_VERSION" = "centos:10s" ]; then
echo "RUN yum -y -q install systemd" >> Dockerfile
fi
cat >> Dockerfile <<'EOF'
RUN (cd /lib/systemd/system/sysinit.target.wants/; for i in *; do [ "$i" = \
systemd-tmpfiles-setup.service ] || rm -f "$i"; done); \
rm -f /lib/systemd/system/multi-user.target.wants/*; \
rm -f /etc/systemd/system/*.wants/*; \
rm -f /lib/systemd/system/local-fs.target.wants/*; \
rm -f /lib/systemd/system/sockets.target.wants/*udev*; \
rm -f /lib/systemd/system/sockets.target.wants/*initctl*; \
rm -f /lib/systemd/system/basic.target.wants/*; \
rm -f /lib/systemd/system/anaconda.target.wants/*;
COPY scripts/ /opt/src/scripts/
COPY ./run.sh /opt/src/run.sh
RUN chmod 755 /opt/src/run.sh
VOLUME [ "/sys/fs/cgroup" ]
CMD ["/sbin/init"]
EOF
cat Dockerfile
cat run.sh
docker build -t "${OS_VERSION//:}-test" .
- name: Test
run: |
docker run -d --name "${OS_VERSION//:}-test-1" -v /sys/fs/cgroup:/sys/fs/cgroup:rw \
--cgroupns=host --privileged "${OS_VERSION//:}-test"
sleep 5
docker exec "${OS_VERSION//:}-test-1" /opt/src/run.sh "${OS_VERSION::6}"
- name: Clear
if: always()
run: |
rm -rf "$GITHUB_WORKSPACE/testing/${OS_VERSION//:}"
docker rm -f "${OS_VERSION//:}-test-1" || true
docker rmi "${OS_VERSION//:}-test" || true
================================================
FILE: .github/workflows/test_set_2.yml
================================================
#
# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>
#
# This work is licensed under the Creative Commons Attribution-ShareAlike 3.0
# Unported License: http://creativecommons.org/licenses/by-sa/3.0/
#
# Attribution required: please include my name in any derivative and let me
# know how you have improved it!
name: test_set_2
on: workflow_call
jobs:
test_set_2:
runs-on: ubuntu-24.04
if: github.repository_owner == 'hwdsl2'
strategy:
matrix:
os_version: ["ubuntu:24.04", "ubuntu:22.04", "debian:13", "debian:12", "debian:11", "alpine:3.23", "alpine:3.22"]
fail-fast: false
container:
image: ${{ matrix.os_version }}
options: --cap-add=NET_ADMIN --device=/dev/ppp
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- name: Test
run: |
set -ex
os_type=""
[ -f /etc/os-release ] && os_type=$(. /etc/os-release && printf '%s' "$ID")
[ -z "$os_type" ] && exit 1
if [ "$os_type" != "alpine" ]; then
os_ver=$(sed 's/\..*//' /etc/debian_version | tr -dc 'A-Za-z0-9')
fi
log1=/var/log/auth.log
if [ "$os_type" = "alpine" ]; then
log2=/var/log/messages
else
log2=/var/log/syslog
fi
restart_ipsec() {
if [ "$os_type" = "alpine" ] || [ "$os_ver" = "trixiesid" ] || [ "$os_ver" = 13 ]; then
ipsec whack --shutdown || true
ipsec pluto --config /etc/ipsec.conf
fi
echo "Waiting for IPsec to restart."
count=0
while ! grep -q "pluto\[$(cat /var/run/pluto/pluto.pid)\]: listening for IKE messages" "$log1"; do
[ "$count" -ge "30" ] && { echo "IPsec failed to start."; exit 1; }
count=$((count+1))
printf '%s' '.'
sleep 0.5
done
echo
}
restart_fail2ban() {
rm -f /var/log/fail2ban.log
service fail2ban restart
echo "Waiting for Fail2ban to restart."
count=0
while ! grep -qs -E "Jail '(sshd?|ssh-iptables)' started" /var/log/fail2ban.log; do
[ "$count" -ge "30" ] && { echo "Fail2ban failed to start."; exit 1; }
count=$((count+1))
printf '%s' '.'
sleep 0.5
done
echo
}
mkdir -p /opt/src
cd /opt/src
ls -ld "$GITHUB_WORKSPACE/vpnsetup.sh"
echo "# hwdsl2" > run.sh
if [ "$os_type" = "alpine" ]; then
apk add -U wget rsyslog sed bash
rsyslogd
else
export DEBIAN_FRONTEND=noninteractive
apt-get -yqq update
apt-get -yqq install wget rsyslog
if [ "$os_ver" = "bookwormsid" ] || [ "$os_ver" = "trixiesid" ] \
|| [ "$os_ver" = 13 ] || [ "$os_ver" = 12 ]; then
rsyslogd
else
service rsyslog start
fi
fi
cp -f "$GITHUB_WORKSPACE"/vpnsetup.sh .
cp -f "$GITHUB_WORKSPACE"/extras/vpnuninstall.sh ./vpnunst.sh
sed -i -e '/curl /a sed -i "/swan_ver_latest=/s/^/#/" "$tmpdir/vpn.sh"' \
-e '/curl /a sed -i \x27/status=0/a sed -i "/swan_ver_latest=/s/^/#/" /opt/src/ikev2.sh\x27 "$tmpdir/vpn.sh"' \
vpnsetup.sh
sh vpnsetup.sh
if [ "$os_type" = "alpine" ]; then
xl2tpd -c /etc/xl2tpd/xl2tpd.conf
restart_ipsec
else
restart_ipsec
restart_fail2ban
cat /var/log/fail2ban.log
fi
netstat -anpu | grep pluto
netstat -anpu | grep xl2tpd
iptables -nvL
iptables -nvL | grep -q 'ppp+'
iptables -nvL | grep -q '192\.168\.43\.0/24'
iptables -nvL -t nat
iptables -nvL -t nat | grep -q '192\.168\.42\.0/24'
iptables -nvL -t nat | grep -q '192\.168\.43\.0/24'
grep pluto "$log1"
grep xl2tpd "$log2"
ipsec status
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
ls -ld /etc/ipsec.d/vpnclient.mobileconfig
ls -ld /etc/ipsec.d/vpnclient.sswan
ls -ld /etc/ipsec.d/vpnclient.p12
ls -l /usr/bin/ikev2.sh
ls -l /usr/bin/addvpnuser.sh
ls -l /usr/bin/delvpnuser.sh
ls -l /opt/src/ikev2.sh
ls -l /opt/src/addvpnuser.sh
ls -l /opt/src/delvpnuser.sh
bash vpnunst.sh <<ANSWERS
y
ANSWERS
rm -f /etc/ipsec.d/vpnclient*
if [ "$os_type" = "alpine" ]; then
killall pluto || true
killall xl2tpd || true
fi
if [ "$os_type" = "alpine" ]; then
cp -f "$GITHUB_WORKSPACE"/vpnsetup_alpine.sh ./vpnsetup.sh
else
cp -f "$GITHUB_WORKSPACE"/vpnsetup_ubuntu.sh ./vpnsetup.sh
fi
sed -i -e '/swan_ver_latest=/s/^/#/' \
-e '/status=0/a sed -i "/swan_ver_latest=/s/^/#/" /opt/src/ikev2.sh' \
vpnsetup.sh
bash vpnsetup.sh
VPN_IPSEC_PSK='your_ipsec_pre_shared_key' \
VPN_USER='your_vpn_username' \
VPN_PASSWORD='your_vpn_password' \
VPN_DNS_SRV1='1.1.1.1' \
VPN_DNS_SRV2='1.0.0.1' \
bash vpnsetup.sh
if [ "$os_type" = "alpine" ]; then
xl2tpd -c /etc/xl2tpd/xl2tpd.conf
fi
restart_ipsec
netstat -anpu | grep pluto
netstat -anpu | grep xl2tpd
iptables -nvL
iptables -nvL | grep -q 'ppp+'
iptables -nvL | grep -q '192\.168\.43\.0/24'
iptables -nvL -t nat
iptables -nvL -t nat | grep -q '192\.168\.42\.0/24'
iptables -nvL -t nat | grep -q '192\.168\.43\.0/24'
ipsec status
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
grep -q "your_ipsec_pre_shared_key" /etc/ipsec.secrets
grep -q "your_vpn_username" /etc/ppp/chap-secrets
grep -q "your_vpn_password" /etc/ppp/chap-secrets
grep -q "your_vpn_username" /etc/ipsec.d/passwd
grep -q 'modecfgdns="1.1.1.1 1.0.0.1"' /etc/ipsec.conf
grep -q 'ms-dns 1.1.1.1' /etc/ppp/options.xl2tpd
grep -q 'ms-dns 1.0.0.1' /etc/ppp/options.xl2tpd
ls -ld /etc/ipsec.d/vpnclient.mobileconfig
ls -ld /etc/ipsec.d/vpnclient.sswan
ls -ld /etc/ipsec.d/vpnclient.p12
ls -l /usr/bin/ikev2.sh
ls -l /usr/bin/addvpnuser.sh
ls -l /usr/bin/delvpnuser.sh
ls -l /opt/src/ikev2.sh
ls -l /opt/src/addvpnuser.sh
ls -l /opt/src/delvpnuser.sh
rm -f /usr/bin/ikev2.sh /opt/src/ikev2.sh
rm -f /etc/ipsec.d/vpnclient*
cp -f "$GITHUB_WORKSPACE"/extras/ikev2setup.sh ./ikev2.sh
sed -i '/swan_ver_latest=/s/^/#/' ikev2.sh
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
bash ikev2.sh <<ANSWERS
ANSWERS
grep -q 'modecfgdns="8.8.8.8 8.8.4.4"' /etc/ipsec.d/ikev2.conf
ls -ld /etc/ipsec.d/vpnclient.mobileconfig
ls -ld /etc/ipsec.d/vpnclient.sswan
ls -ld /etc/ipsec.d/vpnclient.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient.p12 | grep AES-256 && exit 1
restart_ipsec
grep pluto "$log1" | tail -n 20
ipsec status | grep -q ikev2-cp
bash ikev2.sh <<ANSWERS
1
invalidclient:
vpnclient
vpnclient2
ANSWERS
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
rm -f /etc/ipsec.d/vpnclient2*
bash ikev2.sh <<ANSWERS
2
nonexistclient
vpnclient2
ANSWERS
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
bash ikev2.sh <<ANSWERS
3
ANSWERS
bash ikev2.sh <<ANSWERS | grep -i "2 clients"
3
ANSWERS
bash ikev2.sh <<ANSWERS
4
nonexistclient
vpnclient2
y
ANSWERS
bash ikev2.sh <<ANSWERS 2>&1 | grep -i "abort"
4
vpnclient2
ANSWERS
bash ikev2.sh <<ANSWERS
5
vpnclient2
y
ANSWERS
bash ikev2.sh <<ANSWERS | grep -i "1 client"
3
ANSWERS
bash ikev2.sh <<ANSWERS 2>&1 | grep -i "abort"
2
vpnclient2
ANSWERS
bash ikev2.sh <<ANSWERS
100
7
ANSWERS
bash ikev2.sh <<ANSWERS 2>&1 | grep -i "abort"
6
ANSWERS
bash ikev2.sh <<ANSWERS
6
y
ANSWERS
restart_ipsec
ls -ld /etc/ipsec.d/ikev2.conf && exit 1
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp && exit 1
certutil -L -d sql:/etc/ipsec.d
rm -f /etc/ipsec.d/vpnclient*
VPN_DNS_SRV1=invaliddns \
bash ikev2.sh --auto 2>&1 | grep -i "invalid"
if [ "$os_type" = "alpine" ]; then
apk del uuidgen
else
apt-get -yqq remove uuid-runtime
fi
sed -i '/^include /d' /etc/ipsec.conf
VPN_CLIENT_NAME=vpnclient1 \
VPN_DNS_NAME=vpn.example.com \
VPN_DNS_SRV1=1.1.1.1 \
VPN_DNS_SRV2=1.0.0.1 \
bash ikev2.sh --auto
grep -q 'leftid=@vpn.example.com' /etc/ipsec.d/ikev2.conf
grep -q 'modecfgdns="1.1.1.1 1.0.0.1"' /etc/ipsec.d/ikev2.conf
ls -ld /etc/ipsec.d/vpnclient1.mobileconfig
ls -ld /etc/ipsec.d/vpnclient1.sswan
ls -ld /etc/ipsec.d/vpnclient1.p12
grep -q 'vpn.example.com' /etc/ipsec.d/vpnclient1.mobileconfig
grep -q 'vpn.example.com' /etc/ipsec.d/vpnclient1.sswan
restart_ipsec
ipsec status | grep -q ikev2-cp
bash ikev2.sh --addclient invalidclient: 2>&1 | grep -i "invalid"
bash ikev2.sh --addclient vpnclient1 2>&1 | grep -i "already exists"
bash ikev2.sh --addclient vpnclient2
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
bash ikev2.sh --exportclient nonexistclient 2>&1 | grep -i "does not exist"
rm -f /etc/ipsec.d/vpnclient2*
bash ikev2.sh --exportclient vpnclient2
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig
ls -ld /etc/ipsec.d/vpnclient2.sswan
ls -ld /etc/ipsec.d/vpnclient2.p12
bash ikev2.sh --addclient vpnclient2 --exportclient vpnclient2 2>&1 | grep -i "invalid"
bash ikev2.sh --listclients | grep "vpnclient1 \+valid"
bash ikev2.sh --listclients | grep "vpnclient2 \+valid"
bash ikev2.sh --listclients | grep "2 clients"
bash ikev2.sh --revokeclient nonexistclient 2>&1 | grep -i "does not exist"
bash ikev2.sh --revokeclient vpnclient2 <<ANSWERS
y
ANSWERS
bash ikev2.sh --listclients | grep "vpnclient2 \+revoked"
ls -ld /etc/ipsec.d/vpnclient2.mobileconfig && exit 1
ls -ld /etc/ipsec.d/vpnclient2.sswan && exit 1
ls -ld /etc/ipsec.d/vpnclient2.p12 && exit 1
bash ikev2.sh --revokeclient vpnclient2 2>&1 | grep -i "already been revoked"
bash ikev2.sh --exportclient vpnclient2 2>&1 | grep -i "revoked"
bash ikev2.sh --deleteclient nonexistclient 2>&1 | grep -i "does not exist"
bash ikev2.sh --deleteclient vpnclient1 <<ANSWERS
y
ANSWERS
bash ikev2.sh --listclients | grep "1 client"
ls -ld /etc/ipsec.d/vpnclient1.mobileconfig && exit 1
ls -ld /etc/ipsec.d/vpnclient1.sswan && exit 1
ls -ld /etc/ipsec.d/vpnclient1.p12 && exit 1
bash ikev2.sh -h 2>&1 | grep -i "usage:"
bash ikev2.sh --invalidoption 2>&1 | grep -i "usage:"
bash ikev2.sh --removeikev2 --exportclient vpnclient1 2>&1 | grep -i "invalid"
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
rm -f /etc/ipsec.d/vpnclient*
bash ikev2.sh <<ANSWERS
y
invalidfqdn
vpn.example.com
y
invaliddns
1.1.1.1
invaliddns
1.0.0.1
y
ANSWERS
grep -q 'leftid=@vpn.example.com' /etc/ipsec.d/ikev2.conf
grep -q 'modecfgdns="1.1.1.1 1.0.0.1"' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
config_file="/etc/ipsec.d/.vpnconfig"
p12_pw=$(grep -s '^IKEV2_CONFIG_PASSWORD=.\+' "$config_file" | tail -n 1 | cut -f2- -d= | sed -e "s/^'//" -e "s/'$//")
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient.p12
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient.p12 | grep AES-256 && exit 1
bash ikev2.sh --addclient vpnclient2
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
bash ikev2.sh --exportclient vpnclient2
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12
pk12util -W "$p12_pw" -l /etc/ipsec.d/vpnclient2.p12 | grep AES-256 && exit 1
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
grep -qs '^IKEV2_CONFIG_PASSWORD=.\+' "$config_file" && exit 1
restart_ipsec
bash ikev2.sh <<ANSWERS
invalidip
1.2.3.4
invalidclient:
vpnclient1
1000
12
y
1.1.1.1
ANSWERS
grep -q 'leftid=1.2.3.4' /etc/ipsec.d/ikev2.conf
grep -q 'modecfgdns=1.1.1.1' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
VPN_DNS_SRV1=1.1.1.1 \
bash ikev2.sh --auto
grep -q 'modecfgdns=1.1.1.1' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
bash ikev2.sh --auto
grep -qs '^IKEV2_CONFIG_PASSWORD=.\+' "$config_file" && exit 1
grep -q 'modecfgdns="8.8.8.8 8.8.4.4"' /etc/ipsec.d/ikev2.conf
restart_ipsec
ipsec status | grep -q ikev2-cp
cp -f "$GITHUB_WORKSPACE"/extras/vpnupgrade.sh ./vpnup.sh
sed -i '/curl /a sed -i "/swan_ver_latest=/s/^/#/" "$tmpdir/vpnup.sh"' vpnup.sh
ver=5.2
if [ "$os_type" = "alpine" ] || [ "$os_ver" = "trixiesid" ] || [ "$os_ver" = 13 ]; then
ipsec whack --shutdown || true
fi
sed -i "s/^SWAN_VER=.*/SWAN_VER=$ver/" vpnup.sh
bash vpnup.sh <<ANSWERS
ANSWERS
restart_ipsec
ipsec --version | grep "$ver"
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
if [ "$os_type" = "alpine" ]; then
cp -f "$GITHUB_WORKSPACE"/extras/vpnupgrade_alpine.sh ./vpnup.sh
else
cp -f "$GITHUB_WORKSPACE"/extras/vpnupgrade_ubuntu.sh ./vpnup.sh
fi
sed -i '/swan_ver_latest=/s/^/#/' vpnup.sh
ver=5.3
if [ "$os_type" = "alpine" ] || [ "$os_ver" = "trixiesid" ] || [ "$os_ver" = 13 ]; then
ipsec whack --shutdown || true
fi
bash vpnup.sh <<ANSWERS
ANSWERS
restart_ipsec
ipsec --version | grep "$ver"
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp
bash ikev2.sh --removeikev2 <<ANSWERS
y
ANSWERS
restart_ipsec
ls -ld /etc/ipsec.d/ikev2.conf && exit 1
ipsec status | grep -q l2tp-psk
ipsec status | grep -q xauth-psk
ipsec status | grep -q ikev2-cp && exit 1
certutil -L -d sql:/etc/ipsec.d
================================================
FILE: LICENSE.md
================================================
### Creative Commons Attribution-ShareAlike 3.0 Unported License
Link to license summary: https://creativecommons.org/licenses/by-sa/3.0/
Copyright (C) 2014-2026 [Lin Song](https://github.com/hwdsl2)
Based on [the work of Thomas Sarlandie](https://github.com/sarfata/voodooprivacy) (Copyright 2012)
See the [aws/](aws/) and [azure/](azure/) subfolders for their respective authors.
The following four files (only) are licensed under the GPL:
[clients.md](docs/clients.md), [clients-zh.md](docs/clients-zh.md), [clients-xauth.md](docs/clients-xauth.md) and [clients-xauth-zh.md](docs/clients-xauth-zh.md)
<p>THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS
OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR
"LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER
APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS
PROHIBITED.</p>
<p>BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU
ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE.
TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A
CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE
IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
CONDITIONS.</p>
<p><strong>1. Definitions</strong></p>
<ol type="a">
<li><strong>"Adaptation"</strong> means a work based upon
the Work, or upon the Work and other pre-existing works,
such as a translation, adaptation, derivative work,
arrangement of music or other alterations of a literary
or artistic work, or phonogram or performance and
includes cinematographic adaptations or any other form in
which the Work may be recast, transformed, or adapted
including in any form recognizably derived from the
original, except that a work that constitutes a
Collection will not be considered an Adaptation for the
purpose of this License. For the avoidance of doubt,
where the Work is a musical work, performance or
phonogram, the synchronization of the Work in
timed-relation with a moving image ("synching") will be
considered an Adaptation for the purpose of this
License.</li>
<li><strong>"Collection"</strong> means a collection of
literary or artistic works, such as encyclopedias and
anthologies, or performances, phonograms or broadcasts,
or other works or subject matter other than works listed
in Section 1(f) below, which, by reason of the selection
and arrangement of their contents, constitute
intellectual creations, in which the Work is included in
its entirety in unmodified form along with one or more
other contributions, each constituting separate and
independent works in themselves, which together are
assembled into a collective whole. A work that
constitutes a Collection will not be considered an
Adaptation (as defined below) for the purposes of this
License.</li>
<li><strong>"Creative Commons Compatible
License"</strong> means a license that is listed at
https://creativecommons.org/compatiblelicenses that has
been approved by Creative Commons as being essentially
equivalent to this License, including, at a minimum,
because that license: (i) contains terms that have the
same purpose, meaning and effect as the License Elements
of this License; and, (ii) explicitly permits the
relicensing of adaptations of works made available under
that license under this License or a Creative Commons
jurisdiction license with the same License Elements as
this License.</li>
<li><strong>"Distribute"</strong> means to make available
to the public the original and copies of the Work or
Adaptation, as appropriate, through sale or other
transfer of ownership.</li>
<li><strong>"License Elements"</strong> means the
following high-level license attributes as selected by
Licensor and indicated in the title of this License:
Attribution, ShareAlike.</li>
<li><strong>"Licensor"</strong> means the individual,
individuals, entity or entities that offer(s) the Work
under the terms of this License.</li>
<li><strong>"Original Author"</strong> means, in the case
of a literary or artistic work, the individual,
individuals, entity or entities who created the Work or
if no individual or entity can be identified, the
publisher; and in addition (i) in the case of a
performance the actors, singers, musicians, dancers, and
other persons who act, sing, deliver, declaim, play in,
interpret or otherwise perform literary or artistic works
or expressions of folklore; (ii) in the case of a
phonogram the producer being the person or legal entity
who first fixes the sounds of a performance or other
sounds; and, (iii) in the case of broadcasts, the
organization that transmits the broadcast.</li>
<li><strong>"Work"</strong> means the literary and/or
artistic work offered under the terms of this License
including without limitation any production in the
literary, scientific and artistic domain, whatever may be
the mode or form of its expression including digital
form, such as a book, pamphlet and other writing; a
lecture, address, sermon or other work of the same
nature; a dramatic or dramatico-musical work; a
choreographic work or entertainment in dumb show; a
musical composition with or without words; a
cinematographic work to which are assimilated works
expressed by a process analogous to cinematography; a
work of drawing, painting, architecture, sculpture,
engraving or lithography; a photographic work to which
are assimilated works expressed by a process analogous to
photography; a work of applied art; an illustration, map,
plan, sketch or three-dimensional work relative to
geography, topography, architecture or science; a
performance; a broadcast; a phonogram; a compilation of
data to the extent it is protected as a copyrightable
work; or a work performed by a variety or circus
performer to the extent it is not otherwise considered a
literary or artistic work.</li>
<li><strong>"You"</strong> means an individual or entity
exercising rights under this License who has not
previously violated the terms of this License with
respect to the Work, or who has received express
permission from the Licensor to exercise rights under
this License despite a previous violation.</li>
<li><strong>"Publicly Perform"</strong> means to perform
public recitations of the Work and to communicate to the
public those public recitations, by any means or process,
including by wire or wireless means or public digital
performances; to make available to the public Works in
such a way that members of the public may access these
Works from a place and at a place individually chosen by
them; to perform the Work to the public by any means or
process and the communication to the public of the
performances of the Work, including by public digital
performance; to broadcast and rebroadcast the Work by any
means including signs, sounds or images.</li>
<li><strong>"Reproduce"</strong> means to make copies of
the Work by any means including without limitation by
sound or visual recordings and the right of fixation and
reproducing fixations of the Work, including storage of a
protected performance or phonogram in digital form or
other electronic medium.</li>
</ol>
<p><strong>2. Fair Dealing Rights.</strong> Nothing in this
License is intended to reduce, limit, or restrict any uses
free from copyright or rights arising from limitations or
exceptions that are provided for in connection with the
copyright protection under copyright law or other
applicable laws.</p>
<p><strong>3. License Grant.</strong> Subject to the terms
and conditions of this License, Licensor hereby grants You
a worldwide, royalty-free, non-exclusive, perpetual (for
the duration of the applicable copyright) license to
exercise the rights in the Work as stated below:</p>
<ol type="a">
<li>to Reproduce the Work, to incorporate the Work into
one or more Collections, and to Reproduce the Work as
incorporated in the Collections;</li>
<li>to create and Reproduce Adaptations provided that any
such Adaptation, including any translation in any medium,
takes reasonable steps to clearly label, demarcate or
otherwise identify that changes were made to the original
Work. For example, a translation could be marked "The
original work was translated from English to Spanish," or
a modification could indicate "The original work has been
modified.";</li>
<li>to Distribute and Publicly Perform the Work including
as incorporated in Collections; and,</li>
<li>to Distribute and Publicly Perform Adaptations.</li>
<li>
<p>For the avoidance of doubt:</p>
<ol type="i">
<li><strong>Non-waivable Compulsory License
Schemes</strong>. In those jurisdictions in which the
right to collect royalties through any statutory or
compulsory licensing scheme cannot be waived, the
Licensor reserves the exclusive right to collect such
royalties for any exercise by You of the rights
granted under this License;</li>
<li><strong>Waivable Compulsory License
Schemes</strong>. In those jurisdictions in which the
right to collect royalties through any statutory or
compulsory licensing scheme can be waived, the
Licensor waives the exclusive right to collect such
royalties for any exercise by You of the rights
granted under this License; and,</li>
<li><strong>Voluntary License Schemes</strong>. The
Licensor waives the right to collect royalties,
whether individually or, in the event that the
Licensor is a member of a collecting society that
administers voluntary licensing schemes, via that
society, from any exercise by You of the rights
granted under this License.</li>
</ol>
</li>
</ol>
<p>The above rights may be exercised in all media and
formats whether now known or hereafter devised. The above
rights include the right to make such modifications as are
technically necessary to exercise the rights in other media
and formats. Subject to Section 8(f), all rights not
expressly granted by Licensor are hereby reserved.</p>
<p><strong>4. Restrictions.</strong> The license granted in
Section 3 above is expressly made subject to and limited by
the following restrictions:</p>
<ol type="a">
<li>You may Distribute or Publicly Perform the Work only
under the terms of this License. You must include a copy
of, or the Uniform Resource Identifier (URI) for, this
License with every copy of the Work You Distribute or
Publicly Perform. You may not offer or impose any terms
on the Work that restrict the terms of this License or
the ability of the recipient of the Work to exercise the
rights granted to that recipient under the terms of the
License. You may not sublicense the Work. You must keep
intact all notices that refer to this License and to the
disclaimer of warranties with every copy of the Work You
Distribute or Publicly Perform. When You Distribute or
Publicly Perform the Work, You may not impose any
effective technological measures on the Work that
restrict the ability of a recipient of the Work from You
to exercise the rights granted to that recipient under
the terms of the License. This Section 4(a) applies to
the Work as incorporated in a Collection, but this does
not require the Collection apart from the Work itself to
be made subject to the terms of this License. If You
create a Collection, upon notice from any Licensor You
must, to the extent practicable, remove from the
Collection any credit as required by Section 4(c), as
requested. If You create an Adaptation, upon notice from
any Licensor You must, to the extent practicable, remove
from the Adaptation any credit as required by Section
4(c), as requested.</li>
<li>You may Distribute or Publicly Perform an Adaptation
only under the terms of: (i) this License; (ii) a later
version of this License with the same License Elements as
this License; (iii) a Creative Commons jurisdiction
license (either this or a later license version) that
contains the same License Elements as this License (e.g.,
Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
Compatible License. If you license the Adaptation under
one of the licenses mentioned in (iv), you must comply
with the terms of that license. If you license the
Adaptation under the terms of any of the licenses
mentioned in (i), (ii) or (iii) (the "Applicable
License"), you must comply with the terms of the
Applicable License generally and the following
provisions: (I) You must include a copy of, or the URI
for, the Applicable License with every copy of each
Adaptation You Distribute or Publicly Perform; (II) You
may not offer or impose any terms on the Adaptation that
restrict the terms of the Applicable License or the
ability of the recipient of the Adaptation to exercise
the rights granted to that recipient under the terms of
the Applicable License; (III) You must keep intact all
notices that refer to the Applicable License and to the
disclaimer of warranties with every copy of the Work as
included in the Adaptation You Distribute or Publicly
Perform; (IV) when You Distribute or Publicly Perform the
Adaptation, You may not impose any effective
technological measures on the Adaptation that restrict
the ability of a recipient of the Adaptation from You to
exercise the rights granted to that recipient under the
terms of the Applicable License. This Section 4(b)
applies to the Adaptation as incorporated in a
Collection, but this does not require the Collection
apart from the Adaptation itself to be made subject to
the terms of the Applicable License.</li>
<li>If You Distribute, or Publicly Perform the Work or
any Adaptations or Collections, You must, unless a
request has been made pursuant to Section 4(a), keep
intact all copyright notices for the Work and provide,
reasonable to the medium or means You are utilizing: (i)
the name of the Original Author (or pseudonym, if
applicable) if supplied, and/or if the Original Author
and/or Licensor designate another party or parties (e.g.,
a sponsor institute, publishing entity, journal) for
attribution ("Attribution Parties") in Licensor's
copyright notice, terms of service or by other reasonable
means, the name of such party or parties; (ii) the title
of the Work if supplied; (iii) to the extent reasonably
practicable, the URI, if any, that Licensor specifies to
be associated with the Work, unless such URI does not
refer to the copyright notice or licensing information
for the Work; and (iv) , consistent with Ssection 3(b),
in the case of an Adaptation, a credit identifying the
use of the Work in the Adaptation (e.g., "French
translation of the Work by Original Author," or
"Screenplay based on original Work by Original Author").
The credit required by this Section 4(c) may be
implemented in any reasonable manner; provided, however,
that in the case of a Adaptation or Collection, at a
minimum such credit will appear, if a credit for all
contributing authors of the Adaptation or Collection
appears, then as part of these credits and in a manner at
least as prominent as the credits for the other
contributing authors. For the avoidance of doubt, You may
only use the credit required by this Section for the
purpose of attribution in the manner set out above and,
by exercising Your rights under this License, You may not
implicitly or explicitly assert or imply any connection
with, sponsorship or endorsement by the Original Author,
Licensor and/or Attribution Parties, as appropriate, of
You or Your use of the Work, without the separate,
express prior written permission of the Original Author,
Licensor and/or Attribution Parties.</li>
<li>Except as otherwise agreed in writing by the Licensor
or as may be otherwise permitted by applicable law, if
You Reproduce, Distribute or Publicly Perform the Work
either by itself or as part of any Adaptations or
Collections, You must not distort, mutilate, modify or
take other derogatory action in relation to the Work
which would be prejudicial to the Original Author's honor
or reputation. Licensor agrees that in those
jurisdictions (e.g. Japan), in which any exercise of the
right granted in Section 3(b) of this License (the right
to make Adaptations) would be deemed to be a distortion,
mutilation, modification or other derogatory action
prejudicial to the Original Author's honor and
reputation, the Licensor will waive or not assert, as
appropriate, this Section, to the fullest extent
permitted by the applicable national law, to enable You
to reasonably exercise Your right under Section 3(b) of
this License (right to make Adaptations) but not
otherwise.</li>
</ol>
<p><strong>5. Representations, Warranties and
Disclaimer</strong></p>
<p>UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN
WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO
REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE
WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING,
WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE
ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE
PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE.
SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED
WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.</p>
<p><strong>6. Limitation on Liability.</strong> EXCEPT TO
THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL
LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY
SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK,
EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.</p>
<p><strong>7. Termination</strong></p>
<ol type="a">
<li>This License and the rights granted hereunder will
terminate automatically upon any breach by You of the
terms of this License. Individuals or entities who have
received Adaptations or Collections from You under this
License, however, will not have their licenses terminated
provided such individuals or entities remain in full
compliance with those licenses. Sections 1, 2, 5, 6, 7,
and 8 will survive any termination of this License.</li>
<li>Subject to the above terms and conditions, the
license granted here is perpetual (for the duration of
the applicable copyright in the Work). Notwithstanding
the above, Licensor reserves the right to release the
Work under different license terms or to stop
distributing the Work at any time; provided, however that
any such election will not serve to withdraw this License
(or any other license that has been, or is required to
be, granted under the terms of this License), and this
License will continue in full force and effect unless
terminated as stated above.</li>
</ol>
<p><strong>8. Miscellaneous</strong></p>
<ol type="a">
<li>Each time You Distribute or Publicly Perform the Work
or a Collection, the Licensor offers to the recipient a
license to the Work on the same terms and conditions as
the license granted to You under this License.</li>
<li>Each time You Distribute or Publicly Perform an
Adaptation, Licensor offers to the recipient a license to
the original Work on the same terms and conditions as the
license granted to You under this License.</li>
<li>If any provision of this License is invalid or
unenforceable under applicable law, it shall not affect
the validity or enforceability of the remainder of the
terms of this License, and without further action by the
parties to this agreement, such provision shall be
reformed to the minimum extent necessary to make such
provision valid and enforceable.</li>
<li>No term or provision of this License shall be deemed
waived and no breach consented to unless such waiver or
consent shall be in writing and signed by the party to be
charged with such waiver or consent.</li>
<li>This License constitutes the entire agreement between
the parties with respect to the Work licensed here. There
are no understandings, agreements or representations with
respect to the Work not specified here. Licensor shall
not be bound by any additional provisions that may appear
in any communication from You. This License may not be
modified without the mutual written agreement of the
Licensor and You.</li>
<li>The rights granted under, and the subject matter
referenced, in this License were drafted utilizing the
terminology of the Berne Convention for the Protection of
Literary and Artistic Works (as amended on September 28,
1979), the Rome Convention of 1961, the WIPO Copyright
Treaty of 1996, the WIPO Performances and Phonograms
Treaty of 1996 and the Universal Copyright Convention (as
revised on July 24, 1971). These rights and subject
matter take effect in the relevant jurisdiction in which
the License terms are sought to be enforced according to
the corresponding provisions of the implementation of
those treaty provisions in the applicable national law.
If the standard suite of rights granted under applicable
copyright law includes additional rights not granted
under this License, such additional rights are deemed to
be included in the License; this License is not intended
to restrict the license of any rights under applicable
law.</li>
</ol>
================================================
FILE: README-ja.md
================================================
[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)
# IPsec VPN サーバー自動セットアップスクリプト
[](https://github.com/hwdsl2/setup-ipsec-vpn/actions/workflows/main.yml) [](https://github.com/hwdsl2/setup-ipsec-vpn/stargazers) [](https://github.com/hwdsl2/docker-ipsec-vpn-server) [](https://github.com/hwdsl2/docker-ipsec-vpn-server)
数分で自分のIPsec VPNサーバーをセットアップし、IPsec/L2TP、Cisco IPsec、IKEv2をサポートします。
IPsec VPNはネットワークトラフィックを暗号化し、インターネット経由でデータが送信される際に、VPNサーバーとあなたの間の誰もがデータを盗聴できないようにします。これは、コーヒーショップ、空港、ホテルの部屋などの安全でないネットワークを使用する際に特に有用です。
IPsecサーバーとして[Libreswan](https://libreswan.org/)を使用し、L2TPプロバイダーとして[xl2tpd](https://github.com/xelerance/xl2tpd)を使用します。
**[» :book: 本:Privacy Tools in the Age of AI](docs/vpn-book-ja.md) [VPNサーバーの構築方法](docs/vpn-book-ja.md)**
## クイックスタート
まず、Ubuntu、Debian、またはCentOSをインストールしたLinuxサーバー\*を準備します。
このワンライナーを使用してIPsec VPNサーバーをセットアップします:
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
VPNログイン情報はランダムに生成され、完了時に表示されます。
**オプション:** 同じサーバーに[WireGuard](https://github.com/hwdsl2/wireguard-install)および/または[OpenVPN](https://github.com/hwdsl2/openvpn-install)をインストールします。
<details>
<summary>
スクリプトの動作を確認する(ターミナル記録)。
</summary>
**注:** この記録はデモ目的のみです。この記録のVPN資格情報は**無効**です。
<p align="center"><img src="docs/images/script-demo.svg"></p>
</details>
<details>
<summary>
ダウンロードできない場合はこちらをクリックしてください。
</summary>
`curl`を使用してダウンロードすることもできます:
```bash
curl -fsSL https://get.vpnsetup.net -o vpn.sh && sudo sh vpn.sh
```
代替セットアップURL:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
ダウンロードできない場合は、[vpnsetup.sh](vpnsetup.sh)を開き、右側の`Raw`ボタンをクリックします。`Ctrl/Cmd+A`を押してすべて選択し、`Ctrl/Cmd+C`を押してコピーし、お気に入りのエディタに貼り付けます。
</details>
事前構築された[Dockerイメージ](https://github.com/hwdsl2/docker-ipsec-vpn-server)も利用可能です。他のオプションやクライアントのセットアップについては、以下のセクションを参照してください。
\* クラウドサーバー、仮想プライベートサーバー(VPS)、または専用サーバー。
## 機能
- 完全自動化されたIPsec VPNサーバーのセットアップ、ユーザー入力不要
- 強力で高速な暗号(例:AES-GCM)をサポートするIKEv2をサポート
- iOS、macOS、Androidデバイスを自動設定するVPNプロファイルを生成
- Windows、macOS、iOS、Android、Chrome OS、LinuxをVPNクライアントとしてサポート
- VPNユーザーと証明書を管理するためのヘルパースクリプトを含む
## 要件
以下のいずれかのインストールを備えたクラウドサーバー、仮想プライベートサーバー(VPS)、または専用サーバー:
- Ubuntu 24.04または22.04
- Debian 13、12、または11
- CentOS Stream 10または9
- Rocky LinuxまたはAlmaLinux
- Oracle Linux
- Amazon Linux 2
<details>
<summary>
他のサポートされているLinuxディストリビューション。
</summary>
- Raspberry Pi OS(Raspbian)
- Kali Linux
- Alpine Linux
- Red Hat Enterprise Linux(RHEL)
</details>
これは、[DigitalOcean](https://blog.ls20.com/digitalocean)、[Vultr](https://blog.ls20.com/vultr)、[Linode](https://blog.ls20.com/linode)、[OVH](https://www.ovhcloud.com/en/vps/)、および[Microsoft Azure](https://azure.microsoft.com)などのパブリッククラウドのLinux VMも含まれます。パブリッククラウドユーザーは、[ユーザーデータ](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#vpnsetup)を使用してデプロイすることもできます。
クイックデプロイ:
[](https://cloud.linode.com/stackscripts/37239) [](aws/README.md) [](azure/README.md)
[**» 自分のVPNを運用したいが、そのためのサーバーがない**](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#gettingavps)
外部ファイアウォールを持つサーバー(例:[EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls))の場合、VPNのUDPポート500および4500を開きます。
事前構築された[Dockerイメージ](https://github.com/hwdsl2/docker-ipsec-vpn-server)も利用可能です。上級ユーザーは[Raspberry Pi](https://www.raspberrypi.com)にインストールできます。[[1]](https://elasticbyte.net/posts/setting-up-a-native-cisco-ipsec-vpn-server-using-a-raspberry-pi/) [[2]](https://www.stewright.me/2018/07/create-a-raspberry-pi-vpn-server-using-l2tpipsec/)
:warning: これらのスクリプトをPCやMacで実行しないでください!これらはサーバーでのみ使用する必要があります!
## インストール
まず、サーバーを更新します:`sudo apt-get update && sudo apt-get dist-upgrade`(Ubuntu/Debian)または`sudo yum update`を実行し、再起動します。これはオプションですが、推奨されます。
VPNをインストールするには、次のオプションのいずれかを選択してください:
**オプション1:** スクリプトにランダムなVPN資格情報を生成させる(完了時に表示されます)。
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
**オプション2:** スクリプトを編集し、自分のVPN資格情報を提供する。
```bash
wget https://get.vpnsetup.net -O vpn.sh
nano -w vpn.sh
[自分の値に置き換える:YOUR_IPSEC_PSK、YOUR_USERNAME、およびYOUR_PASSWORD]
sudo sh vpn.sh
```
**注:** 安全なIPsec PSKは少なくとも20のランダムな文字で構成されるべきです。
**オプション3:** 環境変数として自分のVPN資格情報を定義する。
```bash
# すべての値は 'シングルクォート' で囲む必要があります
# これらの特殊文字を値に使用しないでください: \ " '
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
```
同じサーバーに[WireGuard](https://github.com/hwdsl2/wireguard-install)および/または[OpenVPN](https://github.com/hwdsl2/openvpn-install)をインストールすることもできます。サーバーがCentOS Stream、Rocky Linux、またはAlmaLinuxを実行している場合、最初にOpenVPN/WireGuardをインストールし、その後IPsec VPNをインストールします。
<details>
<summary>
ダウンロードできない場合はこちらをクリックしてください。
</summary>
`curl`を使用してダウンロードすることもできます。例えば:
```bash
curl -fL https://get.vpnsetup.net -o vpn.sh
sudo sh vpn.sh
```
代替セットアップURL:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
ダウンロードできない場合は、[vpnsetup.sh](vpnsetup.sh)を開き、右側の`Raw`ボタンをクリックします。`Ctrl/Cmd+A`を押してすべて選択し、`Ctrl/Cmd+C`を押してコピーし、お気に入りのエディタに貼り付けます。
</details>
<details>
<summary>
古いLibreswanバージョン4をインストールしたい。
</summary>
一般的には、最新の[Libreswan](https://libreswan.org/)バージョン5を使用することをお勧めします。これはこのプロジェクトのデフォルトバージョンです。ただし、古いLibreswanバージョン4をインストールしたい場合:
```bash
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_SWAN_VER=4.15 sh vpn.sh
```
**注:** Libreswanバージョン5がすでにインストールされている場合、最初に[VPNをアンインストール](docs/uninstall.md)してからLibreswanバージョン4をインストールする必要があるかもしれません。あるいは、[アップデートスクリプト](#libreswanのアップグレード)をダウンロードし、`SWAN_VER=4.15`を指定して編集し、スクリプトを実行します。
</details>
## VPNオプションのカスタマイズ
### 代替DNSサーバーの使用
デフォルトでは、VPNがアクティブなときにクライアントは[Google Public DNS](https://developers.google.com/speed/public-dns/)を使用するように設定されています。VPNをインストールする際に、すべてのVPNモードに対してカスタムDNSサーバーを指定することができます。例:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
`VPN_DNS_SRV1`を使用してプライマリDNSサーバーを指定し、`VPN_DNS_SRV2`を使用してセカンダリDNSサーバーを指定します(オプション)。
以下は、参考のためのいくつかの人気のあるパブリックDNSプロバイダーのリストです。
| プロバイダー | プライマリDNS | セカンダリDNS | 注記 |
| -------- | ----------- | ------------- | ----- |
| [Google Public DNS](https://developers.google.com/speed/public-dns) | 8.8.8.8 | 8.8.4.4 | このプロジェクトのデフォルト |
| [Cloudflare](https://1.1.1.1/dns/) | 1.1.1.1 | 1.0.0.1 | 参照:[Cloudflare for families](https://1.1.1.1/family/) |
| [Quad9](https://www.quad9.net) | 9.9.9.9 | 149.112.112.112 | 悪意のあるドメインをブロック |
| [OpenDNS](https://www.opendns.com/home-internet-security/) | 208.67.222.222 | 208.67.220.220 | フィッシングドメインをブロック、設定可能。 |
| [CleanBrowsing](https://cleanbrowsing.org/filters/) | 185.228.168.9 | 185.228.169.9 | [ドメインフィルター](https://cleanbrowsing.org/filters/)利用可能 |
| [NextDNS](https://nextdns.io/?from=bg25bwmp) | さまざま | さまざま | 広告ブロック、無料プラン利用可能。[詳細はこちら](https://nextdns.io/?from=bg25bwmp)。 |
| [Control D](https://controld.com/free-dns) | さまざま | さまざま | 広告ブロック、設定可能。[詳細はこちら](https://controld.com/free-dns)。 |
VPNセットアップ後にDNSサーバーを変更する必要がある場合は、[高度な使用法](docs/advanced-usage.md)を参照してください。
**注:** サーバーにIKEv2がすでに設定されている場合、上記の変数はIKEv2モードには影響しません。その場合、DNSサーバーなどのIKEv2オプションをカスタマイズするには、まず[IKEv2を削除](docs/ikev2-howto.md#remove-ikev2)し、`sudo ikev2.sh`を使用して再設定します。
### IKEv2オプションのカスタマイズ
VPNをインストールする際に、上級ユーザーはオプションでIKEv2オプションをカスタマイズできます。
<details open>
<summary>
オプション1: VPNセットアップ時にIKEv2をスキップし、カスタムオプションを使用してIKEv2を設定します。
</summary>
VPNをインストールする際に、IKEv2をスキップし、IPsec/L2TPおよびIPsec/XAuth("Cisco IPsec")モードのみをインストールできます:
```bash
sudo VPN_SKIP_IKEV2=yes sh vpn.sh
```
(オプション)VPNクライアントにカスタムDNSサーバーを指定する場合は、`VPN_DNS_SRV1`およびオプションで`VPN_DNS_SRV2`を定義します。詳細については、[代替DNSサーバーの使用](#代替dnsサーバーの使用)を参照してください。
その後、IKEv2ヘルパースクリプトを実行して、カスタムオプションを使用して対話的にIKEv2を設定します:
```bash
sudo ikev2.sh
```
次のオプションをカスタマイズできます:VPNサーバーのDNS名、最初のクライアントの名前と有効期間、VPNクライアントのDNSサーバー、およびクライアント構成ファイルをパスワードで保護するかどうか。
**注:** サーバーにIKEv2がすでに設定されている場合、`VPN_SKIP_IKEV2`変数は影響しません。その場合、IKEv2オプションをカスタマイズするには、まず[IKEv2を削除](docs/ikev2-howto.md#remove-ikev2)し、`sudo ikev2.sh`を使用して再設定します。
</details>
<details>
<summary>
オプション2: 環境変数を使用してIKEv2オプションをカスタマイズします。
</summary>
VPNをインストールする際に、オプションでIKEv2サーバーアドレスのDNS名を指定できます。DNS名は完全修飾ドメイン名(FQDN)である必要があります。例:
```bash
sudo VPN_DNS_NAME='vpn.example.com' sh vpn.sh
```
同様に、最初のIKEv2クライアントの名前を指定できます。指定しない場合、デフォルトは`vpnclient`です。
```bash
sudo VPN_CLIENT_NAME='your_client_name' sh vpn.sh
```
デフォルトでは、VPNがアクティブなときにクライアントは[Google Public DNS](https://developers.google.com/speed/public-dns/)を使用するように設定されています。すべてのVPNモードに対してカスタムDNSサーバーを指定できます。例:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
デフォルトでは、IKEv2クライアント構成のインポート時にパスワードは必要ありません。ランダムなパスワードを使用してクライアント構成ファイルを保護することを選択できます。
```bash
sudo VPN_PROTECT_CONFIG=yes sh vpn.sh
```
</details>
<details>
<summary>
参考のために:IKEv1およびIKEv2パラメータのリスト。
</summary>
| IKEv1パラメータ\* | デフォルト値 | カスタマイズ(環境変数)\*\* |
| ------------ | ---- | ----------------- |
| サーバーアドレス(DNS名)| - | いいえ、ただしDNS名を使用して接続できます |
| サーバーアドレス(パブリックIP)| 自動検出 | VPN_PUBLIC_IP |
| IPsec事前共有キー | 自動生成 | VPN_IPSEC_PSK |
| VPNユーザー名 | vpnuser | VPN_USER |
| VPNパスワード | 自動生成 | VPN_PASSWORD |
| クライアントのDNSサーバー | Google Public DNS | VPN_DNS_SRV1、VPN_DNS_SRV2 |
| IKEv2セットアップをスキップ | いいえ | VPN_SKIP_IKEV2=yes |
\* これらのIKEv1パラメータは、IPsec/L2TPおよびIPsec/XAuth("Cisco IPsec")モード用です。
\*\* vpn(setup).shを実行する際に、これらを環境変数として定義します。
| IKEv2パラメータ\* | デフォルト値 | カスタマイズ(環境変数)\*\* | カスタマイズ(対話型)\*\*\* |
| ----------- | ---- | ------------------ | ----------------- |
| サーバーアドレス(DNS名)| - | VPN_DNS_NAME | ✅ |
| サーバーアドレス(パブリックIP)| 自動検出 | VPN_PUBLIC_IP | ✅ |
| 最初のクライアントの名前 | vpnclient | VPN_CLIENT_NAME | ✅ |
| クライアントのDNSサーバー | Google Public DNS | VPN_DNS_SRV1、VPN_DNS_SRV2 | ✅ |
| クライアント構成ファイルを保護する | いいえ | VPN_PROTECT_CONFIG=yes | ✅ |
| MOBIKEの有効/無効 | サポートされている場合は有効 | ❌ | ✅ |
| クライアント証明書の有効期間 | 10年(120ヶ月)| VPN_CLIENT_VALIDITY\*\*\*\* | ✅ |
| CAおよびサーバー証明書の有効期間 | 10年(120ヶ月)| ❌ | ❌ |
| CA証明書名 | IKEv2 VPN CA | ❌ | ❌ |
| 証明書キーサイズ | 3072ビット | ❌ | ❌ |
\* これらのIKEv2パラメータは、IKEv2モード用です。
\*\* vpn(setup).shを実行する際、または自動モードでIKEv2を設定する際に、これらを環境変数として定義します(`sudo ikev2.sh --auto`)。
\*\*\* 対話型IKEv2セットアップ中にカスタマイズできます(`sudo ikev2.sh`)。上記のオプション1を参照してください。
\*\*\*\* `VPN_CLIENT_VALIDITY`を使用して、クライアント証明書の有効期間を月単位で指定します。1から120の間の整数である必要があります。
これらのパラメータに加えて、上級ユーザーはVPNセットアップ中に[VPNサブネットをカスタマイズ](docs/advanced-usage.md#customize-vpn-subnets)することもできます。
</details>
## 次のステップ
*他の言語で読む:[English](README.md#next-steps)、[简体中文](README-zh.md#下一步)、[繁體中文](README-zh-Hant.md#下一步)、[日本語](README-ja.md#次のステップ)、[Русский](README-ru.md#следующие-шаги)。*
コンピュータやデバイスをVPNに接続します。詳細は以下のリンク(英語)をご覧ください。
**[IKEv2 VPNクライアントの設定(推奨)](docs/ikev2-howto.md)**
**[IPsec/L2TP VPNクライアントの設定](docs/clients.md)**
**[IPsec/XAuth("Cisco IPsec")VPNクライアントの設定](docs/clients-xauth.md)**
**:book: [VPN本](docs/vpn-book.md)を読んで[追加コンテンツ](https://ko-fi.com/post/Support-this-project-and-get-access-to-supporter-o-O5O7FVF8J)にアクセスしてください。**
自分のVPNを楽しんでください! :sparkles::tada::rocket::sparkles:
## 重要な注意事項
**Windowsユーザー**:IPsec/L2TPモードの場合、VPNサーバーまたはクライアントがNAT(例:家庭用ルーター)の背後にある場合、[一度だけレジストリを変更](docs/clients.md#windows-error-809)する必要があります。
同じVPNアカウントを複数のデバイスで使用できます。ただし、IPsec/L2TPの制限により、同じNAT(例:家庭用ルーター)の背後から複数のデバイスを接続する場合は、[IKEv2](docs/ikev2-howto.md)または[IPsec/XAuth](docs/clients-xauth.md)モードを使用する必要があります。VPNユーザーアカウントを表示または更新するには、[VPNユーザーの管理](docs/manage-users.md)を参照してください。
外部ファイアウォールを持つサーバー(例:[EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls))の場合、VPNのUDPポート500および4500を開きます。Aliyunユーザーは、[#433](https://github.com/hwdsl2/setup-ipsec-vpn/issues/433)を参照してください。
クライアントは、VPNがアクティブなときに[Google Public DNS](https://developers.google.com/speed/public-dns/)を使用するように設定されています。別のDNSプロバイダーを好む場合は、[高度な使用法](docs/advanced-usage.md)を参照してください。
カーネルサポートを使用すると、IPsec/L2TPのパフォーマンスが向上する可能性があります。これは[すべてのサポートされているOS](#要件)で利用可能です。Ubuntuユーザーは`linux-modules-extra-$(uname -r)`パッケージをインストールし、`service xl2tpd restart`を実行する必要があります。
スクリプトは、変更を加える前に既存の構成ファイルをバックアップし、`.old-date-time`サフィックスを付けます。
## Libreswanのアップグレード
このワンライナーを使用して、VPNサーバー上の[Libreswan](https://libreswan.org)([変更ログ](https://github.com/libreswan/libreswan/blob/main/CHANGES) | [アナウンス](https://lists.libreswan.org))を更新します。
```bash
wget https://get.vpnsetup.net/upg -O vpnup.sh && sudo sh vpnup.sh
```
<details>
<summary>
ダウンロードできない場合はこちらをクリックしてください。
</summary>
`curl`を使用してダウンロードすることもできます:
```bash
curl -fsSL https://get.vpnsetup.net/upg -o vpnup.sh && sudo sh vpnup.sh
```
代替アップデートURL:
```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
```
ダウンロードできない場合は、[vpnupgrade.sh](extras/vpnupgrade.sh)を開き、右側の`Raw`ボタンをクリックします。`Ctrl/Cmd+A`を押してすべて選択し、`Ctrl/Cmd+C`を押してコピーし、お気に入りのエディタに貼り付けます。
</details>
最新のサポートされているLibreswanバージョンは`5.2`です。インストールされているバージョンを確認します:`ipsec --version`。
**注:** `xl2tpd`は、Ubuntu/Debianの`apt-get`などのシステムのパッケージマネージャーを使用して更新できます。
## VPNユーザーの管理
[VPNユーザーの管理](docs/manage-users.md)(英語)を参照してください。
- [ヘルパースクリプトを使用してVPNユーザーを管理する](docs/manage-users.md#manage-vpn-users-using-helper-scripts)
- [VPNユーザーを表示する](docs/manage-users.md#view-vpn-users)
- [IPsec PSKを表示または更新する](docs/manage-users.md#view-or-update-the-ipsec-psk)
- [VPNユーザーを手動で管理する](docs/manage-users.md#manually-manage-vpn-users)
## 高度な使用法
[高度な使用法](docs/advanced-usage.md)(英語)を参照してください。
- [代替DNSサーバーの使用](docs/advanced-usage.md#use-alternative-dns-servers)
- [DNS名とサーバーIPの変更](docs/advanced-usage.md#dns-name-and-server-ip-changes)
- [IKEv2専用VPN](docs/advanced-usage.md#ikev2-only-vpn)
- [内部VPN IPとトラフィック](docs/advanced-usage.md#internal-vpn-ips-and-traffic)
- [VPNサーバーのパブリックIPを指定する](docs/advanced-usage.md#specify-vpn-servers-public-ip)
- [VPNサブネットのカスタマイズ](docs/advanced-usage.md#customize-vpn-subnets)
- [IPv6サポート](docs/advanced-usage.md#ipv6-support)
- [VPNクライアントへのポートフォワーディング](docs/advanced-usage.md#port-forwarding-to-vpn-clients)
- [スプリットトンネリング](docs/advanced-usage.md#split-tunneling)
- [VPNサーバーのサブネットにアクセスする](docs/advanced-usage.md#access-vpn-servers-subnet)
- [サーバーのサブネットからVPNクライアントにアクセスする](docs/advanced-usage.md#access-vpn-clients-from-servers-subnet)
- [IPTablesルールの変更](docs/advanced-usage.md#modify-iptables-rules)
- [Google BBR輻輳制御の展開](docs/advanced-usage.md#deploy-google-bbr-congestion-control)
## VPNのアンインストール
IPsec VPNをアンインストールするには、[ヘルパースクリプト](extras/vpnuninstall.sh)を実行します:
**警告:** このヘルパースクリプトは、サーバーからIPsec VPNを削除します。すべてのVPN構成は**永久に削除**され、Libreswanおよびxl2tpdは削除されます。これは**元に戻すことはできません**!
```bash
wget https://get.vpnsetup.net/unst -O unst.sh && sudo bash unst.sh
```
<details>
<summary>
ダウンロードできない場合はこちらをクリックしてください。
</summary>
`curl`を使用してダウンロードすることもできます:
```bash
curl -fsSL https://get.vpnsetup.net/unst -o unst.sh && sudo bash unst.sh
```
代替スクリプトURL:
```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
```
</details>
詳細については、[VPNのアンインストール](docs/uninstall.md)を参照してください。
## フィードバックと質問
- このプロジェクトに提案がありますか?[改善リクエスト](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose)を開いてください。[プルリクエスト](https://github.com/hwdsl2/setup-ipsec-vpn/pulls)も歓迎します。
- 再現可能なバグを見つけた場合、[IPsec VPN](https://github.com/libreswan/libreswan/issues?q=is%3Aissue)または[VPNスクリプト](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose)のバグレポートを開いてください。
- 質問がありますか?まず、[既存の問題](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue)と、この[Gist](https://gist.github.com/hwdsl2/9030462#comments)および[私のブログ](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#disqus_thread)のコメントを検索してください。
- VPNに関連する質問は、[Libreswan](https://lists.libreswan.org)または[strongSwan](https://lists.strongswan.org)のメーリングリストで質問するか、次のウィキを参照してください:[[1]](https://libreswan.org/wiki/Main_Page) [[2]](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/security_guide/sec-securing_virtual_private_networks) [[3]](https://wiki.strongswan.org/projects/strongswan/wiki/UserDocumentation) [[4]](https://wiki.gentoo.org/wiki/IPsec_L2TP_VPN_server) [[5]](https://wiki.archlinux.org/index.php/Openswan_L2TP/IPsec_VPN_client_setup)。
## ライセンス
著作権 (C) 2014-2026 [Lin Song](https://github.com/hwdsl2) [](https://www.linkedin.com/in/linsongui)
[Thomas Sarlandieの作品](https://github.com/sarfata/voodooprivacy)に基づく(著作権2012)
[](http://creativecommons.org/licenses/by-sa/3.0/)
この作品は[クリエイティブ・コモンズ表示-継承3.0非移植ライセンス](http://creativecommons.org/licenses/by-sa/3.0/)の下でライセンスされています。
帰属が必要です:私の名前を派生物に含め、改善方法を教えてください!
================================================
FILE: README-ru.md
================================================
[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)
# Скрипты автоматической настройки сервера IPsec VPN
[](https://github.com/hwdsl2/setup-ipsec-vpn/actions/workflows/main.yml) [](https://github.com/hwdsl2/setup-ipsec-vpn/stargazers) [](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-ru.md) [](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-ru.md)
Разверните собственный сервер IPsec VPN всего за несколько минут с поддержкой IPsec/L2TP, Cisco IPsec и IKEv2.
IPsec VPN шифрует сетевой трафик, поэтому никто между вами и VPN-сервером не сможет перехватывать ваши данные во время их передачи через Интернет. Это особенно полезно при использовании незащищённых сетей, например в кофейнях, аэропортах или гостиничных номерах.
Мы будем использовать [Libreswan](https://libreswan.org/) в качестве сервера IPsec и [xl2tpd](https://github.com/xelerance/xl2tpd) в качестве поставщика L2TP.
**[» :book: Книга: Privacy Tools in the Age of AI](docs/vpn-book.md) [Build Your Own VPN Server](docs/vpn-book.md)**
## Быстрый старт
Сначала подготовьте ваш Linux-сервер\* с установленной системой Ubuntu, Debian или CentOS.
Используйте эту однострочную команду для настройки сервера IPsec VPN:
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
Данные для входа в VPN будут сгенерированы случайным образом и показаны после завершения установки.
**Дополнительно:** Установите [WireGuard](https://github.com/hwdsl2/wireguard-install/blob/master/README-ru.md) и/или [OpenVPN](https://github.com/hwdsl2/openvpn-install/blob/master/README-ru.md) на тот же сервер.
<details>
<summary>
Посмотреть работу скрипта (запись терминала).
</summary>
**Примечание:** Эта запись предназначена только для демонстрационных целей. Учетные данные VPN в этой записи **НЕ** являются действительными.
<p align="center"><img src="docs/images/script-demo.svg"></p>
</details>
<details>
<summary>
Нажмите здесь, если не удаётся скачать.
</summary>
Вы также можете использовать `curl` для загрузки:
```bash
curl -fsSL https://get.vpnsetup.net -o vpn.sh && sudo sh vpn.sh
```
Альтернативные URL для установки:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
Если вы не можете скачать файл, откройте [vpnsetup.sh](vpnsetup.sh), затем нажмите кнопку `Raw` справа. Нажмите `Ctrl/Cmd+A`, чтобы выделить всё, `Ctrl/Cmd+C`, чтобы скопировать, затем вставьте в ваш любимый редактор.
</details>
Также доступен готовый [образ Docker](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-ru.md). Для других вариантов и настройки клиентов прочитайте разделы ниже.
\* Облачный сервер, виртуальный частный сервер (VPS) или выделенный сервер.
## Возможности
- Полностью автоматическая настройка сервера IPsec VPN, ввод пользователя не требуется
- Поддержка IKEv2 с мощными и быстрыми шифрами (например, AES-GCM)
- Генерация профилей VPN для автоматической настройки устройств iOS, macOS и Android
- Поддержка Windows, macOS, iOS, Android, Chrome OS и Linux в качестве VPN-клиентов
- Включает вспомогательные скрипты для управления пользователями VPN и сертификатами
## Требования
Облачный сервер, виртуальный частный сервер (VPS) или выделенный сервер с установленной системой:
- Ubuntu 24.04 или 22.04
- Debian 13, 12 или 11
- CentOS Stream 10 или 9
- Rocky Linux или AlmaLinux
- Oracle Linux
- Amazon Linux 2
<details>
<summary>
Другие поддерживаемые дистрибутивы Linux.
</summary>
- Raspberry Pi OS (Raspbian)
- Kali Linux
- Alpine Linux
- Red Hat Enterprise Linux (RHEL)
</details>
Это также включает виртуальные машины Linux в публичных облаках, таких как [DigitalOcean](https://blog.ls20.com/digitalocean), [Vultr](https://blog.ls20.com/vultr), [Linode](https://blog.ls20.com/linode), [OVH](https://www.ovhcloud.com/en/vps/) и [Microsoft Azure](https://azure.microsoft.com). Пользователи публичных облаков также могут выполнить развёртывание с помощью [пользовательскими данными](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#vpnsetup).
Быстрое развёртывание в:
[](https://cloud.linode.com/stackscripts/37239) [](aws/README.md) [](azure/README.md)
[**» Я хочу запустить собственный VPN, но у меня нет сервера для этого**](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#gettingavps)
Для серверов с внешним файрволом (например, [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)) откройте UDP-порты 500 и 4500 для VPN.
Также доступен готовый [образ Docker](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-ru.md). Продвинутые пользователи могут установить его на [Raspberry Pi](https://www.raspberrypi.com). [[1]](https://elasticbyte.net/posts/setting-up-a-native-cisco-ipsec-vpn-server-using-a-raspberry-pi/) [[2]](https://www.stewright.me/2018/07/create-a-raspberry-pi-vpn-server-using-l2tpipsec/)
:warning: **НЕ** запускайте эти скрипты на вашем ПК или Mac! Их следует использовать только на сервере!
## Установка
Сначала обновите ваш сервер с помощью `sudo apt-get update && sudo apt-get dist-upgrade` (Ubuntu/Debian) или `sudo yum update`, затем перезагрузите систему. Это необязательно, но рекомендуется.
Чтобы установить VPN, выберите один из следующих вариантов:
**Вариант 1:** Позвольте скрипту сгенерировать случайные учетные данные VPN (они будут показаны после завершения).
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
**Вариант 2:** Отредактируйте скрипт и укажите собственные учетные данные VPN.
```bash
wget https://get.vpnsetup.net -O vpn.sh
nano -w vpn.sh
[Замените на собственные значения: YOUR_IPSEC_PSK, YOUR_USERNAME и YOUR_PASSWORD]
sudo sh vpn.sh
```
**Примечание:** Безопасный IPsec PSK должен состоять как минимум из 20 случайных символов.
**Вариант 3:** Определите учетные данные VPN как переменные окружения.
```bash
# Все значения ДОЛЖНЫ быть заключены в 'одинарные кавычки'
# НЕ используйте внутри значений следующие специальные символы: \ " '
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
```
При желании вы можете установить [WireGuard](https://github.com/hwdsl2/wireguard-install/blob/master/README-ru.md) и/или [OpenVPN](https://github.com/hwdsl2/openvpn-install/blob/master/README-ru.md) на том же сервере. Если ваш сервер работает на CentOS Stream, Rocky Linux или AlmaLinux, сначала установите OpenVPN/WireGuard, а затем установите IPsec VPN.
<details>
<summary>
Нажмите здесь, если не удаётся скачать.
</summary>
Вы также можете использовать `curl` для загрузки. Например:
```bash
curl -fL https://get.vpnsetup.net -o vpn.sh
sudo sh vpn.sh
```
Альтернативные URL для установки:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
Если вы не можете скачать файл, откройте [vpnsetup.sh](vpnsetup.sh), затем нажмите кнопку `Raw` справа. Нажмите `Ctrl/Cmd+A`, чтобы выделить всё, `Ctrl/Cmd+C`, чтобы скопировать, затем вставьте в ваш любимый редактор.
</details>
<details>
<summary>
Я хочу установить более старую версию Libreswan 4.
</summary>
Обычно рекомендуется использовать последнюю версию [Libreswan](https://libreswan.org/) 5, которая является версией по умолчанию в этом проекте. Однако если вы хотите установить более старую версию Libreswan 4:
```bash
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_SWAN_VER=4.15 sh vpn.sh
```
**Примечание:** Если версия Libreswan 5 уже установлена, возможно, вам сначала потребуется [удалить VPN](docs/uninstall.md), прежде чем устанавливать Libreswan версии 4. В качестве альтернативы можно скачать [скрипт обновления](#обновление-libreswan), отредактировать его, указав `SWAN_VER=4.15`, затем запустить скрипт.
</details>
## Настройка параметров VPN
### Использование альтернативных DNS-серверов
По умолчанию клиенты настроены использовать [Google Public DNS](https://developers.google.com/speed/public-dns/) при активном VPN. При установке VPN вы можете при желании указать собственные DNS-серверы для всех режимов VPN. Пример:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
Используйте `VPN_DNS_SRV1` для указания основного DNS-сервера и `VPN_DNS_SRV2` для указания резервного DNS-сервера (необязательно).
Ниже приведён список некоторых популярных публичных DNS-провайдеров для справки.
| Провайдер | Основной DNS | Резервный DNS | Примечания |
| -------- | ----------- | ------------- | ----- |
| [Google Public DNS](https://developers.google.com/speed/public-dns) | 8.8.8.8 | 8.8.4.4 | Используется по умолчанию в этом проекте |
| [Cloudflare](https://1.1.1.1/dns/) | 1.1.1.1 | 1.0.0.1 | См. также: [Cloudflare for families](https://1.1.1.1/family/) |
| [Quad9](https://www.quad9.net) | 9.9.9.9 | 149.112.112.112 | Блокирует вредоносные домены |
| [OpenDNS](https://www.opendns.com/home-internet-security/) | 208.67.222.222 | 208.67.220.220 | Блокирует фишинговые домены, настраиваемый |
| [CleanBrowsing](https://cleanbrowsing.org/filters/) | 185.228.168.9 | 185.228.169.9 | Доступны [фильтры доменов](https://cleanbrowsing.org/filters/) |
| [NextDNS](https://nextdns.io/?from=bg25bwmp) | Различается | Различается | Блокировка рекламы, доступен бесплатный тариф. [Подробнее](https://nextdns.io/?from=bg25bwmp). |
| [Control D](https://controld.com/free-dns) | Различается | Различается | Блокировка рекламы, настраиваемый. [Подробнее](https://controld.com/free-dns). |
Если вам нужно изменить DNS-серверы после настройки VPN, см. раздел [Расширенное использование](docs/advanced-usage.md).
**Примечание:** Если IKEv2 уже настроен на сервере, переменные выше не влияют на режим IKEv2. В этом случае для настройки параметров IKEv2, таких как DNS-серверы, вы можете сначала [удалить IKEv2](docs/ikev2-howto.md#remove-ikev2), а затем снова настроить его с помощью `sudo ikev2.sh`.
### Настройка параметров IKEv2
При установке VPN продвинутые пользователи могут при желании настроить параметры IKEv2.
<details open>
<summary>
Вариант 1: Пропустить IKEv2 во время настройки VPN, затем настроить IKEv2 с пользовательскими параметрами.
</summary>
При установке VPN вы можете пропустить IKEv2 и установить только режимы IPsec/L2TP и IPsec/XAuth («Cisco IPsec»):
```bash
sudo VPN_SKIP_IKEV2=yes sh vpn.sh
```
(Необязательно) Если вы хотите указать пользовательские DNS-серверы для клиентов VPN, определите `VPN_DNS_SRV1` и при необходимости `VPN_DNS_SRV2`. Подробности смотрите в разделе [Использование альтернативных DNS-серверов](#использование-альтернативных-dns-серверов).
После этого запустите вспомогательный скрипт IKEv2, чтобы настроить IKEv2 в интерактивном режиме с пользовательскими параметрами:
```bash
sudo ikev2.sh
```
Вы можете настроить следующие параметры: DNS-имя VPN-сервера, имя и срок действия первого клиента, DNS-сервер для VPN-клиентов и необходимость защиты файлов конфигурации клиента паролем.
**Примечание:** Переменная `VPN_SKIP_IKEV2` не действует, если IKEv2 уже настроен на сервере. В этом случае для настройки параметров IKEv2 вы можете сначала [удалить IKEv2](docs/ikev2-howto.md#remove-ikev2), а затем снова настроить его с помощью `sudo ikev2.sh`.
</details>
<details>
<summary>
Вариант 2: Настройка параметров IKEv2 с помощью переменных окружения.
</summary>
При установке VPN вы можете при желании указать DNS-имя для адреса сервера IKEv2. DNS-имя должно быть полным доменным именем (FQDN). Пример:
```bash
sudo VPN_DNS_NAME='vpn.example.com' sh vpn.sh
```
Аналогично вы можете указать имя для первого клиента IKEv2. По умолчанию используется `vpnclient`, если имя не указано.
```bash
sudo VPN_CLIENT_NAME='your_client_name' sh vpn.sh
```
По умолчанию клиенты используют [Google Public DNS](https://developers.google.com/speed/public-dns/) при активном VPN. Вы можете указать собственные DNS-серверы для всех режимов VPN. Пример:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
По умолчанию пароль не требуется при импорте конфигурации клиента IKEv2. Вы можете защитить файлы конфигурации клиента случайным паролем.
```bash
sudo VPN_PROTECT_CONFIG=yes sh vpn.sh
```
</details>
<details>
<summary>
Для справки: список параметров IKEv1 и IKEv2.
</summary>
| Параметр IKEv1\* | Значение по умолчанию | Настройка (переменная окружения)\*\* |
| --------------------------- | --------------------- | ------------------------------------ |
| Адрес сервера (DNS-имя) | - | Нет, но можно подключаться по DNS-имени |
| Адрес сервера (публичный IP)| Автоопределение | VPN_PUBLIC_IP |
| Предварительно общий ключ IPsec | Автоматическая генерация | VPN_IPSEC_PSK |
| Имя пользователя VPN | vpnuser | VPN_USER |
| Пароль VPN | Автоматическая генерация | VPN_PASSWORD |
| DNS-серверы для клиентов | Google Public DNS | VPN_DNS_SRV1, VPN_DNS_SRV2 |
| Пропустить настройку IKEv2 | no | VPN_SKIP_IKEV2=yes |
\* Эти параметры IKEv1 используются для режимов IPsec/L2TP и IPsec/XAuth («Cisco IPsec»).
\*\* Определяются как переменные окружения при запуске vpn(setup).sh.
| Параметр IKEv2\* | Значение по умолчанию | Настройка (переменная окружения)\*\* | Настройка (интерактивно)\*\*\* |
| --------------------------- | --------------------- | ------------------------------------ | ------------------------------- |
| Адрес сервера (DNS-имя) | - | VPN_DNS_NAME | ✅ |
| Адрес сервера (публичный IP)| Автоопределение | VPN_PUBLIC_IP | ✅ |
| Имя первого клиента | vpnclient | VPN_CLIENT_NAME | ✅ |
| DNS-серверы для клиентов | Google Public DNS | VPN_DNS_SRV1, VPN_DNS_SRV2 | ✅ |
| Защита файлов конфигурации клиента | no | VPN_PROTECT_CONFIG=yes | ✅ |
| Включить/отключить MOBIKE | Включено, если поддерживается | ❌ | ✅ |
| Срок действия сертификата клиента | 10 лет (120 месяцев) | VPN_CLIENT_VALIDITY\*\*\*\* | ✅ |
| Срок действия сертификатов CA и сервера | 10 лет (120 месяцев) | ❌ | ❌ |
| Имя сертификата CA | IKEv2 VPN CA | ❌ | ❌ |
| Размер ключа сертификата | 3072 бита | ❌ | ❌ |
\* Эти параметры IKEv2 используются для режима IKEv2.
\*\* Определяются как переменные окружения при запуске vpn(setup).sh или при автоматической настройке IKEv2 (`sudo ikev2.sh --auto`).
\*\*\* Можно настроить во время интерактивной настройки IKEv2 (`sudo ikev2.sh`). См. вариант 1 выше.
\*\*\*\* Используйте `VPN_CLIENT_VALIDITY`, чтобы указать срок действия сертификата клиента в месяцах. Значение должно быть целым числом от 1 до 120.
Помимо этих параметров, продвинутые пользователи также могут [настроить подсети VPN](docs/advanced-usage.md#customize-vpn-subnets) во время настройки VPN.
</details>
## Следующие шаги
*Прочитать на других языках: [English](README.md#next-steps), [简体中文](README-zh.md#下一步), [繁體中文](README-zh-Hant.md#下一步), [日本語](README-ja.md#次のステップ), [Русский](README-ru.md#следующие-шаги).*
Настройте ваш компьютер или устройство для использования VPN. Пожалуйста, обратитесь к следующим инструкциям (на английском языке):
**[Настройка клиентов IKEv2 VPN (рекомендуется)](docs/ikev2-howto.md)**
**[Настройка клиентов IPsec/L2TP VPN](docs/clients.md)**
**[Настройка клиентов IPsec/XAuth («Cisco IPsec»)](docs/clients-xauth.md)**
**Прочитайте [:book: книгу о VPN](docs/vpn-book.md), чтобы получить доступ к [дополнительному контенту](https://ko-fi.com/post/Support-this-project-and-get-access-to-supporter-o-O5O7FVF8J).**
Наслаждайтесь собственным VPN! :sparkles::tada::rocket::sparkles:
## Важные замечания
**Пользователи Windows**: для режима IPsec/L2TP требуется [одноразовое изменение реестра](docs/clients.md#windows-error-809), если VPN-сервер или клиент находится за NAT (например, домашним роутером).
Одна и та же учетная запись VPN может использоваться на нескольких ваших устройствах. Однако из-за ограничения IPsec/L2TP, если вы хотите подключить несколько устройств из-за одного NAT (например, домашнего роутера), необходимо использовать режим [IKEv2](docs/ikev2-howto.md) или [IPsec/XAuth](docs/clients-xauth.md). Чтобы просмотреть или изменить учетные записи пользователей VPN, см. [Управление пользователями VPN](docs/manage-users.md).
Для серверов с внешним файрволом (например, [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)) откройте UDP-порты 500 и 4500 для VPN. Пользователям Aliyun см. [#433](https://github.com/hwdsl2/setup-ipsec-vpn/issues/433).
Клиенты настроены использовать [Google Public DNS](https://developers.google.com/speed/public-dns/) при активном VPN. Если вы предпочитаете другого DNS-провайдера, см. [Расширенное использование](docs/advanced-usage.md).
Использование поддержки ядра может повысить производительность IPsec/L2TP. Она доступна на [всех поддерживаемых ОС](#требования). Пользователям Ubuntu следует установить пакет `linux-modules-extra-$(uname -r)` и выполнить `service xl2tpd restart`.
Скрипты создадут резервные копии существующих файлов конфигурации перед внесением изменений, с суффиксом `.old-date-time`.
## Обновление Libreswan
Используйте эту однострочную команду для обновления [Libreswan](https://libreswan.org) ([список изменений](https://github.com/libreswan/libreswan/blob/main/CHANGES) | [объявления](https://lists.libreswan.org)) на вашем VPN-сервере.
```bash
wget https://get.vpnsetup.net/upg -O vpnup.sh && sudo sh vpnup.sh
```
<details>
<summary>
Нажмите здесь, если не удаётся скачать.
</summary>
Вы также можете использовать `curl` для загрузки:
```bash
curl -fsSL https://get.vpnsetup.net/upg -o vpnup.sh && sudo sh vpnup.sh
```
Альтернативные URL для обновления:
```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
```
Если вы не можете скачать файл, откройте [vpnupgrade.sh](extras/vpnupgrade.sh), затем нажмите кнопку `Raw` справа. Нажмите `Ctrl/Cmd+A`, чтобы выделить всё, `Ctrl/Cmd+C`, чтобы скопировать, затем вставьте в ваш любимый редактор.
</details>
Последняя поддерживаемая версия Libreswan — `5.3`. Проверить установленную версию: `ipsec --version`.
**Примечание:** `xl2tpd` можно обновить с помощью менеджера пакетов вашей системы, например `apt-get` в Ubuntu/Debian.
## Управление пользователями VPN
См. [Управление пользователями VPN](docs/manage-users.md) (на английском языке).
- [Управление пользователями VPN с помощью вспомогательных скриптов](docs/manage-users.md#manage-vpn-users-using-helper-scripts)
- [Просмотр пользователей VPN](docs/manage-users.md#view-vpn-users)
- [Просмотр или обновление IPsec PSK](docs/manage-users.md#view-or-update-the-ipsec-psk)
- [Ручное управление пользователями VPN](docs/manage-users.md#manually-manage-vpn-users)
## Расширенное использование
См. [Расширенное использование](docs/advanced-usage.md) (на английском языке).
- [Использование альтернативных DNS-серверов](docs/advanced-usage.md#use-alternative-dns-servers)
- [Изменения DNS-имени и IP-адреса сервера](docs/advanced-usage.md#dns-name-and-server-ip-changes)
- [VPN только с IKEv2](docs/advanced-usage.md#ikev2-only-vpn)
- [Внутренние IP-адреса VPN и трафик](docs/advanced-usage.md#internal-vpn-ips-and-traffic)
- [Указание публичного IP-адреса VPN-сервера](docs/advanced-usage.md#specify-vpn-servers-public-ip)
- [Настройка подсетей VPN](docs/advanced-usage.md#customize-vpn-subnets)
- [Поддержка IPv6](docs/advanced-usage.md#ipv6-support)
- [Переадресация портов клиентам VPN](docs/advanced-usage.md#port-forwarding-to-vpn-clients)
- [Раздельная маршрутизация (Split tunneling)](docs/advanced-usage.md#split-tunneling)
- [Доступ к подсети VPN-сервера](docs/advanced-usage.md#access-vpn-servers-subnet)
- [Доступ к клиентам VPN из подсети сервера](docs/advanced-usage.md#access-vpn-clients-from-servers-subnet)
- [Изменение правил IPTables](docs/advanced-usage.md#modify-iptables-rules)
- [Развёртывание алгоритма управления перегрузкой Google BBR](docs/advanced-usage.md#deploy-google-bbr-congestion-control)
## Удаление VPN
Чтобы удалить IPsec VPN, запустите [вспомогательный скрипт](extras/vpnuninstall.sh):
**Предупреждение:** Этот вспомогательный скрипт удалит IPsec VPN с вашего сервера. Вся конфигурация VPN будет **безвозвратно удалена**, а Libreswan и xl2tpd будут удалены. Это **нельзя отменить**!
```bash
wget https://get.vpnsetup.net/unst -O unst.sh && sudo bash unst.sh
```
<details>
<summary>
Нажмите здесь, если не удаётся скачать.
</summary>
Вы также можете использовать `curl` для загрузки:
```bash
curl -fsSL https://get.vpnsetup.net/unst -o unst.sh && sudo bash unst.sh
```
Альтернативные URL скрипта:
```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
```
</details>
Для получения дополнительной информации см. [Удаление VPN](docs/uninstall.md).
## Обратная связь и вопросы
- Есть предложение по улучшению этого проекта? Создайте [Предложить улучшение](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose). [Pull request](https://github.com/hwdsl2/setup-ipsec-vpn/pulls) также приветствуются.
- Если вы нашли воспроизводимую ошибку, создайте отчёт об ошибке для [IPsec VPN](https://github.com/libreswan/libreswan/issues?q=is%3Aissue) или для [скрипты VPN](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose).
- Есть вопрос? Пожалуйста, сначала выполните поиск по [существующим issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue) и комментариям [в этом Gist](https://gist.github.com/hwdsl2/9030462#comments) и [в моём блоге](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#disqus_thread).
- Задавайте вопросы, связанные с VPN, в списках рассылки [Libreswan](https://lists.libreswan.org) или [strongSwan](https://lists.strongswan.org), либо прочитайте эти вики: [[1]](https://libreswan.org/wiki/Main_Page) [[2]](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/security_guide/sec-securing_virtual_private_networks) [[3]](https://wiki.strongswan.org/projects/strongswan/wiki/UserDocumentation) [[4]](https://wiki.gentoo.org/wiki/IPsec_L2TP_VPN_server) [[5]](https://wiki.archlinux.org/index.php/Openswan_L2TP/IPsec_VPN_client_setup).
## Лицензия
Copyright (C) 2014-2026 [Lin Song](https://github.com/hwdsl2) [](https://www.linkedin.com/in/linsongui)
Основано на [работе Thomas Sarlandie](https://github.com/sarfata/voodooprivacy) (Copyright 2012)
[](http://creativecommons.org/licenses/by-sa/3.0/)
Эта работа распространяется по лицензии [Creative Commons Attribution-ShareAlike 3.0 Unported License](http://creativecommons.org/licenses/by-sa/3.0/)
Требуется указание авторства: пожалуйста, указывайте моё имя в любых производных работах и сообщайте мне, как вы её улучшили!
================================================
FILE: README-zh-Hant.md
================================================
[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)
# IPsec VPN 伺服器一鍵安裝腳本
[](https://github.com/hwdsl2/setup-ipsec-vpn/actions/workflows/main.yml) [](https://github.com/hwdsl2/setup-ipsec-vpn/stargazers) [](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh-Hant.md) [](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh-Hant.md)
使用 Linux 腳本一鍵快速架設自己的 IPsec VPN 伺服器。支援 IPsec/L2TP、Cisco IPsec 和 IKEv2 協議。
IPsec VPN 可以加密你的網路流量,以防止在透過網際網路傳送時,你和 VPN 伺服器之間的任何人對你的資料進行未經授權的存取。在使用不安全的網路時,這一點特別有用,例如在咖啡廳、機場或旅館房間。
我們將使用 [Libreswan](https://libreswan.org/) 作為 IPsec 伺服器,以及 [xl2tpd](https://github.com/xelerance/xl2tpd) 作為 L2TP 提供者。
**[» :book: Book: Privacy Tools in the Age of AI](docs/vpn-book-zh-Hant.md) [架設自己的 VPN 伺服器](docs/vpn-book-zh-Hant.md)**
## 快速開始
首先,在你的 Linux 伺服器\* 上安裝 Ubuntu、Debian 或 CentOS。
使用以下命令快速架設 IPsec VPN 伺服器:
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
你的 VPN 登入憑證將會自動隨機生成,並在安裝完成後顯示。
**可選:** 在同一台伺服器上安裝 [WireGuard](https://github.com/hwdsl2/wireguard-install/blob/master/README-zh-Hant.md) 和/或 [OpenVPN](https://github.com/hwdsl2/openvpn-install/blob/master/README-zh-Hant.md)。
<details>
<summary>
查看腳本的範例輸出(終端記錄)。
</summary>
**註:** 此終端記錄僅用於示範目的。該記錄中的 VPN 憑據 **無效**。
<p align="center"><img src="docs/images/script-demo.svg"></p>
</details>
<details>
<summary>
如果無法下載,請點這裡。
</summary>
你也可以使用 `curl` 下載:
```bash
curl -fsSL https://get.vpnsetup.net -o vpn.sh && sudo sh vpn.sh
```
或者,你也可以使用這些連結:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
如果無法下載,打開 [vpnsetup.sh](vpnsetup.sh),然後點擊右側的 `Raw` 按鈕。按快捷鍵 `Ctrl/Cmd+A` 全選,`Ctrl/Cmd+C` 複製,然後貼上到你喜歡的編輯器。
</details>
另外,你也可以使用預先建構的 [Docker 映像](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh-Hant.md)。如需了解其他選項以及客戶端設定,請繼續閱讀以下部分。
\* 一個雲端伺服器、虛擬專用伺服器 (VPS) 或專用伺服器。
## 功能特性
- 全自動的 IPsec VPN 伺服器設定,無需使用者輸入
- 支援具有強大且快速加密演算法(例如 AES-GCM)的 IKEv2 模式
- 生成 VPN 設定檔以自動設定 iOS、macOS 和 Android 裝置
- 支援 Windows、macOS、iOS、Android、Chrome OS 和 Linux 客戶端
- 包含輔助腳本以管理 VPN 使用者和憑證
## 系統需求
一個雲端伺服器、虛擬專用伺服器 (VPS) 或專用伺服器,安裝以下作業系統之一:
- Ubuntu 24.04 或 22.04
- Debian 13、12 或 11
- CentOS Stream 10 或 9
- Rocky Linux 或 AlmaLinux
- Oracle Linux
- Amazon Linux 2
<details>
<summary>
其他受支援的 Linux 發行版。
</summary>
- Raspberry Pi OS (Raspbian)
- Kali Linux
- Alpine Linux
- Red Hat Enterprise Linux (RHEL)
</details>
這也包括公共雲服務中的 Linux 虛擬機,例如 [DigitalOcean](https://blog.ls20.com/digitalocean)、[Vultr](https://blog.ls20.com/vultr)、[Linode](https://blog.ls20.com/linode)、[OVH](https://www.ovhcloud.com/en/vps/) 和 [Microsoft Azure](https://azure.microsoft.com)。公共雲使用者也可以使用[使用者資料](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#vpnsetup)部署。
使用以下按鈕快速部署:
[](https://cloud.linode.com/stackscripts/37239) [](aws/README-zh.md) [](azure/README-zh.md)
[**» 我想建立並使用自己的 VPN,但沒有可用的伺服器**](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#gettingavps)
對於有外部防火牆的伺服器(例如 [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)),請為 VPN 開啟 UDP 連接埠 500 和 4500。
另外,你也可以使用預先建構的 [Docker 映像](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh-Hant.md)。進階使用者可以在 [Raspberry Pi](https://www.raspberrypi.com) 上安裝。[[1]](https://elasticbyte.net/posts/setting-up-a-native-cisco-ipsec-vpn-server-using-a-raspberry-pi/) [[2]](https://www.stewright.me/2018/07/create-a-raspberry-pi-vpn-server-using-l2tpipsec/)
:warning: **不要** 在你的 PC 或 Mac 上執行這些腳本!它們只能用在伺服器上!
## 安裝說明
首先,更新你的伺服器:執行 `sudo apt-get update && sudo apt-get dist-upgrade` (Ubuntu/Debian) 或 `sudo yum update` 並重新啟動。此步驟為可選,但建議執行。
要安裝 VPN,請從以下選項中選擇一個:
**選項 1:** 使用腳本隨機生成的 VPN 登入憑證(完成後會顯示)。
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
**選項 2:** 編輯腳本並提供你自己的 VPN 登入憑證。
```bash
wget https://get.vpnsetup.net -O vpn.sh
nano -w vpn.sh
[替換為你自己的值: YOUR_IPSEC_PSK, YOUR_USERNAME 和 YOUR_PASSWORD]
sudo sh vpn.sh
```
**註:** 一個安全的 IPsec PSK 應至少包含 20 個隨機字元。
**選項 3:** 將你自己的 VPN 登入憑證定義為環境變數。
```bash
# 所有變數值必須用 '單引號' 括起來
# *不要* 在值中使用這些字元: \ " '
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_IPSEC_PSK='你的IPsec預共享金鑰' \
VPN_USER='你的VPN使用者名稱' \
VPN_PASSWORD='你的VPN密碼' \
sh vpn.sh
```
你可以選擇在同一台伺服器上安裝 [WireGuard](https://github.com/hwdsl2/wireguard-install/blob/master/README-zh-Hant.md) 和/或 [OpenVPN](https://github.com/hwdsl2/openvpn-install/blob/master/README-zh-Hant.md)。如果你的伺服器執行 CentOS Stream、Rocky Linux 或 AlmaLinux,請先安裝 OpenVPN/WireGuard,然後再安裝 IPsec VPN。
<details>
<summary>
如果無法下載,請點這裡。
</summary>
你也可以使用 `curl` 下載。例如:
```bash
curl -fL https://get.vpnsetup.net -o vpn.sh
sudo sh vpn.sh
```
或者,你也可以使用這些連結:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
如果無法下載,打開 [vpnsetup.sh](vpnsetup.sh),然後點擊右側的 `Raw` 按鈕。按快捷鍵 `Ctrl/Cmd+A` 全選,`Ctrl/Cmd+C` 複製,然後貼上到你喜歡的編輯器。
</details>
<details>
<summary>
我需要安裝較舊版本的 Libreswan 版本 4。
</summary>
一般建議使用最新的 [Libreswan](https://libreswan.org/) 版本 5,它是本專案的預設版本。不過,如果你想要安裝較舊版本的 Libreswan 版本 4:
```bash
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_SWAN_VER=4.15 sh vpn.sh
```
**註:** 如果 Libreswan 版本 5 已經安裝,你可能需要先[解除安裝 VPN](docs/uninstall-zh.md),然後再安裝 Libreswan 版本 4。或者,你也可以下載[升級腳本](#升級libreswan),編輯它並指定 `SWAN_VER=4.15`,然後執行腳本。
</details>
## 自訂 VPN 選項
### 使用其他 DNS 伺服器
在 VPN 已連線時,客戶端預設設定為使用 [Google Public DNS](https://developers.google.com/speed/public-dns/)。在安裝 VPN 時,你可以為所有 VPN 模式指定其他 DNS 伺服器。此為可選設定。示例如下:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
使用 `VPN_DNS_SRV1` 指定主要 DNS 伺服器,使用 `VPN_DNS_SRV2` 指定次要 DNS 伺服器(可選)。
以下是一些常見的公共 DNS 提供商列表,供你參考。
| 提供商 | 主 DNS | 輔助 DNS | 註解 |
| ----- | ------ | ------- | ---- |
| [Google Public DNS](https://developers.google.com/speed/public-dns) | 8.8.8.8 | 8.8.4.4 | 本專案預設 |
| [Cloudflare](https://1.1.1.1/dns/) | 1.1.1.1 | 1.0.0.1 | 另見:[Cloudflare for families](https://1.1.1.1/family/) |
| [Quad9](https://www.quad9.net) | 9.9.9.9 | 149.112.112.112 | 阻擋惡意網域 |
| [OpenDNS](https://www.opendns.com/home-internet-security/) | 208.67.222.222 | 208.67.220.220 | 阻擋網路釣魚網域,可設定。 |
| [CleanBrowsing](https://cleanbrowsing.org/filters/) | 185.228.168.9 | 185.228.169.9 | 提供[網域過濾器](https://cleanbrowsing.org/filters/) |
| [NextDNS](https://nextdns.io/?from=bg25bwmp) | 依需求選擇 | 依需求選擇 | 廣告攔截,提供免費方案。[了解更多](https://nextdns.io/?from=bg25bwmp)。 |
| [Control D](https://controld.com/free-dns) | 依需求選擇 | 依需求選擇 | 廣告攔截,可自訂設定。[了解更多](https://controld.com/free-dns)。 |
如果你需要在安裝 VPN 之後更改 DNS 伺服器,請參見[進階用法](docs/advanced-usage-zh.md)。
**註:** 如果伺服器上已經設定 IKEv2,以上變數對 IKEv2 模式無效。在此情況下,如需自訂 IKEv2 選項(例如 DNS 伺服器),你可以先[移除 IKEv2](docs/ikev2-howto-zh.md#移除-ikev2),然後執行 `sudo ikev2.sh` 重新設定。
### 自訂 IKEv2 選項
在安裝 VPN 時,進階使用者可以自訂 IKEv2 選項。此為可選設定。
<details open>
<summary>
選項 1:在安裝 VPN 時跳過 IKEv2,然後使用自訂選項設定 IKEv2。
</summary>
在安裝 VPN 時,你可以跳過 IKEv2,只安裝 IPsec/L2TP 和 IPsec/XAuth("Cisco IPsec")模式:
```bash
sudo VPN_SKIP_IKEV2=yes sh vpn.sh
```
(可選)如果要為 VPN 客戶端指定其他 DNS 伺服器,你可以定義 `VPN_DNS_SRV1` 和 `VPN_DNS_SRV2`(可選)。更多資訊請參見[使用其他 DNS 伺服器](#使用其他-dns-伺服器)。
然後執行 IKEv2 輔助腳本,以互動方式使用自訂選項設定 IKEv2:
```bash
sudo ikev2.sh
```
你可以自訂以下選項:VPN 伺服器的網域名稱、第一個客戶端的名稱與憑證有效期限、VPN 客戶端的 DNS 伺服器,以及是否對客戶端設定檔進行密碼保護。
**註:** 如果伺服器上已經設定 IKEv2,則 `VPN_SKIP_IKEV2` 變數無效。在此情況下,如需自訂 IKEv2 選項,你可以先[移除 IKEv2](docs/ikev2-howto-zh.md#移除-ikev2),然後執行 `sudo ikev2.sh` 重新設定。
</details>
<details>
<summary>
選項 2:使用環境變數自訂 IKEv2 選項。
</summary>
在安裝 VPN 時,你可以指定一個網域名稱作為 IKEv2 伺服器位址。此為可選設定。該網域名稱必須是完整網域名稱 (FQDN)。示例如下:
```bash
sudo VPN_DNS_NAME='vpn.example.com' sh vpn.sh
```
同樣地,你也可以指定第一個 IKEv2 客戶端的名稱。如果未指定,則使用預設值 `vpnclient`。
```bash
sudo VPN_CLIENT_NAME='your_client_name' sh vpn.sh
```
在 VPN 已連線時,客戶端預設設定為使用 [Google Public DNS](https://developers.google.com/speed/public-dns/)。你可以為所有 VPN 模式指定其他 DNS 伺服器。示例如下:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
預設情況下,匯入 IKEv2 客戶端設定時不需要密碼。你可以選擇使用隨機密碼保護客戶端設定檔。
```bash
sudo VPN_PROTECT_CONFIG=yes sh vpn.sh
```
</details>
<details>
<summary>
供參考:IKEv1 和 IKEv2 參數列表。
</summary>
| IKEv1 參數\* |預設值 |自訂(環境變數)\*\* |
| ------------ | ---- | ----------------- |
|伺服器位址(DNS 網域名稱)| - |不能,但你可以使用 DNS 網域名稱進行連線 |
|伺服器位址(公網 IP)|自動偵測 | VPN_PUBLIC_IP |
| IPsec 預共享金鑰 |自動生成 | VPN_IPSEC_PSK |
| VPN 使用者名稱 | vpnuser | VPN_USER |
| VPN 密碼 |自動生成 | VPN_PASSWORD |
|客戶端的 DNS 伺服器 |Google Public DNS | VPN_DNS_SRV1, VPN_DNS_SRV2 |
|跳過 IKEv2 安裝 |no | VPN_SKIP_IKEV2=yes |
\* 這些 IKEv1 參數適用於 IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式。
\*\* 在執行 vpn(setup).sh 時將這些定義為環境變數。
| IKEv2 參數\* |預設值 |自訂(環境變數)\*\* |自訂(互動式)\*\*\* |
| ----------- | ---- | ------------------ | ----------------- |
|伺服器位址(DNS 網域名稱)| - | VPN_DNS_NAME | ✅ |
|伺服器位址(公網 IP)|自動偵測 | VPN_PUBLIC_IP | ✅ |
|第一個客戶端的名稱 | vpnclient | VPN_CLIENT_NAME | ✅ |
|客戶端的 DNS 伺服器 |Google Public DNS | VPN_DNS_SRV1, VPN_DNS_SRV2 | ✅ |
|保護客戶端設定檔 |no | VPN_PROTECT_CONFIG=yes | ✅ |
|啟用/停用 MOBIKE |如果系統支援則啟用 | ❌ | ✅ |
|客戶端憑證有效期限 | 10 年(120 個月)| VPN_CLIENT_VALIDITY\*\*\*\* | ✅ |
| CA 和伺服器憑證有效期限 | 10 年(120 個月)| ❌ | ❌ |
| CA 憑證名稱 | IKEv2 VPN CA | ❌ | ❌ |
|憑證金鑰長度 | 3072 bits | ❌ | ❌ |
\* 這些 IKEv2 參數適用於 IKEv2 模式。
\*\* 在執行 vpn(setup).sh 時,或在自動模式下設定 IKEv2 時 (`sudo ikev2.sh --auto`) 將這些定義為環境變數。
\*\*\* 可以在互動式設定 IKEv2 期間自訂 (`sudo ikev2.sh`)。參見上面的選項 1。
\*\*\*\* 使用 `VPN_CLIENT_VALIDITY` 定義客戶端憑證的有效期限(單位:月)。它必須是 1 到 120 之間的整數。
除了這些參數,高級使用者還可以在安裝時[自訂 VPN 子網](docs/advanced-usage-zh.md#自定义-vpn-子网)。
</details>
## 下一步
*其他語言版本: [English](README.md#next-steps), [简体中文](README-zh.md#下一步), [繁體中文](README-zh-Hant.md#下一步), [日本語](README-ja.md#次のステップ), [Русский](README-ru.md#следующие-шаги)。*
設定你的電腦或其他裝置使用 VPN。請參見以下連結(簡體中文):
**[設定 IKEv2 VPN 客戶端(推薦)](docs/ikev2-howto-zh.md)**
**[設定 IPsec/L2TP VPN 客戶端](docs/clients-zh.md)**
**[設定 IPsec/XAuth ("Cisco IPsec") VPN 客戶端](docs/clients-xauth-zh.md)**
**閱讀 [:book: VPN book](docs/vpn-book-zh-Hant.md) 以存取[額外內容](https://ko-fi.com/post/Support-this-project-and-get-access-to-supporter-o-X8X5FVFZC)。**
開始使用自己的專屬 VPN! :sparkles::tada::rocket::sparkles:
## 重要提示
**Windows 使用者** 對於 IPsec/L2TP 模式,在首次連線之前需要[修改登錄檔](docs/clients-zh.md#windows-错误-809),以解決 VPN 伺服器或客戶端與 NAT(例如家用路由器)的相容問題。
同一個 VPN 帳戶可以在你的多個裝置上使用。但由於 IPsec/L2TP 的限制,如果需要連線到同一個 NAT(例如家用路由器)後面的多個裝置,你必須使用 [IKEv2](docs/ikev2-howto-zh.md) 或 [IPsec/XAuth](docs/clients-xauth-zh.md) 模式。要查看或變更 VPN 使用者帳戶,請參見[管理 VPN 使用者](docs/manage-users-zh.md)。
對於有外部防火牆的伺服器(例如 [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)),請為 VPN 開啟 UDP 連接埠 500 和 4500。阿里雲使用者請參見 [#433](https://github.com/hwdsl2/setup-ipsec-vpn/issues/433)。
在 VPN 已連線時,客戶端設定為使用 [Google Public DNS](https://developers.google.com/speed/public-dns/)。如果偏好其他的網域解析服務,請參見[進階用法](docs/advanced-usage-zh.md)。
使用核心支援有助於提升 IPsec/L2TP 效能。它在所有[支援的系統](#系統需求)上可用。Ubuntu 系統需要安裝 `linux-modules-extra-$(uname -r)` 軟體套件並執行 `service xl2tpd restart`。
這些腳本在變更現有設定檔之前會先建立備份,並使用 `.old-日期-時間` 作為檔名後綴。
## 升級Libreswan
使用以下命令更新你的 VPN 伺服器上的 [Libreswan](https://libreswan.org)([更新日誌](https://github.com/libreswan/libreswan/blob/main/CHANGES) | [通知清單](https://lists.libreswan.org))。
```bash
wget https://get.vpnsetup.net/upg -O vpnup.sh && sudo sh vpnup.sh
```
<details>
<summary>
如果無法下載,請點這裡。
</summary>
你也可以使用 `curl` 下載:
```bash
curl -fsSL https://get.vpnsetup.net/upg -o vpnup.sh && sudo sh vpnup.sh
```
或者,你也可以使用這些連結:
```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
```
如果無法下載,打開 [vpnupgrade.sh](extras/vpnupgrade.sh),然後點擊右側的 `Raw` 按鈕。按快捷鍵 `Ctrl/Cmd+A` 全選,`Ctrl/Cmd+C` 複製,然後貼上到你喜歡的編輯器。
</details>
目前支援的 Libreswan 最新版本是 `5.3`。查看已安裝版本:`ipsec --version`。
**註:** `xl2tpd` 可以使用系統的套件管理器進行更新,例如 Ubuntu/Debian 上的 `apt-get`。
## 管理 VPN 使用者
請參見[管理 VPN 使用者](docs/manage-users-zh.md)(簡體中文)。
- [使用輔助腳本管理 VPN 使用者](docs/manage-users-zh.md#使用辅助脚本管理-vpn-用户)
- [查看 VPN 使用者](docs/manage-users-zh.md#查看-vpn-用户)
- [查看或變更 IPsec PSK](docs/manage-users-zh.md#查看或更改-ipsec-psk)
- [手動管理 VPN 使用者](docs/manage-users-zh.md#手动管理-vpn-用户)
## 進階用法
請參見[進階用法](docs/advanced-usage-zh.md)(簡體中文)。
- [使用其他 DNS 伺服器](docs/advanced-usage-zh.md#使用其他的-dns-服务器)
- [網域名稱與變更伺服器 IP](docs/advanced-usage-zh.md#域名和更改服务器-ip)
- [僅限 IKEv2 的 VPN](docs/advanced-usage-zh.md#仅限-ikev2-的-vpn)
- [VPN 內網 IP 與流量](docs/advanced-usage-zh.md#vpn-内网-ip-和流量)
- [指定 VPN 伺服器的公有 IP](docs/advanced-usage-zh.md#指定-vpn-服务器的公有-ip)
- [自訂 VPN 子網](docs/advanced-usage-zh.md#自定义-vpn-子网)
- [IPv6 支援](docs/advanced-usage-zh.md#ipv6-支持)
- [轉發連接埠到 VPN 客戶端](docs/advanced-usage-zh.md#转发端口到-vpn-客户端)
- [VPN 分流](docs/advanced-usage-zh.md#vpn-分流)
- [存取 VPN 伺服器的網段](docs/advanced-usage-zh.md#访问-vpn-服务器的网段)
- [VPN 伺服器網段存取 VPN 客戶端](docs/advanced-usage-zh.md#vpn-服务器网段访问-vpn-客户端)
- [變更 IPTables 規則](docs/advanced-usage-zh.md#更改-iptables-规则)
- [部署 Google BBR 壅塞控制](docs/advanced-usage-zh.md#部署-google-bbr-拥塞控制)
## 移除 VPN
要移除 IPsec VPN,執行[輔助腳本](extras/vpnuninstall.sh):
**警告:** 此輔助腳本將從你的伺服器中刪除 IPsec VPN。所有 VPN 設定將被**永久刪除**,並且 Libreswan 和 xl2tpd 將被移除。此操作**無法復原**!
```bash
wget https://get.vpnsetup.net/unst -O unst.sh && sudo bash unst.sh
```
<details>
<summary>
如果無法下載,請點這裡。
</summary>
你也可以使用 `curl` 下載:
```bash
curl -fsSL https://get.vpnsetup.net/unst -o unst.sh && sudo bash unst.sh
```
或者,你也可以使用這些連結:
```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
```
</details>
更多資訊請參見[移除 VPN](docs/uninstall-zh.md)。
## 問題與回饋
- 如果你對本專案有建議,請提交一個[改進建議](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose),或歡迎提交 [Pull request](https://github.com/hwdsl2/setup-ipsec-vpn/pulls)。
- 如果你發現可重現的程式漏洞,請為 [IPsec VPN](https://github.com/libreswan/libreswan/issues?q=is%3Aissue) 或 [VPN 腳本](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose)提交錯誤回報。
- 有問題想提問?請先搜尋[既有的 issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue) 以及[這個 Gist](https://gist.github.com/hwdsl2/9030462#comments) 和[我的部落格](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#disqus_thread)上已有的留言。
- VPN 相關問題可在 [Libreswan](https://lists.libreswan.org) 或 [strongSwan](https://lists.strongswan.org) 郵件列表提問,或參考以下網站:[[1]](https://libreswan.org/wiki/Main_Page) [[2]](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/security_guide/sec-securing_virtual_private_networks) [[3]](https://wiki.strongswan.org/projects/strongswan/wiki/UserDocumentation) [[4]](https://wiki.gentoo.org/wiki/IPsec_L2TP_VPN_server) [[5]](https://wiki.archlinux.org/index.php/Openswan_L2TP/IPsec_VPN_client_setup)。
## 授權條款
版權所有 (C) 2014-2026 [Lin Song](https://github.com/hwdsl2) [](https://www.linkedin.com/in/linsongui)
基於 [Thomas Sarlandie 的工作](https://github.com/sarfata/voodooprivacy)(版權所有 2012)
[](http://creativecommons.org/licenses/by-sa/3.0/)
此專案採用 [Creative Commons 姓名標示-相同方式分享 3.0](http://creativecommons.org/licenses/by-sa/3.0/) 授權條款。
必須署名:請在任何衍生作品中包含我的名字,並且讓我知道你是如何改進它的!
================================================
FILE: README-zh.md
================================================
[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)
# IPsec VPN 服务器一键安装脚本
[](https://github.com/hwdsl2/setup-ipsec-vpn/actions/workflows/main.yml) [](https://github.com/hwdsl2/setup-ipsec-vpn/stargazers) [](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh.md) [](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh.md)
使用 Linux 脚本一键快速搭建自己的 IPsec VPN 服务器。支持 IPsec/L2TP, Cisco IPsec 和 IKEv2 协议。
IPsec VPN 可以加密你的网络流量,以防止在通过因特网传送时,你和 VPN 服务器之间的任何人对你的数据的未经授权的访问。在使用不安全的网络时,这是特别有用的,例如在咖啡厅,机场或旅馆房间。
我们将使用 [Libreswan](https://libreswan.org/) 作为 IPsec 服务器,以及 [xl2tpd](https://github.com/xelerance/xl2tpd) 作为 L2TP 提供者。
**[» :book: Book: Privacy Tools in the Age of AI](docs/vpn-book-zh.md) [搭建自己的 VPN 服务器](docs/vpn-book-zh.md)**
## 快速开始
首先,在你的 Linux 服务器\* 上安装 Ubuntu, Debian 或者 CentOS。
使用以下命令快速搭建 IPsec VPN 服务器:
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
你的 VPN 登录凭证将会被自动随机生成,并在安装完成后显示。
**可选:** 在同一台服务器上安装 [WireGuard](https://github.com/hwdsl2/wireguard-install/blob/master/README-zh.md) 和/或 [OpenVPN](https://github.com/hwdsl2/openvpn-install/blob/master/README-zh.md)。
<details>
<summary>
查看脚本的示例输出(终端记录)。
</summary>
**注:** 此终端记录仅用于演示目的。该记录中的 VPN 凭据 **无效**。
<p align="center"><img src="docs/images/script-demo.svg"></p>
</details>
<details>
<summary>
如果无法下载,请点这里。
</summary>
你也可以使用 `curl` 下载:
```bash
curl -fsSL https://get.vpnsetup.net -o vpn.sh && sudo sh vpn.sh
```
或者,你也可以使用这些链接:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
如果无法下载,打开 [vpnsetup.sh](vpnsetup.sh),然后点击右边的 `Raw` 按钮。按快捷键 `Ctrl/Cmd+A` 全选,`Ctrl/Cmd+C` 复制,然后粘贴到你喜欢的编辑器。
</details>
另外,你也可以使用预构建的 [Docker 镜像](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh.md)。如需了解其它选项以及客户端配置,请继续阅读以下部分。
\* 一个云服务器,虚拟专用服务器 (VPS) 或者专用服务器。
## 功能特性
- 全自动的 IPsec VPN 服务器配置,无需用户输入
- 支持具有强大和快速加密算法(例如 AES-GCM)的 IKEv2 模式
- 生成 VPN 配置文件以自动配置 iOS, macOS 和 Android 设备
- 支持 Windows, macOS, iOS, Android, Chrome OS 和 Linux 客户端
- 包括辅助脚本以管理 VPN 用户和证书
## 系统要求
一个云服务器,虚拟专用服务器 (VPS) 或者专用服务器,安装以下操作系统之一:
- Ubuntu 24.04 或者 22.04
- Debian 13、12 或者 11
- CentOS Stream 10 或者 9
- Rocky Linux 或者 AlmaLinux
- Oracle Linux
- Amazon Linux 2
<details>
<summary>
其他受支持的 Linux 发行版。
</summary>
- Raspberry Pi OS (Raspbian)
- Kali Linux
- Alpine Linux
- Red Hat Enterprise Linux (RHEL)
</details>
这也包括公共云服务中的 Linux 虚拟机,例如 [DigitalOcean](https://blog.ls20.com/digitalocean), [Vultr](https://blog.ls20.com/vultr), [Linode](https://blog.ls20.com/linode), [OVH](https://www.ovhcloud.com/en/vps/) 和 [Microsoft Azure](https://azure.microsoft.com)。公共云用户也可以使用[用户数据](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#vpnsetup)部署。
使用以下按钮快速部署:
[](https://cloud.linode.com/stackscripts/37239) [](aws/README-zh.md) [](azure/README-zh.md)
[**» 我想建立并使用自己的 VPN,但是没有可用的服务器**](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#gettingavps)
对于有外部防火墙的服务器(比如 [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)),请为 VPN 打开 UDP 端口 500 和 4500。
另外,你也可以使用预构建的 [Docker 镜像](https://github.com/hwdsl2/docker-ipsec-vpn-server/blob/master/README-zh.md)。高级用户可以在 [Raspberry Pi](https://www.raspberrypi.com) 上安装。[[1]](https://elasticbyte.net/posts/setting-up-a-native-cisco-ipsec-vpn-server-using-a-raspberry-pi/) [[2]](https://www.stewright.me/2018/07/create-a-raspberry-pi-vpn-server-using-l2tpipsec/)
:warning: **不要** 在你的 PC 或者 Mac 上运行这些脚本!它们只能用在服务器上!
## 安装说明
首先,更新你的服务器:运行 `sudo apt-get update && sudo apt-get dist-upgrade` (Ubuntu/Debian) 或者 `sudo yum update` 并重启。这一步是可选的,但推荐。
要安装 VPN,请从以下选项中选择一个:
**选项 1:** 使用脚本随机生成的 VPN 登录凭证(完成后会显示)。
```bash
wget https://get.vpnsetup.net -O vpn.sh && sudo sh vpn.sh
```
**选项 2:** 编辑脚本并提供你自己的 VPN 登录凭证。
```bash
wget https://get.vpnsetup.net -O vpn.sh
nano -w vpn.sh
[替换为你自己的值: YOUR_IPSEC_PSK, YOUR_USERNAME 和 YOUR_PASSWORD]
sudo sh vpn.sh
```
**注:** 一个安全的 IPsec PSK 应该至少包含 20 个随机字符。
**选项 3:** 将你自己的 VPN 登录凭证定义为环境变量。
```bash
# 所有变量值必须用 '单引号' 括起来
# *不要* 在值中使用这些字符: \ " '
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_IPSEC_PSK='你的IPsec预共享密钥' \
VPN_USER='你的VPN用户名' \
VPN_PASSWORD='你的VPN密码' \
sh vpn.sh
```
你可以选择在同一台服务器上安装 [WireGuard](https://github.com/hwdsl2/wireguard-install/blob/master/README-zh.md) 和/或 [OpenVPN](https://github.com/hwdsl2/openvpn-install/blob/master/README-zh.md)。如果你的服务器运行 CentOS Stream, Rocky Linux 或 AlmaLinux,请先安装 OpenVPN/WireGuard,然后安装 IPsec VPN。
<details>
<summary>
如果无法下载,请点这里。
</summary>
你也可以使用 `curl` 下载。例如:
```bash
curl -fL https://get.vpnsetup.net -o vpn.sh
sudo sh vpn.sh
```
或者,你也可以使用这些链接:
```bash
https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh
https://gitlab.com/hwdsl2/setup-ipsec-vpn/-/raw/master/vpnsetup.sh
```
如果无法下载,打开 [vpnsetup.sh](vpnsetup.sh),然后点击右边的 `Raw` 按钮。按快捷键 `Ctrl/Cmd+A` 全选,`Ctrl/Cmd+C` 复制,然后粘贴到你喜欢的编辑器。
</details>
<details>
<summary>
我需要安装较旧版本的 Libreswan 版本 4。
</summary>
一般建议使用最新的 [Libreswan](https://libreswan.org/) 版本 5,它是本项目的默认版本。但是,如果你想要安装较旧版本的 Libreswan 版本 4:
```bash
wget https://get.vpnsetup.net -O vpn.sh
sudo VPN_SWAN_VER=4.15 sh vpn.sh
```
**注:** 如果 Libreswan 版本 5 已经安装,你可能需要首先[卸载 VPN](docs/uninstall-zh.md),然后安装 Libreswan 版本 4。或者,你也可以下载[升级脚本](#升级libreswan),编辑它并指定 `SWAN_VER=4.15`,然后运行脚本。
</details>
## 自定义 VPN 选项
### 使用其他的 DNS 服务器
在 VPN 已连接时,客户端默认配置为使用 [Google Public DNS](https://developers.google.com/speed/public-dns/)。在安装 VPN 时,你可以为所有的 VPN 模式指定另外的 DNS 服务器。这是可选的。示例如下:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
使用 `VPN_DNS_SRV1` 指定主 DNS 服务器,使用 `VPN_DNS_SRV2` 指定辅助 DNS 服务器(可选)。
以下是一些流行的公共 DNS 提供商的列表,供你参考。
| 提供商 | 主 DNS | 辅助 DNS | 注释 |
| ----- | ------ | ------- | ---- |
| [Google Public DNS](https://developers.google.com/speed/public-dns) | 8.8.8.8 | 8.8.4.4 | 本项目默认 |
| [Cloudflare](https://1.1.1.1/dns/) | 1.1.1.1 | 1.0.0.1 | 另见:[Cloudflare for families](https://1.1.1.1/family/) |
| [Quad9](https://www.quad9.net) | 9.9.9.9 | 149.112.112.112 | 阻止恶意域 |
| [OpenDNS](https://www.opendns.com/home-internet-security/) | 208.67.222.222 | 208.67.220.220 | 阻止网络钓鱼域,可配置。 |
| [CleanBrowsing](https://cleanbrowsing.org/filters/) | 185.228.168.9 | 185.228.169.9 | [域过滤器](https://cleanbrowsing.org/filters/)可用 |
| [NextDNS](https://nextdns.io/?from=bg25bwmp) | 按需选择 | 按需选择 | 广告拦截,免费套餐可用。[了解更多](https://nextdns.io/?from=bg25bwmp)。 |
| [Control D](https://controld.com/free-dns) | 按需选择 | 按需选择 | 广告拦截,可配置。[了解更多](https://controld.com/free-dns)。 |
如果你需要在安装 VPN 之后更改 DNS 服务器,参见[高级用法](docs/advanced-usage-zh.md)。
**注:** 如果服务器上已经配置了 IKEv2,则以上变量对 IKEv2 模式无效。在这种情况下,如需自定义 IKEv2 选项(例如 DNS 服务器),你可以首先[移除 IKEv2](docs/ikev2-howto-zh.md#移除-ikev2),然后运行 `sudo ikev2.sh` 重新配置。
### 自定义 IKEv2 选项
在安装 VPN 时,高级用户可以自定义 IKEv2 选项。这是可选的。
<details open>
<summary>
选项 1: 在安装 VPN 时跳过 IKEv2,然后使用自定义选项配置 IKEv2。
</summary>
在安装 VPN 时,你可以跳过 IKEv2,仅安装 IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式:
```bash
sudo VPN_SKIP_IKEV2=yes sh vpn.sh
```
(可选)如需为 VPN 客户端指定另外的 DNS 服务器,你可以定义 `VPN_DNS_SRV1` 和 `VPN_DNS_SRV2`(可选)。有关详细信息,参见[使用其他的 DNS 服务器](#使用其他的-dns-服务器)。
然后运行 IKEv2 辅助脚本以使用自定义选项以交互方式配置 IKEv2:
```bash
sudo ikev2.sh
```
你可以自定义以下选项:VPN 服务器的域名,第一个客户端的名称和证书有效期,VPN 客户端的 DNS 服务器以及是否对客户端配置文件进行密码保护。
**注:** 如果服务器上已经配置了 IKEv2,则 `VPN_SKIP_IKEV2` 变量无效。在这种情况下,如需自定义 IKEv2 选项,你可以首先[移除 IKEv2](docs/ikev2-howto-zh.md#移除-ikev2),然后运行 `sudo ikev2.sh` 重新配置。
</details>
<details>
<summary>
选项 2: 使用环境变量自定义 IKEv2 选项。
</summary>
在安装 VPN 时,你可以指定一个域名作为 IKEv2 服务器地址。这是可选的。该域名必须是一个全称域名(FQDN)。示例如下:
```bash
sudo VPN_DNS_NAME='vpn.example.com' sh vpn.sh
```
类似地,你可以指定第一个 IKEv2 客户端的名称。如果未指定,则使用默认值 `vpnclient`。
```bash
sudo VPN_CLIENT_NAME='your_client_name' sh vpn.sh
```
在 VPN 已连接时,客户端默认配置为使用 [Google Public DNS](https://developers.google.com/speed/public-dns/)。你可以为所有的 VPN 模式指定另外的 DNS 服务器。示例如下:
```bash
sudo VPN_DNS_SRV1=1.1.1.1 VPN_DNS_SRV2=1.0.0.1 sh vpn.sh
```
默认情况下,导入 IKEv2 客户端配置时不需要密码。你可以选择使用随机密码保护客户端配置文件。
```bash
sudo VPN_PROTECT_CONFIG=yes sh vpn.sh
```
</details>
<details>
<summary>
供参考:IKEv1 和 IKEv2 参数列表。
</summary>
| IKEv1 参数\* |默认值 |自定义(环境变量)\*\* |
| ------------ | ---- | ----------------- |
|服务器地址(DNS域名)| - |不能,但你可以使用 DNS 域名进行连接 |
|服务器地址(公网IP)|自动检测 | VPN_PUBLIC_IP |
| IPsec 预共享密钥 |自动生成 | VPN_IPSEC_PSK |
| VPN 用户名 | vpnuser | VPN_USER |
| VPN 密码 |自动生成 | VPN_PASSWORD |
|客户端的 DNS 服务器 |Google Public DNS | VPN_DNS_SRV1, VPN_DNS_SRV2 |
|跳过 IKEv2 安装 |no | VPN_SKIP_IKEV2=yes |
\* 这些 IKEv1 参数适用于 IPsec/L2TP 和 IPsec/XAuth ("Cisco IPsec") 模式。
\*\* 在运行 vpn(setup).sh 时将这些定义为环境变量。
| IKEv2 参数\* |默认值 |自定义(环境变量)\*\* |自定义(交互式)\*\*\* |
| ----------- | ---- | ------------------ | ----------------- |
|服务器地址(DNS域名)| - | VPN_DNS_NAME | ✅ |
|服务器地址(公网IP)|自动检测 | VPN_PUBLIC_IP | ✅ |
|第一个客户端的名称 | vpnclient | VPN_CLIENT_NAME | ✅ |
|客户端的 DNS 服务器 |Google Public DNS | VPN_DNS_SRV1, VPN_DNS_SRV2 | ✅ |
|保护客户端配置文件 |no | VPN_PROTECT_CONFIG=yes | ✅ |
|启用/禁用 MOBIKE |如果系统支持则启用 | ❌ | ✅ |
|客户端证书有效期 | 10 年(120 个月)| VPN_CLIENT_VALIDITY\*\*\*\* | ✅ |
| CA 和服务器证书有效期 | 10 年(120 个月)| ❌ | ❌ |
| CA 证书名称 | IKEv2 VPN CA | ❌ | ❌ |
|证书密钥长度 | 3072 bits | ❌ | ❌ |
\* 这些 IKEv2 参数适用于 IKEv2 模式。
\*\* 在运行 vpn(setup).sh 时,或者在自动模式下配置 IKEv2 时 (`sudo ikev2.sh --auto`) 将这些定义为环境变量。
\*\*\* 可以在交互式配置 IKEv2 期间自定义 (`sudo ikev2.sh`)。参见上面的选项 1。
\*\*\*\* 使用 `VPN_CLIENT_VALIDITY` 定义客户端证书的有效期(单位:月)。它必须是 1 到 120 之间的整数。
除了这些参数,高级用户还可以在安装时[自定义 VPN 子网](docs/advanced-usage-zh.md#自定义-vpn-子网)。
</details>
## 下一步
*其他语言版本: [English](README.md#next-steps), [简体中文](README-zh.md#下一步), [繁體中文](README-zh-Hant.md#下一步), [日本語](README-ja.md#次のステップ), [Русский](README-ru.md#следующие-шаги)。*
配置你的计算机或其它设备使用 VPN。请参见:
**[配置 IKEv2 VPN 客户端(推荐)](docs/ikev2-howto-zh.md)**
**[配置 IPsec/L2TP VPN 客户端](docs/clients-zh.md)**
**[配置 IPsec/XAuth ("Cisco IPsec") VPN 客户端](docs/clients-xauth-zh.md)**
**阅读 [:book: VPN book](docs/vpn-book-zh.md) 以访问[额外内容](https://ko-fi.com/post/Support-this-project-and-get-access-to-supporter-o-X8X5FVFZC)。**
开始使用自己的专属 VPN! :sparkles::tada::rocket::sparkles:
## 重要提示
**Windows 用户** 对于 IPsec/L2TP 模式,在首次连接之前需要[修改注册表](docs/clients-zh.md#windows-错误-809),以解决 VPN 服务器或客户端与 NAT(比如家用路由器)的兼容问题。
同一个 VPN 账户可以在你的多个设备上使用。但是由于 IPsec/L2TP 的局限性,如果需要连接在同一个 NAT(比如家用路由器)后面的多个设备,你必须使用 [IKEv2](docs/ikev2-howto-zh.md) 或者 [IPsec/XAuth](docs/clients-xauth-zh.md) 模式。要查看或更改 VPN 用户账户,请参见[管理 VPN 用户](docs/manage-users-zh.md)。
对于有外部防火墙的服务器(比如 [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)),请为 VPN 打开 UDP 端口 500 和 4500。阿里云用户请参见 [#433](https://github.com/hwdsl2/setup-ipsec-vpn/issues/433)。
在 VPN 已连接时,客户端配置为使用 [Google Public DNS](https://developers.google.com/speed/public-dns/)。如果偏好其它的域名解析服务,请参见[高级用法](docs/advanced-usage-zh.md)。
使用内核支持有助于提高 IPsec/L2TP 性能。它在所有[受支持的系统](#系统要求)上可用。Ubuntu 系统需要安装 `linux-modules-extra-$(uname -r)` 软件包并运行 `service xl2tpd restart`。
这些脚本在更改现有的配置文件之前会先做备份,使用 `.old-日期-时间` 为文件名后缀。
## 升级Libreswan
使用以下命令更新你的 VPN 服务器上的 [Libreswan](https://libreswan.org)([更新日志](https://github.com/libreswan/libreswan/blob/main/CHANGES) | [通知列表](https://lists.libreswan.org))。
```bash
wget https://get.vpnsetup.net/upg -O vpnup.sh && sudo sh vpnup.sh
```
<details>
<summary>
如果无法下载,请点这里。
</summary>
你也可以使用 `curl` 下载:
```bash
curl -fsSL https://get.vpnsetup.net/upg -o vpnup.sh && sudo sh vpnup.sh
```
或者,你也可以使用这些链接:
```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
```
如果无法下载,打开 [vpnupgrade.sh](extras/vpnupgrade.sh),然后点击右边的 `Raw` 按钮。按快捷键 `Ctrl/Cmd+A` 全选,`Ctrl/Cmd+C` 复制,然后粘贴到你喜欢的编辑器。
</details>
当前支持的 Libreswan 最新版本是 `5.3`。查看已安装版本:`ipsec --version`。
**注:** `xl2tpd` 可以使用系统的软件包管理器进行更新,例如 Ubuntu/Debian 上的 `apt-get`。
## 管理 VPN 用户
请参见[管理 VPN 用户](docs/manage-users-zh.md)。
- [使用辅助脚本管理 VPN 用户](docs/manage-users-zh.md#使用辅助脚本管理-vpn-用户)
- [查看 VPN 用户](docs/manage-users-zh.md#查看-vpn-用户)
- [查看或更改 IPsec PSK](docs/manage-users-zh.md#查看或更改-ipsec-psk)
- [手动管理 VPN 用户](docs/manage-users-zh.md#手动管理-vpn-用户)
## 高级用法
请参见[高级用法](docs/advanced-usage-zh.md)。
- [使用其他的 DNS 服务器](docs/advanced-usage-zh.md#使用其他的-dns-服务器)
- [域名和更改服务器 IP](docs/advanced-usage-zh.md#域名和更改服务器-ip)
- [仅限 IKEv2 的 VPN](docs/advanced-usage-zh.md#仅限-ikev2-的-vpn)
- [VPN 内网 IP 和流量](docs/advanced-usage-zh.md#vpn-内网-ip-和流量)
- [指定 VPN 服务器的公有 IP](docs/advanced-usage-zh.md#指定-vpn-服务器的公有-ip)
- [自定义 VPN 子网](docs/advanced-usage-zh.md#自定义-vpn-子网)
- [IPv6 支持](docs/advanced-usage-zh.md#ipv6-支持)
- [转发端口到 VPN 客户端](docs/advanced-usage-zh.md#转发端口到-vpn-客户端)
- [VPN 分流](docs/advanced-usage-zh.md#vpn-分流)
- [访问 VPN 服务器的网段](docs/advanced-usage-zh.md#访问-vpn-服务器的网段)
- [VPN 服务器网段访问 VPN 客户端](docs/advanced-usage-zh.md#vpn-服务器网段访问-vpn-客户端)
- [更改 IPTables 规则](docs/advanced-usage-zh.md#更改-iptables-规则)
- [部署 Google BBR 拥塞控制](docs/advanced-usage-zh.md#部署-google-bbr-拥塞控制)
## 卸载 VPN
要卸载 IPsec VPN,运行[辅助脚本](extras/vpnuninstall.sh):
**警告:** 此辅助脚本将从你的服务器中删除 IPsec VPN。所有的 VPN 配置将被**永久删除**,并且 Libreswan 和 xl2tpd 将被移除。此操作**不可撤销**!
```bash
wget https://get.vpnsetup.net/unst -O unst.sh && sudo bash unst.sh
```
<details>
<summary>
如果无法下载,请点这里。
</summary>
你也可以使用 `curl` 下载:
```bash
curl -fsSL https://get.vpnsetup.net/unst -o unst.sh && sudo bash unst.sh
```
或者,你也可以使用这些链接:
```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
```
</details>
更多信息请参见[卸载 VPN](docs/uninstall-zh.md)。
## 问题和反馈
- 如果你有对本项目的建议,请提交一个[改进建议](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose),或者欢迎提交 [Pull request](https://github.com/hwdsl2/setup-ipsec-vpn/pulls)。
- 如果你发现了一个可重复的程序漏洞,请为 [IPsec VPN](https://github.com/libreswan/libreswan/issues?q=is%3Aissue) 或者 [VPN 脚本](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose)提交一个错误报告。
- 有问题需要提问?请先搜索[已有的 issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue) 以及在[这个 Gist](https://gist.github.com/hwdsl2/9030462#comments) 和[我的博客](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#disqus_thread)上已有的留言。
- VPN 的相关问题可在 [Libreswan](https://lists.libreswan.org) 或 [strongSwan](https://lists.strongswan.org) 邮件列表提问,或者参考这些网站:[[1]](https://libreswan.org/wiki/Main_Page) [[2]](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/security_guide/sec-securing_virtual_private_networks) [[3]](https://wiki.strongswan.org/projects/strongswan/wiki/UserDocumentation) [[4]](https://wiki.gentoo.org/wiki/IPsec_L2TP_VPN_server) [[5]](https://wiki.archlinux.org/index.php/Openswan_L2TP/IPsec_VPN_client_setup)。
## 授权协议
版权所有 (C) 2014-2026 [Lin Song](https://github.com/hwdsl2) [](https://www.linkedin.com/in/linsongui)
基于 [Thomas Sarlandie 的工作](https://github.com/sarfata/voodooprivacy) (版权所有 2012)
[](http://creativecommons.org/licenses/by-sa/3.0/)
这个项目是以[知识共享署名-相同方式共享3.0](http://creativecommons.org/licenses/by-sa/3.0/) 许可协议授权。
必须署名: 请包括我的名字在任何衍生产品,并且让我知道你是如何改善它的!
================================================
FILE: README.md
================================================
[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)
# IPsec VPN Server Auto Setup Scripts
[](https://github.com/hwdsl2/setup-ipsec-vpn/actions/workflows/main.yml) [](https://github.com/hwdsl2/setup-ipsec-vpn/stargazers) [](https://github.com/hwdsl2/docker-ipsec-vpn-server) [](https://github.com/hwdsl2/docker-ipsec-vpn-server)
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](https://libreswan.org/) as the IPsec server, and [xl2tpd](https://github.com/xelerance/xl2tpd) as the L2TP provider.
**[» :book: Book: Privacy Tools in the Age of AI](docs/vpn-book.md) [Build Your Own VPN Server](docs/vpn-book.md)**
## Quick start
First, prepare your Linux server\* with an install of Ubuntu, Debian or CentOS.
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.
**Optional:** Install [WireGuard](https://github.com/hwdsl2/wireguard-install) and/or [OpenVPN](https://github.com/hwdsl2/openvpn-install) on the same server.
<details>
<summary>
See the script in action (terminal recording).
</summary>
**Note:** This recording is for demo purposes only. VPN credentials in this recording are **NOT** valid.
<p align="center"><img src="docs/images/script-demo.svg"></p>
</details>
<details>
<summary>
Click here if you are unable to download.
</summary>
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](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.
</details>
A pre-built [Docker image](https://github.com/hwdsl2/docker-ipsec-vpn-server) is also available. For other options and client setup, read the sections below.
\* A cloud server, virtual private server (VPS) or dedicated server.
## 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
## Requirements
A cloud server, virtual private server (VPS) or dedicated server, with an install of:
- Ubuntu 24.04 or 22.04
- Debian 13, 12 or 11
- CentOS Stream 10 or 9
- Rocky Linux or AlmaLinux
- Oracle Linux
- Amazon Linux 2
<details>
<summary>
Other supported Linux distributions.
</summary>
- Raspberry Pi OS (Raspbian)
- Kali Linux
- Alpine Linux
- Red Hat Enterprise Linux (RHEL)
</details>
This also includes Linux VMs in public clouds, such as [DigitalOcean](https://blog.ls20.com/digitalocean), [Vultr](https://blog.ls20.com/vultr), [Linode](https://blog.ls20.com/linode), [OVH](https://www.ovhcloud.com/en/vps/) and [Microsoft Azure](https://azure.microsoft.com). Public cloud users can also deploy using [user data](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#vpnsetup).
Quick deploy to:
[](https://cloud.linode.com/stackscripts/37239) [](aws/README.md) [](azure/README.md)
[**» I want to run my own VPN but don't have a server for that**](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#gettingavps)
For servers with an external firewall (e.g. [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)), open UDP ports 500 and 4500 for the VPN.
A pre-built [Docker image](https://github.com/hwdsl2/docker-ipsec-vpn-server) is also available. Advanced users can install on a [Raspberry Pi](https://www.raspberrypi.com). [[1]](https://elasticbyte.net/posts/setting-up-a-native-cisco-ipsec-vpn-server-using-a-raspberry-pi/) [[2]](https://www.stewright.me/2018/07/create-a-raspberry-pi-vpn-server-using-l2tpipsec/)
: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
```
You may optionally install [WireGuard](https://github.com/hwdsl2/wireguard-install) and/or [OpenVPN](https://github.com/hwdsl2/openvpn-install) on the same server. If your server runs CentOS Stream, Rocky Linux or AlmaLinux, first install OpenVPN/WireGuard, then install the IPsec VPN.
<details>
<summary>
Click here if you are unable to download.
</summary>
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](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.
</details>
<details>
<summary>
I want to install the older Libreswan version 4.
</summary>
It is generally recommended to use the latest [Libreswan](https://libreswan.org/) 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](docs/uninstall.md) before installing Libreswan version 4. Alternatively, download the [update script](#upgrade-libreswan), edit it to specify `SWAN_VER=4.15`, then run the script.
</details>
## Customize VPN options
### Use alternative DNS servers
By default, clients are set to use [Google Public DNS](https://developers.google.com/speed/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](https://developers.google.com/speed/public-dns) | 8.8.8.8 | 8.8.4.4 | Default in this project |
| [Cloudflare](https://1.1.1.1/dns/) | 1.1.1.1 | 1.0.0.1 | See also: [Cloudflare for families](https://1.1.1.1/family/) |
| [Quad9](https://www.quad9.net) | 9.9.9.9 | 149.112.112.112 | Blocks malicious domains |
| [OpenDNS](https://www.opendns.com/home-internet-security/) | 208.67.222.222 | 208.67.220.220 | Blocks phishing domains, configurable. |
| [CleanBrowsing](https://cleanbrowsing.org/filters/) | 185.228.168.9 | 185.228.169.9 | [Domain filters](https://cleanbrowsing.org/filters/) available |
| [NextDNS](https://nextdns.io/?from=bg25bwmp) | Varies | Varies | Ad blocking, free tier available. [Learn more](https://nextdns.io/?from=bg25bwmp). |
| [Control D](https://controld.com/free-dns) | Varies | Varies | Ad blocking, configurable. [Learn more](https://controld.com/free-dns). |
If you need to change DNS servers after VPN setup, see [Advanced usage](docs/advanced-usage.md).
**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](docs/ikev2-howto.md#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.
<details open>
<summary>
Option 1: Skip IKEv2 during VPN setup, then set up IKEv2 using custom options.
</summary>
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](#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](docs/ikev2-howto.md#remove-ikev2), then set it up again using `sudo ikev2.sh`.
</details>
<details>
<summary>
Option 2: Customize IKEv2 options using environment variables.
</summary>
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](https://developers.google.com/speed/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
```
</details>
<details>
<summary>
For reference: List of IKEv1 and IKEv2 parameters.
</summary>
| 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](docs/advanced-usage.md#customize-vpn-subnets) during VPN setup.
</details>
## Next steps
*Read this in other languages: [English](README.md#next-steps), [简体中文](README-zh.md#下一步), [繁體中文](README-zh-Hant.md#下一步), [日本語](README-ja.md#次のステップ), [Русский](README-ru.md#следующие-шаги).*
Get your computer or device to use the VPN. Please refer to:
**[Configure IKEv2 VPN Clients (recommended)](docs/ikev2-howto.md)**
**[Configure IPsec/L2TP VPN Clients](docs/clients.md)**
**[Configure IPsec/XAuth ("Cisco IPsec") VPN Clients](docs/clients-xauth.md)**
**Read [:book: VPN book](docs/vpn-book.md) to access [extra content](https://ko-fi.com/post/Support-this-project-and-get-access-to-supporter-o-O5O7FVF8J).**
Enjoy your very own VPN! :sparkles::tada::rocket::sparkles:
## Important notes
**Windows users**: For IPsec/L2TP mode, a [one-time registry change](docs/clients.md#windows-error-809) 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](docs/ikev2-howto.md) or [IPsec/XAuth](docs/clients-xauth.md) mode. To view or update VPN user accounts, see [Manage VPN users](docs/manage-users.md).
For servers with an external firewall (e.g. [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)/[GCE](https://cloud.google.com/vpc/docs/firewalls)), open UDP ports 500 and 4500 for the VPN. Aliyun users, see [#433](https://github.com/hwdsl2/setup-ipsec-vpn/issues/433).
Clients are set to use [Google Public DNS](https://developers.google.com/speed/public-dns/) when the VPN is active. If another DNS provider is preferred, see [Advanced usage](docs/advanced-usage.md).
Using kernel support could improve IPsec/L2TP performance. It is available on [all supported OS](#requirements). 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](https://libreswan.org) ([changelog](https://github.com/libreswan/libreswan/blob/main/CHANGES) | [announce](https://lists.libreswan.org)) on your VPN server.
```bash
wget https://get.vpnsetup.net/upg -O vpnup.sh && sudo sh vpnup.sh
```
<details>
<summary>
Click here if you are unable to download.
</summary>
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](extras/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.
</details>
The latest supported Libreswan version is `5.3`. 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](docs/manage-users.md).
- [Manage VPN users using helper scripts](docs/manage-users.md#manage-vpn-users-using-helper-scripts)
- [View VPN users](docs/manage-users.md#view-vpn-users)
- [View or update the IPsec PSK](docs/manage-users.md#view-or-update-the-ipsec-psk)
- [Manually manage VPN users](docs/manage-users.md#manually-manage-vpn-users)
## Advanced usage
See [Advanced usage](docs/advanced-usage.md).
- [Use alternative DNS servers](docs/advanced-usage.md#use-alternative-dns-servers)
- [DNS name and server IP changes](docs/advanced-usage.md#dns-name-and-server-ip-changes)
- [IKEv2-only VPN](docs/advanced-usage.md#ikev2-only-vpn)
- [Internal VPN IPs and traffic](docs/advanced-usage.md#internal-vpn-ips-and-traffic)
- [Specify VPN server's public IP](docs/advanced-usage.md#specify-vpn-servers-public-ip)
- [Customize VPN subnets](docs/advanced-usage.md#customize-vpn-subnets)
- [IPv6 support](docs/advanced-usage.md#ipv6-support)
- [Port forwarding to VPN clients](docs/advanced-usage.md#port-forwarding-to-vpn-clients)
- [Split tunneling](docs/advanced-usage.md#split-tunneling)
- [Access VPN server's subnet](docs/advanced-usage.md#access-vpn-servers-subnet)
- [Access VPN clients from server's subnet](docs/advanced-usage.md#access-vpn-clients-from-servers-subnet)
- [Modify IPTables rules](docs/advanced-usage.md#modify-iptables-rules)
- [Deploy Google BBR congestion control](docs/advanced-usage.md#deploy-google-bbr-congestion-control)
## Uninstall the VPN
To uninstall IPsec VPN, run the [helper script](extras/vpnuninstall.sh):
**Warning:** 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
```
<details>
<summary>
Click here if you are unable to download.
</summary>
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
```
</details>
For more information, see [Uninstall the VPN](docs/uninstall.md).
## Feedback & Questions
- Have a suggestion for this project? Open an [Enhancement request](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose). [Pull requests](https://github.com/hwdsl2/setup-ipsec-vpn/pulls) are also welcome.
- If you found a reproducible bug, open a bug report for the [IPsec VPN](https://github.com/libreswan/libreswan/issues?q=is%3Aissue) or for the [VPN scripts](https://github.com/hwdsl2/setup-ipsec-vpn/issues/new/choose).
- Got a question? Please first search [existing issues](https://github.com/hwdsl2/setup-ipsec-vpn/issues?q=is%3Aissue) and comments [in this Gist](https://gist.github.com/hwdsl2/9030462#comments) and [on my blog](https://blog.ls20.com/ipsec-l2tp-vpn-auto-setup-for-ubuntu-12-04-on-amazon-ec2/#disqus_thread).
- Ask VPN related questions on the [Libreswan](https://lists.libreswan.org) or [strongSwan](https://lists.strongswan.org) mailing list, or read these wikis: [[1]](https://libreswan.org/wiki/Main_Page) [[2]](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/security_guide/sec-securing_virtual_private_networks) [[3]](https://wiki.strongswan.org/projects/strongswan/wiki/UserDocumentation) [[4]](https://wiki.gentoo.org/wiki/IPsec_L2TP_VPN_server) [[5]](https://wiki.archlinux.org/index.php/Openswan_L2TP/IPsec_VPN_client_setup).
## License
Copyright (C) 2014-2026 [Lin Song](https://github.com/hwdsl2) [](https://www.linkedin.com/in/linsongui)
Based on [the work of Thomas Sarlandie](https://github.com/sarfata/voodooprivacy) (Copyright 2012)
[](http://creativecommons.org/licenses/by-sa/3.0/)
This work is licensed under the [Creative Commons Attribution-ShareAlike 3.0 Unported License](http://creativecommons.org/licenses/by-sa/3.0/)
Attribution required: please include my name in any derivative and let me know how you have improved it!
================================================
FILE: aws/README-zh.md
================================================
[English](README.md) | [中文](README-zh.md)
# 使用 CloudFormation 在 Amazon EC2 上部署
使用这个模板,你可以在 Amazon Elastic Compute Cloud(Amazon EC2)上快速搭建一个 IPsec VPN 服务器。在继续之前,请参见 EC2 [定价细节](https://aws.amazon.com/cn/ec2/pricing/on-demand/)。在部署中使用 `t2.micro` 或 `t3.micro` 服务器实例可能符合 [AWS 免费套餐](https://aws.amazon.com/cn/free/)的资格。
可用的自定义参数:
- Amazon EC2 实例类型
> <details><summary><strong>注:</strong> 在某些 AWS 区域中,此模版提供的某些实例类型可能不可用。(点击查看详情)
> </summary>
>
> 比如 `m5a.large` 可能无法在 `ap-east-1` 区域部署(仅为假设)。在此情况下,你会在部署过程中遇到此错误:`The requested configuration is currently not supported. Please check the documentation for supported configurations`。新开放的 AWS 区域更容易出现此问题,因为它们提供的实例类型较少。如需了解更多关于实例可用性的信息,请参见 [https://instances.vantage.sh/](https://instances.vantage.sh/)。</details>
- VPN 服务器的操作系统(Ubuntu **24.04**/22.04, Debian 12/11, Amazon Linux 2)
- 你的 VPN 用户名
- 你的 VPN 密码
- 你的 VPN IPsec PSK(预共享密钥)
> **注:** 一个安全的 IPsec PSK 应该至少包含 20 个随机字符。\*不要\* 在值中使用这些字符: `\ " '`
确保使用 **AWS 账户根用户** 或者有 **管理员权限** 的 **IAM 用户** 部署此模板。
右键单击这个 [**模板链接**](https://raw.githubusercontent.com/hwdsl2/setup-ipsec-vpn/master/aws/cloudformation-template-ipsec.json),并将它保存到你的计算机上的一个新文件。然后在 ["创建堆栈" 向导](https://console.aws.amazon.com/cloudformation/home#/stacks/new)中将其作为模板源上传。要指定一个 AWS 区域,你可以使用导航栏上你的帐户信息右侧的选择器。继续创建堆栈,在最后一步你需要确认(选择)此模板可以创建 IAM 资源。
当你在最后一步中点击 "create stack" 之后,请等待堆栈创建和 VPN 安装完成,可能需要最多 15 分钟。一旦堆栈的部署状态变成 **"CREATE_COMPLETE"** ,你就可以连接到 VPN 服务器了。单击 **Outputs** 选项卡以查看你的 VPN 登录信息,然后继续下一步:[配置 VPN 客户端](../README-zh.md#下一步)。
点击下面的图标开始:
[](https://console.aws.amazon.com/cloudformation/home#/stacks/new)
## 延伸阅读
了解有关此 CloudFormation 模板设计的更多信息:
[Introduction to AWS CloudFormation with Example Project Walk-Through](https://nixsanctuary.com/introduction-to-aws-cloudformation-with-example-project-walk-through/)
## 屏幕截图
<details>
<summary>
点这里查看屏幕截图。
</summary>




</details>
## 常见问题
<details>
<summary>
如何在部署结束后提取 IKEv2 连接配置文件?
</summary>
部署完成之后,生成的 IKEv2 配置文件已经被上传到了一个新创建的 AWS Simple Storage Service (S3) 储存桶。下载配置文件的链接可以在 **Outputs** 页面下找到。
点击下载链接下载名为 `profiles.zip` 的压缩包文件。解压密码为**你在创建堆栈时输入的 VPN 连接密码**。
值得注意的是,IKEv2 配置文件的下载链接将会在**1天后过期**,从堆栈部署完成时算起。如果你将堆栈删除,存放 IKEv2 配置文件的储存桶不会被自动删除。
关于如何在 IKEv2 模式下配置你的客户端,请参见: [IKEv2 VPN 配置和使用指南](../docs/ikev2-howto-zh.md)。

</details>
<details>
<summary>
部署后如何通过 SSH 连接到服务器?
</summary>
**选项 1:** 使用 [EC2 Instance Connect](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/ec2-instance-connect-methods.html) 进行连接。
**选项 2:** 使用 SSH 连接到服务器。详情如下。
你需要你的 Amazon EC2 实例的用户名和私钥,才能通过 SSH 登录到该实例。
EC2 上的每个 Linux 服务器发行版本都有它自己的默认登录用户名。新实例默认禁用密码登录,必须使用私钥或 “密钥对” 登录。
默认用户名列表:
> **参考链接:** [https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key)
| 发行版本 | 默认登录用户名 |
| --- | --- |
| Ubuntu | `ubuntu` |
| Debian | `admin` |
| Amazon Linux 2 | `ec2-user` |
此模板在部署期间为你生成一个密钥对。在成功创建堆栈后,你可以使用以下的其中一种方式来获取私钥。
1. 在 **Outputs** 页面下拷贝密钥对 ID ,然后使用以下命令来提取私钥内容并且将其保存为一个证书文件:
> **注:** 在使用以下命令前,你需要在你的电脑上正确的安装和配置好 AWS 命令行。更多关于开始使用 AWS 命令行的信息,请参照 [Get started with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html) 。
```
$ aws ssm get-parameter --region your-region --name /ec2/keypair/your-key-pair-id --with-decryption --query Parameter.Value --output text > new-key-file.pem
```

2. 直接从 **Outputs** 页面拷贝私钥对内容 ,然后将其保存入一个证书文件。请注意在保存到你的计算机之前,你可能需要修改私钥的格式,比如用换行符替换所有的空格。在保存后,需要为该私钥文件设置[适当的权限](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key)才能使用。

要为私钥文件设置适当的权限,请在该文件所在的目录下运行以下命令:
```bash
$ sudo chmod 400 new-key-file.pem
```
使用 SSH 登录到 EC2 实例的示例命令:
```bash
$ ssh -i path/to/your/new-key-file.pem instance-username@instance-ip-address
```
</details>
<details>
<summary>
如何删除 CloudFormation 堆栈?
</summary>
你可以使用 CloudFormation 堆栈页面上的 "Delete" 按钮删除你创建的 CloudFormation 堆栈和它相关的资源。请注意,删除堆栈时存放生成的 IKEv2 配置文件的 S3 储存桶不会被自动删除。参见上面的 "如何在部署结束后提取 IKEv2 连接配置文件"。
</details>
## 作者
版权所有 (C) 2020-2025 [Scott X. L.](https://github.com/scottpedia) <[ge105@ncf.ca](mailto:ge105@ncf.ca)>
================================================
FILE: aws/README.md
================================================
[English](README.md) | [中文](README-zh.md)
# Deploy to Amazon EC2 using CloudFormation
This template will create a fully-working IPsec VPN server on Amazon Elastic Compute Cloud (Amazon EC2). Please make sure to check the EC2 [pricing details](https://aws.amazon.com/ec2/pricing/on-demand/) before continuing. Using a `t2.micro` or `t3.micro` server instance for your deployment may qualify for the [AWS Free Tier](https://aws.amazon.com/free/).
Available customization parameters:
- Amazon EC2 instance type
> <details><summary><strong>Note</strong>: It is possible that not all instance type options offered by this template are available in a specific AWS region.(expand for details)
> </summary>
>
> For example, you may not be able to deploy an `m5a.large` instance in `ap-east-1` (hypothetically). In that case, you might experience the following error during deployment: `The requested configuration is currently not supported. Please check the documentation for supported configurations`. Newly released regions are more prone to having this problem as there are less variety of instances. For more info about instance type availability, refer to [https://instances.vantage.sh/](https://instances.vantage.sh/).</details>
- OS for your VPN server (Ubuntu **24.04**/22.04, Debian 12/11, Amazon Linux 2)
- Your VPN username
- Your VPN password
- Your VPN IPsec PSK (pre-shared key)
> **Note:** A secure IPsec PSK should consist of at least 20 random characters. DO NOT use these special characters within values: `\ " '`
Make sure to deploy this template with an **AWS Account Root User** or an **IAM Account** with **Administrator Access**.
Right-click this [**template link**](https://raw.githubusercontent.com/hwdsl2/setup-ipsec-vpn/master/aws/cloudformation-template-ipsec.json) and save as a file on your computer. Then upload it as the template source in the [stack creation wizard](https://console.aws.amazon.com/cloudformation/home#/stacks/new). You may choose an AWS region using the selector to the right of your account information on the navigation bar. Continue creating the stack, and in the final step make sure to confirm that this template may create IAM resources.
After you click "create stack" in the final step, please wait for the stack creation and VPN setup to complete, which may take up to 15 minutes. As soon as the stack's status changes to **"CREATE_COMPLETE"**, you are ready to connect to the VPN server. Click the **Outputs** tab to view your VPN login details. Then continue to [Next steps: Configure VPN Clients](../README.md#next-steps).
Click the icon below to start:
[](https://console.aws.amazon.com/cloudformation/home#/stacks/new)
## Further reading
Learn more about the design of this CloudFormation template:
[Introduction to AWS CloudFormation with Example Project Walk-Through](https://nixsanctuary.com/introduction-to-aws-cloudformation-with-example-project-walk-through/)
## Screenshots
<details>
<summary>
Click here to view screenshots.
</summary>




</details>
## FAQs
<details>
<summary>
How to retrieve the IKEv2 credentials following the deployment?
</summary>
After the deployment completes, connection credentials generated for IKEv2 mode are uploaded to a newly created AWS Simple Storage Service (S3) bucket. The download link is then provided under the **Outputs** tab.
Simply click on the link to download an archive named `profiles.zip`. To extract the contents from the archive, you will be prompted to enter a password, which is the **VPN password you specified when creating the stack**.
It's important to note that the link provided for downloading the IKEv2 credentials **will expire in 1 day** following the successful deployment of the stack. If you delete the stack, the bucket that stores the IKEv2 crendentials will not be automatically deleted.
To learn more about how to configure your clients using IKEv2 mode, please refer to: [Guide: How to Set Up and Use IKEv2 VPN](../docs/ikev2-howto.md).

</details>
<details>
<summary>
How to connect to the server via SSH after deployment?
</summary>
**Option 1:** Connect using [EC2 Instance Connect](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-methods.html).
**Option 2:** Connect to the server using SSH. See details below.
You need to know the username and the private key for your Amazon EC2 instance in order to login to it via SSH.
Each Linux server distribution on EC2 has its own default login username. Password login is disabled by default for new instances, and the use of private keys, or "key pairs", is enforced.
List of default usernames:
> **Reference:** [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connection-prereqs.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connection-prereqs.html)
| Distribution | Default Login Username |
| --- | --- |
| Ubuntu | `ubuntu` |
| Debian | `admin` |
| Amazon Linux 2 | `ec2-user` |
This template generates a key pair for you during deployment, and to acquire the private key you can choose one of the following two methods.
1. Copy the key pair ID displayed under the **Outputs** tab, and use the following command to retrieve the private key material and save it into a certificate file:
> **Note:** You need to first properly set up the AWS CLI on your computer before using the following command. For more information on how to get started with AWS CLI, please refer to [Get started with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).
```
$ aws ssm get-parameter --region your-region --name /ec2/keypair/your-key-pair-id --with-decryption --query Parameter.Value --output text > new-key-file.pem
```

2. Copy the private key material directly from the **Outputs** tab, and save it into a certificate file. Note that You may need to format the private key by replacing all spaces with newlines, before saving to a file. The file will need to be set with [proper permissions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key) before using.

To apply proper permissions to your private key file, run the following command under the directory where the file is located:
```bash
$ sudo chmod 400 new-key-file.pem
```
Example command to login to your EC2 instance using SSH:
```bash
$ ssh -i path/to/your/new-key-file.pem instance-username@instance-ip-address
```
</details>
<details>
<summary>
How to delete the CloudFormation stack?
</summary>
You may use the "Delete" button on the CloudFormation stack page to delete the CloudFormation stack you created and its associated resources. Note that when deleting the stack, the S3 bucket that stores the generated IKEv2 credentials will not be automatically deleted. Refer to "How to retrieve the IKEv2 credentials following the deployment" above.
</details>
## Author
Copyright (C) 2020-2025 [Scott X. L.](https://github.com/scottpedia) <[ge105@ncf.ca](mailto:ge105@ncf.ca)>
================================================
FILE: aws/cloudformation-template-ipsec.json
================================================
{
"Metadata": {
"README": {
"Fn::Join": [
"\n",
[
"",
"AWS Cloudformation Template for deploying IPSec VPN Servers on AWS EC2,",
"based on the work of Lin Song <linsongui@gmail.com> : https://github.com/hwdsl2/setup-ipsec-vpn",
"The latest version of this template can be found at : https://github.com/hwdsl2/setup-ipsec-vpn/aws",
"",
"Copyright (C) 2020-2025 Scott X. L. <ge105@ncf.ca>",
"",
"This work is licensed under the Creative Commons Attribution-ShareAlike 3.0",
"Unported License: http://creativecommons.org/licenses/by-sa/3.0/",
"",
"Attribution required: Please include my name in any derivative and let me",
"know how you have improved it!",
""
]
]
}
},
"AWSTemplateFormatVersion": "2010-09-09",
"Mappings": {
"OS": {
"Ubuntu2204": {
"HelperInstallationCommands": "export DEBIAN_FRONTEND=noninteractive\napt-get -yq update\napt-get -yq install python3-pip zip awscli\npython3 -m pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz"
},
"Ubuntu2404": {
"HelperInstallationCommands": "export DEBIAN_FRONTEND=noninteractive\nrm -rf /usr/lib/python3.*/EXTERNALLY-MANAGED\napt-get -yq update\napt-get -yq install python3-pip zip\nsnap install aws-cli --classic\npython3 -m pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz"
},
"Debian11": {
"HelperInstallationCommands": "export DEBIAN_FRONTEND=noninteractive\napt-get -yq update\napt-get -yq install python3-pip zip awscli\npython3 -m pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz"
},
"Debian12": {
"HelperInstallationCommands": "export DEBIAN_FRONTEND=noninteractive\nrm -rf /usr/lib/python3.*/EXTERNALLY-MANAGED\napt-get -yq update\napt-get -yq install python3-pip zip awscli\npython3 -m pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz"
},
"AmazonLinux2": {
"HelperInstallationCommands": "export PATH=\"$PATH:/opt/aws/bin\""
}
}
},
"Resources": {
"IAMInstanceProfile": {
"Type": "AWS::IAM::InstanceProfile",
"Properties": {
"InstanceProfileName": {
"Ref": "KeyPair"
},
"Path": "/setup-ipsec-vpn/",
"Roles": [
{
"Ref": "S3ExecutionRole"
}
]
},
"DependsOn": [
"S3ExecutionRole",
"KeyPair"
]
},
"Ikev2S3Bucket": {
"Type": "AWS::S3::Bucket",
"DeletionPolicy": "Retain",
"Properties": {
"PublicAccessBlockConfiguration": {
"BlockPublicAcls": false,
"BlockPublicPolicy": false,
"IgnorePublicAcls": false,
"RestrictPublicBuckets": false
},
"LifecycleConfiguration": {
"Rules": [
{
"Id": "DeletionAfterOneDay",
"Status": "Enabled",
"ExpirationInDays": 1
}
]
},
"BucketName": {
"Fn::GetAtt": [
"KeyPairDisplayFunctionInfo",
"Combination"
]
}
},
"Metadata": {},
"DependsOn": [
"KeyPair"
]
},
"OpenBucketPolicy": {
"Type": "AWS::S3::BucketPolicy",
"Properties": {
"Bucket": {
"Ref": "Ikev2S3Bucket"
},
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": {
"Fn::Join": [
"",
[
"arn:aws:s3:::",
{
"Ref": "Ikev2S3Bucket"
},
"/*"
]
]
}
}
]
}
}
},
"VpnVpc": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": "10.0.0.0/24"
},
"Metadata": {}
},
"VpnSubnet": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"VpcId": {
"Ref": "VpnVpc"
},
"CidrBlock": "10.0.0.0/24",
"MapPublicIpOnLaunch": true,
"AvailabilityZone": {
"Fn::Select": [
"0",
{
"Fn::GetAZs": ""
}
]
}
},
"Metadata": {},
"DependsOn": [
"VpnVpc",
"VpcInternetGateway"
]
},
"VpnRouteTable": {
"Type": "AWS::EC2::RouteTable",
"Properties": {
"VpcId": {
"Ref": "VpnVpc"
}
},
"Metadata": {},
"DependsOn": [
"VpnSubnet"
]
},
"PublicInternetRoute": {
"Type": "AWS::EC2::Route",
"Properties": {
"DestinationCidrBlock": "0.0.0.0/0",
"RouteTableId": {
"Ref": "VpnRouteTable"
},
"GatewayId": {
"Ref": "VpcInternetGateway"
}
},
"Metadata": {},
"DependsOn": [
"VpnRouteTable",
"VpcInternetGateway",
"InternetGatewayAttachment"
]
},
"VpnInstance": {
"Type": "AWS::EC2::Instance",
"CreationPolicy": {
"ResourceSignal": {
"Timeout": "PT15M"
}
},
"Properties": {
"IamInstanceProfile": {
"Ref": "IAMInstanceProfile"
},
"UserData": {
"Fn::Base64": {
"Fn::Join": [
"\n",
[
"#!/bin/bash -xe",
{ "Fn::Sub": "trap 'cfn-signal -e 1 --resource VpnInstance --stack ${AWS::StackName} --region ${AWS::Region}' ERR" },
"sleep 60",
{
"Fn::FindInMap": [
"OS",
{
"Ref": "OS"
},
"HelperInstallationCommands"
]
},
{ "Fn::Sub": "export VPN_IPSEC_PSK='${VpnIpsecPsk}'" },
{ "Fn::Sub": "export VPN_USER='${VpnUser}'" },
{ "Fn::Sub": "export VPN_PASSWORD='${VpnPassword}'" },
"wget -t 3 -T 30 -nv -O vpn.sh https://github.com/hwdsl2/setup-ipsec-vpn/raw/master/vpnsetup.sh",
"sh vpn.sh",
"mkdir /root/profiles",
"cp /root/vpnclient* /root/profiles",
{ "Fn::Sub": "cd /root/ && zip -er --password '${VpnPassword}' profiles.zip ./profiles" },
{ "Fn::Sub": "aws s3 cp /root/profiles.zip s3://${Ikev2S3Bucket}/" },
{ "Fn::Sub": "cfn-signal -e 0 --stack ${AWS::StackName} --resource VpnInstance --region ${AWS::Region}" }
]
]
}
},
"SecurityGroupIds": [
{
"Fn::GetAtt": [
"VpnSecurityGroup",
"GroupId"
]
}
],
"SubnetId": {
"Ref": "VpnSubnet"
},
"AvailabilityZone": {
"Fn::Select": [
"0",
{
"Fn::GetAZs": ""
}
]
},
"InstanceType": {
"Ref": "InstanceType"
},
"KeyName": {
"Ref": "KeyPair"
},
"ImageId": {
"Fn::GetAtt": [
"AMIInfo",
"AMIId"
]
}
},
"Metadata": {},
"DependsOn": [
"VpnRouteTable",
"KeyPair",
"AMIInfoFunction",
"VpnSecurityGroup",
"Ikev2S3Bucket",
"IAMInstanceProfile"
]
},
"KeyPair": {
"Type": "AWS::EC2::KeyPair",
"Properties": {
"KeyName": {
"Fn::Join": [
"-",
[
"setup-ipsec-vpn",
{
"Ref": "AWS::StackName"
}
]
]
}
}
},
"VpnSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupDescription": "The VPN Security Group, allowing ingress UDP traffic at port 4500 and 500.",
"GroupName": "VpnSecurityGroup",
"VpcId": {
"Ref": "VpnVpc"
},
"SecurityGroupIngress": [
{
"CidrIp": "0.0.0.0/0",
"IpProtocol": "tcp",
"FromPort": 22,
"ToPort": 22
},
{
"CidrIp": "0.0.0.0/0",
"IpProtocol": "udp",
"FromPort": 500,
"ToPort": 500
},
{
"CidrIp": "0.0.0.0/0",
"IpProtocol": "udp",
"FromPort": 4500,
"ToPort": 4500
}
],
"SecurityGroupEgress": [
{
"CidrIp": "0.0.0.0/0",
"IpProtocol": -1
}
]
},
"Metadata": {}
},
"VpcInternetGateway": {
"Type": "AWS::EC2::InternetGateway",
"Properties": {},
"Metadata": {},
"DependsOn": [
"VpnVpc"
]
},
"SubnetRouteTableAssociation": {
"Type": "AWS::EC2::SubnetRouteTableAssociation",
"Properties": {
"RouteTableId": {
"Ref": "VpnRouteTable"
},
"SubnetId": {
"Ref": "VpnSubnet"
}
},
"Metadata": {}
},
"KeyPairDisplayFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "python3.12",
"Role": {
"Fn::GetAtt": [
"LambdaExecutionRole",
"Arn"
]
},
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"import boto3",
"import cfnresponse",
"import string",
"import random",
"import traceback",
"'''",
"This python program should be embedded into its designated cloudformation",
"template as the inline code of one of the lambda functions.",
"Its function is to create a random combination of 20 characters for the naming of the Ikev2S3Bucket, and",
"to retrieve the private key material for display under the Outputs tab.",
"'''",
"def handler(event, context):",
" try:",
" if event['RequestType'] == 'Delete':",
" cfnresponse.send(event, context, cfnresponse.SUCCESS, {})",
" elif event['RequestType'] == 'Create':",
" rCombination = 'setup-ipsec-vpn-' + ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(20)).lower()",
" region = event['ResourceProperties']['Region']",
" ssm = boto3.client('ssm',region)",
" response = ssm.get_parameter(",
{
"Fn::Join": [
"",
[
" Name='/ec2/keypair/",
{
"Fn::GetAtt": [
"KeyPair",
"KeyPairId"
]
},
"',"
]
]
},
" WithDecryption=True",
" )",
" keyMaterial = response['Parameter']['Value']",
" cfnresponse.send(event, context, cfnresponse.SUCCESS, {'KeyMaterial':keyMaterial, 'Combination':rCombination}, 'KeyPairDisplayFunctionInfo')",
" except Exception as e:",
" cfnresponse.send(event, context, cfnresponse.FAILED, {'ErrorMsg':traceback.format_exc()})"
]
]
}
},
"Timeout": 30
},
"Metadata": {},
"DependsOn": [
"LambdaExecutionRole",
"KeyPair"
]
},
"KeyPairDisplayFunctionInfo": {
"Type": "Custom::KeyPairDisplayFunctionInfo",
"Properties": {
"Region": {
"Ref": "AWS::Region"
},
"ServiceToken": {
"Fn::GetAtt": [
"KeyPairDisplayFunction",
"Arn"
]
}
},
"Metadata": {},
"DependsOn": [
"KeyPairDisplayFunction",
"KeyPair"
]
},
"AMIInfo": {
"Type": "Custom::AMIInfo",
"Properties": {
"Region": {
"Ref": "AWS::Region"
},
"ServiceToken": {
"Fn::GetAtt": [
"AMIInfoFunction",
"Arn"
]
},
"Distribution": {
"Ref": "OS"
}
},
"Metadata": {},
"DependsOn": [
"AMIInfoFunction"
]
},
"AMIInfoFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "python3.12",
"Role": {
"Fn::GetAtt": [
"LambdaExecutionRole",
"Arn"
]
},
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"import boto3",
"import cfnresponse",
"import trac
gitextract_z3qo90ab/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── 00-bug-report.md │ │ ├── 10-bug-report-zh.md │ │ ├── 20-enhancement-request.md │ │ └── 30-enhancement-request-zh.md │ └── workflows/ │ ├── check_urls.yml │ ├── cron.yml │ ├── main.yml │ ├── shellcheck.yml │ ├── test_set_1.yml │ └── test_set_2.yml ├── LICENSE.md ├── README-ja.md ├── README-ru.md ├── README-zh-Hant.md ├── README-zh.md ├── README.md ├── aws/ │ ├── README-zh.md │ ├── README.md │ └── cloudformation-template-ipsec.json ├── azure/ │ ├── README-zh.md │ ├── README.md │ ├── azuredeploy.json │ ├── azuredeploy.parameters.json │ └── install.sh ├── docs/ │ ├── advanced-usage-zh.md │ ├── advanced-usage.md │ ├── bbr-zh.md │ ├── bbr.md │ ├── clients-xauth-zh.md │ ├── clients-xauth.md │ ├── clients-zh.md │ ├── clients.md │ ├── ikev2-howto-zh.md │ ├── ikev2-howto.md │ ├── manage-users-zh.md │ ├── manage-users.md │ ├── uninstall-zh.md │ ├── uninstall.md │ ├── vpn-book-ja.md │ ├── vpn-book-zh-Hant.md │ ├── vpn-book-zh.md │ └── vpn-book.md ├── extras/ │ ├── add_vpn_user.sh │ ├── del_vpn_user.sh │ ├── ikev2changeaddr.sh │ ├── ikev2onlymode.sh │ ├── ikev2setup.sh │ ├── update_vpn_users.sh │ ├── vpnuninstall.sh │ ├── vpnupgrade.sh │ ├── vpnupgrade_alpine.sh │ ├── vpnupgrade_amzn.sh │ ├── vpnupgrade_centos.sh │ └── vpnupgrade_ubuntu.sh ├── vpnsetup.sh ├── vpnsetup_alpine.sh ├── vpnsetup_amzn.sh ├── vpnsetup_centos.sh └── vpnsetup_ubuntu.sh
Condensed preview — 59 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (751K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/00-bug-report.md",
"chars": 2148,
"preview": "---\nname: Bug report\nabout: Tell us about a problem you are experiencing\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Chec"
},
{
"path": ".github/ISSUE_TEMPLATE/10-bug-report-zh.md",
"chars": 1522,
"preview": "---\nname: 错误报告\nabout: 请使用这个模板来提交 bug\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**任务列表**\n\n- [ ] 我已阅读[自述文件](https://github."
},
{
"path": ".github/ISSUE_TEMPLATE/20-enhancement-request.md",
"chars": 1401,
"preview": "---\nname: Enhancement request\nabout: Suggest an improvement for this project\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**"
},
{
"path": ".github/ISSUE_TEMPLATE/30-enhancement-request-zh.md",
"chars": 912,
"preview": "---\nname: 改进建议\nabout: 请使用这个模板来提交改进建议\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**任务列表**\n\n- [ ] 我搜索了已有的 [Issues](https://g"
},
{
"path": ".github/workflows/check_urls.yml",
"chars": 5465,
"preview": "#\n# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>\n#\n# This work is licensed under the Creative Commons Attribut"
},
{
"path": ".github/workflows/cron.yml",
"chars": 653,
"preview": "#\n# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>\n#\n# This work is licensed under the Creative Commons Attribut"
},
{
"path": ".github/workflows/main.yml",
"chars": 833,
"preview": "#\n# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>\n#\n# This work is licensed under the Creative Commons Attribut"
},
{
"path": ".github/workflows/shellcheck.yml",
"chars": 1019,
"preview": "#\n# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>\n#\n# This work is licensed under the Creative Commons Attribut"
},
{
"path": ".github/workflows/test_set_1.yml",
"chars": 19864,
"preview": "#\n# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>\n#\n# This work is licensed under the Creative Commons Attribut"
},
{
"path": ".github/workflows/test_set_2.yml",
"chars": 17156,
"preview": "#\n# Copyright (C) 2020-2026 Lin Song <linsongui@gmail.com>\n#\n# This work is licensed under the Creative Commons Attribut"
},
{
"path": "LICENSE.md",
"chars": 20843,
"preview": "### Creative Commons Attribution-ShareAlike 3.0 Unported License\nLink to license summary: https://creativecommons.org/li"
},
{
"path": "README-ja.md",
"chars": 17161,
"preview": "[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)\n"
},
{
"path": "README-ru.md",
"chars": 24449,
"preview": "[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)\n"
},
{
"path": "README-zh-Hant.md",
"chars": 15764,
"preview": "[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)\n"
},
{
"path": "README-zh.md",
"chars": 15681,
"preview": "[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)\n"
},
{
"path": "README.md",
"chars": 22473,
"preview": "[English](README.md) | [简体中文](README-zh.md) | [繁體中文](README-zh-Hant.md) | [日本語](README-ja.md) | [Русский](README-ru.md)\n"
},
{
"path": "aws/README-zh.md",
"chars": 4490,
"preview": "[English](README.md) | [中文](README-zh.md)\n\n# 使用 CloudFormation 在 Amazon EC2 上部署\n\n使用这个模板,你可以在 Amazon Elastic Compute Clou"
},
{
"path": "aws/README.md",
"chars": 7372,
"preview": "[English](README.md) | [中文](README-zh.md)\n\n# Deploy to Amazon EC2 using CloudFormation\n\nThis template will create a full"
},
{
"path": "aws/cloudformation-template-ipsec.json",
"chars": 28821,
"preview": "{\n \"Metadata\": {\n \"README\": {\n \"Fn::Join\": [\n \"\\n\",\n [\n "
},
{
"path": "azure/README-zh.md",
"chars": 1453,
"preview": "[English](README.md) | [中文](README-zh.md)\n\n# 在 Microsoft Azure 上部署\n\n使用这个模板,你可以在 Microsoft Azure Cloud 上快速搭建一个 VPN 服务器([定"
},
{
"path": "azure/README.md",
"chars": 1865,
"preview": "[English](README.md) | [中文](README-zh.md)\n\n# Deploy to Microsoft Azure\n\nThis template will create a fully working VPN se"
},
{
"path": "azure/azuredeploy.json",
"chars": 8931,
"preview": "{\n \"$schema\": \"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\",\n \"contentVersion\": \"1"
},
{
"path": "azure/azuredeploy.parameters.json",
"chars": 321,
"preview": "{\n \"$schema\": \"https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#\",\n \"contentVersion\": "
},
{
"path": "azure/install.sh",
"chars": 203,
"preview": "#!/bin/sh\n\nexport VPN_IPSEC_PSK=\"$1\"\nexport VPN_USER=\"$2\"\nexport VPN_PASSWORD=\"$3\"\n\nwget -t 3 -T 30 -nv -O vpn.sh https:"
},
{
"path": "docs/advanced-usage-zh.md",
"chars": 18299,
"preview": "[English](advanced-usage.md) | [中文](advanced-usage-zh.md)\n\n# 高级用法\n\n* [使用其他的 DNS 服务器](#使用其他的-dns-服务器)\n* [域名和更改服务器 IP](#域名"
},
{
"path": "docs/advanced-usage.md",
"chars": 28602,
"preview": "[English](advanced-usage.md) | [中文](advanced-usage-zh.md)\n\n# Advanced Usage\n\n* [Use alternative DNS servers](#use-altern"
},
{
"path": "docs/bbr-zh.md",
"chars": 1671,
"preview": "[English](bbr.md) | [中文](bbr-zh.md)\n\n# 高级用法:部署 Google BBR 拥塞控制算法\n\nGoogle BBR是一种拥塞控制算法,它能够显著提升服务器吞吐率并降低延迟。\n\nGoogle BBR已经被"
},
{
"path": "docs/bbr.md",
"chars": 2538,
"preview": "[English](bbr.md) | [中文](bbr-zh.md)\n\n# Advanced usage: Deploy Google BBR congestion control algorithm\n\nGoogle BBR is a c"
},
{
"path": "docs/clients-xauth-zh.md",
"chars": 6198,
"preview": "[English](clients-xauth.md) | [中文](clients-xauth-zh.md)\n\n# 配置 IPsec/XAuth VPN 客户端\n\n在成功[搭建自己的 VPN 服务器](../README-zh.md)之后"
},
{
"path": "docs/clients-xauth.md",
"chars": 10743,
"preview": "[English](clients-xauth.md) | [中文](clients-xauth-zh.md)\n\n# Configure IPsec/XAuth VPN Clients\n\nAfter [setting up your own"
},
{
"path": "docs/clients-zh.md",
"chars": 20271,
"preview": "[English](clients.md) | [中文](clients-zh.md)\n\n# 配置 IPsec/L2TP VPN 客户端\n\n在成功[搭建自己的 VPN 服务器](../README-zh.md)之后,按照下面的步骤来配置你的"
},
{
"path": "docs/clients.md",
"chars": 33503,
"preview": "[English](clients.md) | [中文](clients-zh.md)\n\n# Configure IPsec/L2TP VPN Clients\n\nAfter [setting up your own VPN server]("
},
{
"path": "docs/ikev2-howto-zh.md",
"chars": 41159,
"preview": "[English](ikev2-howto.md) | [中文](ikev2-howto-zh.md)\n\n# IKEv2 VPN 配置和使用指南\n\n* [导言](#导言)\n* [配置 IKEv2 VPN 客户端](#配置-ikev2-vpn"
},
{
"path": "docs/ikev2-howto.md",
"chars": 67105,
"preview": "[English](ikev2-howto.md) | [中文](ikev2-howto-zh.md)\n\n# Guide: How to Set Up and Use IKEv2 VPN\n\n* [Introduction](#introdu"
},
{
"path": "docs/manage-users-zh.md",
"chars": 3875,
"preview": "[English](manage-users.md) | [中文](manage-users-zh.md)\n\n# 管理 VPN 用户\n\n在默认情况下,将只创建一个用于 VPN 登录的用户账户。如果你需要查看或管理 IPsec/L2TP 和 "
},
{
"path": "docs/manage-users.md",
"chars": 6096,
"preview": "[English](manage-users.md) | [中文](manage-users-zh.md)\n\n# Manage VPN Users\n\nBy default, a single user account for VPN log"
},
{
"path": "docs/uninstall-zh.md",
"chars": 3745,
"preview": "[English](uninstall.md) | [中文](uninstall-zh.md)\n\n# 卸载 VPN\n\n* [使用辅助脚本卸载 VPN](#使用辅助脚本卸载-vpn)\n* [手动卸载 VPN](#手动卸载-vpn)\n\n## 使"
},
{
"path": "docs/uninstall.md",
"chars": 4952,
"preview": "[English](uninstall.md) | [中文](uninstall-zh.md)\n\n# Uninstall the VPN\n\n* [Uninstall using helper script](#uninstall-using"
},
{
"path": "docs/vpn-book-ja.md",
"chars": 2024,
"preview": "[« トップページへ戻る](../README-ja.md) | [English](vpn-book.md) | [简体中文](vpn-book-zh.md) | [繁體中文](vpn-book-zh-Hant.md) | ["
},
{
"path": "docs/vpn-book-zh-Hant.md",
"chars": 2443,
"preview": "[« 返回首頁](../README-zh-Hant.md) | [English](vpn-book.md) | [简体中文](vpn-book-zh.md) | [繁體中文](vpn-book-zh-Hant.md) | ["
},
{
"path": "docs/vpn-book-zh.md",
"chars": 2431,
"preview": "[« 返回主页](../README-zh.md) | [English](vpn-book.md) | [简体中文](vpn-book-zh.md) | [繁體中文](vpn-book-zh-Hant.md) | [日本語]("
},
{
"path": "docs/vpn-book.md",
"chars": 2736,
"preview": "[« Back to home page](../README.md) | [English](vpn-book.md) | [简体中文](vpn-book-zh.md) | [繁體中文](vpn-book-zh-Hant.md"
},
{
"path": "extras/add_vpn_user.sh",
"chars": 3853,
"preview": "#!/bin/bash\n#\n# Script to add/update a VPN user for both IPsec/L2TP and Cisco IPsec\n#\n# Copyright (C) 2018-2024 Lin Song"
},
{
"path": "extras/del_vpn_user.sh",
"chars": 3455,
"preview": "#!/bin/bash\n#\n# Script to delete a VPN user for both IPsec/L2TP and Cisco IPsec\n#\n# Copyright (C) 2018-2024 Lin Song <li"
},
{
"path": "extras/ikev2changeaddr.sh",
"chars": 8123,
"preview": "#!/bin/bash\n#\n# Script to change IKEv2 VPN server address\n#\n# The latest version of this script is available at:\n# https"
},
{
"path": "extras/ikev2onlymode.sh",
"chars": 4455,
"preview": "#!/bin/bash\n#\n# Script to enable or disable IKEv2-only mode\n#\n# Copyright (C) 2022-2024 Lin Song <linsongui@gmail.com>\n#"
},
{
"path": "extras/ikev2setup.sh",
"chars": 51164,
"preview": "#!/bin/bash\n#\n# Script to set up and manage IKEv2 on Ubuntu, Debian, CentOS/RHEL, Rocky Linux,\n# AlmaLinux, Oracle Linux"
},
{
"path": "extras/update_vpn_users.sh",
"chars": 5236,
"preview": "#!/bin/bash\n#\n# Script to update VPN users for both IPsec/L2TP and Cisco IPsec\n#\n# Copyright (C) 2018-2024 Lin Song <lin"
},
{
"path": "extras/vpnuninstall.sh",
"chars": 12153,
"preview": "#!/bin/bash\n#\n# Script to uninstall IPsec VPN\n#\n# DO NOT RUN THIS SCRIPT ON YOUR PC OR MAC!\n#\n# The latest version of th"
},
{
"path": "extras/vpnupgrade.sh",
"chars": 5683,
"preview": "#!/bin/sh\n#\n# Script to update Libreswan on Ubuntu, Debian, CentOS/RHEL, Rocky Linux,\n# AlmaLinux, Oracle Linux, Amazon "
},
{
"path": "extras/vpnupgrade_alpine.sh",
"chars": 9356,
"preview": "#!/bin/bash\n#\n# Script to update Libreswan on Alpine Linux\n#\n# The latest version of this script is available at:\n# http"
},
{
"path": "extras/vpnupgrade_amzn.sh",
"chars": 9072,
"preview": "#!/bin/bash\n#\n# Script to update Libreswan on Amazon Linux 2\n#\n# The latest version of this script is available at:\n# ht"
},
{
"path": "extras/vpnupgrade_centos.sh",
"chars": 10629,
"preview": "#!/bin/bash\n#\n# Script to update Libreswan on CentOS/RHEL, Rocky Linux, AlmaLinux and Oracle Linux\n#\n# The latest versio"
},
{
"path": "extras/vpnupgrade_ubuntu.sh",
"chars": 10695,
"preview": "#!/bin/bash\n#\n# Script to update Libreswan on Ubuntu and Debian\n#\n# The latest version of this script is available at:\n#"
},
{
"path": "vpnsetup.sh",
"chars": 10135,
"preview": "#!/bin/sh\n#\n# Script for automatic setup of an IPsec VPN server on Ubuntu, Debian, CentOS/RHEL,\n# Rocky Linux, AlmaLinux"
},
{
"path": "vpnsetup_alpine.sh",
"chars": 20549,
"preview": "#!/bin/bash\n#\n# Script for automatic setup of an IPsec VPN server on Alpine Linux\n#\n# DO NOT RUN THIS SCRIPT ON YOUR PC "
},
{
"path": "vpnsetup_amzn.sh",
"chars": 21223,
"preview": "#!/bin/bash\n#\n# Script for automatic setup of an IPsec VPN server on Amazon Linux 2\n#\n# DO NOT RUN THIS SCRIPT ON YOUR P"
},
{
"path": "vpnsetup_centos.sh",
"chars": 26935,
"preview": "#!/bin/bash\n#\n# Script for automatic setup of an IPsec VPN server on CentOS/RHEL, Rocky Linux,\n# AlmaLinux and Oracle Li"
},
{
"path": "vpnsetup_ubuntu.sh",
"chars": 25802,
"preview": "#!/bin/bash\n#\n# Script for automatic setup of an IPsec VPN server on Ubuntu and Debian\n#\n# DO NOT RUN THIS SCRIPT ON YOU"
}
]
About this extraction
This page contains the full source code of the hwdsl2/setup-ipsec-vpn GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 59 files (700.9 KB), approximately 239.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.