使用WireGuard+Iptables实现高性能内网穿透

wireguard和iptables都是内核级的软件,理论上性能会高于frp(没对比过实际的性能表现),感兴趣的可以试一试

本文将以debian12作为演示

1.在客户端和服务端上均安装WireGuard和配置wg密钥

apt install wireguard -y
wg genkey | tee privatekey | wg pubkey > publickey

会在当前目录生成,publickey是公钥,privatekey是私钥
什么?你问windows怎么办,windows对wireguard没有内核级别的支持,还是老实用frp吧

2.配置服务端wireguard

首先服务的需要有一个udp端口用于wireguard的通信,记得开启端口,本文以10001端口示例

iptables -I INPUT -p UDP --dport 10001 -j ACCEPT

接着配置服务端的wg配置文件

在 /etc/wireguard 目录下新建一个名为 <隧道名>.conf 的文件:

[Interface]
Address = 10.0.100.1/24
ListenPort = 10001
PrivateKey = 你服务端生成的私钥

[Peer]
PublicKey = 客户端的公钥
AllowedIPs = 10.0.100.2/32

接着使用 wg-quick up <隧道名> 启动隧道

3.配置客户端wireguard

在 /etc/wireguard 目录下新建一个名为 <隧道名>.conf 的文件:

[Interface]
Address = 10.0.100.2/24
ListenPort = 客户端监听的端口,随意
PrivateKey = 客户端的私钥

[Peer]
PublicKey = 服务端的公钥
AllowedIPs = 10.0.100.1/32
Endpoint = 服务端的ip:端口,例如1.1.1.1:10001
PersistentKeepalive = 30

接着使用 wg-quick up <隧道名> 启动隧道

确保客户端和服务端的隧道都正常启动后,使用ping检查隧道联通性,客户端和服务端互相ping对方的隧道ip,例如本文中服务端的隧道ip是10.0.100.1,客户端的隧道ip为10.0.100.2,如果能ping通,进行接下来的操作

配置服务端iptables实现端口转发

开启ip转发

echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sysctl -p

配置NAT端口转发

iptables -t nat -A PREROUTING -p tcp --dport <服务端对外端口> -j DNAT --to-destination <客户端隧道ip:客户端要转发的端口号>
iptables -t nat -A POSTROUTING -d <客户端隧道ip> -p tcp --dport <客户端要转发的端口号> -j SNAT --to <服务端隧道ip>

#例如把映射客户端的80端口到服务端的8888端口,应该这样配置
#iptables -t nat -A PREROUTING -p tcp --dport 8888 -j DNAT --to-destination 10.0.100.2:80
#iptables -t nat -A POSTROUTING -d 10.0.100.2 -p tcp --dport 80 -j SNAT --to 10.0.100.1

在iptables放行转发的端口

iptables -I INPUT -p tcp --dport 8888 -j ACCEPT

接下来一切顺利的话,内网穿透完成,按照本文的示例配置访问服务端的8888端口将转发到客户端的80端口

评论

  1. 5月前
    2023-6-29 21:07:47

    这个方案不错(☆ω☆),可以试试详细介绍一下WireGuard和iptables的实现原理

发送评论 编辑评论


				

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇