diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go
index c95203f2a..c7f50dbf6 100644
--- a/adapter/outbound/openvpn.go
+++ b/adapter/outbound/openvpn.go
@@ -47,9 +47,11 @@ type OpenVPNOption struct {
Cipher string `proxy:"cipher,omitempty"`
Auth string `proxy:"auth,omitempty"`
CA string `proxy:"ca"`
- Cert string `proxy:"cert"`
- Key string `proxy:"key"`
+ Cert string `proxy:"cert,omitempty"`
+ Key string `proxy:"key,omitempty"`
TLSCrypt string `proxy:"tls-crypt"`
+ Username string `proxy:"username,omitempty"`
+ Password string `proxy:"password,omitempty"`
MTU int `proxy:"mtu,omitempty"`
UDP bool `proxy:"udp,omitempty"`
@@ -69,6 +71,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) {
Cert: []byte(option.Cert),
Key: []byte(option.Key),
TLSCrypt: []byte(option.TLSCrypt),
+ Username: option.Username,
+ Password: option.Password,
}
if err := cfg.Prepare(); err != nil {
return nil, err
diff --git a/docs/config.yaml b/docs/config.yaml
index 18b14572e..4dddba4ff 100644
--- a/docs/config.yaml
+++ b/docs/config.yaml
@@ -1115,19 +1115,22 @@ proxies: # socks5
port: 1194
proto: udp # udp/tcp,默认 udp
# dev: tun # 目前仅支持 tun,默认 tun
- # cipher: AES-128-GCM # 目前仅支持 AES-128-GCM,默认 AES-128-GCM
+ # cipher: AES-128-GCM # 支持 AES-128-GCM / AES-256-GCM,默认 AES-128-GCM
# auth: SHA256 # 目前仅支持 SHA256,默认 SHA256
+ # username / password: auth-user-pass 模式(与下方 cert+key 二选一,不能都不填)
+ # username: "user"
+ # password: "pass"
# 从 .ovpn 中复制 内的内容,不需要保留 标签
ca: |
-----BEGIN CERTIFICATE-----
MIIB...example
-----END CERTIFICATE-----
- # 从 .ovpn 中复制 内的内容,不需要保留 标签
+ # 从 .ovpn 中复制 内的内容(auth-user-pass 时可省略 cert / key)
cert: |
-----BEGIN CERTIFICATE-----
MIIB...example
-----END CERTIFICATE-----
- # 从 .ovpn 中复制 内的内容,不需要保留 标签
+ # 从 .ovpn 中复制 内的内容
key: |
-----BEGIN PRIVATE KEY-----
MIIE...example
diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go
index d218fe562..b70b7cbb4 100644
--- a/transport/openvpn/client.go
+++ b/transport/openvpn/client.go
@@ -83,7 +83,12 @@ func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
return nil, fmt.Errorf("openvpn tls handshake: %w", err)
}
- clientRecord, err := NewClientKeyMethod2Record(InstallScriptOptionsString(c.config.Proto), InstallScriptPeerInfo())
+ clientRecord, err := NewClientKeyMethod2Record(
+ InstallScriptOptionsString(c.config.Proto, c.config.Cipher, c.config.Auth),
+ InstallScriptPeerInfo(c.config.Cipher),
+ strings.TrimSpace(c.config.Username),
+ c.config.Password,
+ )
if err != nil {
return nil, err
}
@@ -101,7 +106,7 @@ func (c *Client) Handshake(ctx context.Context) (*PushReply, error) {
sources := clientRecord.Sources
sources.Server = serverRecord.Sources.Server
- keys, err := DeriveClientKeyMaterial(sources, c.control.LocalSessionID(), c.control.RemoteSessionID())
+ keys, err := DeriveClientKeyMaterial(sources, c.control.LocalSessionID(), c.control.RemoteSessionID(), c.config.DataCipherKeyLength())
if err != nil {
return nil, fmt.Errorf("derive data channel keys: %w", err)
}
@@ -228,33 +233,39 @@ func (c *Client) readPushReply(ctx context.Context) (*PushReply, error) {
}
func (c *Client) tlsConfig() (*tls.Config, error) {
- cert, err := tls.X509KeyPair(c.config.Cert, c.config.Key)
- if err != nil {
- return nil, fmt.Errorf("parse client certificate/key: %w", err)
- }
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(c.config.CA) {
return nil, errors.New("parse openvpn ca certificate")
}
- return &tls.Config{
- Certificates: []tls.Certificate{cert},
+ verify := func(cs tls.ConnectionState) error {
+ if len(cs.PeerCertificates) == 0 {
+ return errors.New("openvpn server did not provide certificate")
+ }
+ intermediates := x509.NewCertPool()
+ for _, cert := range cs.PeerCertificates[1:] {
+ intermediates.AddCert(cert)
+ }
+ _, err := cs.PeerCertificates[0].Verify(x509.VerifyOptions{
+ Roots: roots,
+ Intermediates: intermediates,
+ KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ })
+ return err
+ }
+ cfg := &tls.Config{
InsecureSkipVerify: true,
- VerifyConnection: func(cs tls.ConnectionState) error {
- if len(cs.PeerCertificates) == 0 {
- return errors.New("openvpn server did not provide certificate")
- }
- intermediates := x509.NewCertPool()
- for _, cert := range cs.PeerCertificates[1:] {
- intermediates.AddCert(cert)
- }
- _, err := cs.PeerCertificates[0].Verify(x509.VerifyOptions{
- Roots: roots,
- Intermediates: intermediates,
- KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
- })
- return err
- },
- }, nil
+ VerifyConnection: verify,
+ }
+ certPEM := bytes.TrimSpace(c.config.Cert)
+ keyPEM := bytes.TrimSpace(c.config.Key)
+ if len(certPEM) > 0 && len(keyPEM) > 0 {
+ cert, err := tls.X509KeyPair(c.config.Cert, c.config.Key)
+ if err != nil {
+ return nil, fmt.Errorf("parse client certificate/key: %w", err)
+ }
+ cfg.Certificates = []tls.Certificate{cert}
+ }
+ return cfg, nil
}
var _ net.Conn = (*ControlConn)(nil)
diff --git a/transport/openvpn/config.go b/transport/openvpn/config.go
index 0b1de102f..e07b2098d 100644
--- a/transport/openvpn/config.go
+++ b/transport/openvpn/config.go
@@ -16,6 +16,7 @@ const (
ProtoTCP = "tcp"
CipherAES128GCM = "AES-128-GCM"
+ CipherAES256GCM = "AES-256-GCM"
AuthSHA256 = "SHA256"
)
@@ -33,9 +34,22 @@ type ClientConfig struct {
Key []byte
TLSCrypt []byte
+ Username string
+ Password string
+
TLSCryptKey []byte
}
+// DataCipherKeyLength returns the AES key size for the negotiated data cipher.
+func (c ClientConfig) DataCipherKeyLength() int {
+ switch c.Cipher {
+ case CipherAES256GCM:
+ return 32
+ default:
+ return 16
+ }
+}
+
func (c ClientConfig) RemoteAddress() string {
return net.JoinHostPort(c.RemoteHost, strconv.Itoa(int(c.RemotePort)))
}
@@ -95,16 +109,14 @@ func (c *ClientConfig) ValidateInstallScriptSubset() error {
if c.Proto != ProtoUDP && c.Proto != ProtoTCP {
return fmt.Errorf("unsupported openvpn proto %q: only udp and tcp are supported", c.Proto)
}
- if c.Cipher != CipherAES128GCM {
- return fmt.Errorf("unsupported openvpn cipher %q: only %s is supported", c.Cipher, CipherAES128GCM)
+ if c.Cipher != CipherAES128GCM && c.Cipher != CipherAES256GCM {
+ return fmt.Errorf("unsupported openvpn cipher %q: only %s and %s are supported", c.Cipher, CipherAES128GCM, CipherAES256GCM)
}
if c.Auth != AuthSHA256 {
return fmt.Errorf("unsupported openvpn auth %q: only %s is supported", c.Auth, AuthSHA256)
}
for name, value := range map[string][]byte{
"ca": c.CA,
- "cert": c.Cert,
- "key": c.Key,
"tls-crypt": c.TLSCrypt,
} {
if len(bytes.TrimSpace(value)) == 0 {
@@ -114,11 +126,19 @@ func (c *ClientConfig) ValidateInstallScriptSubset() error {
if block, _ := pem.Decode(c.CA); block == nil {
return errors.New("inline block is not PEM")
}
- if block, _ := pem.Decode(c.Cert); block == nil {
- return errors.New("inline block is not PEM")
- }
- if block, _ := pem.Decode(c.Key); block == nil {
- return errors.New("inline block is not PEM")
+ hasCert := len(bytes.TrimSpace(c.Cert)) > 0 || len(bytes.TrimSpace(c.Key)) > 0
+ if hasCert {
+ if len(bytes.TrimSpace(c.Cert)) == 0 || len(bytes.TrimSpace(c.Key)) == 0 {
+ return errors.New("openvpn cert and key must both be set when using client certificate auth")
+ }
+ if block, _ := pem.Decode(c.Cert); block == nil {
+ return errors.New("inline block is not PEM")
+ }
+ if block, _ := pem.Decode(c.Key); block == nil {
+ return errors.New("inline block is not PEM")
+ }
+ } else if strings.TrimSpace(c.Username) == "" {
+ return errors.New("openvpn requires either cert+key or username (auth-user-pass)")
}
return nil
}
diff --git a/transport/openvpn/config_test.go b/transport/openvpn/config_test.go
index 87f27011d..76009d0e2 100644
--- a/transport/openvpn/config_test.go
+++ b/transport/openvpn/config_test.go
@@ -100,3 +100,41 @@ func TestClientConfigRequiresTLSCrypt(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
}
+
+func TestClientConfigAuthUserPassAES256(t *testing.T) {
+ cfg := &ClientConfig{
+ RemoteHost: "vpn.example.com",
+ RemotePort: 31194,
+ Proto: "udp",
+ Dev: "tun",
+ Cipher: "AES-256-GCM",
+ Auth: "SHA256",
+ CA: []byte(testCert),
+ Username: "user",
+ Password: "secret",
+ TLSCrypt: []byte(testTLSCryptBlock()),
+ }
+ if err := cfg.Prepare(); err != nil {
+ t.Fatal(err)
+ }
+ if cfg.Cipher != CipherAES256GCM {
+ t.Fatalf("unexpected cipher: %s", cfg.Cipher)
+ }
+ if cfg.DataCipherKeyLength() != 32 {
+ t.Fatalf("unexpected data key length helper: %d", cfg.DataCipherKeyLength())
+ }
+}
+
+func TestClientConfigRequiresAuth(t *testing.T) {
+ cfg := yamlStyleConfig()
+ cfg.Cert = nil
+ cfg.Key = nil
+ cfg.Username = ""
+ err := cfg.Prepare()
+ if err == nil {
+ t.Fatal("expected missing auth error")
+ }
+ if !strings.Contains(err.Error(), "cert+key or username") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
diff --git a/transport/openvpn/keymethod.go b/transport/openvpn/keymethod.go
index 290745cda..1b3abf0a4 100644
--- a/transport/openvpn/keymethod.go
+++ b/transport/openvpn/keymethod.go
@@ -50,7 +50,7 @@ type KeyMethod2Record struct {
PeerInfo string
}
-func NewClientKeyMethod2Record(options, peerInfo string) (*KeyMethod2Record, error) {
+func NewClientKeyMethod2Record(options, peerInfo, username, password string) (*KeyMethod2Record, error) {
var record KeyMethod2Record
if _, err := rand.Read(record.Sources.Client.PreMaster[:]); err != nil {
return nil, err
@@ -63,6 +63,8 @@ func NewClientKeyMethod2Record(options, peerInfo string) (*KeyMethod2Record, err
}
record.Options = options
record.PeerInfo = peerInfo
+ record.Username = username
+ record.Password = password
return &record, nil
}
@@ -111,7 +113,10 @@ func ParseServerKeyMethod2Record(packet []byte) (*KeyMethod2Record, error) {
return record, nil
}
-func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession SessionID) (*KeyMaterial, error) {
+func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession SessionID, cipherKeyLen int) (*KeyMaterial, error) {
+ if cipherKeyLen != 16 && cipherKeyLen != 32 {
+ return nil, fmt.Errorf("unsupported data cipher key length %d", cipherKeyLen)
+ }
var master [48]byte
if err := openvpnPRF(
sources.Client.PreMaster[:],
@@ -141,23 +146,27 @@ func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession Se
clientToServer := keyBlock[:maxCipherKeyLength+maxHMACKeyLength]
serverToClient := keyBlock[maxCipherKeyLength+maxHMACKeyLength:]
return &KeyMaterial{
- SendCipherKey: cloneBytes(clientToServer[:16]),
+ SendCipherKey: cloneBytes(clientToServer[:cipherKeyLen]),
SendHMACKey: cloneBytes(clientToServer[maxCipherKeyLength : maxCipherKeyLength+maxHMACKeyLength]),
- RecvCipherKey: cloneBytes(serverToClient[:16]),
+ RecvCipherKey: cloneBytes(serverToClient[:cipherKeyLen]),
RecvHMACKey: cloneBytes(serverToClient[maxCipherKeyLength : maxCipherKeyLength+maxHMACKeyLength]),
}, nil
}
-func InstallScriptOptionsString(proto string) string {
+func InstallScriptOptionsString(proto, cipher, auth string) string {
protoName := "UDPv4"
if proto == ProtoTCP {
protoName = "TCPv4_CLIENT"
}
- return fmt.Sprintf("V4,dev-type tun,link-mtu 1550,tun-mtu 1500,proto %s,cipher %s,auth %s,keysize 128,key-method 2,tls-client", protoName, CipherAES128GCM, AuthSHA256)
+ keysize := "128"
+ if cipher == CipherAES256GCM {
+ keysize = "256"
+ }
+ return fmt.Sprintf("V4,dev-type tun,link-mtu 1550,tun-mtu 1500,proto %s,cipher %s,auth %s,keysize %s,key-method 2,tls-client", protoName, cipher, auth, keysize)
}
-func InstallScriptPeerInfo() string {
- return "IV_VER=mihomo-openvpn\nIV_PROTO=6\nIV_CIPHERS=AES-128-GCM\n"
+func InstallScriptPeerInfo(cipher string) string {
+ return fmt.Sprintf("IV_VER=mihomo-openvpn\nIV_PROTO=6\nIV_CIPHERS=%s\n", cipher)
}
func appendOpenVPNString(out []byte, s string) []byte {
diff --git a/transport/openvpn/keymethod_test.go b/transport/openvpn/keymethod_test.go
index 0db7cba0a..ec3d4a145 100644
--- a/transport/openvpn/keymethod_test.go
+++ b/transport/openvpn/keymethod_test.go
@@ -8,8 +8,8 @@ import (
func TestKeyMethod2ClientMarshalAndDerive(t *testing.T) {
record := &KeyMethod2Record{
- Options: InstallScriptOptionsString(ProtoUDP),
- PeerInfo: InstallScriptPeerInfo(),
+ Options: InstallScriptOptionsString(ProtoUDP, CipherAES128GCM, AuthSHA256),
+ PeerInfo: InstallScriptPeerInfo(CipherAES128GCM),
}
for i := range record.Sources.Client.PreMaster {
record.Sources.Client.PreMaster[i] = byte(i + 1)
@@ -35,7 +35,7 @@ func TestKeyMethod2ClientMarshalAndDerive(t *testing.T) {
var clientID, serverID SessionID
copy(clientID[:], []byte("client01"))
copy(serverID[:], []byte("server01"))
- keys, err := DeriveClientKeyMaterial(record.Sources, clientID, serverID)
+ keys, err := DeriveClientKeyMaterial(record.Sources, clientID, serverID, 16)
if err != nil {
t.Fatal(err)
}
@@ -50,6 +50,38 @@ func TestKeyMethod2ClientMarshalAndDerive(t *testing.T) {
}
}
+func TestKeyMethod2DeriveAES256(t *testing.T) {
+ record := &KeyMethod2Record{
+ Options: InstallScriptOptionsString(ProtoUDP, CipherAES256GCM, AuthSHA256),
+ PeerInfo: InstallScriptPeerInfo(CipherAES256GCM),
+ }
+ for i := range record.Sources.Client.PreMaster {
+ record.Sources.Client.PreMaster[i] = byte(i + 1)
+ }
+ for i := range record.Sources.Client.Random1 {
+ record.Sources.Client.Random1[i] = byte(i + 2)
+ record.Sources.Client.Random2[i] = byte(i + 3)
+ record.Sources.Server.Random1[i] = byte(i + 4)
+ record.Sources.Server.Random2[i] = byte(i + 5)
+ }
+ var clientID, serverID SessionID
+ copy(clientID[:], []byte("client01"))
+ copy(serverID[:], []byte("server01"))
+ keys, err := DeriveClientKeyMaterial(record.Sources, clientID, serverID, 32)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(keys.SendCipherKey) != 32 || len(keys.RecvCipherKey) != 32 {
+ t.Fatalf("unexpected cipher key lengths: %d/%d", len(keys.SendCipherKey), len(keys.RecvCipherKey))
+ }
+ if len(keys.SendHMACKey) != maxHMACKeyLength || len(keys.RecvHMACKey) != maxHMACKeyLength {
+ t.Fatalf("unexpected hmac key lengths: %d/%d", len(keys.SendHMACKey), len(keys.RecvHMACKey))
+ }
+ if bytes.Equal(keys.SendCipherKey, keys.RecvCipherKey) {
+ t.Fatalf("send and recv keys should differ")
+ }
+}
+
func TestParseServerKeyMethod2Record(t *testing.T) {
var packet []byte
packet = binary.BigEndian.AppendUint32(packet, 0)