diff --git a/adapter/outbound/openvpn.go b/adapter/outbound/openvpn.go index 3c7b1e6..88760d0 100644 --- a/adapter/outbound/openvpn.go +++ b/adapter/outbound/openvpn.go @@ -35,6 +35,14 @@ type OpenVPN struct { runCancel context.CancelFunc runLock *semaphore.Weighted running bool + + // auto-connect state, guarded by runLock: the session auth-token reused + // on reconnect, credentials the server rejected, and the channel closed + // when the current tunnel goes down. + tokenUser string + tokenPass string + authFailed bool + linkDown chan struct{} } type OpenVPNOption struct { @@ -59,12 +67,18 @@ type OpenVPNOption struct { Username string `proxy:"username,omitempty"` Password string `proxy:"password,omitempty"` PeerInfo map[string]string `proxy:"peer-info,omitempty"` + PeerInfoRaw string `proxy:"peer-info-raw,omitempty"` + OptionsString string `proxy:"options-string,omitempty"` Ping int `proxy:"ping,omitempty"` PingRestart int `proxy:"ping-restart,omitempty"` TranWindow *int `proxy:"tran-window,omitempty"` HandshakeTimeout int `proxy:"handshake-timeout,omitempty"` - MTU int `proxy:"mtu,omitempty"` - UDP bool `proxy:"udp,omitempty"` + // AutoConnect keeps the tunnel up like OpenVPN Connect: connect when the + // proxy is created, reconnect 2 s after the link drops with the session + // auth-token, stop after AUTH_FAILED until new credentials (a new proxy). + AutoConnect bool `proxy:"auto-connect,omitempty"` + MTU int `proxy:"mtu,omitempty"` + UDP bool `proxy:"udp,omitempty"` IPStack IPStackOption `proxy:"ip-stack,omitempty"` @@ -117,6 +131,8 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { Username: option.Username, Password: option.Password, PeerInfo: option.PeerInfo, + PeerInfoRaw: option.PeerInfoRaw, + OptionsString: option.OptionsString, PingInterval: time.Duration(option.Ping) * time.Second, PingRestart: time.Duration(option.PingRestart) * time.Second, TransitionWindow: transitionWindow, @@ -152,9 +168,100 @@ func NewOpenVPN(option OpenVPNOption) (*OpenVPN, error) { } outbound.dialer = option.NewDialer(outbound.DialOptions()) outbound.runCtx, outbound.runCancel = context.WithCancel(context.Background()) + registerOpenVPN(outbound) + if option.AutoConnect { + go outbound.autoConnect() + } return outbound, nil } +// openVPNInstances are the live OpenVPN proxies: closed on shutdown so they +// send the exit notification, and an auto-connect proxy replaces an older +// one with the same name and provider (a provider or config reload), as the +// server allows one session per user. +var ( + openVPNMu sync.Mutex + openVPNInstances = map[*OpenVPN]struct{}{} +) + +func registerOpenVPN(o *OpenVPN) { + var replaced []*OpenVPN + openVPNMu.Lock() + if o.option.AutoConnect { + for other := range openVPNInstances { + if other.option.AutoConnect && other.name == o.name && other.option.ProviderName == o.option.ProviderName { + delete(openVPNInstances, other) + replaced = append(replaced, other) + } + } + } + openVPNInstances[o] = struct{}{} + openVPNMu.Unlock() + for _, other := range replaced { + _ = other.Close() + } +} + +// CloseOpenVPN closes every OpenVPN proxy, sending the exit notification. +// Called on shutdown. +func CloseOpenVPN() { + openVPNMu.Lock() + all := make([]*OpenVPN, 0, len(openVPNInstances)) + for o := range openVPNInstances { + all = append(all, o) + } + openVPNMu.Unlock() + var wg sync.WaitGroup + for _, o := range all { + wg.Add(1) + go func(o *OpenVPN) { + defer wg.Done() + _ = o.Close() + }(o) + } + wg.Wait() +} + +// openVPNRestartDelay is OpenVPN Connect's pause before a reconnect. +const openVPNRestartDelay = 2 * time.Second + +var errOpenVPNAuthRejected = errors.New("openvpn credentials were rejected, waiting for new ones") + +func (o *OpenVPN) autoConnect() { + for o.runCtx.Err() == nil { + _, _, err := o.run(o.runCtx) + if o.runCtx.Err() != nil { + return + } + if errors.Is(err, errOpenVPNAuthRejected) { + log.Warnln("[OpenVPN](%s) %v", o.name, err) + return + } + if err != nil { + log.Warnln("[OpenVPN](%s) connect failed, retrying in %s: %v", o.name, openVPNRestartDelay, err) + } else { + var down chan struct{} + if o.runLock.Acquire(o.runCtx, 1) == nil { + down = o.linkDown + o.runLock.Release(1) + } + if down != nil { + select { + case <-down: + case <-o.runCtx.Done(): + return + } + log.Infoln("[OpenVPN](%s) tunnel down, reconnecting in %s", o.name, openVPNRestartDelay) + } + } + select { + case <-time.After(openVPNRestartDelay): + case <-o.runCtx.Done(): + return + } + } +} + func (o *OpenVPN) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) { tunDevice, r, err := o.run(ctx) if err != nil { @@ -234,6 +341,22 @@ func (o *OpenVPN) IsL3Protocol(metadata *C.Metadata) bool { } func (o *OpenVPN) Close() error { + openVPNMu.Lock() + delete(openVPNInstances, o) + openVPNMu.Unlock() + // Tell the server before the packet loops see the cancel and close the + // client. A handshake in progress holds runLock: nothing to notify then. + if o.runLock.TryAcquire(1) { + client := o.client + o.runLock.Release(1) + if client != nil { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + if err := client.SendExitNotify(ctx); err != nil { + log.Debugln("[OpenVPN](%s) exit notify: %v", o.name, err) + } + cancel() + } + } if o.runCancel != nil { o.runCancel() } @@ -278,6 +401,9 @@ func (o *OpenVPN) run(ctx context.Context) (ipStack, resolver.Resolver, error) { } return o.tunDevice, o.resolver, nil } + if o.authFailed { + return nil, nil, errOpenVPNAuthRejected + } if o.runCtx.Err() != nil { return nil, nil, o.runCtx.Err() } @@ -318,7 +444,17 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R if err != nil { return nil, nil, fmt.Errorf("connect OpenVPN server: %w", err) } - client, err := ovpn.NewClient(o.config, packetIO) + config := o.config + if o.option.AutoConnect && o.tokenPass != "" { + // reconnect with the session token, like OpenVPN Connect + withToken := *o.config + if o.tokenUser != "" { + withToken.Username = o.tokenUser + } + withToken.Password = o.tokenPass + config = &withToken + } + client, err := ovpn.NewClient(config, packetIO) if err != nil { _ = packetIO.Close() return nil, nil, err @@ -326,6 +462,13 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R push, err := client.Handshake(handshakeCtx) if err != nil { _ = client.Close() + if o.option.AutoConnect && ovpn.IsAuthFailed(err) { + // Connect drops a rejected token and, with a static challenge, + // waits for the user's next OTP: here a new proxy from the provider. + o.tokenUser, o.tokenPass = "", "" + o.authFailed = true + return nil, nil, fmt.Errorf("%w: %v", errOpenVPNAuthRejected, err) + } return nil, nil, fmt.Errorf("make OpenVPN handshake: %w", err) } log.Debugln("[OpenVPN](%s) handshake complete: prefixes=%v routes=%v peer-id=%d dns=%v redirect=%t block-ipv6=%t", o.name, push.Prefixes, push.Routes, push.PeerID, push.DNS, push.Redirect, push.BlockIPv6) @@ -347,6 +490,7 @@ func (o *OpenVPN) startLocked(handshakeCtx context.Context) (ipStack, resolver.R o.client = client o.tunDevice = tunDevice o.running = true + o.linkDown = make(chan struct{}) if o.option.RemoteDnsResolve && len(o.dns) > 0 && o.resolver == nil { nss := append([]dns.NameServer(nil), o.dns...) for i := range nss { @@ -393,6 +537,7 @@ func (o *OpenVPN) startPacketLoops() { runCtx, runCancel := context.WithCancel(o.runCtx) client := o.client tunDevice := o.tunDevice + linkDown := o.linkDown var stopOnce sync.Once stop := func() { stopOnce.Do(func() { @@ -405,7 +550,11 @@ func (o *OpenVPN) startPacketLoops() { o.tunDevice = nil o.running = false } + if user, pass, ok := client.AuthToken(); ok { + o.tokenUser, o.tokenPass = user, pass + } o.runLock.Release(1) + close(linkDown) }) } go func() { diff --git a/adapter/provider/provider.go b/adapter/provider/provider.go index fa7d56b..c472539 100644 --- a/adapter/provider/provider.go +++ b/adapter/provider/provider.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "runtime" + "slices" "strings" "sync" "time" @@ -103,6 +104,13 @@ func (bp *baseProvider) RegisterHealthCheckTask(url string, expectedStatus utils func (bp *baseProvider) setProxies(proxies []C.Proxy) { bp.mutex.Lock() defer bp.mutex.Unlock() + // Replaced OpenVPN proxies close now, sending the exit notification and + // freeing the server session, instead of whenever the GC finalizes them. + for _, old := range bp.proxies { + if old.Type() == C.OpenVPN && !slices.Contains(proxies, old) { + go old.Close() + } + } bp.proxies = proxies bp.version += 1 bp.healthCheck.setProxies(proxies) diff --git a/hub/executor/executor.go b/hub/executor/executor.go index 796face..a7df5cd 100644 --- a/hub/executor/executor.go +++ b/hub/executor/executor.go @@ -13,6 +13,7 @@ import ( "github.com/metacubex/mihomo/adapter" "github.com/metacubex/mihomo/adapter/inbound" + "github.com/metacubex/mihomo/adapter/outbound" "github.com/metacubex/mihomo/adapter/outboundgroup" "github.com/metacubex/mihomo/component/auth" "github.com/metacubex/mihomo/component/ca" @@ -530,6 +531,8 @@ func updateIPTables(cfg *config.Config) { } func Shutdown() { + // OpenVPN tunnels tell the server they are leaving (explicit exit notify) + outbound.CloseOpenVPN() listener.Cleanup() tproxy.CleanupTProxyIPTables() resolver.StoreFakePoolState() diff --git a/transport/openvpn/client.go b/transport/openvpn/client.go index 053b0bf..868b445 100644 --- a/transport/openvpn/client.go +++ b/transport/openvpn/client.go @@ -286,12 +286,15 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { primaryCipher = normalizeCipher(c.config.DataCiphers[0]) } - clientRecord, err := NewClientKeyMethod2Record( - InstallScriptOptionsString(c.config.Proto, primaryCipher, c.config.Auth, c.config.CompLZO), - InstallScriptPeerInfo(primaryCipher, c.config.DataCiphers, c.config.CompLZO, c.config.PeerInfo), - c.authUser, - c.authPass, - ) + options := InstallScriptOptionsString(c.config.Proto, primaryCipher, c.config.Auth, c.config.CompLZO) + if c.config.OptionsString != "" { + options = c.config.OptionsString + } + peerInfo := InstallScriptPeerInfo(primaryCipher, c.config.DataCiphers, c.config.CompLZO, c.config.PeerInfo) + if c.config.PeerInfoRaw != "" { + peerInfo = RawPeerInfo(c.config.PeerInfoRaw) + } + clientRecord, err := NewClientKeyMethod2Record(options, peerInfo, c.authUser, c.authPass) if err != nil { return nil, err } @@ -336,11 +339,7 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { return nil, fmt.Errorf("negotiate data cipher: %w", err) } c.negotiatedCipher = negotiatedCipher - cipherKeyLen := CipherKeyLength(negotiatedCipher) - keys.SendCipherKey = keys.SendCipherKey[:cipherKeyLen] - keys.RecvCipherKey = keys.RecvCipherKey[:cipherKeyLen] - keyID := c.control.KeyID() - newData, err := NewDataChannel(keys, negotiatedCipher, c.config.Auth, push.PeerID, keyID) + newData, err := c.newDataChannel(keys, push, negotiatedCipher) if err != nil { return nil, err } @@ -370,16 +369,17 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { } c.negotiatedCipher = negotiatedCipher - // Slice the derived keys to the negotiated cipher's key length. - cipherKeyLen := CipherKeyLength(negotiatedCipher) - keys.SendCipherKey = keys.SendCipherKey[:cipherKeyLen] - keys.RecvCipherKey = keys.RecvCipherKey[:cipherKeyLen] - - keyID := c.control.KeyID() - newData, err := NewDataChannel(keys, negotiatedCipher, c.config.Auth, push.PeerID, keyID) + newData, err := c.newDataChannel(keys, push, negotiatedCipher) if err != nil { return nil, err } + // Dynamic tls-crypt: the first key state derives the control-channel + // key for all renegotiations (tls_session_generate_dynamic_tls_crypt_key). + if push.DynTLSCrypt && c.control.KeyID() == 0 { + if err := c.installDynamicTLSCrypt(); err != nil { + return nil, err + } + } c.installDataChannel(newData) c.captureAuthToken(push) c.markSend() @@ -387,6 +387,123 @@ func (c *Client) doKeyExchange(ctx context.Context) (*PushReply, error) { return push, nil } +// OpenVPN keying material exporter labels (ssl_backend.h). +const ( + exportKeyDataLabel = "EXPORTER-OpenVPN-datakeys" + exportDynamicTLSCryptLabel = "EXPORTER-OpenVPN-dynamic-tls-crypt" +) + +// newDataChannel builds the data channel of the current key state. prf holds +// the key-method 2 PRF keys; with tls-ekm the TLS keying material exporter +// replaces them (generate_key_expansion_tls_export). The epoch format takes +// its E1 secrets from the full cipher key slots. +func (c *Client) newDataChannel(prf *KeyMaterial, push *PushReply, cipherName string) (*DataChannel, error) { + keys := prf + if push.TLSEKM { + block, err := c.exportKeyingMaterial(exportKeyDataLabel) + if err != nil { + return nil, err + } + keys = keyMaterialFromBlock(block, maxCipherKeyLength) + } + keyID := c.control.KeyID() + if push.AEADEpoch { + return NewEpochDataChannel(keys, cipherName, push.PeerID, keyID) + } + cipherKeyLen := CipherKeyLength(cipherName) + keys.SendCipherKey = keys.SendCipherKey[:cipherKeyLen] + keys.RecvCipherKey = keys.RecvCipherKey[:cipherKeyLen] + return NewDataChannel(keys, cipherName, c.config.Auth, push.PeerID, keyID) +} + +func (c *Client) exportKeyingMaterial(label string) ([]byte, error) { + conn := c.tlsConn.Load() + if conn == nil { + return nil, errors.New("openvpn keying material export: no tls session") + } + state := conn.ConnectionState() + block, err := state.ExportKeyingMaterial(label, nil, keyBlockSize) + if err != nil { + return nil, fmt.Errorf("openvpn keying material export: %w", err) + } + return block, nil +} + +// installDynamicTLSCrypt derives the tls-crypt key for key IDs > 0: the +// exported key block XORed with the original tls-auth / tls-crypt key. +func (c *Client) installDynamicTLSCrypt() error { + block, err := c.exportKeyingMaterial(exportDynamicTLSCryptLabel) + if err != nil { + return err + } + var original []byte + switch { + case len(c.config.TLSCryptV2Key) > 0: + original = c.config.TLSCryptV2Key + case len(c.config.TLSCryptKey) > 0: + original = c.config.TLSCryptKey + case len(c.config.TLSAuthKey) > 0: + original = c.config.TLSAuthKey + } + for i := 0; i < len(original) && i < len(block); i++ { + block[i] ^= original[i] + } + crypt, err := NewTLSCrypt(block, true) + if err != nil { + return err + } + c.control.SetRenegCrypt(crypt) + return nil +} + +// OCC explicit-exit-notify data channel message (OCC_STRING + OCC_EXIT). +var occExitPacket = []byte{ + 0x28, 0x7f, 0x34, 0x6b, 0xd4, 0xef, 0x7a, 0x81, + 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9c, + 6, +} + +// SendExitNotify tells the server this client is disconnecting, as OpenVPN +// Connect does (send_explicit_exit_notify): an EXIT control message when the +// server pushed cc-exit, the OCC exit data packet otherwise. Only on UDP: a +// TCP server sees the connection close. +func (c *Client) SendExitNotify(ctx context.Context) error { + if c == nil || c.config.Proto != ProtoUDP { + return nil + } + push := c.push + if push == nil { + return nil + } + if !push.CCExit { + return c.writeDataPacket(ctx, occExitPacket, false) + } + conn := c.tlsConn.Load() + if conn == nil { + return errors.New("openvpn exit notify: no tls session") + } + if deadline, ok := ctx.Deadline(); ok { + _ = conn.SetWriteDeadline(deadline) + } + _, err := conn.Write([]byte("EXIT\x00")) + return err +} + +// AuthToken returns the session auth-token pushed by the server (with its +// auth-token-user), which OpenVPN Connect reuses as the password when it +// reconnects. +func (c *Client) AuthToken() (user, pass string, ok bool) { + if c == nil || c.push == nil || c.push.AuthTokenPass == "" { + return "", "", false + } + return c.authUser, c.authPass, true +} + +// IsAuthFailed reports whether err is the server's AUTH_FAILED. +func IsAuthFailed(err error) bool { + return errors.Is(err, errAuthFailed) +} + // consumeRekeyPush updates the cached push state after an authenticated // rekey: it inherits the previous peer-id and applies any fresh auth-token // pushed by send_push_reply_auth_token. Must be called only when c.push is @@ -1652,6 +1769,10 @@ func mergePushReply(prev, next *PushReply) *PushReply { if !next.BlockIPv6 { next.BlockIPv6 = prev.BlockIPv6 } + next.TLSEKM = next.TLSEKM || prev.TLSEKM + next.DynTLSCrypt = next.DynTLSCrypt || prev.DynTLSCrypt + next.AEADEpoch = next.AEADEpoch || prev.AEADEpoch + next.CCExit = next.CCExit || prev.CCExit if next.AuthTokenPass == "" { next.AuthTokenPass = prev.AuthTokenPass } @@ -1768,6 +1889,12 @@ func (c *Client) tlsConfig() (*tls.Config, error) { // servers rekey the control channel at regular intervals (default 1h). Renegotiation: tls.RenegotiateFreelyAsClient, } + // The keying material exporter is unavailable with renegotiation + // enabled. OpenVPN rekeys with a new TLS session per key ID, never by + // TLS renegotiation, so disable it when tls-ekm can be negotiated. + if announcesKeyExport(c.config.PeerInfoRaw) { + cfg.Renegotiation = tls.RenegotiateNever + } certPEM := bytes.TrimSpace(c.config.Cert) keyPEM := bytes.TrimSpace(c.config.Key) if len(certPEM) > 0 && len(keyPEM) > 0 { diff --git a/transport/openvpn/config.go b/transport/openvpn/config.go index 51690c3..13b115e 100644 --- a/transport/openvpn/config.go +++ b/transport/openvpn/config.go @@ -55,6 +55,13 @@ type ClientConfig struct { Password string PeerInfo map[string]string + // PeerInfoRaw replaces the generated peer-info verbatim (lines in the + // given order, e.g. copied from another client's log). Its IV_PROTO must + // announce only features this client implements: DATA_V2, REQUEST_PUSH, + // TLS_KEY_EXPORT, AUTH_PENDING_KW, DYN_TLS_CRYPT, DATA_EPOCH. + PeerInfoRaw string + // OptionsString replaces the generated key-method 2 options string. + OptionsString string PingInterval time.Duration PingRestart time.Duration diff --git a/transport/openvpn/control.go b/transport/openvpn/control.go index bd0f7e7..7cca17b 100644 --- a/transport/openvpn/control.go +++ b/transport/openvpn/control.go @@ -64,6 +64,13 @@ type ControlChannel struct { // protected control packets, mirroring OpenVPN's packet_id_rec. Soft key // resets do not replace the outer TLS wrapper or reset its packet IDs. recReplay replayState + // renegCrypt is the dynamic tls-crypt wrapper of key IDs > 0 + // (tls_session_get_tls_wrap), with its own packet IDs and replay window + // (OpenVPN tls_wrap_reneg). + renegCrypt ControlCryptor + renegPacketID uint32 + renegPacketTime uint32 + renegReplay replayState } // replayState is the receive-side OpenVPN long-form packet-id window. @@ -96,10 +103,22 @@ func reliableMessageBefore(messageID, recvMessage uint32) bool { // against the anti-replay window. Returns an error for replayed or stale // packets. Must be called with c.mu held. func (c *ControlChannel) checkReplayLocked(packetID, unixTime uint32) error { + return c.checkReplayStateLocked(&c.recReplay, packetID, unixTime) +} + +// checkKeyReplayLocked checks against the window of the wrapper that +// protects keyID: key IDs > 0 have their own with dynamic tls-crypt. +func (c *ControlChannel) checkKeyReplayLocked(keyID uint8, packetID, unixTime uint32) error { + if keyID != 0 && c.renegCrypt != nil { + return c.checkReplayStateLocked(&c.renegReplay, packetID, unixTime) + } + return c.checkReplayStateLocked(&c.recReplay, packetID, unixTime) +} + +func (c *ControlChannel) checkReplayStateLocked(r *replayState, packetID, unixTime uint32) error { if packetID == 0 { return errors.New("openvpn control replay: packet id 0") } - r := &c.recReplay replayClock := c.replayClock if replayClock == nil { replayClock = time.Now @@ -172,6 +191,21 @@ func NewControlChannel(io ControlIO, crypt ControlCryptor, local SessionID) *Con } } +// SetRenegCrypt installs the dynamic tls-crypt wrapper for key IDs > 0. +func (c *ControlChannel) SetRenegCrypt(crypt ControlCryptor) { + c.mu.Lock() + c.renegCrypt = crypt + c.mu.Unlock() +} + +// cryptForLocked returns the wrapper of control packets with keyID. +func (c *ControlChannel) cryptForLocked(keyID uint8) ControlCryptor { + if keyID != 0 && c.renegCrypt != nil { + return c.renegCrypt + } + return c.crypt +} + func (c *ControlChannel) LocalSessionID() SessionID { return c.local } @@ -543,7 +577,14 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro if err != nil { return nil, err } - packet, packetID, unixTime, err := DecodeControlPacket(c.crypt, raw) + c.mu.Lock() + crypt := c.crypt + if len(raw) > 0 { + _, rawKeyID := parseOpcodeKeyID(raw[0]) + crypt = c.cryptForLocked(rawKeyID) + } + c.mu.Unlock() + packet, packetID, unixTime, err := DecodeControlPacket(crypt, raw) if err != nil { // Invalid control datagrams are packet loss, not TLS stream errors. // OpenVPN drops malformed/authentication-failed packets and keeps the @@ -564,8 +605,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro initialReset := (packet.Opcode == PControlHardResetServerV2 || packet.Opcode == PControlHardResetServerV1) && packet.KeyID == c.keyID && packet.MessageID == 0 - if initialReset && c.crypt != nil { - if err := c.checkReplayLocked(packetID, unixTime); err != nil { + if initialReset && crypt != nil { + if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { c.mu.Unlock() continue } @@ -597,8 +638,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro if packet.KeyID == NextKeyID(curKey) && packet.MessageID == 0 && sameSession { // tls-auth/tls-crypt packet IDs belong to the outer TLS // session and remain continuous across key-state soft resets. - if c.crypt != nil { - if err := c.checkReplayLocked(packetID, unixTime); err != nil { + if crypt != nil { + if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { c.mu.Unlock() continue } @@ -625,8 +666,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro // cannot be fed into the new TLS session. continue } - if c.crypt != nil && !replayChecked { - if err := c.checkReplayLocked(packetID, unixTime); err != nil { + if crypt != nil && !replayChecked { + if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { c.mu.Unlock() continue } @@ -642,8 +683,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro continue } if softReset { - if c.crypt != nil { - if err := c.checkReplayLocked(packetID, unixTime); err != nil { + if crypt != nil { + if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { c.mu.Unlock() continue } @@ -652,8 +693,8 @@ func (c *ControlChannel) read(ctx context.Context, watchSoftReset bool) (*Contro c.mu.Unlock() return packet, nil } - if c.crypt != nil { - if err := c.checkReplayLocked(packetID, unixTime); err != nil { + if crypt != nil { + if err := c.checkKeyReplayLocked(packet.KeyID, packetID, unixTime); err != nil { c.mu.Unlock() continue } @@ -785,16 +826,21 @@ func (c *ControlChannel) writeControlPacketWithAbort(ctx context.Context, packet // writeControlPacketGranted writes while the caller owns sendGate. func (c *ControlChannel) writeControlPacketGranted(ctx context.Context, packet *ControlPacket, abortActive bool) error { c.mu.Lock() - if c.crypt != nil && c.sendPacketID == ^uint32(0) { + crypt := c.cryptForLocked(packet.KeyID) + sendPacketID, sendPacketTime := &c.sendPacketID, &c.sendPacketTime + if crypt != c.crypt { + sendPacketID, sendPacketTime = &c.renegPacketID, &c.renegPacketTime + } + if crypt != nil && *sendPacketID == ^uint32(0) { c.mu.Unlock() return errors.New("openvpn control packet id exhausted; new session required") } - if c.crypt != nil && c.sendPacketTime == 0 { - c.sendPacketTime = uint32(c.clock().Unix()) + if crypt != nil && *sendPacketTime == 0 { + *sendPacketTime = uint32(c.clock().Unix()) } - c.sendPacketID++ - packetID := c.sendPacketID - unixTime := c.sendPacketTime + *sendPacketID++ + packetID := *sendPacketID + unixTime := *sendPacketTime opCtx, cancel := context.WithCancelCause(ctx) c.writeGeneration++ generation := c.writeGeneration @@ -803,7 +849,7 @@ func (c *ControlChannel) writeControlPacketGranted(ctx context.Context, packet * c.mu.Unlock() defer c.finishWrite(generation, cancel) - encoded, err := packet.Encode(c.crypt, packetID, unixTime) + encoded, err := packet.Encode(crypt, packetID, unixTime) if err != nil { return err } diff --git a/transport/openvpn/data.go b/transport/openvpn/data.go index 51e171d..8a674f1 100644 --- a/transport/openvpn/data.go +++ b/transport/openvpn/data.go @@ -79,6 +79,28 @@ type DataChannel struct { randMu sync.Mutex randBuf []byte randOffset int + + // epoch is set for the epoch data key format (aead-epoch); it replaces + // the AEAD keys and packet ID above. Guarded by d.mu. + epoch *epochState +} + +// NewEpochDataChannel creates a data channel in the epoch data key format. +// keys must hold at least the first 32 bytes of each cipher key slot. +func NewEpochDataChannel(keys *KeyMaterial, cipherName string, peerID uint32, keyID uint8) (*DataChannel, error) { + if keys == nil { + return nil, errors.New("nil openvpn key material") + } + epoch, err := newEpochState(cipherName, keys.SendCipherKey, keys.RecvCipherKey) + if err != nil { + return nil, err + } + return &DataChannel{ + epoch: epoch, + keyID: keyID & KeyIDMask, + peerID: peerID, + header: dataHeader(peerID, keyID), + }, nil } func NewDataChannel(keys *KeyMaterial, cipherName, authName string, peerID uint32, keyID uint8) (*DataChannel, error) { @@ -198,6 +220,9 @@ func (d *DataChannel) Encrypt(packet []byte) ([]byte, error) { if d == nil { return nil, errors.New("nil openvpn data channel") } + if d.epoch != nil { + return d.encryptEpoch(packet) + } packetID, err := d.nextPacketID() if err != nil { @@ -265,6 +290,9 @@ func (d *DataChannel) Decrypt(packet []byte) ([]byte, error) { if err != nil { return nil, err } + if d.epoch != nil { + return d.decryptEpoch(packet, headerSize) + } if d.recvAEAD != nil { return d.decryptAEAD(packet, headerSize) } diff --git a/transport/openvpn/data_epoch.go b/transport/openvpn/data_epoch.go new file mode 100644 index 0000000..ac241b2 --- /dev/null +++ b/transport/openvpn/data_epoch.go @@ -0,0 +1,300 @@ +package openvpn + +import ( + "crypto/cipher" + "crypto/hmac" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" +) + +// Epoch data keys (OpenVPN 2.7 crypto_epoch.c, pushed as "protocol-flags +// aead-epoch" to peers announcing IV_PROTO_DATA_EPOCH). The packet ID is +// 64 bits (16-bit epoch + 48-bit counter), the AEAD tag follows the +// ciphertext, and every epoch has its own key derived with +// OVPN-Expand-Label from a per-direction epoch secret. + +const ( + // future receive keys kept ahead of the current one (init_epoch_keys) + epochFutureKeys = 4 + epochSecretSize = 32 + epochPacketIDSize = 8 + epochCounterMax = uint64(1)<<48 - 1 + // AES-GCM usage limit q + s <= 2^36 - 1 blocks (cipher_get_aead_limits); + // ChaCha20-Poly1305 has none. + epochAESGCMBlockLimit = uint64(1)<<36 - 1 +) + +type epochKey struct { + epoch uint16 + aead cipher.AEAD + iv [DataChannelIVSize]byte + blocks uint64 + replay epochReplay +} + +// epochReplay is the per-key receive window (packet_id_rec, 64 packets). +type epochReplay struct { + highest uint64 + window uint64 + seen bool +} + +type epochState struct { + cipherName string + limit uint64 + + sendSecret [epochSecretSize]byte + sendEpoch uint16 + send *epochKey + sendCounter uint64 + + // recvSecret is the secret of the highest generated receive epoch. + recvSecret [epochSecretSize]byte + recvEpoch uint16 + recv *epochKey + retiring *epochKey + future []*epochKey +} + +// ovpnHKDFExpand is HKDF-Expand (RFC 5869) with HMAC-SHA256 (ovpn_hkdf_expand). +func ovpnHKDFExpand(secret, info []byte, size int) []byte { + out := make([]byte, 0, size+sha256.Size) + var prev []byte + for block := byte(1); len(out) < size; block++ { + mac := hmac.New(sha256.New, secret) + mac.Write(prev) + mac.Write(info) + mac.Write([]byte{block}) + prev = mac.Sum(nil) + out = append(out, prev...) + } + return out[:size] +} + +// ovpnExpandLabel is OVPN-Expand-Label(secret, label, "", size): the TLS 1.3 +// HkdfLabel layout with the "ovpn " prefix and an empty context. +func ovpnExpandLabel(secret []byte, label string, size int) []byte { + info := make([]byte, 0, 2+1+5+len(label)+1) + info = binary.BigEndian.AppendUint16(info, uint16(size)) + info = append(info, byte(5+len(label))) + info = append(info, "ovpn "...) + info = append(info, label...) + info = append(info, 0) + return ovpnHKDFExpand(secret, info, size) +} + +// E_n+1 = OVPN-Expand-Label(E_n, "datakey upd", "", 32) +func epochIterate(secret *[epochSecretSize]byte) { + copy(secret[:], ovpnExpandLabel(secret[:], "datakey upd", epochSecretSize)) +} + +func newEpochKey(cipherName string, secret []byte, epoch uint16) (*epochKey, error) { + aead, err := newDataChannelAEAD(cipherName, ovpnExpandLabel(secret, "data_key", CipherKeyLength(cipherName))) + if err != nil { + return nil, err + } + k := &epochKey{epoch: epoch, aead: aead} + copy(k.iv[:], ovpnExpandLabel(secret, "data_iv", DataChannelIVSize)) + return k, nil +} + +// newEpochState starts both directions at epoch 1. The E1 secrets are the +// first 32 bytes of the cipher key slots of the key2 block (init_epoch_keys). +func newEpochState(cipherName string, sendSecret, recvSecret []byte) (*epochState, error) { + if !isDataChannelAEAD(cipherName) { + return nil, fmt.Errorf("openvpn epoch data keys need an AEAD cipher, got %q", cipherName) + } + if len(sendSecret) < epochSecretSize || len(recvSecret) < epochSecretSize { + return nil, errors.New("openvpn epoch key material is too short") + } + s := &epochState{cipherName: cipherName, sendEpoch: 1, recvEpoch: 1} + if cipherName != CipherChaCha20Poly1305 { + s.limit = epochAESGCMBlockLimit + } + copy(s.sendSecret[:], sendSecret) + copy(s.recvSecret[:], recvSecret) + var err error + if s.send, err = newEpochKey(cipherName, s.sendSecret[:], 1); err != nil { + return nil, err + } + if s.recv, err = newEpochKey(cipherName, s.recvSecret[:], 1); err != nil { + return nil, err + } + return s, s.fillFuture() +} + +// fillFuture keeps keys for epochs recv+1 .. recv+epochFutureKeys +// (epoch_generate_future_receive_keys). +func (s *epochState) fillFuture() error { + kept := s.future[:0] + for _, k := range s.future { + if k.epoch > s.recv.epoch { + kept = append(kept, k) + } + } + s.future = kept + for s.recvEpoch < s.recv.epoch+epochFutureKeys && s.recvEpoch < ^uint16(0) { + epochIterate(&s.recvSecret) + s.recvEpoch++ + k, err := newEpochKey(s.cipherName, s.recvSecret[:], s.recvEpoch) + if err != nil { + return err + } + s.future = append(s.future, k) + } + return nil +} + +// advanceSend moves the send key to epoch (epoch_iterate_send_key); the +// packet counter restarts for the new key. +func (s *epochState) advanceSend(epoch uint16) error { + for s.sendEpoch < epoch { + epochIterate(&s.sendSecret) + s.sendEpoch++ + } + k, err := newEpochKey(s.cipherName, s.sendSecret[:], s.sendEpoch) + if err != nil { + return err + } + s.send = k + s.sendCounter = 0 + return nil +} + +// lookup returns the receive key of epoch (epoch_lookup_decrypt_key). +func (s *epochState) lookup(epoch uint16) *epochKey { + if s.recv.epoch == epoch { + return s.recv + } + if s.retiring != nil && s.retiring.epoch == epoch { + return s.retiring + } + // at the edge of the epoch space the window cannot move any further + if epoch > ^uint16(0)-epochFutureKeys-1 { + return nil + } + for _, k := range s.future { + if k.epoch == epoch { + return k + } + } + return nil +} + +// promote makes an authenticated future key the current receive key and +// follows the peer with the send key (epoch_replace_update_recv_key). +func (s *epochState) promote(k *epochKey) error { + if s.send.epoch < k.epoch { + if err := s.advanceSend(k.epoch); err != nil { + return err + } + } + s.retiring = s.recv + s.recv = k + return s.fillFuture() +} + +func (r *epochReplay) accept(id uint64) error { + if !r.seen { + *r = epochReplay{highest: id, window: 1, seen: true} + return nil + } + if id > r.highest { + shift := id - r.highest + if shift >= dataChannelReplayWindow { + r.window = 1 + } else { + r.window = r.window<= dataChannelReplayWindow || r.window&mask != 0 { + return fmt.Errorf("openvpn replayed data packet id %d", id) + } + r.window |= mask + return nil +} + +func epochNonce(iv [DataChannelIVSize]byte, packetID []byte) [DataChannelIVSize]byte { + for i, b := range packetID { + iv[i] ^= b + } + return iv +} + +func (d *DataChannel) encryptEpoch(packet []byte) ([]byte, error) { + s := d.epoch + d.mu.Lock() + // epoch_check_send_iterate: a fresh key before the usage limit or the + // 48-bit counter runs out + if (s.limit != 0 && s.send.blocks >= s.limit) || s.sendCounter >= epochCounterMax { + if s.sendEpoch == ^uint16(0) { + d.mu.Unlock() + return nil, errDataPacketIDExhausted + } + if err := s.advanceSend(s.sendEpoch + 1); err != nil { + d.mu.Unlock() + return nil, err + } + } + s.sendCounter++ + key := s.send + key.blocks += uint64(epochPacketIDSize+len(packet)+DataChannelTagSize+15) / 16 + var packetID [epochPacketIDSize]byte + binary.BigEndian.PutUint64(packetID[:], uint64(key.epoch)<<48|s.sendCounter) + d.mu.Unlock() + + header := d.header + nonce := epochNonce(key.iv, packetID[:]) + out := make([]byte, 0, len(header)+epochPacketIDSize+len(packet)+DataChannelTagSize) + out = append(out, header...) + out = append(out, packetID[:]...) + return key.aead.Seal(out, nonce[:], packet, aeadAdditionalData(header, packetID[:])), nil +} + +func (d *DataChannel) decryptEpoch(packet []byte, headerSize int) ([]byte, error) { + if len(packet) < headerSize+epochPacketIDSize+DataChannelTagSize+1 { + return nil, errors.New("openvpn data packet too short") + } + header := packet[:headerSize] + packetID := packet[headerSize : headerSize+epochPacketIDSize] + id := binary.BigEndian.Uint64(packetID) + epoch := uint16(id >> 48) + if epoch == 0 { + return nil, errors.New("openvpn data packet with epoch 0") + } + s := d.epoch + d.mu.Lock() + key := s.lookup(epoch) + d.mu.Unlock() + if key == nil { + return nil, fmt.Errorf("openvpn data packet with unknown epoch %d", epoch) + } + nonce := epochNonce(key.iv, packetID) + plain, err := key.aead.Open(nil, nonce[:], packet[headerSize+epochPacketIDSize:], aeadAdditionalData(header, packetID)) + if err != nil { + return nil, err + } + + d.mu.Lock() + defer d.mu.Unlock() + // The peer authenticated a packet with a newer epoch: move to it. Lookup + // again, a concurrent packet may have promoted it already. + if key != s.recv && key != s.retiring { + if s.lookup(epoch) != key { + return nil, fmt.Errorf("openvpn data packet with stale epoch %d", epoch) + } + if err := s.promote(key); err != nil { + return nil, err + } + } + if err := key.replay.accept(id & epochCounterMax); err != nil { + return nil, err + } + return plain, nil +} diff --git a/transport/openvpn/data_epoch_test.go b/transport/openvpn/data_epoch_test.go new file mode 100644 index 0000000..a675846 --- /dev/null +++ b/transport/openvpn/data_epoch_test.go @@ -0,0 +1,263 @@ +package openvpn + +import ( + "bytes" + "context" + "encoding/binary" + "testing" +) + +// Vectors from OpenVPN tests/unit_tests/openvpn/test_crypto.c. + +func TestOVPNHKDFExpandVector(t *testing.T) { + prk := []byte{0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0x3f, + 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, + 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5} + info := []byte{0x00, 0x1b, 0x0e, 0x6f, 0x76, 0x70, 0x6e, 0x20, 0x75, + 0x6e, 0x69, 0x74, 0x20, 0x74, 0x65, 0x73, 0x74, 0x00} + want := []byte{0x87, 0x5a, 0x8e, 0xec, 0x18, 0x55, 0x63, 0x80, 0xb8, + 0xd9, 0x33, 0xed, 0x32, 0x3c, 0x2d, 0xf8, 0xe8, 0xec, + 0xcf, 0x49, 0x72, 0xe6, 0x83, 0xf0, 0x6a, 0x83, 0xac} + if got := ovpnHKDFExpand(prk, info, len(want)); !bytes.Equal(got, want) { + t.Fatalf("hkdf expand = %x, want %x", got, want) + } + // the info above is the HkdfLabel of "unit test" with length 27 + if got := ovpnExpandLabel(prk, "unit test", len(want)); !bytes.Equal(got, want) { + t.Fatalf("expand label = %x, want %x", got, want) + } +} + +func TestOVPNExpandLabelVector(t *testing.T) { + secret := []byte{0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0x3f, + 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, + 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5} + want := []byte{0x18, 0x5e, 0xaa, 0x1c, 0x7f, 0x22, 0x8a, 0xb8, + 0xeb, 0x29, 0x77, 0x32, 0x14, 0xd9, 0x20, 0x46} + if got := ovpnExpandLabel(secret, "unit test", 16); !bytes.Equal(got, want) { + t.Fatalf("expand label = %x, want %x", got, want) + } +} + +func TestEpochDataKeyDeriveVector(t *testing.T) { + secret := make([]byte, epochSecretSize) + secret[0], secret[1] = 19, 12 + wantKey := []byte{0xed, 0x85, 0x33, 0xdb, 0x1c, 0x28, 0xac, 0xe4, + 0x18, 0xe9, 0x00, 0x6a, 0xb2, 0x9c, 0x17, 0x41, + 0x7d, 0x60, 0xeb, 0xe6, 0xcd, 0x90, 0xbf, 0x0a} + wantIV := []byte{0x86, 0x89, 0x0a, 0xab, 0xf0, 0x32, + 0xcb, 0x59, 0xf4, 0xcf, 0xa3, 0x4e} + if got := ovpnExpandLabel(secret, "data_key", CipherKeyLength(CipherAES192GCM)); !bytes.Equal(got, wantKey) { + t.Fatalf("data key = %x, want %x", got, wantKey) + } + k, err := newEpochKey(CipherAES192GCM, secret, 17) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(k.iv[:], wantIV) { + t.Fatalf("implicit iv = %x, want %x", k.iv, wantIV) + } +} + +func newEpochPair(t *testing.T, cipherName string) (client, server *DataChannel) { + t.Helper() + c2s := bytes.Repeat([]byte{0x23}, maxCipherKeyLength) + s2c := bytes.Repeat([]byte{0x27}, maxCipherKeyLength) + client, err := NewEpochDataChannel(&KeyMaterial{SendCipherKey: c2s, RecvCipherKey: s2c}, cipherName, 7, 0) + if err != nil { + t.Fatal(err) + } + server, err = NewEpochDataChannel(&KeyMaterial{SendCipherKey: s2c, RecvCipherKey: c2s}, cipherName, 7, 0) + if err != nil { + t.Fatal(err) + } + return client, server +} + +func TestEpochDataChannelWireFormat(t *testing.T) { + client, server := newEpochPair(t, CipherAES256GCM) + payload := []byte("epoch data channel payload") + packet, err := client.Encrypt(payload) + if err != nil { + t.Fatal(err) + } + // P_DATA_V2 header, 16-bit epoch + 48-bit counter, ciphertext, tag at the end + if want := 4 + 8 + len(payload) + DataChannelTagSize; len(packet) != want { + t.Fatalf("packet length %d, want %d", len(packet), want) + } + if id := binary.BigEndian.Uint64(packet[4:12]); id != 1<<48|1 { + t.Fatalf("packet id %x, want epoch 1 counter 1", id) + } + plain, err := server.Decrypt(packet) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(plain, payload) { + t.Fatalf("plaintext %q", plain) + } + if _, err := server.Decrypt(packet); err == nil { + t.Fatal("replayed packet accepted") + } + tampered := cloneBytes(packet) + tampered[2] ^= 1 // peer-id is authenticated + if _, err := server.Decrypt(tampered); err == nil { + t.Fatal("tampered header accepted") + } +} + +func TestEpochDataChannelFollowsPeerEpoch(t *testing.T) { + for _, cipherName := range []string{CipherAES128GCM, CipherChaCha20Poly1305} { + client, server := newEpochPair(t, cipherName) + old, err := server.Encrypt([]byte("epoch 1")) + if err != nil { + t.Fatal(err) + } + server.mu.Lock() + if err := server.epoch.advanceSend(3); err != nil { + t.Fatal(err) + } + server.mu.Unlock() + packet, err := server.Encrypt([]byte("epoch 3")) + if err != nil { + t.Fatal(err) + } + if epoch := binary.BigEndian.Uint16(packet[4:6]); epoch != 3 { + t.Fatalf("server epoch %d", epoch) + } + if plain, err := client.Decrypt(packet); err != nil || string(plain) != "epoch 3" { + t.Fatalf("decrypt epoch 3: %q %v", plain, err) + } + // the retiring epoch still decrypts after the switch + if plain, err := client.Decrypt(old); err != nil || string(plain) != "epoch 1" { + t.Fatalf("decrypt retiring epoch: %q %v", plain, err) + } + reply, err := client.Encrypt([]byte("reply")) + if err != nil { + t.Fatal(err) + } + if epoch := binary.BigEndian.Uint16(reply[4:6]); epoch != 3 { + t.Fatalf("client did not follow to epoch 3, sent %d", epoch) + } + if id := binary.BigEndian.Uint64(reply[4:12]) & epochCounterMax; id != 1 { + t.Fatalf("counter did not restart: %d", id) + } + if plain, err := server.Decrypt(reply); err != nil || string(plain) != "reply" { + t.Fatalf("server decrypt: %q %v", plain, err) + } + // beyond the future window + server.mu.Lock() + if err := server.epoch.advanceSend(3 + epochFutureKeys + 1); err != nil { + t.Fatal(err) + } + server.mu.Unlock() + far, _ := server.Encrypt([]byte("far")) + if _, err := client.Decrypt(far); err == nil { + t.Fatal("epoch outside the future window accepted") + } + } +} + +func TestEpochSendKeyIteratesAtUsageLimit(t *testing.T) { + client, server := newEpochPair(t, CipherAES256GCM) + client.mu.Lock() + client.epoch.send.blocks = client.epoch.limit + client.mu.Unlock() + packet, err := client.Encrypt([]byte("x")) + if err != nil { + t.Fatal(err) + } + if epoch := binary.BigEndian.Uint16(packet[4:6]); epoch != 2 { + t.Fatalf("epoch %d, want 2", epoch) + } + if _, err := server.Decrypt(packet); err != nil { + t.Fatal(err) + } +} + +func TestPushReplyProtocolFlags(t *testing.T) { + reply, err := ParsePushReply("PUSH_REPLY,ifconfig 172.16.192.3 255.255.252.0,peer-id 7,cipher AES-256-GCM,protocol-flags cc-exit tls-ekm dyn-tls-crypt aead-epoch,tun-mtu 1500") + if err != nil { + t.Fatal(err) + } + if !reply.TLSEKM || !reply.DynTLSCrypt || !reply.AEADEpoch || !reply.CCExit { + t.Fatalf("flags not parsed: %+v", reply) + } + legacy, err := ParsePushReply("PUSH_REPLY,ifconfig 10.8.0.2 255.255.255.0,key-derivation tls-ekm") + if err != nil { + t.Fatal(err) + } + if !legacy.TLSEKM || legacy.DynTLSCrypt || legacy.AEADEpoch { + t.Fatalf("key-derivation: %+v", legacy) + } + // a token-only rekey push keeps the negotiated features + merged := mergePushReply(reply, &PushReply{PeerID: PeerIDUnset}) + if !merged.TLSEKM || !merged.DynTLSCrypt || !merged.AEADEpoch || !merged.CCExit { + t.Fatalf("merge lost flags: %+v", merged) + } +} + +func TestRawPeerInfo(t *testing.T) { + got := RawPeerInfo("IV_VER=3.11.1\r\n IV_PLAT=mac\n\nIV_PROTO=8094") + if want := "IV_VER=3.11.1\nIV_PLAT=mac\nIV_PROTO=8094\n"; got != want { + t.Fatalf("raw peer info %q, want %q", got, want) + } +} + +func TestDynamicTLSCryptWrapsRenegotiations(t *testing.T) { + clientIO, serverIO := newMemoryPacketPair() + defer clientIO.Close() + defer serverIO.Close() + base, err := NewTLSCrypt(testStaticKey(), true) + if err != nil { + t.Fatal(err) + } + dynKey := bytes.Repeat([]byte{0x5a}, staticKeySize) + dyn, err := NewTLSCrypt(dynKey, true) + if err != nil { + t.Fatal(err) + } + var id SessionID + copy(id[:], "client01") + channel := NewControlChannel(clientIO, base, id) + ctx := context.Background() + send := func(keyID uint8) []byte { + t.Helper() + packet := &ControlPacket{Opcode: PAckV1, KeyID: keyID, LocalSession: id, AckIDs: []uint32{1}} + if err := channel.writeControlPacket(ctx, packet); err != nil { + t.Fatal(err) + } + raw, err := serverIO.ReadPacket(ctx) + if err != nil { + t.Fatal(err) + } + return raw + } + send(0) + channel.SetRenegCrypt(dyn) + + serverBase, _ := NewTLSCrypt(testStaticKey(), false) + serverDyn, _ := NewTLSCrypt(dynKey, false) + if _, packetID, _, _, err := serverBase.Unwrap(send(0)); err != nil || packetID != 2 { + t.Fatalf("key 0 after dyn: id %d err %v", packetID, err) + } + raw := send(1) + if _, _, _, _, err := serverBase.Unwrap(raw); err == nil { + t.Fatal("key 1 wrapped with the original tls-crypt key") + } + // tls_wrap_reneg has its own packet ID sequence + if _, packetID, _, _, err := serverDyn.Unwrap(raw); err != nil || packetID != 1 { + t.Fatalf("key 1: id %d err %v", packetID, err) + } + + channel.mu.Lock() + defer channel.mu.Unlock() + if err := channel.checkKeyReplayLocked(0, 50, 1000); err != nil { + t.Fatal(err) + } + // the reneg window is separate: id 1 is fresh there + if err := channel.checkKeyReplayLocked(1, 1, 2000); err != nil { + t.Fatal(err) + } + if err := channel.checkKeyReplayLocked(0, 49, 1000); err != nil { + t.Fatalf("key 0 window disturbed by key 1: %v", err) + } +} diff --git a/transport/openvpn/keymethod.go b/transport/openvpn/keymethod.go index 8f2c104..b451163 100644 --- a/transport/openvpn/keymethod.go +++ b/transport/openvpn/keymethod.go @@ -11,6 +11,7 @@ import ( "fmt" "hash" "sort" + "strconv" "strings" ) @@ -238,6 +239,12 @@ func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession Se return nil, err } + return keyMaterialFromBlock(keyBlock, cipherKeyLen), nil +} + +// keyMaterialFromBlock splits an OpenVPN key2 block (two cipher+HMAC slots, +// client-to-server first) into the client's send and receive keys. +func keyMaterialFromBlock(keyBlock []byte, cipherKeyLen int) *KeyMaterial { clientToServer := keyBlock[:maxCipherKeyLength+maxHMACKeyLength] serverToClient := keyBlock[maxCipherKeyLength+maxHMACKeyLength:] return &KeyMaterial{ @@ -245,7 +252,7 @@ func DeriveClientKeyMaterial(sources KeySource2, clientSession, serverSession Se SendHMACKey: cloneBytes(clientToServer[maxCipherKeyLength : maxCipherKeyLength+maxHMACKeyLength]), RecvCipherKey: cloneBytes(serverToClient[:cipherKeyLen]), RecvHMACKey: cloneBytes(serverToClient[maxCipherKeyLength : maxCipherKeyLength+maxHMACKeyLength]), - }, nil + } } func InstallScriptOptionsString(proto, cipher, auth string, compLZO string) string { @@ -311,6 +318,37 @@ func InstallScriptPeerInfo(cipher string, dataCiphers []string, compLZO string, return info } +// RawPeerInfo normalizes a verbatim peer-info block: one KEY=value per line, +// blank lines dropped, each line newline-terminated like OpenVPN sends it. +func RawPeerInfo(raw string) string { + var b strings.Builder + for _, line := range strings.Split(strings.ReplaceAll(raw, "\r\n", "\n"), "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + b.WriteString(line) + b.WriteByte('\n') + } + return b.String() +} + +// IV_PROTO_TLS_KEY_EXPORT: the server derives the data keys with the TLS +// keying material exporter. +const ivProtoTLSKeyExport = 1 << 3 + +// announcesKeyExport reports whether a raw peer-info announces +// IV_PROTO_TLS_KEY_EXPORT. +func announcesKeyExport(peerInfo string) bool { + for _, line := range strings.Split(peerInfo, "\n") { + if value, ok := strings.CutPrefix(strings.TrimSpace(line), "IV_PROTO="); ok { + proto, err := strconv.Atoi(value) + return err == nil && proto&ivProtoTLSKeyExport != 0 + } + } + return false +} + func appendOpenVPNString(out []byte, s string) []byte { if s == "" { return binary.BigEndian.AppendUint16(out, 0) diff --git a/transport/openvpn/push.go b/transport/openvpn/push.go index df84904..ae17dcb 100644 --- a/transport/openvpn/push.go +++ b/transport/openvpn/push.go @@ -29,6 +29,14 @@ type PushReply struct { // option (legacy or fallback). Cipher string + // Negotiated protocol features ("protocol-flags", or the older + // "key-derivation tls-ekm"). The server enables them for the bits the + // client announced in IV_PROTO. + TLSEKM bool // data keys from the TLS keying material exporter + DynTLSCrypt bool // control packets of key IDs > 0 use a derived tls-crypt key + AEADEpoch bool // epoch data key format + CCExit bool // exit notification as an EXIT control message + // AuthToken is the most recently pushed auth-token / auth-token-user // pair. Empty when the server does not rotate credentials. AuthTokenUser string @@ -144,6 +152,23 @@ func parsePushReplyInner(message string) (*PushReply, error) { if len(fields) >= 2 { reply.Cipher = strings.TrimSpace(fields[1]) } + case "key-derivation": + if len(fields) >= 2 && fields[1] == "tls-ekm" { + reply.TLSEKM = true + } + case "protocol-flags": + for _, flag := range fields[1:] { + switch flag { + case "tls-ekm": + reply.TLSEKM = true + case "dyn-tls-crypt": + reply.DynTLSCrypt = true + case "aead-epoch": + reply.AEADEpoch = true + case "cc-exit": + reply.CCExit = true + } + } case "auth-token": if len(fields) >= 2 { reply.AuthTokenPass = strings.TrimSpace(fields[1])