feat: add ping keepalive support for OpenVPN (#2859)

This commit is contained in:
puppywang authored and GitHub committed 2026-06-02 11:33:59 +08:00
1 parent bd72c65b5e
commit 90b1066e1a
8 files changed
+220 -73

No files matched your search

+81 -29
View File
@@ -8,6 +8,7 @@ import (
"net/netip"
"os"
"sync"
"time"
"github.com/metacubex/mihomo/common/contextutils"
"github.com/metacubex/mihomo/component/dialer"
@@ -41,22 +42,24 @@ type OpenVPN struct {
type OpenVPNOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CompLZO string `proxy:"comp-lzo,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Proto string `proxy:"proto,omitempty"`
Dev string `proxy:"dev,omitempty"`
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CompLZO string `proxy:"comp-lzo,omitempty"`
CA string `proxy:"ca"`
Cert string `proxy:"cert,omitempty"`
Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt,omitempty"`
Username string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
Ping int `proxy:"ping,omitempty"`
PingRestart int `proxy:"ping-restart,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
Dns []string `proxy:"dns,omitempty"`
@@ -64,19 +67,21 @@ type OpenVPNOption struct {
func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
cfg := &ovpn.ClientConfig{
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
RemoteHost: option.Server,
RemotePort: uint16(option.Port),
Proto: option.Proto,
Dev: option.Dev,
Cipher: option.Cipher,
Auth: option.Auth,
CompLZO: option.CompLZO,
CA: []byte(option.CA),
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
Username: option.Username,
Password: option.Password,
PingInterval: time.Duration(option.Ping) * time.Second,
PingRestart: time.Duration(option.PingRestart) * time.Second,
}
if err := cfg.Prepare(); err != nil {
return nil, err
@@ -401,4 +406,51 @@ func (o *OpenVPN) startPacketLoops() {
}
}
}()
if o.config.PingInterval > 0 {
go func() {
defer stop()
ticker := time.NewTicker(o.config.PingInterval)
defer ticker.Stop()
for runCtx.Err() == nil {
select {
case <-ticker.C:
if sinceSend := client.SinceSend(); sinceSend >= o.config.PingInterval {
if err := client.WritePing(runCtx); err != nil {
if !errors.Is(err, context.Canceled) && !errors.Is(err, net.ErrClosed) {
log.Warnln("[OpenVPN](%s) error writing ping packet: %v", o.name, err)
}
return
}
log.Debugln("[OpenVPN](%s) sent ping packet after %s idle", o.name, sinceSend.Round(time.Second))
}
case <-runCtx.Done():
return
}
}
}()
}
if o.config.PingRestart > 0 {
go func() {
defer stop()
ticker := time.NewTicker(o.config.PingRestart)
defer ticker.Stop()
for runCtx.Err() == nil {
select {
case <-ticker.C:
if sinceReceive := client.SinceReceive(); sinceReceive >= o.config.PingRestart {
log.Warnln(
"[OpenVPN](%s) ping-restart timeout: no packet received for %s",
o.name,
sinceReceive.Round(time.Second),
)
return
}
case <-runCtx.Done():
return
}
}
}()
}
}
+2
View File
@@ -1199,6 +1199,8 @@ proxies: # socks5
# 00000000000000000000000000000000
# ...
# -----END OpenVPN Static key V1-----
# ping: 10 # 默认值为 0
# ping-restart: 60 # 默认值为 0
# mtu: 1500
udp: true
# 一个出站代理的标识。当值不为空时,将使用指定的 proxy 发出连接
+68 -4
View File
@@ -9,9 +9,11 @@ import (
"io"
"net"
"strings"
"sync/atomic"
"time"
"github.com/metacubex/tls"
"golang.org/x/sync/semaphore"
)
const (
@@ -29,6 +31,11 @@ type Client struct {
push *PushReply
cancel context.CancelFunc
writeSem semaphore.Weighted
lastSendNano atomic.Int64
lastReceiveNano atomic.Int64
}
func NewClient(config *ClientConfig, io PacketIO) (*Client, error) {
@@ -53,12 +60,15 @@ func NewClient(config *ClientConfig, io PacketIO) (*Client, error) {
runCtx, cancel := context.WithCancel(context.Background())
mux := NewPacketMux(io)
go mux.Run(runCtx)
return &Client{
client := &Client{
config: config,
mux: mux,
control: NewControlChannel(mux, crypt, local),
cancel: cancel,
}, nil
}
client.markSend()
client.markReceive()
return client, nil
}
func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
@@ -126,22 +136,48 @@ func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
return nil, err
}
c.push = push
c.data, err = NewDataChannel(keys, c.config.Cipher, c.config.Auth, push.PeerID, c.config.CompLZO)
c.data, err = NewDataChannel(keys, c.config.Cipher, c.config.Auth, push.PeerID)
if err != nil {
return nil, err
}
c.markSend()
c.markReceive()
return push, nil
}
func (c *Client) WriteIPPacket(ctx context.Context, packet []byte) error {
return c.writeDataPacket(ctx, packet, true)
}
func (c *Client) WritePing(ctx context.Context) error {
return c.writeDataPacket(ctx, openVPNPingPacket, false)
}
func (c *Client) writeDataPacket(ctx context.Context, packet []byte, compress bool) error {
if c.data == nil {
return errors.New("openvpn data channel is not ready")
}
if err := c.writeSem.Acquire(ctx, 1); err != nil {
return err
}
defer c.writeSem.Release(1)
if compress && c.config.CompLZO == CompLzoYes {
compressed, err := lzo1xCompressSafe(packet)
if err != nil {
return err
}
packet = compressed
}
encrypted, err := c.data.Encrypt(packet)
if err != nil {
return err
}
return c.mux.WritePacket(ctx, encrypted)
err = c.mux.WritePacket(ctx, encrypted)
if err != nil {
return err
}
c.markSend()
return nil
}
func (c *Client) ReadIPPacket(ctx context.Context) ([]byte, error) {
@@ -157,10 +193,38 @@ func (c *Client) ReadIPPacket(ctx context.Context) ([]byte, error) {
if err != nil {
continue
}
c.markReceive()
if IsPingPacket(plain) {
continue
}
if c.config.CompLZO == CompLzoYes && len(plain) > 0 {
return lzo1xDecompressSafe(plain)
}
return plain, nil
}
}
func (c *Client) SinceSend() time.Duration {
return time.Duration(int64(time.Since(start)) - c.lastSendNano.Load())
}
func (c *Client) SinceReceive() time.Duration {
return time.Duration(int64(time.Since(start)) - c.lastReceiveNano.Load())
}
func (c *Client) markSend() {
c.lastSendNano.Store(int64(time.Since(start)))
}
func (c *Client) markReceive() {
c.lastReceiveNano.Store(int64(time.Since(start)))
}
// The absolute value doesn't matter, but it should be in the past,
// so that every timestamp obtained with Now() is non-zero,
// even on systems with low timer resolutions (e.g. Windows).
var start = time.Now().Add(-time.Hour)
func (c *Client) Close() error {
if c.cancel != nil {
c.cancel()
+10
View File
@@ -9,6 +9,7 @@ import (
"net"
"strconv"
"strings"
"time"
)
const (
@@ -50,6 +51,9 @@ type ClientConfig struct {
Username string
Password string
PingInterval time.Duration
PingRestart time.Duration
TLSCryptKey []byte
}
@@ -182,6 +186,12 @@ func (c *ClientConfig) ValidateInstallScriptSubset() error {
} else if strings.TrimSpace(c.Username) == "" {
return errors.New("openvpn requires either cert+key or username (auth-user-pass)")
}
if c.PingInterval < 0 {
return errors.New("openvpn ping interval must be positive")
}
if c.PingRestart < 0 {
return errors.New("openvpn ping restart must be positive")
}
return nil
}
+19 -32
View File
@@ -1,6 +1,7 @@
package openvpn
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
@@ -28,6 +29,18 @@ const (
PeerIDUnset uint32 = 0xffffff
)
// OpenVPN data-channel ping payload, matching PING_STRING in upstream OpenVPN.
var openVPNPingPacket = []byte{
0x2a, 0x18, 0x7b, 0xf3,
0x64, 0x1e, 0xb4, 0xcb,
0x07, 0xed, 0x2d, 0x0a,
0x98, 0x1f, 0xc7, 0x48,
}
func IsPingPacket(packet []byte) bool {
return bytes.Equal(packet, openVPNPingPacket)
}
type DataChannel struct {
sendAEAD cipher.AEAD
recvAEAD cipher.AEAD
@@ -44,10 +57,9 @@ type DataChannel struct {
sendImplicitIV [DataChannelIVSize]byte
recvImplicitIV [DataChannelIVSize]byte
keyID uint8
peerID uint32
header []byte
compLZO string
keyID uint8
peerID uint32
header []byte
mu sync.Mutex
sendPacketID uint32
@@ -60,7 +72,7 @@ type DataChannel struct {
randOffset int
}
func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint32, compLZO string) (*DataChannel, error) {
func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint32) (*DataChannel, error) {
if keys == nil {
return nil, errors.New("nil openvpn key material")
}
@@ -81,7 +93,6 @@ func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint3
recvAEAD: recv,
peerID: peerID,
header: dataHeader(peerID, 0),
compLZO: compLZO,
}
copy(d.sendImplicitIV[4:], keys.SendHMACKey[:DataChannelIVSize-4])
copy(d.recvImplicitIV[4:], keys.RecvHMACKey[:DataChannelIVSize-4])
@@ -112,7 +123,6 @@ func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint3
authSize: authSize,
peerID: peerID,
header: dataHeader(peerID, 0),
compLZO: compLZO,
}
d.sendMACPool.New = func() any {
return hmac.New(d.authHash, d.sendHMACKey)
@@ -178,14 +188,6 @@ func (d *DataChannel) Encrypt(packet []byte) ([]byte, error) {
return nil, errors.New("nil openvpn data channel")
}
// Prepend comp-lzo header (0xfa = not compressed) to satisfy servers expecting the framing.
if d.compLZO == CompLzoYes {
lzoPacket := make([]byte, 1+len(packet))
lzoPacket[0] = lzoCompressNone
copy(lzoPacket[1:], packet)
packet = lzoPacket
}
packetID := d.nextPacketID()
if d.sendAEAD != nil {
return d.encryptAEAD(packet, packetID)
@@ -245,25 +247,10 @@ func (d *DataChannel) Decrypt(packet []byte) ([]byte, error) {
if err != nil {
return nil, err
}
var plain []byte
if d.recvAEAD != nil {
plain, err = d.decryptAEAD(packet, headerSize)
} else {
plain, err = d.decryptCBC(packet, headerSize)
return d.decryptAEAD(packet, headerSize)
}
if err != nil {
return nil, err
}
if d.compLZO == CompLzoYes && len(plain) > 0 {
decompressed, err := lzo1xDecompressSafe(plain)
if err != nil {
return nil, err
}
if len(decompressed) > 0 {
return decompressed, nil
}
}
return plain, nil
return d.decryptCBC(packet, headerSize)
}
func (d *DataChannel) decryptAEAD(packet []byte, headerSize int) ([]byte, error) {
+8 -8
View File
@@ -21,11 +21,11 @@ func TestDataChannelAESGCMV2RoundTrip(t *testing.T) {
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7, "")
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7, "")
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
@@ -75,11 +75,11 @@ func TestDataChannelAcceptsOutOfOrderPacketsWithinReplayWindow(t *testing.T) {
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7, "")
client, err := NewDataChannel(clientKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7, "")
server, err := NewDataChannel(serverKeys, CipherAES128GCM, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
@@ -154,11 +154,11 @@ func TestDataChannelChaCha20Poly1305V2RoundTrip(t *testing.T) {
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, CipherChaCha20Poly1305, AuthSHA256, 7, "")
client, err := NewDataChannel(clientKeys, CipherChaCha20Poly1305, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, CipherChaCha20Poly1305, AuthSHA256, 7, "")
server, err := NewDataChannel(serverKeys, CipherChaCha20Poly1305, AuthSHA256, 7)
if err != nil {
t.Fatal(err)
}
@@ -194,11 +194,11 @@ func TestDataChannelAESCBCSHA1V2RoundTrip(t *testing.T) {
RecvCipherKey: clientKeys.SendCipherKey,
RecvHMACKey: clientKeys.SendHMACKey,
}
client, err := NewDataChannel(clientKeys, CipherAES128CBC, AuthSHA1, 7, "")
client, err := NewDataChannel(clientKeys, CipherAES128CBC, AuthSHA1, 7)
if err != nil {
t.Fatal(err)
}
server, err := NewDataChannel(serverKeys, CipherAES128CBC, AuthSHA1, 7, "")
server, err := NewDataChannel(serverKeys, CipherAES128CBC, AuthSHA1, 7)
if err != nil {
t.Fatal(err)
}
+9
View File
@@ -41,3 +41,12 @@ func lzo1xDecompressSafe(src []byte) ([]byte, error) {
return nil, ErrLZODecompress
}
}
// lzo1xCompressSafe handles OpenVPN comp-lzo data packets.
// Prepend comp-lzo header (0xfa = not compressed) to satisfy servers expecting the framing.
func lzo1xCompressSafe(src []byte) ([]byte, error) {
lzoPacket := make([]byte, 1+len(src))
lzoPacket[0] = lzoCompressNone
copy(lzoPacket[1:], src)
return lzoPacket, nil
}
+23
View File
@@ -0,0 +1,23 @@
package openvpn
import (
"bytes"
"crypto/rand"
"testing"
)
func TestLzo1xSafe(t *testing.T) {
data := make([]byte, 1024)
rand.Read(data)
compressed, err := lzo1xCompressSafe(data)
if err != nil {
t.Fatal(err)
}
decompressed, err := lzo1xDecompressSafe(compressed)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, decompressed) {
t.Fatal("decompressed data is not equal to original")
}
}