Despliegue strongSwan en un dispositivo Linux local para establecer una conexión IPsec-VPN de doble túnel con Alibaba Cloud VPN Gateway. Esto le permitirá lograr una comunicación de sitio a sitio de alta disponibilidad.
Escenario de ejemplo
A continuación se muestra un despliegue típico. Un dispositivo strongSwan en su red local establece una conexión IPsec-VPN de doble túnel con Alibaba Cloud. De este modo, se habilita la comunicación entre la VPC y su centro de datos.
Planificación de direcciones IP
Lado del centro de datos local
Bloque CIDR privado: 172.16.0.0/16
-
Dispositivo strongSwan
Tarjeta de interfaz de red eth0: 172.16.20.80, salida pública 1 asignada por NAT: 120.XX.XX.202
-
(opcional) Tarjeta de interfaz de red eth1: 172.16.21.248, salida pública 2 asignada por NAT: 47.XX.XX.127
NotaPara un escenario sin NAT, consulte "How do I configure strongSwan when the network interface has a public IP address (non-NAT)?".
Su dispositivo puede establecer una conexión IPsec-VPN en modo de doble túnel con Alibaba Cloud, ya sea que cuente con una salida de red pública (salida única) o dos salidas de red públicas (salida doble). Este tema incluye ejemplos para ambos casos.
Lado de Alibaba Cloud
-
Bloque CIDR de la VPC: 192.168.0.0/16
Bloque CIDR de vSwitch 1: 192.168.10.0/24
Bloque CIDR de vSwitch 2: 192.168.20.0/24
Bloque CIDR de vSwitch 3: 192.168.40.0/24
Bloque CIDR de vSwitch 4: 192.168.50.0/24
Bloque CIDR de vSwitch 5: 192.168.55.0/24
-
VPN Gateway
Dirección IPsec 1: 47.XX.XX.151
-
Dirección IPsec 2: 47.XX.XX.87
NotaUna vez que usted crea una instancia de VPN gateway, el sistema asigna automáticamente dos direcciones IPsec a dicha instancia.
Dirección IP de BGP
Este tema abarca tanto el enrutamiento estático como el enrutamiento dinámico mediante Border Gateway Protocol (BGP). Si no planea usar BGP, omita esta sección. A continuación se detalla la planificación de bloques CIDR de BGP utilizada en este tema.
Recurso | Túnel | Bloque CIDR del túnel BGP | Dirección IP de BGP | Número AS de BGP |
VPN Gateway | Tunnel 1 | 169.254.10.0/30 Nota En una misma instancia de VPN gateway, el bloque CIDR de cada túnel debe ser único. | 169.254.10.1 | 65535 |
Tunnel 2 | 169.254.20.0/30 | 169.254.20.1 | ||
Dispositivo strongSwan | Tunnel 1 | 169.254.10.0/30 | 169.254.10.2 | 65530 |
Tunnel 2 | 169.254.20.0/30 | 169.254.20.2 |
Plan de configuración de parámetros de VPN
En este ejemplo, ambos túneles utilizan los mismos valores de parámetros. Para cada túnel, las configuraciones de IKE e IPsec en el dispositivo strongSwan deben coincidir con las del lado de Alibaba Cloud.
Clave precompartida: ChangeMe***
-
Configuración de IKE
Versión de IKE: ikev2
Modo de negociación: main
Algoritmo de cifrado: aes
Algoritmo de autenticación: sha1
Grupo DH: group2
Tiempo de vida de SA (segundos): 86400
-
Configuración de IPsec:
Algoritmo de cifrado: aes
Algoritmo de autenticación: sha1
Grupo DH: group2
Tiempo de vida de SA (segundos): 86400
Preparativos en el lado de Alibaba Cloud
Complete la configuración de Alibaba Cloud según la cantidad de salidas públicas y el método de enrutamiento que utilice. Seleccione la pestaña que corresponda a su escenario.
Salida doble - enrutamiento dinámico BGP
Para obtener más información, consulte Dual-tunnel mode with BGP. Complete los pasos Create a VPN gateway, Create customer gateways, Create an IPsec-VPN connection y Enable BGP dynamic routing.
Dado que el dispositivo strongSwan tiene dos direcciones IP de salida pública, cree dos customer gateways.
Cuando cree la conexión IPsec-VPN, asocie Tunnel 1 con la salida pública 1 y Tunnel 2 con la salida pública 2. Este ejemplo utiliza Destination Routing Mode.
Salida doble - enrutamiento estático
Para obtener más información, consulte Standard VPN Gateway quick start. Complete los pasos Create a VPN gateway, Create a customer gateway, Create an IPsec connection y Configure VPN Gateway routes.
Dado que el dispositivo strongSwan tiene dos direcciones IP de salida pública, cree dos customer gateways.
Cuando cree la conexión IPsec-VPN, asocie Tunnel 1 con la salida pública 1 y Tunnel 2 con la salida pública 2. Este ejemplo utiliza Destination Routing Mode.
Salida única - enrutamiento dinámico BGP
Para obtener más información, consulte Dual-tunnel mode with BGP. Complete los pasos Create a VPN gateway, Create customer gateways, Create an IPsec-VPN connection y Enable BGP dynamic routing.
El dispositivo strongSwan cuenta con una sola dirección IP de salida pública. Cree un customer gateway.
Cuando cree la conexión IPsec-VPN, asocie ambos túneles al mismo customer gateway. Este ejemplo utiliza Destination Routing Mode.
Salida única - enrutamiento estático
Para obtener más información, consulte Standard VPN Gateway quick start. Complete los pasos Create a VPN gateway, Create a customer gateway, Create an IPsec connection y Configure VPN Gateway routes. Tome en cuenta los siguientes puntos:
El dispositivo strongSwan cuenta con una sola dirección IP de salida pública. Cree un customer gateway.
-
Cuando cree la conexión IPsec-VPN, seleccione el modo Protected Data Flows y asocie ambos túneles al mismo customer gateway. Configure los siguientes parámetros:
Establezca Local Network en el bloque CIDR de la VPC del lado de Alibaba Cloud, es decir, 192.168.0.0/16.
Establezca Remote Network en el bloque CIDR privado del centro de datos local, es decir, 172.16.0.0/16.
Para los escenarios donde la conexión IPsec-VPN se asocia con un transit router, se recomienda utilizar el protocolo de enrutamiento dinámico BGP. No se recomienda este método.
Comience a configurar el dispositivo strongSwan
A continuación se muestra un ejemplo con un dispositivo strongSwan que ejecuta el sistema operativo "CentOS Stream 9 64-bit". Para otros sistemas operativos, consulte la documentación oficial de strongSwan.
1. Configure la política del firewall para permitir el tráfico
Permita el protocolo ESP (protocolo IP 50), el puerto UDP 500 y el puerto UDP 4500 en el dispositivo strongSwan.
iptables -I INPUT -p 50 -j ACCEPT
iptables -I INPUT -p udp --dport 500 -j ACCEPT
iptables -I INPUT -p udp --dport 4500 -j ACCEPT
2. Habilite el reenvío de tráfico
echo 1 > /proc/sys/net/ipv4/ip_forward
Habilite el reenvío de IP para que el dispositivo strongSwan enrute el tráfico entre la red local y la VPC. El siguiente comando surte efecto de inmediato y se mantiene tras los reinicios.
3. Instale el software strongSwan
dnf install epel-release -y
dnf install strongswan -y
4. Configure los túneles duales
Salida dual: enrutamiento estático y enrutamiento dinámico BGP
La salida dual requiere interfaces de red virtuales XFRM. Antes de continuar, compruebe lo siguiente: strongSwan 5.8.0 o posterior, kernel de Linux 4.19 o posterior, iproute2 5.1.0 o posterior y compatibilidad con el módulo XFRM (ejecute lsmod | grep xfrm para comprobarlo). Para obtener más información, consulte Interfaces XFRM en Linux.
-
Agregue rutas para que el tráfico hacia la dirección IPsec 1 pase por eth0 y el tráfico hacia la dirección IPsec 2 pase por eth1.
ip route add 47.XX.XX.151 via 172.16.20.253 dev eth0 # 172.16.20.253 is the private gateway address of eth0. ip route add 47.XX.XX.87 via 172.16.21.253 dev eth1 # 172.16.21.253 is the private gateway address of eth1.Compruebe la conectividad con ambas direcciones IPsec.
ping 47.XX.XX.151 ping 47.XX.XX.87 -
Cree dos interfaces de red virtuales para establecer los túneles IPsec-VPN.
ip link add ipsec0 type xfrm dev eth0 if_id 42 # Create an XFRM virtual network interface for Tunnel 1. The interface ID is 42 and the underlying interface is the public interface eth0. ip link add ipsec1 type xfrm dev eth1 if_id 43 # Create an XFRM virtual network interface for Tunnel 2. The interface ID is 43 and the underlying interface is the public interface eth1. ip link set ipsec0 up # Start the XFRM virtual network interface for Tunnel 1. ip link set ipsec1 up # Start the XFRM virtual network interface for Tunnel 2.ImportanteLa configuración para crear una interfaz de red virtual es temporal. Después de reiniciar el dispositivo strongSwan, debe agregarla de nuevo y ejecutar el comando
sudo systemctl restart strongswan;swanctl --load-all(este comando requiere permisos de root). Consulte el contenido a continuación para agregar un script de inicio al dispositivo strongSwan. De este modo, la interfaz de red virtual se vuelve a agregar automáticamente después de cada reinicio. -
Modifique el archivo de configuración de strongSwan.
-
Respalde el archivo de configuración original de strongSwan.
mv /etc/strongswan/swanctl/swanctl.conf /etc/strongswan/swanctl/swanctl.conf.bak -
Cree un nuevo archivo de configuración de strongSwan.
vi /etc/strongswan/swanctl/swanctl.conf -
Agregue la siguiente configuración. Cada valor de parámetro debe coincidir con la configuración del túnel correspondiente en Alibaba Cloud.
ImportantePara el enrutamiento estático, quite el comentario de las líneas
updown = /root/connect_1.shyupdown = /root/connect_2.shen la configuración.connections { vco1 { # Add the VPN configuration for IPsec-VPN Tunnel 1. version = 2 # Specify the IKE version. It must be the same as the IKE version of Tunnel 1 on the Alibaba Cloud side. 2 indicates IKEv2. local_addrs = 172.16.20.80 # The IP address of the first on-premises network interface card. remote_addrs = 47.XX.XX.151 # Specify the peer IP address of Tunnel 1 as the gateway IP address of Tunnel 1 on the Alibaba Cloud side, which is IPsec address 1. dpd_delay = 10 rekey_time = 84600 # Specify the SA lifetime for Tunnel 1. It must be the same as the SA lifetime in the IKE configurations of Tunnel 1 on the Alibaba Cloud side. over_time = 1800 proposals = aes128-sha1-modp1024 # Specify the encryption algorithm, authentication algorithm, and DH group for Tunnel 1. They must be the same as those in the IKE configurations of Tunnel 1 on the Alibaba Cloud side. group2 corresponds to modp1024. encap = yes local { auth = psk # Set the authentication method for the on-premises side to PSK, which is the pre-shared key method. id = 120.XX.XX.202 # The first on-premises public egress IP address. It must be the same as the RemoteId of Tunnel 1 on the Alibaba Cloud side. } remote { auth = psk # Set the authentication method for the peer to PSK. This means Alibaba Cloud uses the pre-shared key method. id = 47.XX.XX.151 # IPsec address 1 on the Alibaba Cloud side. It must be the same as the LocalId of Tunnel 1 on the Alibaba Cloud side. } children { vco_child1 { local_ts = 0.0.0.0/0 # The policy-based traffic selector for the destination-based routing mode on Alibaba Cloud is 0.0.0.0/0. remote_ts = 0.0.0.0/0 # The policy-based traffic selector for the destination-based routing mode on Alibaba Cloud is 0.0.0.0/0. mode = tunnel rekey_time = 85500 life_time = 86400 # Specify the SA lifetime for Tunnel 1. It must be the same as the SA lifetime in the IPsec configurations of Tunnel 1 on the Alibaba Cloud side. dpd_action = restart start_action = start close_action = start esp_proposals = aes128-sha1-modp1024 # Specify the encryption algorithm, authentication algorithm, and DH group for Tunnel 1. They must be the same as those in the IPsec configurations of Tunnel 1 on the Alibaba Cloud side. group2 corresponds to modp1024. if_id_out = 42 # Specify the egress and ingress interfaces for Tunnel 1 as the XFRM virtual network interface of Tunnel 1. if_id_in = 42 #updown = /root/connect_1.sh # Execute the /root/connect_1.sh script to configure routes based on the UP and DOWN status of Tunnel 1. This parameter is required only when you use static routing. } } } vco2 { # Add the VPN configuration for IPsec-VPN Tunnel 2. version = 2 # Specify the IKE version. It must be the same as the IKE version of Tunnel 2 on the Alibaba Cloud side. 2 indicates IKEv2. local_addrs = 172.16.21.248 # The IP address of the second on-premises network interface card. remote_addrs = 47.XX.XX.87 # IPsec address 2 on the Alibaba Cloud side. dpd_delay = 10 rekey_time = 84600 # SA lifetime. Must match Tunnel 2 IKE configurations. over_time = 1800 # proposals = aes128-sha1-modp1024 # group2 = modp1024. Must match Tunnel 2 IKE configurations. encap = yes local { auth = psk # Pre-shared key authentication. id = 47.XX.XX.127 # Second on-premises public egress IP. Must match RemoteId of Tunnel 2. } remote { auth = psk # Set the authentication method for the peer to PSK. This means Alibaba Cloud uses the pre-shared key method. id = 47.XX.XX.87 # IPsec address 2 on the Alibaba Cloud side. It must be the same as the LocalId of Tunnel 2 on the Alibaba Cloud side. } children { vco_child2 { local_ts = 0.0.0.0/0 # The policy-based traffic selector for the destination-based routing mode on Alibaba Cloud is 0.0.0.0/0. remote_ts = 0.0.0.0/0 # The policy-based traffic selector for the destination-based routing mode on Alibaba Cloud is 0.0.0.0/0. mode = tunnel rekey_time = 85500 life_time = 86400 # Specify the SA lifetime for Tunnel 2. It must be the same as the SA lifetime in the IPsec configurations of Tunnel 2 on the Alibaba Cloud side. dpd_action = restart start_action = start close_action = start esp_proposals = aes128-sha1-modp1024 # Specify the encryption algorithm, authentication algorithm, and DH group for Tunnel 2. They must be the same as those in the IPsec configurations of Tunnel 2 on the Alibaba Cloud side. group2 corresponds to modp1024. if_id_out = 43 # Specify the egress and ingress interfaces for Tunnel 2 as the XFRM virtual network interface of Tunnel 2. if_id_in = 43 #updown = /root/connect_2.sh # Execute the /root/connect_2.sh script to configure routes based on the UP and DOWN status of Tunnel 2. This parameter is required only when you use static routing. } } } } secrets { ike-vco1 { id = 47.XX.XX.151 # The public IP address of Tunnel 1 of the VPN gateway on the Alibaba Cloud side. secret = ChangeMe*** # Specify the pre-shared key for Tunnel 1. The key must be the same as the pre-shared key of Tunnel 1 on the Alibaba Cloud side. } ike-vco2 { id = 47.XX.XX.87 # The public IP address of Tunnel 2 of the VPN gateway on the Alibaba Cloud side. secret = ChangeMe*** # Specify the pre-shared key for Tunnel 2. The key must be the same as the pre-shared key of Tunnel 2 on the Alibaba Cloud side. } }
-
-
Reinicie el proceso de strongSwan, vuelva a cargar su configuración y compruebe el estado del túnel.
sudo systemctl restart strongswan swanctl --load-all watch swanctl --list-sasComo se muestra a continuación, si el estado de
vco1yvco2esESTABLISHED, la conexión IPsec-VPN entre el dispositivo strongSwan y la VPN gateway se estableció correctamente. Sin embargo, las redes aún no pueden comunicarse con normalidad, por lo que debe configurar las rutas.plugin 'sqlite': failed to load - sqlite_plugin_create not found and no plugin file available vco2: #4, ESTABLISHED, IKEv2, 2d3fbef28a433cfd_i 3f1960ea7d80a293_r* local '47.___.127' @ ___[4500] remote '47.__ __87' @ ___ AES_CBC-128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024 established 3424s ago, rekeying in 79868s vco_child2: #4, reqid 2, INSTALLED, TUNNEL-in-UDP, ESP:AES_CBC-128/HMAC_SHA1_96 installed 3424s ago, rekeying in 81353s, expires in 82976s in c7f56760 (-|0x0000002b), 16396 bytes, 245 packets, 47s ago out 2b09776f (-|0x0000002b), 9621 bytes, 149 packets, 47s ago local 0.0.0.0/0 remote 0.0.0.0/0 vco1: #1, ESTABLISHED, IKEv2, 96ccc381f9e7693e_i* d1a7dec1832e5cb6_r local '120.___.202' @ ___ remote '47.__ ___.151' @ ___ AES_CBC-128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024 established 3447s ago, rekeying in 79436s vco_child1: #1, reqid 1, INSTALLED, TUNNEL-in-UDP, ESP:AES_CBC-128/HMAC_SHA1_96 installed 3447s ago, rekeying in 81457s, expires in 82953s in c8f4286f (-|0x0000002a), 16127 bytes, 239 packets, 43s ago out f5bccc3d (-|0x0000002a), 9828 bytes, 152 packets, 43s ago local 0.0.0.0/0 -
Configure las rutas.
Consulte la sección correspondiente al método de enrutamiento que planea utilizar.
Enrutamiento dinámico BGP
NotaDespués de reiniciar el dispositivo strongSwan, debe agregar nuevamente la configuración de BGP.
-
Configure las direcciones IP de BGP en las interfaces XFRM.
ip address add 169.254.10.2/30 dev ipsec0 ip address add 169.254.20.2/30 dev ipsec1 -
Instale FRR (Free Range Routing) para admitir BGP.
yum install -y frr -
Ejecute el comando
vi /etc/frr/daemonspara editar el archivo de configuración y habilitar el enrutamiento dinámico BGP.Presione la tecla
ipara entrar al modo de edición. Cambie el valor del parámetro bgpd ayespara habilitar el enrutamiento dinámico BGP. Presione la teclaEscpara salir del modo de edición e introduzca:wqpara guardar la configuración. -
Habilite e inicie FRR.
systemctl enable frr systemctl restart frr -
Agregue la configuración de BGP. Reemplace las direcciones IP y los números de AS con sus valores reales.
-
Acceda a la interfaz de configuración de FRR.
vtysh -
Entre al modo de configuración.
config terminal -
Agregue la configuración de BGP con los siguientes comandos.
Reemplace los siguientes valores con sus direcciones reales:
Replace "169.254.10.1" and "169.254.20.1" with the actual BGP IP addresses of the tunnels on the Alibaba Cloud side.
Replace "65535" with the actual BGP AS number of the VPN Gateway.
Replace "172.16.20.0/24" and "172.16.21.0/24" with the actual CIDR blocks of your on-premises data center.
route-map allow-all permit 1 exit router bgp 65530 bgp router-id 169.254.10.2 neighbor 169.254.10.1 remote-as 65535 neighbor 169.254.10.1 timers 10 30 neighbor 169.254.20.1 remote-as 65535 neighbor 169.254.20.1 timers 10 30 address-family ipv4 unicast network 172.16.20.0/24 network 172.16.21.0/24 neighbor 169.254.10.1 soft-reconfiguration inbound neighbor 169.254.10.1 route-map allow-all in neighbor 169.254.10.1 route-map allow-all out neighbor 169.254.20.1 soft-reconfiguration inbound neighbor 169.254.20.1 route-map allow-all in neighbor 169.254.20.1 route-map allow-all out maximum-paths 32 exit-address-family exit
-
-
Run
exitto leave configuration mode, then runshow ip bgpto view the BGP routes.You can see that the strongSwan device has successfully learned the routes of the VPC on the cloud, and the on-premises data center and the VPC on the cloud can communicate normally.
Network Next Hop Metric LocPrf Weight Path *> 172.16.20.0/24 0.0.0.0 0 32768 i *> 172.16.21.0/24 0.0.0.0 0 32768 i * 192.168.10.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.20.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.40.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.50.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.55.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i
Enrutamiento estático
Cree dos scripts que strongSwan llamará para configurar las rutas y controlar el flujo de tráfico.
-
Cree y edite el script /root/connect_1.sh.
vi /root/connect_1.sh -
Agregue y guarde a continuación el contenido correspondiente.
#!/usr/bin/env bash if [ x"$PLUTO_VERB" == "xup-client" ]; then echo "ip route add 192.168.0.0/16 dev ipsec0" >> /root/vpn_route.log;ip route add 192.168.0.0/16 dev ipsec0 metric 100 elif [ x"$PLUTO_VERB" == "xdown-client" ]; then echo "ip route del 192.168.0.0/16 dev ipsec0" >> /root/vpn_route.log;ip route del 192.168.0.0/16 dev ipsec0 metric 100 fiEste script agrega una ruta para el tráfico que va del centro de datos local hacia la VPC de Alibaba Cloud (192.168.0.0/16). El tráfico pasa por la interfaz de red virtual XFRM del Túnel 1 cuando este se encuentra activo. La métrica de esta ruta se establece en 100, lo que le otorga mayor prioridad que la ruta del Túnel 2. Si el Túnel 1 se cae, el script elimina la ruta.
-
Cree y edite el script /root/connect_2.sh.
vi /root/connect_2.sh -
Agregue y guarde a continuación el contenido correspondiente.
#!/usr/bin/env bash if [ x"$PLUTO_VERB" == "xup-client" ]; then echo "ip route add 192.168.0.0/16 dev ipsec1" >> /root/vpn_route.log;ip route add 192.168.0.0/16 dev ipsec1 metric 101 elif [ x"$PLUTO_VERB" == "xdown-client" ]; then echo "ip route del 192.168.0.0/16 dev ipsec1" >> /root/vpn_route.log;ip route del 192.168.0.0/16 dev ipsec1 metric 101 fiEste script agrega una ruta para el tráfico que va del centro de datos local hacia la VPC de Alibaba Cloud (192.168.0.0/16). El tráfico pasa por la interfaz de red virtual XFRM del Túnel 2 cuando este se encuentra activo. La métrica de esta ruta se establece en 101, lo que le otorga menor prioridad que la ruta del Túnel 1. Si el Túnel 2 se cae, el script elimina la ruta.
-
Otorgue permisos de ejecución a ambos scripts.
sudo chmod +x /root/connect_1.sh sudo chmod +x /root/connect_2.sh -
Reinicie el proceso de strongSwan.
sudo systemctl restart strongswan -
Compruebe las rutas.
route -n
-
Salida única: enrutamiento dinámico BGP
El enrutamiento dinámico BGP requiere interfaces de red virtuales XFRM. Compruebe que cuenta con los siguientes elementos: strongSwan 5.8.0 o posterior, kernel de Linux 4.19 o posterior, iproute2 5.1.0 o posterior y compatibilidad con el módulo XFRM (ejecute lsmod | grep xfrm para verificarlo). Para obtener más información, consulte Interfaces XFRM en Linux.
-
Cree dos interfaces de red virtuales para establecer los túneles IPsec-VPN.
ip link add ipsec0 type xfrm dev eth0 if_id 42 # Create an XFRM virtual network interface for Tunnel 1. The interface ID is 42 and the underlying interface is the public interface eth0. ip link add ipsec1 type xfrm dev eth0 if_id 43 # Create an XFRM virtual network interface for Tunnel 2. The interface ID is 43 and the underlying interface is the public interface eth0. ip link set ipsec0 up # Start the XFRM virtual network interface for Tunnel 1. ip link set ipsec1 up # Start the XFRM virtual network interface for Tunnel 2.ImportanteLa configuración para crear una interfaz de red virtual es temporal. Después de reiniciar el dispositivo strongSwan, debe agregarla de nuevo y ejecutar el comando
sudo systemctl restart strongswan;swanctl --load-all(este comando requiere permisos de root). Consulte el siguiente contenido para agregar un script de inicio al dispositivo strongSwan. De esta manera, la interfaz de red virtual se agregará automáticamente después de cada reinicio. -
Modifique el archivo de configuración de strongSwan.
-
Respalde el archivo de configuración original de strongSwan.
mv /etc/strongswan/swanctl/swanctl.conf /etc/strongswan/swanctl/swanctl.conf.bak -
Cree un nuevo archivo de configuración de strongSwan.
vi /etc/strongswan/swanctl/swanctl.conf -
La siguiente configuración es similar al ejemplo de salida doble. Solo se comentan las diferencias. Agregue y guarde esta configuración.
connections { vco1 { version = 2 local_addrs = 172.16.20.80 # Both tunnels use the same eth0 interface (single egress). remote_addrs = 47.XX.XX.151 dpd_delay = 10 rekey_time = 84600 over_time = 1800 proposals = aes128-sha1-modp1024 encap = yes local { auth = psk id = 120.XX.XX.202 } remote { auth = psk id = 47.XX.XX.151 } children { vco_child1 { local_ts = 0.0.0.0/0 remote_ts = 0.0.0.0/0 mode = tunnel rekey_time = 85500 life_time = 86400 dpd_action = restart start_action = start close_action = start esp_proposals = aes128-sha1-modp1024 if_id_out = 42 if_id_in = 42 } } } vco2 { version = 2 local_addrs = 172.16.20.80 # Same as vco1 (single egress). remote_addrs = 47.XX.XX.87 dpd_delay = 10 rekey_time = 84600 over_time = 1800 # proposals = aes128-sha1-modp1024 encap = yes local { auth = psk id = 120.XX.XX.202 # Same public egress IP as vco1 (single egress). } remote { auth = psk id = 47.XX.XX.87 } children { vco_child2 { local_ts = 0.0.0.0/0 remote_ts = 0.0.0.0/0 mode = tunnel rekey_time = 85500 life_time = 86400 dpd_action = restart start_action = start close_action = start esp_proposals = aes128-sha1-modp1024 if_id_out = 43 if_id_in = 43 } } } } secrets { ike-vco1 { secret = ChangeMe*** } } ike-vco2 { secret = ChangeMe*** } } }
-
-
Reinicie el proceso de strongSwan, vuelva a cargar su configuración y compruebe el estado del túnel.
sudo systemctl restart strongswan swanctl --load-all watch swanctl --list-sasComo se muestra en el siguiente resultado, si el estado de
vco1yvco2esESTABLISHED, la conexión IPsec-VPN entre el dispositivo strongSwan y el VPN gateway se estableció correctamente. Sin embargo, las redes aún no pueden comunicarse con normalidad, por lo que debe configurar las rutas.plugin 'sqlite': failed to load - sqlite_plugin_create not found and no plugin file available vco2: #5, ESTABLISHED, IKEv2, e9cf2986f8fdcb37_i 6be3688815c6a80f_r* local '120.___.202' @ 172.___[4500] remote '47.___.87' @ 47.___[4500] AES_CBC-128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024 established 1096s ago, rekeying in 82251s vco_child2: #5, reqid 1, INSTALLED, TUNNEL-in-UDP, ESP:AES_CBC-128/HMAC_SHA1_96 installed 1096s ago, rekeying in 83517s, expires in 85304s in cbc4e224, 0 bytes, 0 packets out 064a42f5, 0 bytes, 0 packets local 172.16.0.0/16 remote 192.168.0.0/16 vco1: #1, ESTABLISHED, IKEv2, 387cbee015ffc74b_i* 70f63f78844ef7de_r local '120.___.202' @ 172.___ remote '47.___.151' @ 47.___[4500] AES_CBC-128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024 established 1128s ago, rekeying in 82830s vco_child1: #1, reqid 1, INSTALLED, TUNNEL-in-UDP, ESP:AES_CBC-128/HMAC_SHA1_96 installed 1128s ago, rekeying in 83970s, expires in 85272s in cd130507, 0 bytes, 0 packets out 6436d869, 0 bytes, 0 packets local 172.16.0.0/16 remote 192.168.0.0/16 -
Configure el enrutamiento dinámico BGP.
NotaDespués de reiniciar el dispositivo strongSwan, debe agregar de nuevo la configuración de BGP.
-
Configure las direcciones IP BGP en las interfaces XFRM.
ip address add 169.254.10.2/30 dev ipsec0 ip address add 169.254.20.2/30 dev ipsec1 -
Instale FRR (Free Range Routing) para admitir BGP.
yum install -y frr -
Ejecute el comando
vi /etc/frr/daemonspara editar el archivo de configuración y habilitar el enrutamiento dinámico BGP.Presione la tecla
ipara entrar al modo de edición. Cambie el valor del parámetro bgpd ayespara habilitar el enrutamiento dinámico BGP. Presione la teclaEscpara salir del modo de edición y luego introduzca:wqpara guardar la configuración. -
Habilite e inicie FRR.
systemctl enable frr systemctl restart frr -
Agregue la configuración de BGP. Reemplace las direcciones IP y los números de AS por sus valores reales.
-
Acceda a la interfaz de configuración de FRR.
vtysh -
Entre al modo de configuración.
config terminal -
Agregue la configuración de BGP con los siguientes comandos.
Reemplace los siguientes valores por sus direcciones reales:
Replace "169.254.10.1" and "169.254.20.1" with the actual BGP IP addresses of the tunnels on the Alibaba Cloud side.
Replace "65535" with the actual BGP AS number of the VPN Gateway.
Replace "172.16.20.0/24" and "172.16.21.0/24" with the actual CIDR blocks of your on-premises data center.
route-map allow-all permit 1 exit router bgp 65530 bgp router-id 169.254.10.2 neighbor 169.254.10.1 remote-as 65535 neighbor 169.254.10.1 timers 10 30 neighbor 169.254.20.1 remote-as 65535 neighbor 169.254.20.1 timers 10 30 address-family ipv4 unicast network 172.16.20.0/24 network 172.16.21.0/24 neighbor 169.254.10.1 soft-reconfiguration inbound neighbor 169.254.10.1 route-map allow-all in neighbor 169.254.10.1 route-map allow-all out neighbor 169.254.20.1 soft-reconfiguration inbound neighbor 169.254.20.1 route-map allow-all in neighbor 169.254.20.1 route-map allow-all out maximum-paths 32 exit-address-family exit
-
-
Run
exitto leave configuration mode, then runshow ip bgpto view the BGP routes.You can see that the strongSwan device has successfully learned the routes of the VPC on the cloud, and the on-premises data center and the VPC on the cloud can communicate normally.
Network Next Hop Metric LocPrf Weight Path *> 172.16.20.0/24 0.0.0.0 0 32768 i *> 172.16.21.0/24 0.0.0.0 0 32768 i * 192.168.10.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.20.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.40.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.50.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i * 192.168.55.0/24 169.254.20.1 200 0 65535 i *> 169.254.10.1 100 0 65535 i
-
Salida única - enrutamiento estático
En el modo de enrutamiento estático con salida única, Alibaba Cloud puede cambiar proactivamente el tráfico al túnel de respaldo si detecta una amenaza en el túnel activo. Supervise el contador XfrmInTmplMismatch en /proc/net/xfrm_stat. Si este valor aumenta de forma continua, significa que el tráfico ya cambió de ruta. Ajuste el parámetro priority del túnel de respaldo en /etc/strongswan/swanctl/swanctl.conf para enrutar el tráfico local a través del túnel de respaldo.
-
Respalde el archivo de configuración original de strongSwan.
mv /etc/strongswan/swanctl/swanctl.conf /etc/strongswan/swanctl/swanctl.conf.bak -
Cree un nuevo archivo de configuración de strongSwan.
vi /etc/strongswan/swanctl/swanctl.conf -
Con base en el plan descrito en Example scenario, agregue y guarde la siguiente configuración.
connections { vco1 { version = 2 local_addrs = 172.16.20.80 remote_addrs = 47.XX.XX.151 dpd_delay = 10 rekey_time = 84600 over_time = 1800 proposals = aes128-sha1-modp1024 encap = yes local { auth = psk id = 120.XX.XX.202 } remote { auth = psk id = 47.XX.XX.151 } children { vco_child1 { local_ts = 172.16.0.0/16 # Policy-based: on-premises private CIDR block. remote_ts = 192.168.0.0/16 # Policy-based: VPC CIDR block. mode = tunnel rekey_time = 85500 life_time = 86400 dpd_action = restart start_action = start close_action = start esp_proposals = aes128-sha1-modp1024 priority = 1 # Active tunnel (higher priority). } } } vco2 { version = 2 local_addrs = 172.16.20.80 remote_addrs = 47.XX.XX.87 dpd_delay = 10 rekey_time = 84600 over_time = 1800 proposals = aes128-sha1-modp1024 encap = yes local { auth = psk id = 120.XX.XX.202 } remote { auth = psk id = 47.XX.XX.87 } children { vco_child2 { local_ts = 172.16.0.0/16 # Policy-based: on-premises private CIDR block. remote_ts = 192.168.0.0/16 # Policy-based: VPC CIDR block. mode = tunnel rekey_time = 85500 life_time = 86400 dpd_action = restart start_action = start close_action = start esp_proposals = aes128-sha1-modp1024 priority = 2 # Standby tunnel (lower priority). } } } } secrets { ike-vco1 { id = 47.XX.XX.151 secret = ChangeMe*** } ike-vco2 { id = 47.XX.XX.87 secret = ChangeMe*** } } -
Reinicie el proceso de strongSwan, vuelva a cargar su configuración y compruebe el estado del túnel.
sudo systemctl restart strongswan swanctl --load-all watch swanctl --list-sasComo se muestra a continuación, si el estado de
vco1yvco2esESTABLISHED, la conexión IPsec-VPN entre el dispositivo strongSwan y el VPN gateway se estableció correctamente. En este punto, el centro de datos local y la VPC ya pueden comunicarse entre sí.plugin 'sqlite': failed to load - sqlite_plugin_create not found and no plugin file available vco2: #5, ESTABLISHED, IKEv2, e9cf2986f8fdcb37_i 6be3688815c6a80f_r* local '120.___.202' @ 172.___[4500] remote '47.___.87' @ 47.___[4500] AES_CBC-128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024 established 1096s ago, rekeying in 82251s vco_child2: #5, reqid 1, INSTALLED, TUNNEL-in-UDP, ESP:AES_CBC-128/HMAC_SHA1_96 installed 1096s ago, rekeying in 83517s, expires in 85304s in cbc4e224, 0 bytes, 0 packets out 064a42f5, 0 bytes, 0 packets local 172.16.0.0/16 remote 192.168.0.0/16 vco1: #1, ESTABLISHED, IKEv2, 387cbee015ffc74b_i* 70f63f78844ef7de_r local '120.___.202' @ 172.___ remote '47.___.151' @ 47.___[4500] AES_CBC-128/HMAC_SHA1_96/PRF_HMAC_SHA1/MODP_1024 established 1128s ago, rekeying in 82830s vco_child1: #1, reqid 1, INSTALLED, TUNNEL-in-UDP, ESP:AES_CBC-128/HMAC_SHA1_96 installed 1128s ago, rekeying in 83970s, expires in 85272s in cd130507, 0 bytes, 0 packets out 6436d869, 0 bytes, 0 packets local 172.16.0.0/16 remote 192.168.0.0/16
5. Comprobar la conectividad y la alta disponibilidad
-
Compruebe la conectividad entre el centro de datos local y la VPC.
Desde un cliente en el centro de datos local, ejecute
pinghacia una instancia ECS dentro de la VPC. Los paquetes de respuesta confirman que la conexión se estableció correctamente.ping <IP_address_of_an_ECS_instance_in_the_VPC> -
Compruebe la alta disponibilidad de la conexión IPsec-VPN.
-
Mientras se ejecuta el ping, interrumpa el túnel activo.
Una forma de interrumpir el túnel consiste en modificar su clave precompartida para que las claves de ambos extremos dejen de coincidir.
Después de interrumpir el túnel principal, ejecute el comando
pingpara observar la conectividad entre ambos lados. Notará que el tráfico depingse interrumpe brevemente y luego se restablece. Esto indica que, tras la interrupción del túnel principal, el tráfico se comunica automáticamente por el túnel secundario.
-
Preguntas frecuentes
¿Cómo configuro un dispositivo strongSwan cuando la conexión IPsec-VPN está asociada a un transit router?
Cuando la conexión IPsec-VPN está asociada a un transit router, la configuración del lado del dispositivo strongSwan es la misma que se describió anteriormente. Se recomienda usar el protocolo de enrutamiento dinámico BGP. Una vez terminada la configuración, podrá consultar en el dispositivo strongSwan las rutas del lado de la VPC aprendidas mediante BGP. Además, los dos túneles de la conexión IPsec-VPN formarán automáticamente un enlace ECMP.
Como se muestra a continuación, después de ejecutar el comando show ip bgp, la marca = multipath indica una ruta de múltiples caminos. Observe que el símbolo a la izquierda de 192.168.10.0/24 es un signo de igual, lo cual señala que se trata de un candidato para múltiples caminos.
*********Z# show ip bgp
BGP table version is 42, local router ID is 169.254.13.2, vrf id 0
Default local pref 100, local AS 65530
Status codes: s suppressed, d damped, h history, * valid, > best, = multipath,
i internal, r RIB-failure, S Stale, R Removed
Nexthop codes: @NNN nexthop's vrf id, < announce-nh-self
Origin codes: i - IGP, e - EGP, ? - incomplete
RPKI validation codes: V valid, I invalid, N Not found
Network Next Hop Metric LocPrf Weight Path
*> 172.16.20.0/24 0.0.0.0 0 32768 i
*> 172.16.21.0/24 0.0.0.0 0 32768 i
*= 192.168.10.0/24 169.254.20.1 0 0 65535 i
*> 169.254.10.1 0 0 65535 i
*= 192.168.20.0/24 169.254.20.1 0 0 65535 i
*> 169.254.10.1 0 0 65535 i
*= 192.168.40.0/24 169.254.20.1 0 0 65535 i
*> 169.254.10.1 0 0 65535 i
*= 192.168.50.0/24 169.254.20.1 0 0 65535 i
*> 169.254.10.1 0 0 65535 i
*= 192.168.55.0/24 169.254.20.1 0 0 65535 i
*> 169.254.10.1 0 0 65535 i
¿StrongSwan admite IKEv1?
Sí, es compatible.
Al configurar el archivo /etc/strongswan/swanctl/swanctl.conf, especifique version = 1.
¿Cómo especifico los flujos de datos protegidos (flujos de interés)?
Al configurar el archivo /etc/strongswan/swanctl/swanctl.conf, especifique el bloque CIDR correspondiente en la siguiente configuración. Asegúrese de que el modo Traffic Selector también esté configurado para la conexión IPsec-VPN del lado de Alibaba Cloud.
Para especificar varios bloques CIDR en cualquiera de los lados, tanto el dispositivo strongSwan como la conexión IPsec-VPN de Alibaba Cloud deben usar IKEv2.
children {
vco_child1 {
local_ts = 172.16.20.0/24,172.16.21.0/24 # The CIDR blocks of the on-premises data center.
remote_ts = 192.168.0.0/16 # The CIDR block of the VPC on the Alibaba Cloud side.
}
}
¿Cómo configuro strongSwan cuando la interfaz de red tiene una dirección IP pública (sin NAT)?
En un escenario sin NAT, es decir, cuando la dirección visible dentro del dispositivo strongSwan es una IP pública, solo necesita cambiar el campo local_addrs de cada túnel en el archivo de configuración /etc/strongswan/swanctl/swanctl.conf por la dirección IP pública. Mantenga el resto de la configuración sin cambios.
connections {
vco1 {
local_addrs = 1.1.XX.XX # Specify the public IP address that is bound to the network interface card of the strongSwan device.
}
}
¿Cómo configuro un solo túnel?
Si el VPN Gateway que adquirió solo admite conexiones IPsec-VPN de un solo túnel, se recomienda Upgrade VPN Gateway to dual-tunnel mode. Una conexión IPsec-VPN en modo de túnel doble admite la recuperación ante desastres entre zonas, lo cual mejora la alta disponibilidad de la red.