Connect Linux Server to Alibaba Cloud VPC via IPsec VPN (Guided)
Scenario Description
Configure IPsec on a Linux server to establish a secure tunnel over the public network connecting to an Alibaba Cloud VPC. Typical use cases: edge servers, lightweight servers, Wuying cloud desktops, and edge nodes establishing secure tunnels via public network to access Alibaba Cloud VPC internal resources.
Architecture: Linux Server (StrongSwan) ←IPsec Dual Tunnel→ VPN Gateway → VPC + VSwitch + Security Group
Preparation
Requirements:
- * Linux server with public IP (NAT supported) and SSH key authentication
- Network: UDP 500/4500, ESP, TCP 22 allowed to this Linux server
- Alibaba Cloud VPC
Resource provisioning is outside this skill's scope.
Pre-checks
1. Aliyun CLI version verification
Pre-check: Aliyun CLI >= 3.3.1 required
Run aliyun version to verify >= 3.3.1. If not installed or version too low, see references/cli-installation-guide.md for installation instructions.
Then run aliyun configure set --auto-plugin-install true to enable automatic plugin installation.
CODEBLOCK0
2. Authentication credential verification
Pre-check: Alibaba Cloud Credentials Required
Security Rules:
- - NEVER read, echo, or print AK/SK values
- ONLY use
aliyun configure list to check credential status
> aliyun configure list
>
Check the output for a valid profile (AK, STS, or OAuth identity).
If no valid profile exists, STOP here and configure credentials outside of this session.
Phase 1: Permission Check
Before proceeding, verify that your Alibaba Cloud account has the necessary permissions.
Required APIs: INLINECODE3
Step 1.1: Use ram-permission-diagnose skill
Trigger the ram-permission-diagnose skill to diagnose current user's permissions:
CODEBLOCK2
Step 1.2: Compare against required policies
Refer to references/ram-policies.md for complete permission requirements.
IMPORTANT: Parameter Confirmation — Before executing any command or API call, ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks, passwords, domain names, resource specifications, etc.) MUST be confirmed with the user. Do NOT assume or use default values without explicit user approval.
Phase 2: Guided Parameter Collection
Interaction Principles:
- - Guided & User-Friendly: Collect from basic to specific — start with foundational params (Region → VPC → VSwitch), use each to auto-query dependent options via API, then drill down to detailed configs
- Interactive: All parameters MUST be explicitly confirmed by user. NO auto-selection
- Immutable Once Confirmed: NEVER change a previously confirmed parameter without explicit user request
- WAIT for user confirmation at each step before proceeding
Parameters to Collect
| # | Parameter | Source | Depends On |
|---|
| 1 | RegionId | API query INLINECODE5 | — |
| 2 |
VpcId | API query
describe-vpcs | RegionId |
| 3 | Bandwidth & Billing | User choice (recommend 10Mbps, 1yr) | — |
| 4 | VPN Gateway Name | Auto-suggest
ipsec-vpn-{REGION}-{DATE} | RegionId |
| 5 | Primary VSwitchId | API query
describe-vpn-gateway-available-zones +
describe-vswitches | RegionId, VpcId, Bandwidth |
| 6 | Backup VSwitchId | Same as above (must be different AZ) | Same as above |
| 7 | Server Public IP | User input (validate IPv4, warn if RFC1918) | — |
| 8 | SSH Username | User input (default: root) | — |
| 9 | SSH Private Key | User input (path to key file, default: ~/.ssh/id_rsa) | — |
| 10 | LocalSubnet | Recommend full VPC CIDR from Step 2 | VpcId |
| 11 | RemoteSubnet | User input (MUST be internal subnet, NOT public IP, NOT 0.0.0.0/0) | Server info |
| 12 | PSK | Auto-generate
openssl rand -base64 24 (min 16 chars) | — |
Step 2.1: Select Region
CODEBLOCK3
Highlight recommended regions (cn-beijing, cn-hangzhou, cn-shanghai, cn-shenzhen).
Step 2.2: Select VPC
CODEBLOCK4
Step 2.3: Configure Bandwidth & Billing
Bandwidth: 5/10(recommended)/20/50/100+ Mbps. Duration: 1mo/3mo/6mo/1yr(recommended)/2yr/3yr.
Step 2.4: Select VSwitches (Primary + Backup, must be different AZ)
CODEBLOCK5
Recommend pairs spanning different AZs. Validate: primary and backup MUST be in different AZ.
Step 2.5: Server Information
- - Server Public IP: User input. Validate IPv4 format; warn if RFC1918 private range detected.
- SSH Username: Default
root. User can specify other admin user. - SSH Private Key: Path to private key file (e.g.,
~/.ssh/id_rsa). - SSH IP: Default same as Server Public IP. User can override if SSH uses a different IP/port.
Step 2.6: Network Planning
- - LocalSubnet: Recommend full VPC CIDR
{VPC_CIDR} from Step 2.2 - RemoteSubnet: User input. Can SSH to server and run
ip addr show to get internal subnet. ⚠️ MUST be internal subnet (e.g., 10.0.0.0/24), NOT public IP or 0.0.0.0/0
Step 2.7: Generate PSK
CODEBLOCK6
⚠️ Save PSK securely. NEVER echo in plain text. Offer: use generated / regenerate / enter custom (min 16 chars).
Phase 3: Server-side Pre-check
SSH to server and collect network info before creating cloud resources:
CODEBLOCK7
Record: Server Internal IP, Local Subnet (e.g., 10.0.0.0/24), Default Gateway, Network Interface.
⚠️ RemoteSubnet in IPsec config must use server's internal subnet, NOT public IP or 0.0.0.0/0.
OS & Privileges: Check OS type, admin privileges, network connectivity, StrongSwan status (which strongswan swanctl). See references/server-precheck.md.
Phase 4: Confirm Configuration
Display collected parameters and ask user to confirm before proceeding. Explain the upcoming steps.
Phase 5: Create Cloud Resources
Step 5.1: Create VPN Gateway
CODEBLOCK8
Wait for activation (5-10 minutes), then get dual-tunnel IPs:
CODEBLOCK9
Common Error Handling
If you encounter InvalidVSwitchId.SecondVswitchNotSupport error when create vpn gateway, after double check the existance of this VSwitch, it means the availability zone of the backup VSwitch does not support VPN deployment.
Solution: Query VPN-supported availability zones and select a VSwitch in a suitable zone within the same VPC.
Note: Always use dual-tunnel mode. Do not fallback to single-tunnel mode.
Step 5.2: Create Customer Gateway
CODEBLOCK10
Record CustomerGatewayId.
Step 5.3: Create IPsec Connection (Dual-tunnel Mode)
Important: Current CLI version has limited support for --tunnel-options-specification parameter in plugin mode. Must use RPC style command with --method POST --force parameters.
CODEBLOCK11
Note: This command uses RPC API style (traditional format) because the current plugin mode create-vpn-connection command has compatibility issues when handling --tunnel-options-specification parameter for dual-tunnel mode. Recommend reporting to Alibaba Cloud CLI team to improve plugin mode support.
Record VpnConnectionId.
Phase 6: Add VPC Routes
⚠️ Important: Manual route addition may be required even with --auto-config-route=true.
CODEBLOCK12
Expected: Status = Available, next hop = VPN Gateway.
Phase 7: Server-side StrongSwan Configuration
See references/strongswan-config.md for complete StrongSwan configuration procedures including:
- - MUST read and follow the referenced document before proceeding
- Pre-configuration backup and validation steps
- Installation commands (Ubuntu/Debian/CentOS)
- INLINECODE26 template with dual-tunnel setup using VICI
- INLINECODE27 configuration with VICI plugin
- Firewall rules (UDP 500/4500, ESP protocol)
- Kernel parameter setup (
net.ipv4.ip_forward) - Connection initiation and rollback procedures
Note: Must use the VICI (Versatile IKE Configuration Interface) method with swanctl.conf instead of the legacy ipsec.conf format. This allows both tunnels to be UP simultaneously using priority-based routing.
Quick Steps:
- 1. Backup existing configuration:
CODEBLOCK13
- 2. Install and configure StrongSwan (see strongswan-config.md for details)
- 3. Validate and load configuration:
CODEBLOCK14
Note: If swanctl command not found, read strongswan-config.md and ensure strongswan-swanctl package is installed. NEVER fallback to legacy ipsec.conf.
- 4. Initiate both tunnels:
CODEBLOCK15
- 5. Verify tunnel status:
CODEBLOCK16
Phase 8: Verification & Diagnostics
Perform real verification (no simulated data):
Step 8.1: Check Aliyun Tunnel Status
CODEBLOCK17
Expected: Both tunnels have:
- -
State = INLINECODE34 - INLINECODE35 =
ipsec_sa_established (after StrongSwan is configured and started)
Step 8.2: Check Server-side StrongSwan Status
Run on server:
CODEBLOCK18
Expected: Both tunnels show ESTABLISHED.
Alternative detailed view:
CODEBLOCK19
Step 8.3: Real Connectivity Test
CODEBLOCK20
Expected: All packets received with reasonable latency.
Step 8.4: Troubleshooting if Failed
See references/troubleshooting.md for detailed diagnosis:
- - Check firewall rules (UDP 500/4500, ESP)
- Verify PSK matching
- Check IKE/IPsec parameter consistency
- Review tunnel logs on both sides
Full verification procedures: references/verification-method.md.
Phase 9: Success Criteria
Success criteria:
- - ✅ VPN Gateway status = INLINECODE38
- ✅ Dual tunnels both show INLINECODE39
- ✅ Server-side StrongSwan both tunnels INLINECODE40
- ✅ Bidirectional ping successful (Server ↔ VPC ECS)
Phase 10: Cleanup (Optional)
Delete resources in order (requires explicit user confirmation):
CODEBLOCK21
Best Practices
- 1. Security: Use strong PSK (min 16 chars, mixed case, numbers, special chars). Rotate regularly.
- High Availability: Deploy dual-tunnel mode with VSwitches across different AZs.
- Encryption Standard: IKEv2 + AES256 + SHA256 + DH Group14 (modp2048).
- Parameter Consistency: All IKE/IPsec params on Aliyun and server side MUST match exactly.
- Firewall Rules: Critical! Allow UDP 500 (IKE), UDP 4500 (NAT-T), ESP protocol (#50).
- Route Management: Always verify routes added after IPsec creation; auto-config may fail.
- Log Analysis: Check both Aliyun tunnel logs and server-side StrongSwan logs when troubleshooting.
- NAT Traversal: If server behind NAT, configure
local_addrs=%defaultroute and encap=yes in swanctl.conf. - Dual-Tunnel Mode: Use
priority parameter in swanctl.conf to allow both tunnels UP simultaneously (priority=100 for master, priority=200 for slave).
Reference Documentation
RAM permission policies |
|
references/server-precheck.md | Server-side pre-check procedures |
|
references/strongswan-config.md | Complete StrongSwan VICI/swanctl config |
|
references/verification-method.md | Verification steps & diagnostics |
|
references/acceptance-criteria.md | Acceptance test criteria |
|
references/troubleshooting.md | Common issues & solutions |
|
references/related-apis.md | Related APIs & CLI commands |
通过IPsec VPN将Linux服务器连接到阿里云VPC(引导式)
场景描述
在Linux服务器上配置IPsec,通过公网建立安全隧道连接到阿里云VPC。典型使用场景:边缘服务器、轻量级服务器、无影云桌面以及边缘节点通过公网建立安全隧道,访问阿里云VPC内部资源。
架构:Linux服务器(StrongSwan)←IPsec双隧道→ VPN网关 → VPC + 交换机 + 安全组
准备工作
要求:
- * 具有公网IP(支持NAT)和SSH密钥认证的Linux服务器
- 网络:允许UDP 500/4500、ESP、TCP 22访问该Linux服务器
- 阿里云VPC
资源预置不在本技能范围内。
前置检查
1. 阿里云CLI版本验证
前置检查:需要阿里云CLI >= 3.3.1
运行 aliyun version 验证版本 >= 3.3.1。如果未安装或版本过低,请参阅 references/cli-installation-guide.md 获取安装说明。
然后运行 aliyun configure set --auto-plugin-install true 启用自动插件安装。
bash
aliyun version
2. 认证凭据验证
前置检查:需要阿里云凭据
安全规则:
- - 切勿读取、回显或打印AK/SK值
- 仅使用 aliyun configure list 检查凭据状态
bash
aliyun configure list
检查输出中是否存在有效的配置文件(AK、STS或OAuth身份)。
如果不存在有效配置文件,请在此处停止,并在当前会话之外配置凭据。
阶段1:权限检查
在继续之前,请验证您的阿里云账户具有必要的权限。
所需API: [vpc:DescribeRegions, vpc:DescribeVpcs, vpc:DescribeVswitches, vpc:CreateRouteEntry, vpc:CreateVpnGateway, vpc:DeleteVpnGateway, vpc:CreateCustomerGateway, vpc:DeleteCustomerGateway, vpc:CreateVpnConnection, vpc:DeleteVpnConnection]
步骤1.1:使用ram-permission-diagnose技能
触发 ram-permission-diagnose 技能诊断当前用户的权限:
bash
触发:ram-permission-diagnose
diagnose permissions for
步骤1.2:与所需策略进行比较
请参阅 references/ram-policies.md 了解完整的权限要求。
重要:参数确认 — 在执行任何命令或API调用之前,所有用户可自定义的参数(例如,RegionId、实例名称、CIDR块、密码、域名、资源规格等)必须与用户确认。未经用户明确批准,不得假设或使用默认值。
阶段2:引导式参数收集
交互原则:
- - 引导式且用户友好:从基础到具体收集 — 从基本参数开始(区域 → VPC → 交换机),使用每个参数通过API自动查询依赖选项,然后深入详细配置
- 交互式:所有参数必须由用户明确确认。不得自动选择
- 确认后不可更改:未经用户明确请求,绝不更改先前确认的参数
- 在继续之前,等待用户在每一步进行确认
需要收集的参数
| # | 参数 | 来源 | 依赖项 |
|---|
| 1 | RegionId | API查询 describe-regions | — |
| 2 |
VpcId | API查询 describe-vpcs | RegionId |
| 3 | 带宽与计费 | 用户选择(推荐10Mbps,1年) | — |
| 4 | VPN网关名称 | 自动建议 ipsec-vpn-{REGION}-{DATE} | RegionId |
| 5 | 主交换机ID | API查询 describe-vpn-gateway-available-zones + describe-vswitches | RegionId, VpcId, 带宽 |
| 6 | 备用交换机ID | 同上(必须为不同可用区) | 同上 |
| 7 | 服务器公网IP | 用户输入(验证IPv4,如为RFC1918则发出警告) | — |
| 8 | SSH用户名 | 用户输入(默认:root) | — |
| 9 | SSH私钥 | 用户输入(密钥文件路径,默认:~/.ssh/id_rsa) | — |
| 10 | 本地子网 | 推荐使用步骤2中的完整VPC CIDR | VpcId |
| 11 | 远程子网 | 用户输入(必须为内部子网,不是公网IP,不是 0.0.0.0/0) | 服务器信息 |
| 12 | PSK | 自动生成 openssl rand -base64 24(最少16个字符) | — |
步骤2.1:选择区域
bash
aliyun vpc describe-regions --cli-query Regions.Region[].{RegionId:RegionId,LocalName:LocalName} --user-agent AlibabaCloud-Agent-Skills
高亮推荐区域(cn-beijing、cn-hangzhou、cn-shanghai、cn-shenzhen)。
步骤2.2:选择VPC
bash
aliyun vpc describe-vpcs --region {REGIONID} --biz-region-id {REGIONID} --cli-query Vpcs.Vpc[].{VpcId:VpcId,VpcName:VpcName,CidrBlock:CidrBlock} --user-agent AlibabaCloud-Agent-Skills
步骤2.3:配置带宽与计费
带宽:5/10(推荐)/20/50/100+ Mbps。时长:1个月/3个月/6个月/1年(推荐)/2年/3年。
步骤2.4:选择交换机(主+备用,必须为不同可用区)
bash
aliyun vpc describe-vpn-gateway-available-zones --region {REGIONID} --biz-region-id {REGIONID} --spec {BANDWIDTH}M --user-agent AlibabaCloud-Agent-Skills
aliyun vpc describe-vswitches --region {REGIONID} --vpc-id {VPCID} --cli-query VSwitches.VSwitch[].{VSwitchId:VSwitchId,VSwitchName:VSwitchName,ZoneId:ZoneId,CidrBlock:CidrBlock,AvailableIpAddressCount:AvailableIpAddressCount} --user-agent AlibabaCloud-Agent-Skills
推荐跨越不同可用区的配对。验证:主和备用交换机必须位于不同可用区。
步骤2.5:服务器信息
- - 服务器公网IP:用户输入。验证IPv4格式;如果检测到RFC1918私有范围则发出警告。
- SSH用户名:默认为 root。用户可以指定其他管理员用户。
- SSH私钥:私钥文件路径(例如,~/.ssh/id_rsa)。
- SSH IP:默认与服务器公网IP相同。如果SSH使用不同的IP/端口,用户可以覆盖。
步骤2.6:网络规划
- - 本地子网:推荐使用步骤2.2中的完整VPC CIDR {VPC_CIDR}
- 远程子网:用户输入。可以SSH到服务器并运行 ip addr show 获取内部子网。⚠️ 必须是内部子网(例如,10.0.0.0/24),不是公网IP或0.0.0.0/0
步骤2.7:生成PSK
bash
PSK=$(openssl rand -base64 24 | tr -d /+= | head -c 20)
⚠️ 安全保存PSK。绝不以明文回显。提供选项:使用生成的/重新生成/输入自定义(最少16个字符)。
阶段3:服务器端前置检查
在创建云资源之前,SSH到服务器并收集网络信息:
bash
ssh -o StrictHostKeyChecking=no -i {SSHKEYPATH} {SSHUSER}@{SSHIP}
ip addr show && ip route show
记录: 服务器内部IP、本地子网(例如,10.0.0.0/24)、默认网关、网络接口。
⚠️ IPsec配置中的 RemoteSubnet 必须使用服务器的内部子网,不是公网IP或0.0.0.0/0。
操作系统与权限: 检查操作系统类型、管理员权限、网络连接、StrongSwan状态(which strongswan swanctl)。请参阅 [