mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-12-01 14:06:50 +00:00
feat: add support for TLSAuth for Openvpn (#2969)
This commit is contained in:
1 parent
9729296862
commit
76d80883dd
10 files changed
+299
-5
No files matched your search
@@ -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,
|
||||
|
||||
@@ -1283,6 +1283,13 @@ proxies: # socks5
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIE...example
|
||||
-----END PRIVATE KEY-----
|
||||
# 从 .ovpn 中复制 <tls-auth></tls-auth> 内的内容,不需要保留 <tls-auth> 标签;与 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> 内的内容,不需要保留 <tls-crypt> 标签;没有 tls-crypt 的配置可省略
|
||||
# tls-crypt: |
|
||||
# -----BEGIN OpenVPN Static key V1-----
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
} {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user