galang-rs/wireguard

GitHub: galang-rs/wireguard

纯 Go 实现的 WireGuard VPN 客户端库,支持用户空间 TUN 设备,无需 CGo 和系统驱动即可创建加密隧道。

Stars: 0 | Forks: 0

Go Version License MIT Platform Status

🔐 WireGuard Go

一个纯 Go 实现的 WireGuard VPN 客户端,支持用户空间 TUN 设备。
无需 CGo。无需系统驱动。隧道本身无需 root 权限。

从零构建,严格遵循官方 WireGuard 白皮书 — 实现了完整的 Noise IKpsk2 握手、ChaCha20-Poly1305 传输加密,并通过虚拟 TUN 接口进行原始 IP 数据包 I/O。

## ✨ 功能特性 ### 🛡️ 完整的 WireGuard 协议 - **Noise IKpsk2 握手** — 完整实现 WireGuard 加密握手 - **Curve25519 DH** — 椭圆曲线 Diffie-Hellman 密钥交换 - **ChaCha20-Poly1305 AEAD** — 用于握手和传输的认证加密 - **BLAKE2s 哈希与 HMAC** — 用于密钥派生 (KDF1/KDF2/KDF3) 和 MAC 计算 - **TAI64N 时间戳** — 通过单调时间戳防止重放攻击 - **预共享密钥 (PSK)** — 可选的额外对称密钥安全层 - **MAC1 & MAC2** — 通过 BLAKE2s-128 防止拒绝服务攻击 ### 🌐 用户空间 TUN 设备 - **纯 Go 实现** — 无需内核 TUN/TAP 驱动 - **原始 IP 数据包 I/O** — 通过 VPN 隧道读写原始 IPv4/IPv6 数据包 - **`net.Conn` 兼容接口** — 实现了 `Read()`、`Write()`、`LocalAddr()`、`RemoteAddr()` - **隧道信息访问** — 通过 `TunnelInfo()` 获取分配的 IP、网关、MTU、DNS ### ⚙️ 架构 - **分层传输栈** — NetworkIO → Muxer → 握手/数据工作器 - **并发工作器模型** — 所有协议层作为独立的 goroutine 运行 - **基于 Channel 的消息传递** — 工作器之间零共享可变状态 - **优雅关闭** — 具有协调关闭序列的工作器管理器 - **函数式选项模式** — 灵活的 `Config`,支持 `WithConfigFile()`、`WithLogger()` 等 ### 📝 配置 - **标准 `.conf` 解析器** — 读取 WireGuard INI 风格的配置文件 - **完整配置支持:** - `[Interface]` — `PrivateKey`、`Address`、`DNS`、`MTU` - `[Peer]` — `PublicKey`、`PresharedKey`、`Endpoint`、`AllowedIPs`、`PersistentKeepalive` - **Base64 密钥编解码** — 标准的 32 字节 WireGuard 密钥 - **配置验证** — 确保存在最低要求的字段 ### 🧪 测试 - **集成测试** — 基于 TUN 的 TCP 握手真实 VPN 连接测试 - **HTTP 出口 IP 验证** — 确认流量通过 VPN 出口 - **原始 TCP 数据包构建器** — 完整的 IPv4 + TCP 数据包构建及校验和 ## 📦 安装 ``` go get github.com/galang-rs/wireguard ``` ## 🚀 如何使用 ### 作为库使用 ``` package main import ( "context" "fmt" "net" "github.com/galang-rs/wireguard/pkg/config" "github.com/galang-rs/wireguard/pkg/tunnel" ) func main() { // 1. Load configuration from .conf file cfg := config.NewConfig(config.WithConfigFile("wg0.conf")) // 2. Start the VPN tunnel ctx := context.Background() tun, err := tunnel.Start(ctx, &net.Dialer{}, cfg) if err != nil { panic(err) } defer tun.Close() // 3. Get tunnel info ti := tun.TunnelInfo() fmt.Printf("Tunnel IP: %s/%s\n", ti.IP, ti.NetMask) fmt.Printf("Gateway: %s\n", ti.GW) fmt.Printf("MTU: %d\n", ti.MTU) // 4. Read/Write raw IP packets buf := make([]byte, 4096) n, _ := tun.Read(buf) // Read decrypted IP packet from VPN fmt.Printf("Received %d bytes\n", n) // tun.Write(ipPacket) // Send IP packet through VPN } ``` ### 作为 CLI 使用 ``` # 构建 CLI go build -o wg ./cmd/wg/ # 使用 config file 运行 ./wg wg0.conf # 或使用默认(当前目录下的 wg0.conf) ./wg ``` ### 使用编程方式配置 ``` cfg := config.NewConfig( config.WithWireGuardOptions(&config.WireGuardOptions{ PrivateKey: myPrivateKey, // [32]byte Address: "10.0.0.2/24", DNS: []string{"1.1.1.1", "8.8.8.8"}, MTU: 1420, Peer: config.PeerOptions{ PublicKey: peerPubKey, // [32]byte Endpoint: "vpn.example.com:51820", AllowedIPs: []string{"0.0.0.0/0", "::/0"}, PersistentKeepalive: 25, }, }), config.WithLogger(myCustomLogger), ) ``` ### WireGuard 配置文件格式 ``` [Interface] PrivateKey = Address = 10.0.0.2/24 DNS = 1.1.1.1, 8.8.8.8 MTU = 1420 [Peer] PublicKey = PresharedKey = Endpoint = vpn.example.com:51820 AllowedIPs = 0.0.0.0/0, ::/0 PersistentKeepalive = 25 ``` ### 运行测试 ``` # 运行 integration test(需要有效的 .conf 和 active VPN server) go test ./pkg/vpn/... -v -run TestWGConnectSurfshark -timeout 120s ``` ## 🏗️ 项目结构 ``` wireguard/ ├── cmd/ │ └── wg/ │ └── main.go # CLI entry point ├── internal/ │ ├── bytesx/ # Byte utilities │ ├── crypto/ │ │ ├── noise.go # Noise IKpsk2 protocol primitives │ │ ├── keypair.go # Transport encryption keypair │ │ └── mac.go # MAC1/MAC2 computation │ ├── domain/ │ │ ├── message.go # WireGuard message types │ │ └── session.go # Session state & TunnelInfo │ ├── optional/ # Generic Optional type │ ├── session/ │ │ └── manager.go # Session manager (handshake state machine) │ ├── transport/ │ │ ├── data/ # Data channel worker │ │ ├── handshake/ # Handshake worker │ │ ├── muxer/ # Protocol demuxer │ │ └── networkio/ # UDP I/O layer │ ├── tunstack/ │ │ └── tun.go # Userspace TUN device │ └── worker/ │ └── manager.go # Goroutine lifecycle manager ├── pkg/ │ ├── config/ │ │ ├── config.go # Config + functional options │ │ ├── options.go # WireGuardOptions & PeerOptions │ │ └── parser.go # .conf file parser │ ├── tunnel/ │ │ └── tunnel.go # Public tunnel API │ └── vpn/ │ └── vpn_test.go # Integration tests ├── go.mod └── go.sum ``` ## 🔧 依赖 | Package | Purpose | |---------|---------| | `golang.org/x/crypto` | Curve25519, ChaCha20-Poly1305, BLAKE2s | | `golang.org/x/sys` | 系统级支持 (间接) | 除 Go 扩展标准库外,**零外部依赖**。 ## 📄 许可证 ``` MIT License Copyright (c) 2026 Galang Reisduanto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- ADDITIONAL TERMS: 1. Attribution — If you use this software in a product, an acknowledgment in the product documentation or "About" section would be appreciated but is not required. 2. Non-Endorsement — The name "galang-rs" or "Galang Reisduanto" may not be used to endorse or promote products derived from this software without specific prior written permission. 3. Good Faith — This software is shared in good faith for the benefit of the open-source community. Commercial use is permitted and encouraged. ``` ## 📬 功能请求与联系 有想法、Bug 报告或自定义功能请求?欢迎联系!

Email

📧 邮箱: galangreisduanto@gmail.com

标签:BLAKE2s, ChaCha20-Poly1305, Curve25519, EVTX分析, Google搜索, Go语言, IKpsk2握手, Noise协议框架, TUN虚拟网卡, VPN, WireGuard, 代理工具, 加密通信, 协议实现, 日志审计, 用户态网络, 程序破解, 纯Go实现, 网络协议栈, 网络安全, 网络安全, 隐私保护, 隐私保护, 隧道, 零CGo