diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go index f38769b9a..bd59d599d 100644 --- a/adapter/outbound/openvpn.go +++ b/adapter/outbound/openvpn.go @@ -52,6 +52,8 @@ type OpenVPNOption struct { CA string `proxy:"ca"` Cert string `proxy:"cert,omitempty"` Key string `proxy:"key,omitempty"` + TLSAuth string `proxy:"tls-auth,omitempty"` + KeyDirection string `proxy:"key-direction,omitempty"` TLSCrypt string `proxy:"tls-crypt,omitempty"` Username string `proxy:"username,omitempty"` Password string `proxy:"password,omitempty"` @@ -81,6 +83,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { CA: []byte(option.CA), Cert: []byte(option.Cert), Key: []byte(option.Key), + TLSAuth: []byte(option.TLSAuth), + KeyDirection: option.KeyDirection, TLSCrypt: []byte(option.TLSCrypt), Username: option.Username, Password: option.Password, diff --git a/docs/config.yaml b/docs/config.yaml index 049b1ddb5..5786db9e6 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -1283,6 +1283,13 @@ proxies: # socks5 -----BEGIN PRIVATE KEY----- MIIE...example -----END PRIVATE KEY----- + # 从 .ovpn 中复制 内的内容,不需要保留 标签;与 tls-crypt 互斥 + # tls-auth: | + # -----BEGIN OpenVPN Static key V1----- + # 00000000000000000000000000000000 + # ... + # -----END OpenVPN Static key V1----- + # key-direction: "1" # tls-auth 使用,支持 "1" 或 "0";如果不填或为空字符串,则为双向模式(bidirectional) # 从 .ovpn 中复制 内的内容,不需要保留 标签;没有 tls-crypt 的配置可省略 # tls-crypt: | # -----BEGIN OpenVPN Static key V1----- diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go index 07e7bd460..0bf0ffef4 100644 --- a/transport/openvpn/client.go +++ b/transport/openvpn/client.go @@ -44,13 +44,19 @@ func NewClient(config *ClientConfig, io PacketIO) (*Client, error) { if io == nil { return nil, errors.New("nil openvpn packet io") } - var crypt *TLSCrypt + var crypt ControlCryptor if len(config.TLSCryptKey) > 0 { var err error crypt, err = NewTLSCrypt(config.TLSCryptKey, true) if err != nil { return nil, err } + } else if len(config.TLSAuthKey) > 0 { + var err error + crypt, err = NewTLSAuth(config.TLSAuthKey, config.KeyDirection) + if err != nil { + return nil, err + } } local, err := NewSessionID() if err != nil { diff --git a/transport/openvpn/config.go b/transport/openvpn/config.go index 59aa1a41b..c0dbc1e22 100644 --- a/transport/openvpn/config.go +++ b/transport/openvpn/config.go @@ -46,8 +46,11 @@ type ClientConfig struct { CA []byte Cert []byte Key []byte + TLSAuth []byte TLSCrypt []byte + KeyDirection string + Username string Password string @@ -57,6 +60,7 @@ type ClientConfig struct { PingRestart time.Duration TLSCryptKey []byte + TLSAuthKey []byte } // DataCipherKeyLength returns the key size for the negotiated data cipher. @@ -132,9 +136,17 @@ func (c *ClientConfig) Prepare() error { c.Cipher = normalizeCipher(c.Cipher) c.Auth = normalizeAuth(c.Auth) c.CompLZO = normalizeCompLZO(c.CompLZO) + if err := c.ValidateInstallScriptSubset(); err != nil { return err } + if len(bytes.TrimSpace(c.TLSAuth)) > 0 { + key, err := DecodeStaticKey(c.TLSAuth) + if err != nil { + return fmt.Errorf("parse tls-auth key: %w", err) + } + c.TLSAuthKey = key + } if len(bytes.TrimSpace(c.TLSCrypt)) > 0 { key, err := DecodeStaticKey(c.TLSCrypt) if err != nil { @@ -164,6 +176,12 @@ func (c *ClientConfig) ValidateInstallScriptSubset() error { if c.Auth != AuthMD5 && c.Auth != AuthSHA1 && c.Auth != AuthSHA256 && c.Auth != AuthSHA384 && c.Auth != AuthSHA512 { return fmt.Errorf("unsupported openvpn auth %q: only %s, %s, %s, %s and %s are supported", c.Auth, AuthMD5, AuthSHA1, AuthSHA256, AuthSHA384, AuthSHA512) } + if c.KeyDirection != "1" && c.KeyDirection != "0" && c.KeyDirection != "" { + return fmt.Errorf("unsupported openvpn key-direction %q: only '1' and '0' are supported", c.KeyDirection) + } + if len(bytes.TrimSpace(c.TLSAuth)) > 0 && len(bytes.TrimSpace(c.TLSCrypt)) > 0 { + return errors.New("openvpn tls-auth and tls-crypt are mutually exclusive") + } for name, value := range map[string][]byte{ "ca": c.CA, } { diff --git a/transport/openvpn/config_test.go b/transport/openvpn/config_test.go index 094c1b13e..1f2fc3ace 100644 --- a/transport/openvpn/config_test.go +++ b/transport/openvpn/config_test.go @@ -185,3 +185,49 @@ func TestClientConfigAuthUserPassChaCha20Poly1305(t *testing.T) { t.Fatalf("unexpected data key length helper: %d", cfg.DataCipherKeyLength()) } } + +func TestClientConfigTLSAuth(t *testing.T) { + cfg := &ClientConfig{ + RemoteHost: "vpn.example.com", + RemotePort: 1194, + Proto: "udp", + Dev: "tun", + Cipher: "AES-128-GCM", + Auth: "SHA256", + CA: []byte(testCert), + Username: "user", + Password: "secret", + TLSAuth: []byte(testTLSCryptBlock()), + KeyDirection: "1", + } + if err := cfg.Prepare(); err != nil { + t.Fatal(err) + } + if len(cfg.TLSAuthKey) != 256 { + t.Fatalf("unexpected tls-auth key length: %d", len(cfg.TLSAuthKey)) + } +} + +func TestClientConfigRejectsTLSAuthTLSCryptTogether(t *testing.T) { + cfg := &ClientConfig{ + RemoteHost: "vpn.example.com", + RemotePort: 1194, + Proto: "udp", + Dev: "tun", + Cipher: "AES-128-GCM", + Auth: "SHA256", + CA: []byte(testCert), + Username: "user", + Password: "secret", + TLSAuth: []byte(testTLSCryptBlock()), + TLSCrypt: []byte(testTLSCryptBlock()), + KeyDirection: "1", + } + err := cfg.Prepare() + if err == nil { + t.Fatal("expected mutual exclusion error") + } + if !strings.Contains(err.Error(), "mutually exclusive") { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/transport/openvpn/control.go b/transport/openvpn/control.go index f7d85de3a..28e3e520a 100644 --- a/transport/openvpn/control.go +++ b/transport/openvpn/control.go @@ -22,7 +22,7 @@ type PacketIO interface { type ControlChannel struct { io PacketIO - crypt *TLSCrypt + crypt ControlCryptor clock func() time.Time keyID uint8 local SessionID @@ -39,7 +39,7 @@ type ControlChannel struct { writeDeadline time.Time } -func NewControlChannel(io PacketIO, crypt *TLSCrypt, local SessionID) *ControlChannel { +func NewControlChannel(io PacketIO, crypt ControlCryptor, local SessionID) *ControlChannel { return &ControlChannel{ io: io, crypt: crypt, diff --git a/transport/openvpn/packet.go b/transport/openvpn/packet.go index f50e41185..a2f6912e7 100644 --- a/transport/openvpn/packet.go +++ b/transport/openvpn/packet.go @@ -7,6 +7,11 @@ import ( "fmt" ) +type ControlCryptor interface { + Wrap(header []byte, packetID uint32, unixTime uint32, plaintext []byte) ([]byte, error) + Unwrap(packet []byte) (header []byte, packetID uint32, unixTime uint32, plaintext []byte, err error) +} + const ( KeyIDMask = 0x07 OpcodeShift = 3 @@ -167,7 +172,7 @@ func DecodeControlPlain(opcode Opcode, plain []byte) (ackIDs []uint32, ackRemote return ackIDs, ackRemote, messageID, payload, nil } -func (p ControlPacket) Encode(crypt *TLSCrypt, packetID uint32, unixTime uint32) ([]byte, error) { +func (p ControlPacket) Encode(crypt ControlCryptor, packetID uint32, unixTime uint32) ([]byte, error) { plain, err := p.EncodePlain() if err != nil { return nil, err @@ -185,7 +190,7 @@ func (p ControlPacket) Encode(crypt *TLSCrypt, packetID uint32, unixTime uint32) return crypt.Wrap(header, packetID, unixTime, plain) } -func DecodeControlPacket(crypt *TLSCrypt, packet []byte) (*ControlPacket, uint32, uint32, error) { +func DecodeControlPacket(crypt ControlCryptor, packet []byte) (*ControlPacket, uint32, uint32, error) { if crypt == nil { if len(packet) < TLSCryptHeaderSize+1 { return nil, 0, 0, errors.New("control packet too short") diff --git a/transport/openvpn/packet_test.go b/transport/openvpn/packet_test.go index c86dfa97d..69eb9bf14 100644 --- a/transport/openvpn/packet_test.go +++ b/transport/openvpn/packet_test.go @@ -58,6 +58,53 @@ func TestControlPacketEncodeDecodeWithTLSCrypt(t *testing.T) { } } +func TestControlPacketEncodeDecodeWithTLSAuth(t *testing.T) { + cryptClient, err := NewTLSAuth(testStaticKey(), "1") + if err != nil { + t.Fatal(err) + } + cryptServer, err := NewTLSAuth(testStaticKey(), "0") + if err != nil { + t.Fatal(err) + } + + var local SessionID + copy(local[:], []byte("client01")) + var remote SessionID + copy(remote[:], []byte("server01")) + + packet := ControlPacket{ + Opcode: PControlV1, + KeyID: 0, + LocalSession: local, + AckIDs: []uint32{3, 4}, + AckRemoteSession: remote, + MessageID: 9, + Payload: []byte("tls auth"), + } + encoded, err := packet.Encode(cryptClient, 77, 1714567890) + if err != nil { + t.Fatal(err) + } + + decoded, packetID, unixTime, err := DecodeControlPacket(cryptServer, encoded) + if err != nil { + t.Fatal(err) + } + if packetID != 77 || unixTime != 1714567890 { + t.Fatalf("unexpected tls-auth packet id/time: %d/%d", packetID, unixTime) + } + if decoded.Opcode != packet.Opcode || decoded.KeyID != packet.KeyID { + t.Fatalf("unexpected opcode/key-id: %s/%d", decoded.Opcode, decoded.KeyID) + } + if decoded.LocalSession != local { + t.Fatalf("unexpected local session: %x", decoded.LocalSession) + } + if !bytes.Equal(decoded.Payload, packet.Payload) { + t.Fatalf("unexpected payload: %q", decoded.Payload) + } +} + func TestControlPacketEncodeDecodePlain(t *testing.T) { var local SessionID copy(local[:], []byte("client01")) diff --git a/transport/openvpn/tlsauth.go b/transport/openvpn/tlsauth.go new file mode 100644 index 000000000..a02a7e0ae --- /dev/null +++ b/transport/openvpn/tlsauth.go @@ -0,0 +1,98 @@ +package openvpn + +import ( + "crypto/hmac" + "crypto/sha1" + "encoding/binary" + "errors" + "fmt" +) + +const ( + TLSAuthPIDSize = 4 + 4 + TLSAuthTagSize = sha1.Size + tlsAuthKeySize = sha1.Size +) + +type TLSAuth struct { + encryptHMACKey []byte + decryptHMACKey []byte +} + +func NewTLSAuth(staticKey []byte, keyDirection string) (*TLSAuth, error) { + if len(staticKey) != staticKeySize { + return nil, fmt.Errorf("invalid tls-auth static key length %d, expected %d", len(staticKey), staticKeySize) + } + if keyDirection != "0" && keyDirection != "1" && keyDirection != "" { + return nil, fmt.Errorf("invalid tls-auth key-direction %q, expected '0', '1', or ''", keyDirection) + } + + key0 := staticKey[:keySlotSize] + key1 := staticKey[keySlotSize:] + + var encrypt, decrypt []byte + if keyDirection == "1" { + encrypt = key1 + decrypt = key0 + } else if keyDirection == "0" { + encrypt = key0 + decrypt = key1 + } else { + encrypt = key0 + decrypt = key0 + } + + return &TLSAuth{ + encryptHMACKey: cloneBytes(encrypt[64 : 64+tlsAuthKeySize]), + decryptHMACKey: cloneBytes(decrypt[64 : 64+tlsAuthKeySize]), + }, nil +} + +func (a *TLSAuth) Wrap(header []byte, packetID uint32, unixTime uint32, plaintext []byte) ([]byte, error) { + if len(header) != TLSCryptHeaderSize { + return nil, fmt.Errorf("invalid tls-auth header length %d, expected %d", len(header), TLSCryptHeaderSize) + } + + var pid [TLSAuthPIDSize]byte + binary.BigEndian.PutUint32(pid[:4], packetID) + binary.BigEndian.PutUint32(pid[4:], unixTime) + tag := a.hmac(a.encryptHMACKey, pid[:], header, plaintext) + + out := make([]byte, 0, len(header)+len(tag)+len(pid)+len(plaintext)) + out = append(out, header...) + out = append(out, tag...) + out = append(out, pid[:]...) + out = append(out, plaintext...) + return out, nil +} + +func (a *TLSAuth) Unwrap(packet []byte) (header []byte, packetID uint32, unixTime uint32, plaintext []byte, err error) { + if len(packet) < TLSCryptHeaderSize+TLSAuthTagSize+TLSAuthPIDSize+1 { + return nil, 0, 0, nil, errors.New("tls-auth packet too short") + } + + headerEnd := TLSCryptHeaderSize + tagEnd := headerEnd + TLSAuthTagSize + pidEnd := tagEnd + TLSAuthPIDSize + header = cloneBytes(packet[:headerEnd]) + tag := packet[headerEnd:tagEnd] + pid := packet[tagEnd:pidEnd] + plaintext = cloneBytes(packet[pidEnd:]) + + tagCheck := a.hmac(a.decryptHMACKey, pid, header, plaintext) + if !hmac.Equal(tag, tagCheck) { + return nil, 0, 0, nil, errors.New("tls-auth authentication failed") + } + + packetID = binary.BigEndian.Uint32(pid[:4]) + unixTime = binary.BigEndian.Uint32(pid[4:]) + return header, packetID, unixTime, plaintext, nil +} + +func (a *TLSAuth) hmac(key []byte, parts ...[]byte) []byte { + mac := hmac.New(sha1.New, key) + for _, part := range parts { + _, _ = mac.Write(part) + } + return mac.Sum(nil) +} diff --git a/transport/openvpn/tlsauth_test.go b/transport/openvpn/tlsauth_test.go new file mode 100644 index 000000000..b881dd4cd --- /dev/null +++ b/transport/openvpn/tlsauth_test.go @@ -0,0 +1,63 @@ +package openvpn + +import ( + "bytes" + "testing" +) + +func TestTLSAuthClientServerRoundTrip(t *testing.T) { + client, err := NewTLSAuth(testStaticKey(), "1") + if err != nil { + t.Fatal(err) + } + server, err := NewTLSAuth(testStaticKey(), "0") + if err != nil { + t.Fatal(err) + } + + header := []byte{0x38, 1, 2, 3, 4, 5, 6, 7, 8} + plaintext := []byte("client hello over openvpn control channel") + packet, err := client.Wrap(header, 7, 1714567890, plaintext) + if err != nil { + t.Fatal(err) + } + if want := TLSCryptHeaderSize + TLSAuthTagSize + TLSAuthPIDSize + len(plaintext); len(packet) != want { + t.Fatalf("unexpected tls-auth packet length: got %d, want %d", len(packet), want) + } + + gotHeader, packetID, unixTime, gotPlaintext, err := server.Unwrap(packet) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(gotHeader, header) { + t.Fatalf("unexpected header: %x", gotHeader) + } + if packetID != 7 || unixTime != 1714567890 { + t.Fatalf("unexpected packet id/time: %d/%d", packetID, unixTime) + } + if !bytes.Equal(gotPlaintext, plaintext) { + t.Fatalf("unexpected plaintext: %q", gotPlaintext) + } +} + +func TestTLSAuthRejectsTamperedPacket(t *testing.T) { + client, err := NewTLSAuth(testStaticKey(), "1") + if err != nil { + t.Fatal(err) + } + server, err := NewTLSAuth(testStaticKey(), "0") + if err != nil { + t.Fatal(err) + } + + packet, err := client.Wrap([]byte{0x38, 1, 2, 3, 4, 5, 6, 7, 8}, 7, 1714567890, []byte("hello")) + if err != nil { + t.Fatal(err) + } + packet[len(packet)-1] ^= 0xff + + _, _, _, _, err = server.Unwrap(packet) + if err == nil { + t.Fatal("expected authentication failure") + } +}