39. 故障排查速查表
39.1 快速诊断流程图
39.1.1 连接问题诊断
无法连接VPN
|
├─> 检查服务状态
| ├─> 服务未运行 → systemctl start wg-quick@wg0
| └─> 服务运行中 → 继续检查
|
├─> 检查网络接口
| ├─> wg0不存在 → 检查配置文件语法
| └─> wg0存在 → 继续检查
|
├─> 检查端口监听
| ├─> 端口未监听 → 检查ListenPort配置
| └─> 端口监听 → 继续检查
|
├─> 检查防火墙
| ├─> 端口被阻止 → ufw allow 51820/udp
| └─> 端口开放 → 继续检查
|
├─> 检查握手状态
| ├─> 从未握手 → 检查密钥配置
| ├─> 握手超时 → 检查保活设置
| └─> 握手正常 → 检查路由和NAT
|
└─> 检查数据传输
├─> 无数据传输 → 检查AllowedIPs和路由
└─> 有数据传输 → 连接正常
39.1.2 性能问题诊断
性能问题
|
├─> 延迟过高
| ├─> 检查MTU → ping -M do -s 1392 10.8.0.1
| ├─> 检查CPU → top
| ├─> 检查网络质量 → mtr 10.8.0.1
| └─> 优化TCP参数 → 启用BBR
|
├─> 吞吐量低
| ├─> 检查缓冲区 → sysctl net.core.rmem_max
| ├─> 检查拥塞控制 → sysctl net.ipv4.tcp_congestion_control
| ├─> 检查硬件加速 → ethtool -k pnet0
| └─> 调整队列长度 → ip link set wg0 txqueuelen 10000
|
├─> 频繁丢包
| ├─> 检查物理链路 → ethtool pnet0
| ├─> 检查缓冲区溢出 → netstat -s | grep overflow
| ├─> 检查防火墙 → iptables -L -n -v
| └─> 调整保活间隔 → PersistentKeepalive = 15
|
└─> CPU占用高
├─> 启用硬件加速 → modprobe aesni_intel
├─> 优化中断分布 → 配置irqbalance
└─> 调整CPU亲和性 → taskset
39.2 错误代码对照表
39.2.1 系统错误
| 错误代码 | 错误信息 | 原因 | 解决方案 |
|---|---|---|---|
| ENOENT | No such file or directory | 配置文件不存在 | 检查/etc/wireguard/wg0.conf |
| EACCES | Permission denied | 权限不足 | 使用sudo或检查文件权限 |
| EADDRINUSE | Address already in use | 端口已被占用 | lsof -i :51820查找占用进程 |
| ENETUNREACH | Network is unreachable | 网络不可达 | 检查路由表和网络连接 |
| EEXIST | File exists | 接口已存在 | ip link delete wg0删除旧接口 |
| EINVAL | Invalid argument | 参数错误 | 检查配置文件语法 |
39.2.2 WireGuard特定错误
| 症状 | 日志特征 | 原因 | 解决方案 |
|---|---|---|---|
| 握手失败 | Invalid handshake | 密钥不匹配 | 验证公钥和私钥对应关系 |
| 配置解析失败 | Configuration parsing error | 语法错误 | wg-quick strip wg0检查语法 |
| 无法创建接口 | Unable to access interface | 模块未加载 | modprobe wireguard |
| Endpoint不可达 | Could not resolve | DNS或网络问题 | 检查Endpoint地址和网络 |
| 密钥格式错误 | Invalid key | Base64格式错误 | 重新生成密钥 |
39.3 常见问题速查
39.3.1 连接问题
问题1:客户端连接后无法访问互联网
# 快速检查
echo "1. 检查IP转发"
sysctl net.ipv4.ip_forward
# 应输出: net.ipv4.ip_forward = 1
echo "2. 检查NAT规则"
iptables -t nat -L POSTROUTING -n -v | grep MASQUERADE
# 应有MASQUERADE规则
echo "3. 检查AllowedIPs"
wg show wg0 allowed-ips
# 客户端应配置0.0.0.0/0
# 快速修复
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE
问题2:连接建立但频繁断开
# 诊断
echo "1. 检查握手时间"
wg show wg0 latest-handshakes
echo "2. 检查保活设置"
wg show wg0 persistent-keepalive
echo "3. 检查MTU"
ip link show wg0 | grep mtu
# 修复
# 在客户端配置添加
PersistentKeepalive = 25
# 调整MTU
sudo ip link set wg0 mtu 1280
问题3:部分网站无法访问
# 诊断MTU问题
ping -M do -s 1400 www.example.com
# 如果失败,需要降低MTU
# 修复 - 添加MSS钳制
sudo iptables -t mangle -A FORWARD -i wg0 -p tcp -m tcp \
--tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
39.3.2 性能问题
问题4:延迟突然增高
# 诊断脚本
#!/bin/bash
echo "=== 延迟诊断 ==="
# 测试VPN延迟
echo "VPN延迟:"
ping -c 10 10.8.0.1 | grep avg
# 测试物理网络
echo "物理网络延迟:"
ping -c 10 192.168.1.66 | grep avg
# 检查CPU
echo "CPU使用:"
top -bn1 | grep "Cpu(s)"
# 检查网络错误
echo "网络错误:"
ip -s link show wg0 | grep errors
# 建议
echo "如果VPN延迟 >> 物理延迟,可能是:"
echo "1. CPU过载 - 降低负载或升级硬件"
echo "2. MTU问题 - 调整MTU设置"
echo "3. 加密性能 - 启用硬件加速"
问题5:速度远低于预期
# 性能测试
#!/bin/bash
echo "=== 性能测试 ==="
# 使用iperf3测试
echo "启动iperf3服务器(在VPN服务器上):"
echo "iperf3 -s"
echo "在客户端运行:"
echo "iperf3 -c 10.8.0.1 -t 30"
# 检查瓶颈
echo "检查CPU:"
echo " 高CPU占用 → 启用硬件加密加速"
echo "检查网络:"
echo " 物理带宽上限 → 硬件限制"
echo " 缓冲区小 → 增大TCP缓冲区"
echo "检查拥塞控制:"
sysctl net.ipv4.tcp_congestion_control
echo " 如非BBR → 启用BBR"
39.3.3 配置问题
问题6:配置修改后不生效
# 检查配置是否加载
echo "1. 检查运行时配置"
wg show wg0
echo "2. 检查配置文件"
cat /etc/wireguard/wg0.conf
echo "3. 重新加载配置(不断开连接)"
sudo wg syncconf wg0 <(wg-quick strip wg0)
echo "4. 或完全重启"
sudo wg-quick down wg0
sudo wg-quick up wg0
echo "5. 验证"
wg show wg0
问题7:多个客户端使用相同IP
# 检测IP冲突
#!/bin/bash
echo "=== IP冲突检测 ==="
# 列出所有AllowedIPs
echo "所有分配的IP:"
sudo wg show wg0 allowed-ips | awk '{print $2}' | sort
# 查找重复
echo "重复的IP:"
sudo wg show wg0 allowed-ips | awk '{print $2}' | sort | uniq -d
# 修复方法
echo "修复步骤:"
echo "1. 编辑配置文件,修改冲突的AllowedIPs"
echo "2. 重新加载: wg syncconf wg0 <(wg-quick strip wg0)"
echo "3. 通知客户端更新Address配置"
39.4 一键诊断脚本
39.4.1 全面诊断工具
#!/bin/bash
# wireguard-doctor.sh - WireGuard全面诊断工具
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
print_status() {
if [ $1 -eq 0 ]; then
echo -e "${GREEN}✓${NC} $2"
else
echo -e "${RED}✗${NC} $2"
fi
}
print_warning() {
echo -e "${YELLOW}⚠${NC} $1"
}
echo "╔════════════════════════════════════════╗"
echo "║ WireGuard 诊断工具 v1.0 ║"
echo "╚════════════════════════════════════════╝"
echo ""
# 1. 系统检查
echo "═══ 1. 系统检查 ═══"
# 检查是否为root
if [ "$EUID" -ne 0 ]; then
print_status 1 "需要root权限"
echo "请使用 sudo 运行此脚本"
exit 1
else
print_status 0 "Root权限"
fi
# 检查WireGuard安装
if command -v wg &> /dev/null; then
print_status 0 "WireGuard已安装 ($(wg --version))"
else
print_status 1 "WireGuard未安装"
exit 1
fi
# 检查内核模块
if lsmod | grep -q wireguard; then
print_status 0 "WireGuard内核模块已加载"
else
print_status 1 "WireGuard内核模块未加载"
echo " 尝试: modprobe wireguard"
fi
echo ""
# 2. 服务检查
echo "═══ 2. 服务检查 ═══"
# 检查systemd服务
if systemctl is-active --quiet wg-quick@wg0; then
print_status 0 "wg-quick@wg0 服务运行中"
# 显示运行时间
uptime=$(systemctl show wg-quick@wg0 --property=ActiveEnterTimestamp --value)
echo " 运行时间: $uptime"
else
print_status 1 "wg-quick@wg0 服务未运行"
echo " 启动: systemctl start wg-quick@wg0"
fi
# 检查开机自启
if systemctl is-enabled --quiet wg-quick@wg0; then
print_status 0 "开机自启已启用"
else
print_warning "开机自启未启用"
echo " 启用: systemctl enable wg-quick@wg0"
fi
echo ""
# 3. 接口检查
echo "═══ 3. 接口检查 ═══"
# 检查wg0接口
if ip link show wg0 &> /dev/null; then
print_status 0 "wg0接口存在"
# 检查接口状态
if ip link show wg0 | grep -q "UP"; then
print_status 0 "wg0接口已启动"
else
print_status 1 "wg0接口未启动"
fi
# 显示IP地址
ip_addr=$(ip addr show wg0 | grep "inet " | awk '{print $2}')
echo " IP地址: $ip_addr"
# 显示MTU
mtu=$(ip link show wg0 | grep -oP 'mtu \K\d+')
echo " MTU: $mtu"
# 检查MTU是否合理
if [ "$mtu" -lt 1280 ]; then
print_warning "MTU可能过小"
elif [ "$mtu" -gt 1420 ]; then
print_warning "MTU可能过大"
fi
else
print_status 1 "wg0接口不存在"
echo " 检查配置: /etc/wireguard/wg0.conf"
fi
echo ""
# 4. 端口检查
echo "═══ 4. 端口检查 ═══"
# 检查监听端口
if ss -ulnp | grep -q :51820; then
print_status 0 "UDP 51820端口正在监听"
# 显示详细信息
ss -ulnp | grep :51820
else
print_status 1 "UDP 51820端口未监听"
echo " 检查配置中的 ListenPort"
fi
echo ""
# 5. 防火墙检查
echo "═══ 5. 防火墙检查 ═══"
# 检查ufw
if command -v ufw &> /dev/null; then
if ufw status | grep -q "51820.*ALLOW"; then
print_status 0 "UFW: 51820端口已允许"
else
print_status 1 "UFW: 51820端口未允许"
echo " 允许端口: ufw allow 51820/udp"
fi
fi
# 检查iptables INPUT
if iptables -L INPUT -n | grep -q "udp.*51820"; then
print_status 0 "iptables INPUT: 允许51820端口"
else
print_warning "iptables INPUT: 未找到51820规则"
fi
# 检查FORWARD规则
if iptables -L FORWARD -n | grep -q "wg0"; then
print_status 0 "iptables FORWARD: wg0转发已配置"
else
print_status 1 "iptables FORWARD: wg0转发未配置"
echo " 添加规则: iptables -A FORWARD -i wg0 -j ACCEPT"
fi
# 检查NAT
if iptables -t nat -L POSTROUTING -n | grep -q "MASQUERADE"; then
print_status 0 "iptables NAT: MASQUERADE已配置"
else
print_status 1 "iptables NAT: MASQUERADE未配置"
echo " 添加规则: iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE"
fi
echo ""
# 6. 配置检查
echo "═══ 6. 配置检查 ═══"
CONFIG_FILE="/etc/wireguard/wg0.conf"
# 检查配置文件存在
if [ -f "$CONFIG_FILE" ]; then
print_status 0 "配置文件存在"
# 检查权限
perms=$(stat -c %a "$CONFIG_FILE")
if [ "$perms" = "600" ]; then
print_status 0 "配置文件权限正确 (600)"
else
print_warning "配置文件权限: $perms (建议600)"
echo " 修复: chmod 600 $CONFIG_FILE"
fi
# 验证语法
if wg-quick strip wg0 &> /dev/null; then
print_status 0 "配置文件语法正确"
else
print_status 1 "配置文件语法错误"
echo " 检查: wg-quick strip wg0"
fi
# 检查私钥
if grep -q "PrivateKey" "$CONFIG_FILE"; then
privkey=$(grep "PrivateKey" "$CONFIG_FILE" | awk '{print $3}')
if [ ${#privkey} -eq 44 ]; then
print_status 0 "PrivateKey格式正确"
else
print_status 1 "PrivateKey格式错误"
fi
else
print_status 1 "缺少PrivateKey"
fi
# 统计peer数量
peer_count=$(grep -c "^\[Peer\]" "$CONFIG_FILE" || echo 0)
echo " 配置的Peer数量: $peer_count"
else
print_status 1 "配置文件不存在: $CONFIG_FILE"
fi
echo ""
# 7. 网络检查
echo "═══ 7. 网络检查 ═══"
# 检查IP转发
ip_forward=$(sysctl -n net.ipv4.ip_forward)
if [ "$ip_forward" = "1" ]; then
print_status 0 "IP转发已启用"
else
print_status 1 "IP转发未启用"
echo " 启用: sysctl -w net.ipv4.ip_forward=1"
fi
# 检查路由
if ip route | grep -q "wg0"; then
print_status 0 "wg0路由已配置"
else
print_warning "未找到wg0路由"
fi
# 检查互联网连接
if ping -c 1 -W 2 8.8.8.8 &> /dev/null; then
print_status 0 "互联网连接正常"
else
print_status 1 "无法访问互联网"
fi
echo ""
# 8. Peer状态
echo "═══ 8. Peer状态 ═══"
if wg show wg0 &> /dev/null; then
# 统计peer
total_peers=$(wg show wg0 peers | wc -l)
echo " 总Peer数: $total_peers"
if [ $total_peers -gt 0 ]; then
# 统计在线peer(最近5分钟有握手)
now=$(date +%s)
online=0
wg show wg0 latest-handshakes | while read pubkey timestamp; do
age=$((now - timestamp))
if [ $timestamp -ne 0 ] && [ $age -lt 300 ]; then
online=$((online + 1))
fi
done
echo " 在线Peer数: $online"
# 显示握手信息
echo ""
echo " 最近握手时间:"
wg show wg0 latest-handshakes | while read pubkey timestamp; do
if [ $timestamp -ne 0 ]; then
age=$((now - timestamp))
if [ $age -lt 60 ]; then
time_str="${age}秒前"
elif [ $age -lt 3600 ]; then
time_str="$((age / 60))分钟前"
else
time_str="$((age / 3600))小时前"
fi
echo " ${pubkey:0:20}...: $time_str"
fi
done
fi
else
print_status 1 "无法获取peer信息"
fi
echo ""
# 9. 性能指标
echo "═══ 9. 性能指标 ═══"
# CPU负载
load=$(uptime | awk -F'load average:' '{print $2}')
echo " 系统负载:$load"
# 内存使用
mem_usage=$(free | awk '/Mem:/ {printf "%.1f%%", $3/$2 * 100}')
echo " 内存使用: $mem_usage"
# 网络统计
if ip link show wg0 &> /dev/null; then
echo " wg0统计:"
ip -s link show wg0 | grep -A 1 "RX:\|TX:" | grep -v "RX:\|TX:"
fi
echo ""
# 10. 日志检查
echo "═══ 10. 最近日志 ═══"
# 检查最近的错误
error_count=$(journalctl -u wg-quick@wg0 --since "1 hour ago" -p err | wc -l)
if [ $error_count -eq 0 ]; then
print_status 0 "最近1小时无错误"
else
print_warning "最近1小时有 $error_count 个错误"
echo " 查看: journalctl -u wg-quick@wg0 -p err"
fi
echo ""
# 总结
echo "╔════════════════════════════════════════╗"
echo "║ 诊断完成 ║"
echo "╚════════════════════════════════════════╝"
echo ""
echo "详细日志: journalctl -u wg-quick@wg0"
echo "配置文件: /etc/wireguard/wg0.conf"
echo "状态查看: wg show wg0"
echo ""
使用方法:
sudo bash wireguard-doctor.sh
39.4.2 性能测试脚本
#!/bin/bash
# wireguard-performance-test.sh
echo "╔════════════════════════════════════════╗"
echo "║ WireGuard 性能测试工具 ║"
echo "╚════════════════════════════════════════╝"
echo ""
TARGET="10.8.0.1"
# 1. 延迟测试
echo "═══ 1. 延迟测试 ═══"
echo "测试目标: $TARGET"
ping_result=$(ping -c 100 -i 0.2 $TARGET 2>/dev/null)
if [ $? -eq 0 ]; then
# 提取统计信息
min=$(echo "$ping_result" | grep "rtt" | awk -F'/' '{print $4}')
avg=$(echo "$ping_result" | grep "rtt" | awk -F'/' '{print $5}')
max=$(echo "$ping_result" | grep "rtt" | awk -F'/' '{print $6}')
loss=$(echo "$ping_result" | grep "packet loss" | awk '{print $6}')
echo " 最小延迟: ${min}ms"
echo " 平均延迟: ${avg}ms"
echo " 最大延迟: ${max}ms"
echo " 丢包率: $loss"
# 评估
avg_int=${avg%.*}
if [ $avg_int -lt 10 ]; then
echo " 评价: 优秀"
elif [ $avg_int -lt 50 ]; then
echo " 评价: 良好"
elif [ $avg_int -lt 100 ]; then
echo " 评价: 一般"
else
echo " 评价: 较差"
fi
else
echo " ✗ 延迟测试失败"
fi
echo ""
# 2. MTU测试
echo "═══ 2. MTU测试 ═══"
optimal_mtu=1500
for test_mtu in 1500 1480 1460 1440 1420 1400 1380 1360 1340 1320 1300 1280; do
data_size=$((test_mtu - 28))
if ping -M do -s $data_size -c 3 -W 2 $TARGET > /dev/null 2>&1; then
optimal_mtu=$test_mtu
break
fi
done
echo " 最优MTU: $optimal_mtu"
current_mtu=$(ip link show wg0 | grep -oP 'mtu \K\d+')
echo " 当前MTU: $current_mtu"
if [ "$current_mtu" != "$optimal_mtu" ]; then
echo " 建议: 调整MTU到 $optimal_mtu"
fi
echo ""
# 3. 带宽测试(需要iperf3)
echo "═══ 3. 带宽测试 ═══"
if command -v iperf3 &> /dev/null; then
echo " 测试时长: 10秒"
echo " 正在测试..."
# TCP测试
tcp_result=$(iperf3 -c $TARGET -t 10 -J 2>/dev/null)
if [ $? -eq 0 ]; then
tcp_speed=$(echo $tcp_result | jq -r '.end.sum_received.bits_per_second' 2>/dev/null)
if [ -n "$tcp_speed" ] && [ "$tcp_speed" != "null" ]; then
tcp_mbps=$(echo "scale=2; $tcp_speed / 1000000" | bc)
echo " TCP吞吐量: ${tcp_mbps} Mbps"
fi
fi
# UDP测试
udp_result=$(iperf3 -c $TARGET -u -b 100M -t 10 -J 2>/dev/null)
if [ $? -eq 0 ]; then
udp_speed=$(echo $udp_result | jq -r '.end.sum.bits_per_second' 2>/dev/null)
udp_loss=$(echo $udp_result | jq -r '.end.sum.lost_percent' 2>/dev/null)
if [ -n "$udp_speed" ] && [ "$udp_speed" != "null" ]; then
udp_mbps=$(echo "scale=2; $udp_speed / 1000000" | bc)
echo " UDP吞吐量: ${udp_mbps} Mbps"
echo " UDP丢包率: ${udp_loss}%"
fi
fi
else
echo " ⚠ iperf3未安装"
echo " 安装: apt install iperf3"
fi
echo ""
# 4. 系统资源
echo "═══ 4. 系统资源 ═══"
# CPU
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | sed 's/%us,//')
echo " CPU使用率: ${cpu_usage}%"
# 内存
mem_usage=$(free | awk '/Mem:/ {printf "%.1f", $3/$2 * 100}')
echo " 内存使用率: ${mem_usage}%"
# 网络统计
if [ -d "/sys/class/net/wg0" ]; then
rx_bytes=$(cat /sys/class/net/wg0/statistics/rx_bytes)
tx_bytes=$(cat /sys/class/net/wg0/statistics/tx_bytes)
rx_errors=$(cat /sys/class/net/wg0/statistics/rx_errors)
tx_errors=$(cat /sys/class/net/wg0/statistics/tx_errors)
rx_mb=$((rx_bytes / 1048576))
tx_mb=$((tx_bytes / 1048576))
echo " 总接收: ${rx_mb}MB"
echo " 总发送: ${tx_mb}MB"
echo " 接收错误: $rx_errors"
echo " 发送错误: $tx_errors"
fi
echo ""
# 5. 性能建议
echo "═══ 5. 性能建议 ═══"
suggestions=()
# 检查BBR
current_cc=$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null)
if [ "$current_cc" != "bbr" ]; then
suggestions+=("启用BBR拥塞控制以提高性能")
fi
# 检查MTU
if [ "$current_mtu" -gt "$optimal_mtu" ]; then
suggestions+=("降低MTU到 $optimal_mtu")
fi
# 检查CPU
cpu_int=${cpu_usage%.*}
if [ $cpu_int -gt 80 ]; then
suggestions+=("CPU使用率过高,考虑启用硬件加密加速")
fi
# 显示建议
if [ ${#suggestions[@]} -eq 0 ]; then
echo " ✓ 当前配置已优化"
else
for suggestion in "${suggestions[@]}"; do
echo " • $suggestion"
done
fi
echo ""
echo "╔════════════════════════════════════════╗"
echo "║ 测试完成 ║"
echo "╚════════════════════════════════════════╝"
40. 配置模板库
40.1 基础配置模板
40.1.1 最小化配置
服务器配置(最小):
# /etc/wireguard/wg0.conf
# 最小化服务器配置
[Interface]
PrivateKey = SERVER_PRIVATE_KEY_HERE
Address = 10.8.0.1/24
ListenPort = 51820
[Peer]
PublicKey = CLIENT_PUBLIC_KEY_HERE
AllowedIPs = 10.8.0.2/32
客户端配置(最小):
# 最小化客户端配置
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY_HERE
Address = 10.8.0.2/24
[Peer]
PublicKey = SERVER_PUBLIC_KEY_HERE
Endpoint = SERVER_IP:51820
AllowedIPs = 10.8.0.0/24
40.1.2 推荐配置
服务器配置(推荐):
# /etc/wireguard/wg0.conf
# 生产环境推荐配置
[Interface]
# 服务器私钥
PrivateKey = SERVER_PRIVATE_KEY_HERE
# 虚拟网络地址
Address = 10.8.0.1/24
# 监听端口
ListenPort = 51820
# MTU优化
MTU = 1420
# 启动时执行
PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostUp = iptables -A FORWARD -o %i -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE
PostUp = ip6tables -A FORWARD -i %i -j ACCEPT
PostUp = ip6tables -A FORWARD -o %i -j ACCEPT
PostUp = ip6tables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE
# 停止时执行
PostDown = iptables -D FORWARD -i %i -j ACCEPT
PostDown = iptables -D FORWARD -o %i -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o pnet0 -j MASQUERADE
PostDown = ip6tables -D FORWARD -i %i -j ACCEPT
PostDown = ip6tables -D FORWARD -o %i -j ACCEPT
PostDown = ip6tables -t nat -D POSTROUTING -o pnet0 -j MASQUERADE
# 客户端1
[Peer]
# 用户: alice
# 添加时间: 2025-03-23
PublicKey = CLIENT1_PUBLIC_KEY_HERE
AllowedIPs = 10.8.0.2/32
# 客户端2
[Peer]
# 用户: bob
# 添加时间: 2025-03-23
PublicKey = CLIENT2_PUBLIC_KEY_HERE
AllowedIPs = 10.8.0.3/32
客户端配置(推荐 - 分流模式):
# WireGuard客户端配置
# 分流模式 - 仅VPN流量通过隧道
[Interface]
# 客户端私钥
PrivateKey = CLIENT_PRIVATE_KEY_HERE
# 虚拟IP地址
Address = 10.8.0.2/24
# DNS服务器
DNS = 223.5.5.5, 114.114.114.114
# MTU设置
MTU = 1420
[Peer]
# 服务器公钥
PublicKey = SERVER_PUBLIC_KEY_HERE
# 服务器地址和端口
Endpoint = SERVER_PUBLIC_IP:51820
# 允许的IP范围(VPN网段)
AllowedIPs = 10.8.0.0/24
# 保活间隔(秒)
PersistentKeepalive = 25
客户端配置(推荐 - 全局模式):
# WireGuard客户端配置
# 全局模式 - 所有流量通过VPN
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY_HERE
Address = 10.8.0.2/24
DNS = 223.5.5.5, 8.8.8.8
MTU = 1420
[Peer]
PublicKey = SERVER_PUBLIC_KEY_HERE
Endpoint = SERVER_PUBLIC_IP:51820
# 所有流量通过VPN
AllowedIPs = 0.0.0.0/0, ::/0
PersistentKeepalive = 25
40.2 高级配置模板
40.2.1 多peer配置
服务器配置(10个客户端):
[Interface]
PrivateKey = SERVER_PRIVATE_KEY_HERE
Address = 10.8.0.1/24
ListenPort = 51820
MTU = 1420
PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o pnet0 -j MASQUERADE
# 客户端 1-10
[Peer]
# alice - 管理员
PublicKey = ALICE_PUBLIC_KEY
AllowedIPs = 10.8.0.2/32
[Peer]
# bob - 开发
PublicKey = BOB_PUBLIC_KEY
AllowedIPs = 10.8.0.3/32
[Peer]
# charlie - 开发
PublicKey = CHARLIE_PUBLIC_KEY
AllowedIPs = 10.8.0.4/32
[Peer]
# david - 测试
PublicKey = DAVID_PUBLIC_KEY
AllowedIPs = 10.8.0.5/32
[Peer]
# eve - 运维
PublicKey = EVE_PUBLIC_KEY
AllowedIPs = 10.8.0.6/32
[Peer]
# frank - 移动设备
PublicKey = FRANK_PUBLIC_KEY
AllowedIPs = 10.8.0.7/32
[Peer]
# grace - 临时访问
PublicKey = GRACE_PUBLIC_KEY
AllowedIPs = 10.8.0.8/32
[Peer]
# henry - 分支机构
PublicKey = HENRY_PUBLIC_KEY
AllowedIPs = 10.8.0.9/32
[Peer]
# iris - 外包
PublicKey = IRIS_PUBLIC_KEY
AllowedIPs = 10.8.0.10/32
[Peer]
# jack - 备用
PublicKey = JACK_PUBLIC_KEY
AllowedIPs = 10.8.0.11/32
40.2.2 带PSK的安全配置
服务器配置(PSK增强):
[Interface]
PrivateKey = SERVER_PRIVATE_KEY_HERE
Address = 10.8.0.1/24
ListenPort = 51820
MTU = 1420
PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o pnet0 -j MASQUERADE
[Peer]
# 高安全客户端(使用PSK)
PublicKey = SECURE_CLIENT_PUBLIC_KEY
PresharedKey = PRESHARED_KEY_HERE
AllowedIPs = 10.8.0.2/32
客户端配置(PSK):
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY_HERE
Address = 10.8.0.2/24
DNS = 223.5.5.5
[Peer]
PublicKey = SERVER_PUBLIC_KEY_HERE
PresharedKey = PRESHARED_KEY_HERE
Endpoint = SERVER_IP:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
40.2.3 多网段访问配置
服务器配置(多内网网段):
[Interface]
PrivateKey = SERVER_PRIVATE_KEY_HERE
# 同时配置多个地址段
Address = 10.8.0.1/24, 172.16.0.1/24
ListenPort = 51820
PostUp = iptables -A FORWARD -i %i -j ACCEPT
PostUp = iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE
# 允许访问内网网段
PostUp = iptables -A FORWARD -s 10.8.0.0/24 -d 192.168.1.0/24 -j ACCEPT
PostUp = iptables -A FORWARD -s 10.8.0.0/24 -d 172.16.0.0/16 -j ACCEPT
PostDown = iptables -D FORWARD -i %i -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o pnet0 -j MASQUERADE
PostDown = iptables -D FORWARD -s 10.8.0.0/24 -d 192.168.1.0/24 -j ACCEPT
PostDown = iptables -D FORWARD -s 10.8.0.0/24 -d 172.16.0.0/16 -j ACCEPT
[Peer]
PublicKey = CLIENT_PUBLIC_KEY_HERE
AllowedIPs = 10.8.0.2/32, 172.16.0.2/32
客户端配置(访问多网段):
[Interface]
PrivateKey = CLIENT_PRIVATE_KEY_HERE
Address = 10.8.0.2/24
DNS = 192.168.1.1
[Peer]
PublicKey = SERVER_PUBLIC_KEY_HERE
Endpoint = SERVER_IP:51820
# VPN网段 + 公司内网段
AllowedIPs = 10.8.0.0/24, 192.168.1.0/24, 172.16.0.0/16
PersistentKeepalive = 25
40.3 特殊场景配置
40.3.1 移动设备配置
针对移动网络优化:
[Interface]
PrivateKey = MOBILE_CLIENT_PRIVATE_KEY
Address = 10.8.0.10/24
DNS = 223.5.5.5, 119.29.29.29
# 移动网络使用较小MTU
MTU = 1280
[Peer]
PublicKey = SERVER_PUBLIC_KEY_HERE
Endpoint = SERVER_IP:51820
AllowedIPs = 0.0.0.0/0
# 移动网络保活间隔缩短
PersistentKeepalive = 15
40.3.2 路由器配置
作为网关的配置:
[Interface]
PrivateKey = ROUTER_PRIVATE_KEY
Address = 10.8.0.100/24
# 设置为内网DNS
DNS = 192.168.1.1
# 启动时配置NAT
PostUp = iptables -t nat -A POSTROUTING -o %i -j MASQUERADE
PostUp = iptables -A FORWARD -i lan0 -o %i -j ACCEPT
PostUp = iptables -A FORWARD -i %i -o lan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
PostDown = iptables -t nat -D POSTROUTING -o %i -j MASQUERADE
PostDown = iptables -D FORWARD -i lan0 -o %i -j ACCEPT
PostDown = iptables -D FORWARD -i %i -o lan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
[Peer]
PublicKey = SERVER_PUBLIC_KEY_HERE
Endpoint = SERVER_IP:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
40.3.3 Docker容器配置
Docker环境WireGuard:
[Interface]
PrivateKey = DOCKER_CLIENT_PRIVATE_KEY
Address = 10.8.0.50/24
DNS = 8.8.8.8
# Docker特定网络配置
PostUp = ip rule add from 172.17.0.0/16 table 200
PostUp = ip route add default via 10.8.0.1 table 200
PostDown = ip rule del from 172.17.0.0/16 table 200
PostDown = ip route del default via 10.8.0.1 table 200
[Peer]
PublicKey = SERVER_PUBLIC_KEY_HERE
Endpoint = SERVER_IP:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
---## 41. 命令速查手册
41.1 WireGuard核心命令
41.1.1 接口管理
# 启动接口
wg-quick up wg0
sudo systemctl start wg-quick@wg0
# 停止接口
wg-quick down wg0
sudo systemctl stop wg-quick@wg0
# 重启接口
wg-quick down wg0 && wg-quick up wg0
sudo systemctl restart wg-quick@wg0
# 重新加载配置(不断开连接)
wg syncconf wg0 <(wg-quick strip wg0)
# 查看接口状态
wg show
wg show wg0
ip link show wg0
ip addr show wg0
41.1.2 查看状态信息
# 查看所有信息
wg show wg0
# 查看公钥
wg show wg0 public-key
# 查看私钥
wg show wg0 private-key
# 查看监听端口
wg show wg0 listen-port
# 查看所有peer
wg show wg0 peers
# 查看peer端点
wg show wg0 endpoints
# 查看允许的IP
wg show wg0 allowed-ips
# 查看最新握手时间
wg show wg0 latest-handshakes
# 查看传输统计
wg show wg0 transfer
# 查看保活设置
wg show wg0 persistent-keepalive
# dump格式输出(脚本友好)
wg show wg0 dump
41.1.3 密钥操作
# 生成私钥
wg genkey
# 从私钥生成公钥
wg pubkey < private.key
echo "PRIVATE_KEY" | wg pubkey
# 生成预共享密钥
wg genpsk
# 一次生成密钥对
wg genkey | tee private.key | wg pubkey > public.key
# 批量生成(10对)
for i in {1..10}; do
wg genkey | tee client${i}_private.key | wg pubkey > client${i}_public.key
done
41.1.4 动态配置
# 添加peer
wg set wg0 peer CLIENT_PUBLIC_KEY allowed-ips 10.8.0.2/32
# 修改peer配置
wg set wg0 peer CLIENT_PUBLIC_KEY \
allowed-ips 10.8.0.2/32 \
endpoint 192.168.1.100:51820 \
persistent-keepalive 25
# 删除peer
wg set wg0 peer CLIENT_PUBLIC_KEY remove
# 修改监听端口
wg set wg0 listen-port 41194
# 设置私钥
wg set wg0 private-key /path/to/private.key
# 保存配置(wg-quick)
wg-quick save wg0
41.2 网络诊断命令
41.2.1 连通性测试
# 基本ping
ping 10.8.0.1
ping -c 10 10.8.0.1
# 指定间隔
ping -i 0.2 10.8.0.1
# 设置包大小
ping -s 1400 10.8.0.1
# 禁止分片(测试MTU)
ping -M do -s 1392 10.8.0.1
# 快速ping
ping -c 100 -i 0.2 -q 10.8.0.1
# ping统计
ping -c 100 10.8.0.1 | grep -E "transmitted|rtt"
41.2.2 路由追踪
# traceroute
traceroute 10.8.0.1
traceroute -n 10.8.0.1 # 不解析域名
traceroute -I 10.8.0.1 # 使用ICMP
# mtr(持续跟踪)
mtr 10.8.0.1
mtr -r -c 100 10.8.0.1 # 报告模式
mtr -n 10.8.0.1 # 不解析域名
41.2.3 端口检查
# netstat
netstat -ulnp | grep 51820
netstat -tunlp | grep 51820
# ss(推荐)
ss -ulnp | grep 51820
ss -tunlp
# lsof
lsof -i :51820
lsof -i UDP:51820
# fuser
fuser 51820/udp
41.2.4 路由查看
# 查看路由表
ip route
ip route show table main
ip route | grep wg0
# 查询特定路由
ip route get 10.8.0.2
ip route get 8.8.8.8
# 查看路由规则
ip rule
ip rule show
# 查看特定路由表
ip route show table 100
41.2.5 抓包分析
# 抓取wg0接口
tcpdump -i wg0
tcpdump -i wg0 -n
tcpdump -i wg0 -nn -v
# 抓取UDP 51820端口
tcpdump -i pnet0 udp port 51820
tcpdump -i pnet0 -nn udp port 51820
# 保存到文件
tcpdump -i wg0 -w capture.pcap
tcpdump -i wg0 -w capture.pcap -c 1000
# 读取文件
tcpdump -r capture.pcap
tcpdump -r capture.pcap -nn
# 过滤ICMP
tcpdump -i wg0 icmp
tcpdump -i wg0 'icmp[icmptype] = icmp-echo'
# 过滤主机
tcpdump -i wg0 host 10.8.0.2
tcpdump -i wg0 src 10.8.0.2
tcpdump -i wg0 dst 10.8.0.1
41.3 系统管理命令
41.3.1 服务管理
# systemctl基础
systemctl start wg-quick@wg0
systemctl stop wg-quick@wg0
systemctl restart wg-quick@wg0
systemctl status wg-quick@wg0
# 开机自启
systemctl enable wg-quick@wg0
systemctl disable wg-quick@wg0
systemctl is-enabled wg-quick@wg0
# 查看服务属性
systemctl show wg-quick@wg0
systemctl cat wg-quick@wg0
# 重新加载systemd
systemctl daemon-reload
# 列出所有WireGuard服务
systemctl list-units | grep wg-quick
41.3.2 日志查看
# journalctl查看服务日志
journalctl -u wg-quick@wg0
journalctl -u wg-quick@wg0 -f # 实时跟踪
journalctl -u wg-quick@wg0 -n 100 # 最近100行
journalctl -u wg-quick@wg0 -r # 倒序
journalctl -u wg-quick@wg0 --since today
journalctl -u wg-quick@wg0 --since "1 hour ago"
journalctl -u wg-quick@wg0 --since "2025-03-23 10:00"
# 按优先级过滤
journalctl -u wg-quick@wg0 -p err
journalctl -u wg-quick@wg0 -p warning
# 格式化输出
journalctl -u wg-quick@wg0 -o json
journalctl -u wg-quick@wg0 -o json-pretty
journalctl -u wg-quick@wg0 -o cat
# dmesg查看内核日志
dmesg | grep wireguard
dmesg -w | grep wireguard # 实时监控
dmesg -T | grep wireguard # 带时间戳
# 传统日志文件
tail -f /var/log/syslog | grep wireguard
grep wireguard /var/log/syslog
41.3.3 防火墙命令
# UFW
ufw status
ufw status verbose
ufw allow 51820/udp
ufw delete allow 51820/udp
ufw enable
ufw disable
# iptables查看
iptables -L -n -v
iptables -L INPUT -n -v
iptables -L FORWARD -n -v
iptables -t nat -L -n -v
iptables -t nat -L POSTROUTING -n -v
# iptables添加规则
iptables -A INPUT -p udp --dport 51820 -j ACCEPT
iptables -A FORWARD -i wg0 -j ACCEPT
iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE
# iptables删除规则
iptables -D INPUT -p udp --dport 51820 -j ACCEPT
iptables -D FORWARD -i wg0 -j ACCEPT
# 按行号删除
iptables -L INPUT -n -v --line-numbers
iptables -D INPUT 5
# 保存规则
iptables-save > /etc/iptables/rules.v4
netfilter-persistent save
# 恢复规则
iptables-restore < /etc/iptables/rules.v4
41.4 性能监控命令
41.4.1 系统监控
# 实时监控
top
htop
top -p $(pgrep -d',' wireguard)
# 负载和运行时间
uptime
w
# CPU信息
lscpu
cat /proc/cpuinfo
mpstat -P ALL 1
# 内存信息
free -h
free -h -s 1 # 每秒刷新
cat /proc/meminfo
# 磁盘使用
df -h
du -sh /var/log/
du -sh /etc/wireguard/
41.4.2 网络监控
# 接口统计
ip -s link show wg0
ip -s -s link show wg0 # 更详细
# 实时流量
iftop -i wg0
nethogs wg0
iptraf-ng
# 带宽测试
iperf3 -s # 服务器端
iperf3 -c 10.8.0.1 # 客户端
iperf3 -c 10.8.0.1 -t 30 # 测试30秒
iperf3 -c 10.8.0.1 -R # 反向测试
iperf3 -c 10.8.0.1 -u -b 100M # UDP测试
# 网络统计
netstat -s
netstat -s | grep -i error
ss -s
41.4.3 性能分析
# 网卡性能
ethtool pnet0
ethtool -S pnet0 # 统计信息
ethtool -k pnet0 # offload特性
ethtool -g pnet0 # ring buffer
# 中断统计
cat /proc/interrupts | grep -E "CPU|wg|pnet"
watch -n 1 'cat /proc/interrupts | grep -E "CPU|wg|pnet"'
# 系统调用跟踪
strace -p $(pgrep -f wg-quick)
# 性能分析
perf top
perf record -g
perf report
41.5 配置管理命令
41.5.1 文件操作
# 查看配置
cat /etc/wireguard/wg0.conf
less /etc/wireguard/wg0.conf
wg-quick strip wg0 # 查看纯配置(无注释)
# 编辑配置
nano /etc/wireguard/wg0.conf
vim /etc/wireguard/wg0.conf
# 验证语法
wg-quick strip wg0 > /dev/null && echo "OK" || echo "Error"
# 备份配置
cp /etc/wireguard/wg0.conf /etc/wireguard/wg0.conf.bak
tar czf /root/wireguard-backup-$(date +%Y%m%d).tar.gz /etc/wireguard/
# 比较配置
diff /etc/wireguard/wg0.conf /etc/wireguard/wg0.conf.bak
41.5.2 权限管理
# 查看权限
ls -l /etc/wireguard/
ls -l /etc/wireguard/*.key
stat /etc/wireguard/wg0.conf
# 设置权限
chmod 600 /etc/wireguard/wg0.conf
chmod 600 /etc/wireguard/*.key
chown root:root /etc/wireguard/*
# 检查权限
find /etc/wireguard -type f -ls
find /etc/wireguard -type f ! -perm 600
41.6 故障排查命令
41.6.1 快速检查
# 一键检查脚本
cat << 'EOF' > /tmp/wg-check.sh
#!/bin/bash
echo "=== Quick WireGuard Check ==="
echo "Service: $(systemctl is-active wg-quick@wg0)"
echo "Interface: $(ip link show wg0 &>/dev/null && echo OK || echo MISSING)"
echo "Port: $(ss -ulnp | grep :51820 &>/dev/null && echo LISTENING || echo NOT_LISTENING)"
echo "Firewall: $(iptables -L INPUT -n | grep 51820 &>/dev/null && echo ALLOWED || echo BLOCKED)"
echo "IP Forward: $(sysctl -n net.ipv4.ip_forward)"
echo "Peers: $(wg show wg0 peers | wc -l)"
EOF
bash /tmp/wg-check.sh
41.6.2 诊断工具
# 网络连通性
ping -c 3 10.8.0.1
curl -I http://10.8.0.1:5000/health
nc -zvu 192.168.1.66 51820
# DNS测试
nslookup google.com
dig google.com
host google.com
# 路由测试
traceroute -n 8.8.8.8
mtr -r -c 10 8.8.8.8
# MTU测试
ping -M do -s 1392 10.8.0.1 -c 3
for size in 1472 1392 1280; do
ping -M do -s $size -c 1 10.8.0.1 &>/dev/null && echo "$size OK" || echo "$size FAIL"
done
42. 参考资料
42.1 官方文档
42.1.1 WireGuard官方
网站和文档:
- WireGuard官网:https://www.wireguard.com/
- 官方文档:https://www.wireguard.com/quickstart/
- 白皮书:https://www.wireguard.com/papers/wireguard.pdf
- 源代码:https://git.zx2c4.com/wireguard-linux/
- GitHub:https://github.com/WireGuard
技术规范:
- Protocol Specification:https://www.wireguard.com/protocol/
- Cryptography:https://www.wireguard.com/papers/
- Performance:https://www.wireguard.com/performance/
42.1.2 Linux内核文档
官方内核文档:
- WireGuard in Linux Kernel:https://www.kernel.org/doc/html/latest/networking/wireguard.html
- Netdevice Documentation:https://www.kernel.org/doc/Documentation/networking/
- IPsec vs WireGuard:内核文档对比
42.2 技术文档
42.2.1 加密算法
ChaCha20-Poly1305:
- RFC 7539:ChaCha20 and Poly1305 for IETF Protocols https://tools.ietf.org/html/rfc7539
Curve25519:
- Curve25519: New Diffie-Hellman Speed Records 作者:Daniel J. Bernstein https://cr.yp.to/ecdh.html
Noise Protocol:
- Noise Protocol Framework http://noiseprotocol.org/
- Noise_IK Pattern(WireGuard使用) http://noiseprotocol.org/noise.html#interactive-handshake-patterns
HKDF:
- RFC 5869:HMAC-based Extract-and-Expand Key Derivation Function https://tools.ietf.org/html/rfc5869
42.2.2 网络协议
UDP:
- RFC 768:User Datagram Protocol https://tools.ietf.org/html/rfc768
IP:
- RFC 791:Internet Protocol https://tools.ietf.org/html/rfc791
- RFC 2460:Internet Protocol Version 6 https://tools.ietf.org/html/rfc2460
42.3 性能优化
42.3.1 网络调优
Linux网络优化:
- Linux Network Tuning Guide https://fasterdata.es.net/network-tuning/linux/
BBR拥塞控制:
- BBR: Congestion-Based Congestion Control Google技术博客 https://cloud.google.com/blog/products/networking/tcp-bbr-congestion-control-comes-to-gcp
TCP优化:
- Red Hat Performance Tuning Guide https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/monitoring_and_managing_system_status_and_performance/
42.3.2 系统优化
内核参数:
- Linux Kernel Networking Documentation https://www.kernel.org/doc/Documentation/networking/
中断优化:
- Interrupt Affinity and SMP Red Hat文档
42.4 安全加固
42.4.1 安全基准
CIS Benchmark:
- CIS Ubuntu Linux Benchmark Center for Internet Security https://www.cisecurity.org/benchmark/ubuntu_linux
NIST指南:
- NIST Special Publication 800-53 Security and Privacy Controls https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-53r5.pdf
42.4.2 审计和日志
Linux Audit:
- Linux Audit Documentation https://github.com/linux-audit/audit-documentation/wiki
fail2ban:
- fail2ban Documentation https://www.fail2ban.org/wiki/index.php/Main_Page
OSSEC:
- OSSEC Host Intrusion Detection System https://www.ossec.net/docs/
42.5 工具和实用程序
42.5.1 网络工具
iperf3:
- iperf3 Documentation https://iperf.fr/iperf-doc.php
mtr:
- mtr Documentation https://www.bitwizard.nl/mtr/
tcpdump:
- tcpdump Manual https://www.tcpdump.org/manpages/tcpdump.1.html
42.5.2 系统工具
systemd:
- systemd Documentation https://www.freedesktop.org/wiki/Software/systemd/
iptables:
42.6 社区资源
42.6.1 论坛和讨论
-
WireGuard Mailing List https://lists.zx2c4.com/mailman/listinfo/wireguard
-
Reddit r/WireGuard https://www.reddit.com/r/WireGuard/
-
Stack Overflow 标签:[wireguard]
42.6.2 第三方教程
Arch Linux Wiki:
Debian Wiki:
- WireGuard https://wiki.debian.org/WireGuard
Ubuntu Documentation:
- WireGuard VPN https://ubuntu.com/server/docs/wireguard-vpn
42.7 相关书籍
-
《WireGuard VPN: Secure and Fast VPN》
- 作者:Jason A. Donenfeld等
- 深入讲解WireGuard技术细节
-
《Linux Network Administrator’s Guide》
- 作者:Tony Bautts等
- O’Reilly Media
- 第三版,涵盖现代Linux网络
-
《TCP/IP Illustrated》
- 作者:W. Richard Stevens
- Addison-Wesley
- 经典网络协议书籍
-
《Applied Cryptography》
- 作者:Bruce Schneier
- Wiley
- 密码学基础
43. 术语表
43.1 WireGuard术语
| 术语 | 英文全称 | 中文解释 |
|---|---|---|
| WireGuard | - | 现代、快速、安全的VPN协议 |
| Peer | Peer | 对等节点,WireGuard中的连接端点 |
| Interface | Network Interface | 网络接口,如wg0 |
| Handshake | Cryptographic Handshake | 加密握手,建立安全连接的过程 |
| Endpoint | Network Endpoint | 网络端点,peer的IP地址和端口 |
| AllowedIPs | Allowed IP Addresses | 允许的IP地址范围,用于路由和访问控制 |
| PrivateKey | Private Key | 私钥,用于解密和签名 |
| PublicKey | Public Key | 公钥,用于加密和验证 |
| PSK | Pre-Shared Key | 预共享密钥,额外的对称加密层 |
| PersistentKeepalive | - | 持久保活,定期发送包保持连接 |
43.2 网络术语
| 术语 | 英文全称 | 中文解释 |
|---|---|---|
| MTU | Maximum Transmission Unit | 最大传输单元,网络层最大数据包大小 |
| MSS | Maximum Segment Size | 最大段大小,TCP层最大数据段 |
| NAT | Network Address Translation | 网络地址转换 |
| SNAT | Source NAT | 源地址转换 |
| DNAT | Destination NAT | 目标地址转换 |
| MASQUERADE | - | IP伪装,动态源NAT |
| TTL | Time To Live | 生存时间,IP包最大跳数 |
| RTT | Round-Trip Time | 往返时间,延迟指标 |
| Throughput | - | 吞吐量,单位时间传输的数据量 |
| Latency | - | 延迟,数据传输所需时间 |
| Jitter | - | 抖动,延迟变化幅度 |
| Packet Loss | - | 丢包,数据包未到达目的地的比率 |
43.3 加密术语
| 术语 | 英文全称 | 中文解释 |
|---|---|---|
| ChaCha20 | - | 流密码算法,用于数据加密 |
| Poly1305 | - | 消息认证码,用于数据完整性 |
| AEAD | Authenticated Encryption with Associated Data | 关联数据认证加密 |
| Curve25519 | - | 椭圆曲线,用于密钥交换 |
| BLAKE2s | - | 哈希函数,用于密钥派生 |
| HKDF | HMAC-based Key Derivation Function | 基于HMAC的密钥派生函数 |
| DH | Diffie-Hellman | 密钥交换协议 |
| ECDH | Elliptic Curve Diffie-Hellman | 椭圆曲线密钥交换 |
| Nonce | Number Once | 一次性数字,防重放 |
| Salt | - | 盐值,增加密钥随机性 |
43.4 系统术语
| 术语 | 英文全称 | 中文解释 |
|---|---|---|
| systemd | - | Linux系统和服务管理器 |
| iptables | - | Linux防火墙管理工具 |
| ufw | Uncomplicated Firewall | 简化的防火墙管理工具 |
| netfilter | - | Linux内核网络包过滤框架 |
| sysctl | System Control | 系统内核参数配置工具 |
| journalctl | Journal Control | systemd日志查看工具 |
| BBR | Bottleneck Bandwidth and RTT | 拥塞控制算法 |
| TCP | Transmission Control Protocol | 传输控制协议 |
| UDP | User Datagram Protocol | 用户数据报协议 |
| ICMP | Internet Control Message Protocol | 互联网控制消息协议 |
43.5 性能优化术语
| 术语 | 英文全称 | 中文解释 |
|---|---|---|
| RPS | Receive Packet Steering | 接收包控制 |
| RSS | Receive Side Scaling | 接收端扩展 |
| XPS | Transmit Packet Steering | 发送包控制 |
| TSO | TCP Segmentation Offload | TCP分段卸载 |
| GSO | Generic Segmentation Offload | 通用分段卸载 |
| GRO | Generic Receive Offload | 通用接收卸载 |
| LRO | Large Receive Offload | 大接收卸载 |
| IRQ | Interrupt Request | 中断请求 |
| CPU Affinity | - | CPU亲和性,绑定进程到特定CPU |
| NUMA | Non-Uniform Memory Access | 非一致性内存访问 |
| Hugepages | - | 大页内存,提高内存管理效率 |
| I/O Scheduler | - | I/O调度器,优化磁盘访问 |
44. 快速参考卡
44.1 紧急救援卡
╔══════════════════════════════════════════════════════════════╗
║ WireGuard紧急救援参考卡 ║
╠══════════════════════════════════════════════════════════════╣
║ 问题:VPN无法连接 ║
║ 1. systemctl status wg-quick@wg0 # 检查服务 ║
║ 2. ip link show wg0 # 检查接口 ║
║ 3. ss -ulnp | grep 51820 # 检查端口 ║
║ 4. wg show wg0 # 查看配置 ║
║ 5. journalctl -u wg-quick@wg0 -n 50 # 查看日志 ║
╠══════════════════════════════════════════════════════════════╣
║ 问题:连接后无法访问互联网 ║
║ 1. sysctl net.ipv4.ip_forward # 检查IP转发 ║
║ 2. iptables -t nat -L -n -v # 检查NAT ║
║ 3. ip route | grep default # 检查路由 ║
║ 修复: ║
║ sysctl -w net.ipv4.ip_forward=1 ║
║ iptables -t nat -A POSTROUTING -o pnet0 -j MASQUERADE ║
╠═══════════════════════════════════════════════════════════════╣
║ 问题:速度很慢 ║
║ 1. ping -c 10 10.8.0.1 # 测试延迟 ║
║ 2. iperf3 -c 10.8.0.1 # 测试带宽 ║
║ 3. top # 检查CPU ║
║ 优化: ║
║ ip link set wg0 mtu 1280 # 降低MTU ║
║ sysctl -w net.ipv4.tcp_congestion_control=bbr # 启用BBR ║
╠═══════════════════════════════════════════════════════════════╣
║ 问题:频繁断开 ║
║ 修改配置:PersistentKeepalive = 15 ║
║ 重新加载:wg syncconf wg0 <(wg-quick strip wg0) ║
╠═══════════════════════════════════════════════════════════════╣
║ 紧急重启 ║
║ systemctl restart wg-quick@wg0 ║
║ 完全重置 ║
║ wg-quick down wg0 ║
║ ip link delete wg0 ║
║ wg-quick up wg0 ║
╠═══════════════════════════════════════════════════════════════╣
║ 备份配置 ║
║ tar czf wireguard-backup.tar.gz /etc/wireguard/ ║
║ 恢复配置 ║
║ tar xzf wireguard-backup.tar.gz -C / ║
╚═══════════════════════════════════════════════════════════════╝
44.2 一页命令卡
╔═══════════════════════════════════════════════════════════════╗
║ WireGuard命令速查卡 ║
╠═══════════════════════════════════════════════════════════════╣
║ 基本操作 ║
║ ┌───────────────────────────────────────────────────────────┐ ║
║ │ 启动 wg-quick up wg0 │ ║
║ │ 停止 wg-quick down wg0 │ ║
║ │ 状态 wg show wg0 │ ║
║ │ 重载 wg syncconf wg0 <(wg-quick strip wg0) │ ║
║ └───────────────────────────────────────────────────────────┘ ║
╠═══════════════════════════════════════════════════════════════╣
║ 密钥管理 ║
║ ┌───────────────────────────────────────────────────────────┐ ║
║ │ 生成 wg genkey | tee private.key | wg pubkey > pub.key │ ║
║ │ PSK wg genpsk │ ║
║ └───────────────────────────────────────────────────────────┘ ║
╠═══════════════════════════════════════════════════════════════╣
║ 诊断命令 ║
║ ┌───────────────────────────────────────────────────────────┐ ║
║ │ 服务 systemctl status wg-quick@wg0 │ ║
║ │ 日志 journalctl -u wg-quick@wg0 -f │ ║
║ │ 端口 ss -ulnp | grep 51820 │ ║
║ │ 路由 ip route | grep wg0 │ ║
║ │ 测试 ping 10.8.0.1 │ ║
║ └───────────────────────────────────────────────────────────┘ ║
╠═══════════════════════════════════════════════════════════════╣
║ 配置位置 ║
║ ┌───────────────────────────────────────────────────────────┐ ║
║ │ 服务器 /etc/wireguard/wg0.conf │ ║
║ │ 密钥 /etc/wireguard/*.key │ ║
║ │ 客户端 /etc/wireguard/clients/ │ ║
║ └───────────────────────────────────────────────────────────┘ ║
╠═══════════════════════════════════════════════════════════════╣
║ 重要参数 ║
║ ┌───────────────────────────────────────────────────────────┐ ║
║ │ IP转发 sysctl net.ipv4.ip_forward │ ║
║ │ 防火墙 ufw allow 51820/udp │ ║
║ │ NAT iptables -t nat -A POSTROUTING -j MASQUERADE │ ║
║ │ MTU ip link set wg0 mtu 1420 │ ║
║ │ 保活 PersistentKeepalive = 25 │ ║
║ └───────────────────────────────────────────────────────────┘ ║
╠═══════════════════════════════════════════════════════════════╣
║ 网络地址 ║
║ ┌───────────────────────────────────────────────────────────┐ ║
║ │ 服务器 10.8.0.1/24 │ ║
║ │ 客户端 10.8.0.2-254/24 │ ║
║ │ 端口 51820/UDP │ ║
║ └───────────────────────────────────────────────────────────┘ ║
╚═══════════════════════════════════════════════════════════════╝
44.3 故障码速查
错误码速查表
| 错误类型 | 典型症状 | 快速修复 |
|---|---|---|
| 服务未启动 | inactive / failed | systemctl start wg-quick@wg0 |
| 配置错误 | parsing error | wg-quick strip wg0 |
| 端口占用 | address in use | fuser -k 51820/udp |
| 权限不足 | permission denied | chmod 600 wg0.conf |
| 接口不存在 | cannot find device | wg-quick up wg0 |
| 握手失败 | invalid handshake | 检查密钥匹配 |
| 无法访问网络 | network unreachable | 检查IP转发和NAT |
| MTU问题 | 大包丢失 | ip link set wg0 mtu 1280 |