# CentOS 7.9 上部署 IPsec 和 L2TP
- 虚拟机上配置两块网卡,一块连接外网,设为公网ip地址。一块为虚拟网卡,ip为子网段。
## 一、配置环境
### 1、首先安装epel
```shell
sudo yum install -y epel-release
```
### 2、然后安装必要软件
```shell
sudo yum install -y libreswan xl2tpd
```
## 二、配置服务
### 1、配置 IPsec
编辑 /etc/ipsec.conf 文件,并添加以下内容:
```
conn vpn
authby=secret
pfs=no
auto=add
keyingtries=3
dpddelay=30
dpdtimeout=120
dpdaction=clear
rekey=no
ikelifetime=8h
keylife=1h
type=transport
left=<服务器公网IP>
leftprotoport=17/1701
right=%any
rightprotoport=17/%any
```
将 <服务器公网IP> 替换为你的服务器的公网 IP 地址。
### 2、配置密钥
编辑 /etc/ipsec.secrets 文件,并添加以下内容:
```
<服务器公网IP> %any: PSK "<预共享密钥>"
```
将 <服务器公网IP> 替换为你的服务器的公网 IP 地址,<预共享密钥> 替换为你设置的预共享密钥。
### 3、配置 L2TP
编辑 /etc/xl2tpd/xl2tpd.conf 文件,并添加以下内容:
```
[global]
ipsec saref = yes
[lns default]
ip range = <分配给 L2TP 客户端的 IP 范围>
local ip = <服务器私网IP>
require chap = yes
refuse pap = yes
require authentication = yes
name = l2tpd
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
```
将 <分配给 L2TP 客户端的 IP 范围> 替换为你希望为 L2TP 客户端分配的 IP 地址范围,建议为第二块网卡的ip段
<服务器私网IP> 替换为你的服务器的私网 IP 地址,建议为第二块网的ip地址。
### 4、配置 L2TP 的用户账号和密码
编辑 /etc/ppp/chap-secrets 文件,并添加以下内容:
```
<L2TP用户名> * <L2TP密码> *
```
将 < L2TP用户名 > 替换为你想要创建的 L2TP 用户名,< L2TP密码 > 替换为相应的密码。
### 5、启用 IP 转发
编辑 /etc/sysctl.conf 文件,并添加以下内容:
```
net.ipv4.ip_forward = 1
```
运行以下命令使配置生效:
```shell
sudo sysctl -p
```
## 三、重启服务
### 1、重启相关服务
运行以下命令重启 IPsec 和 L2TP 服务:
```shell
sudo systemctl restart ipsec
sudo systemctl restart xl2tpd
```
### 2、防火墙
```shell
firewall-cmd --zone=public --permanent --add-port=1701/udp
firewall-cmd --zone=public --permanent --add-service=ipsec
firewall-cmd --zone=public --permanent --add-masquerade
firewall-cmd --reload
```