Source file src/crypto/tls/ech.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls
     6  
     7  import (
     8  	"bytes"
     9  	"crypto/ecdh"
    10  	"crypto/hpke"
    11  	"errors"
    12  	"fmt"
    13  	"io"
    14  	"net/netip"
    15  	"slices"
    16  	"strings"
    17  
    18  	"golang.org/x/crypto/cryptobyte"
    19  )
    20  
    21  // echAEADTagLen is the AEAD tag length used to size HPKE ciphertexts in the
    22  // outer encrypted_client_hello extension. All HPKE AEADs supported by
    23  // crypto/hpke (AES-128-GCM, AES-256-GCM, ChaCha20Poly1305) use a 16 byte tag.
    24  // If support is added for an AEAD with a different tag length this constant
    25  // must also be replaced with a per-AEAD constant.
    26  const echAEADTagLen = 16
    27  
    28  type echCipher struct {
    29  	KDFID  uint16
    30  	AEADID uint16
    31  }
    32  
    33  type echExtension struct {
    34  	Type uint16
    35  	Data []byte
    36  }
    37  
    38  type echConfig struct {
    39  	raw []byte
    40  
    41  	Version uint16
    42  	Length  uint16
    43  
    44  	ConfigID             uint8
    45  	KemID                uint16
    46  	PublicKey            []byte
    47  	SymmetricCipherSuite []echCipher
    48  
    49  	MaxNameLength uint8
    50  	PublicName    []byte
    51  	Extensions    []echExtension
    52  }
    53  
    54  var errMalformedECHConfigList = errors.New("tls: malformed ECHConfigList")
    55  
    56  type echConfigErr struct {
    57  	field string
    58  }
    59  
    60  func (e *echConfigErr) Error() string {
    61  	if e.field == "" {
    62  		return "tls: malformed ECHConfig"
    63  	}
    64  	return fmt.Sprintf("tls: malformed ECHConfig, invalid %s field", e.field)
    65  }
    66  
    67  func parseECHConfig(enc []byte) (skip bool, ec echConfig, err error) {
    68  	s := cryptobyte.String(enc)
    69  	ec.raw = enc
    70  	if !s.ReadUint16(&ec.Version) {
    71  		return false, echConfig{}, &echConfigErr{"version"}
    72  	}
    73  	if !s.ReadUint16(&ec.Length) {
    74  		return false, echConfig{}, &echConfigErr{"length"}
    75  	}
    76  	if len(ec.raw) < int(ec.Length)+4 {
    77  		return false, echConfig{}, &echConfigErr{"length"}
    78  	}
    79  	ec.raw = ec.raw[:int(ec.Length)+4]
    80  	if ec.Version != extensionEncryptedClientHello {
    81  		s.Skip(int(ec.Length))
    82  		return true, echConfig{}, nil
    83  	}
    84  	if !s.ReadUint8(&ec.ConfigID) {
    85  		return false, echConfig{}, &echConfigErr{"config_id"}
    86  	}
    87  	if !s.ReadUint16(&ec.KemID) {
    88  		return false, echConfig{}, &echConfigErr{"kem_id"}
    89  	}
    90  	if !readUint16LengthPrefixed(&s, &ec.PublicKey) {
    91  		return false, echConfig{}, &echConfigErr{"public_key"}
    92  	}
    93  	var cipherSuites cryptobyte.String
    94  	if !s.ReadUint16LengthPrefixed(&cipherSuites) {
    95  		return false, echConfig{}, &echConfigErr{"cipher_suites"}
    96  	}
    97  	for !cipherSuites.Empty() {
    98  		var c echCipher
    99  		if !cipherSuites.ReadUint16(&c.KDFID) {
   100  			return false, echConfig{}, &echConfigErr{"cipher_suites kdf_id"}
   101  		}
   102  		if !cipherSuites.ReadUint16(&c.AEADID) {
   103  			return false, echConfig{}, &echConfigErr{"cipher_suites aead_id"}
   104  		}
   105  		ec.SymmetricCipherSuite = append(ec.SymmetricCipherSuite, c)
   106  	}
   107  	if !s.ReadUint8(&ec.MaxNameLength) {
   108  		return false, echConfig{}, &echConfigErr{"maximum_name_length"}
   109  	}
   110  	var publicName cryptobyte.String
   111  	if !s.ReadUint8LengthPrefixed(&publicName) {
   112  		return false, echConfig{}, &echConfigErr{"public_name"}
   113  	}
   114  	ec.PublicName = publicName
   115  	var extensions cryptobyte.String
   116  	if !s.ReadUint16LengthPrefixed(&extensions) {
   117  		return false, echConfig{}, &echConfigErr{"extensions"}
   118  	}
   119  	for !extensions.Empty() {
   120  		var e echExtension
   121  		if !extensions.ReadUint16(&e.Type) {
   122  			return false, echConfig{}, &echConfigErr{"extensions type"}
   123  		}
   124  		if !extensions.ReadUint16LengthPrefixed((*cryptobyte.String)(&e.Data)) {
   125  			return false, echConfig{}, &echConfigErr{"extensions data"}
   126  		}
   127  		ec.Extensions = append(ec.Extensions, e)
   128  	}
   129  
   130  	return false, ec, nil
   131  }
   132  
   133  // parseECHConfigList parses a RFC 9849 ECHConfigList, returning a
   134  // slice of parsed ECHConfigs, in the same order they were parsed, or an error
   135  // if the list is malformed.
   136  func parseECHConfigList(data []byte) ([]echConfig, error) {
   137  	s := cryptobyte.String(data)
   138  	var length uint16
   139  	if !s.ReadUint16(&length) {
   140  		return nil, errMalformedECHConfigList
   141  	}
   142  	if int(length) != len(data)-2 {
   143  		return nil, errMalformedECHConfigList
   144  	}
   145  	var configs []echConfig
   146  	for len(s) > 0 {
   147  		if len(s) < 4 {
   148  			return nil, errors.New("tls: malformed ECHConfig")
   149  		}
   150  		configLen := int(s[2])<<8 | int(s[3])
   151  		skip, ec, err := parseECHConfig(s)
   152  		if err != nil {
   153  			return nil, err
   154  		}
   155  		s = s[configLen+4:]
   156  		if !skip {
   157  			configs = append(configs, ec)
   158  		}
   159  	}
   160  	return configs, nil
   161  }
   162  
   163  func pickECHConfig(list []echConfig) (*echConfig, hpke.PublicKey, hpke.KDF, hpke.AEAD) {
   164  	for _, ec := range list {
   165  		if !validDNSName(string(ec.PublicName)) {
   166  			continue
   167  		}
   168  		var unsupportedExt bool
   169  		for _, ext := range ec.Extensions {
   170  			// If high order bit is set to 1 the extension is mandatory.
   171  			// Since we don't support any extensions, if we see a mandatory
   172  			// bit, we skip the config.
   173  			if ext.Type&uint16(1<<15) != 0 {
   174  				unsupportedExt = true
   175  			}
   176  		}
   177  		if unsupportedExt {
   178  			continue
   179  		}
   180  		kem, err := hpke.NewKEM(ec.KemID)
   181  		if err != nil {
   182  			continue
   183  		}
   184  		pub, err := kem.NewPublicKey(ec.PublicKey)
   185  		if err != nil {
   186  			// This is an error in the config, but killing the connection feels
   187  			// excessive.
   188  			continue
   189  		}
   190  		for _, cs := range ec.SymmetricCipherSuite {
   191  			// All of the supported AEADs and KDFs are fine, rather than
   192  			// imposing some sort of preference here, we just pick the first
   193  			// valid suite.
   194  			kdf, err := hpke.NewKDF(cs.KDFID)
   195  			if err != nil {
   196  				continue
   197  			}
   198  			// 0xFFFF is an export-only AEAD that cannot seal/open, making
   199  			// it an invalid choice for encrypting ClientHelloInner.
   200  			if cs.AEADID == 0xFFFF {
   201  				continue
   202  			}
   203  			aead, err := hpke.NewAEAD(cs.AEADID)
   204  			if err != nil {
   205  				continue
   206  			}
   207  			return &ec, pub, kdf, aead
   208  		}
   209  	}
   210  	return nil, nil, nil, nil
   211  }
   212  
   213  func encodeInnerClientHello(inner *clientHelloMsg, maxNameLength int) ([]byte, error) {
   214  	h, err := inner.marshalMsg(true)
   215  	if err != nil {
   216  		return nil, err
   217  	}
   218  	h = h[4:] // strip four byte prefix
   219  
   220  	var paddingLen int
   221  	if inner.serverName != "" {
   222  		paddingLen = max(0, maxNameLength-len(inner.serverName))
   223  	} else {
   224  		paddingLen = maxNameLength + 9
   225  	}
   226  	paddingLen += 31 - ((len(h) + paddingLen - 1) % 32)
   227  
   228  	return append(h, make([]byte, paddingLen)...), nil
   229  }
   230  
   231  func skipUint8LengthPrefixed(s *cryptobyte.String) bool {
   232  	var skip uint8
   233  	if !s.ReadUint8(&skip) {
   234  		return false
   235  	}
   236  	return s.Skip(int(skip))
   237  }
   238  
   239  func skipUint16LengthPrefixed(s *cryptobyte.String) bool {
   240  	var skip uint16
   241  	if !s.ReadUint16(&skip) {
   242  		return false
   243  	}
   244  	return s.Skip(int(skip))
   245  }
   246  
   247  type rawExtension struct {
   248  	extType uint16
   249  	data    []byte
   250  }
   251  
   252  func extractRawExtensions(hello *clientHelloMsg) ([]rawExtension, error) {
   253  	s := cryptobyte.String(hello.original)
   254  	if !s.Skip(4+2+32) || // header, version, random
   255  		!skipUint8LengthPrefixed(&s) || // session ID
   256  		!skipUint16LengthPrefixed(&s) || // cipher suites
   257  		!skipUint8LengthPrefixed(&s) { // compression methods
   258  		return nil, errors.New("tls: malformed outer client hello")
   259  	}
   260  	var rawExtensions []rawExtension
   261  	var extensions cryptobyte.String
   262  	if !s.ReadUint16LengthPrefixed(&extensions) {
   263  		return nil, errors.New("tls: malformed outer client hello")
   264  	}
   265  
   266  	for !extensions.Empty() {
   267  		var extension uint16
   268  		var extData cryptobyte.String
   269  		if !extensions.ReadUint16(&extension) ||
   270  			!extensions.ReadUint16LengthPrefixed(&extData) {
   271  			return nil, errors.New("tls: invalid inner client hello")
   272  		}
   273  		rawExtensions = append(rawExtensions, rawExtension{extension, extData})
   274  	}
   275  	return rawExtensions, nil
   276  }
   277  
   278  func decodeInnerClientHello(outer *clientHelloMsg, encoded []byte) (*clientHelloMsg, error) {
   279  	// Reconstructing the inner client hello from its encoded form is somewhat
   280  	// complicated. It is missing its header (message type and length), session
   281  	// ID, and the extensions may be compressed. Since we need to put the
   282  	// extensions back in the same order as they were in the raw outer hello,
   283  	// and since we don't store the raw extensions, or the order we parsed them
   284  	// in, we need to reparse the raw extensions from the outer hello in order
   285  	// to properly insert them into the inner hello. This _should_ result in raw
   286  	// bytes which match the hello as it was generated by the client.
   287  	innerReader := cryptobyte.String(encoded)
   288  	var versionAndRandom, sessionID, cipherSuites, compressionMethods []byte
   289  	var extensions cryptobyte.String
   290  	if !innerReader.ReadBytes(&versionAndRandom, 2+32) ||
   291  		!readUint8LengthPrefixed(&innerReader, &sessionID) ||
   292  		len(sessionID) != 0 ||
   293  		!readUint16LengthPrefixed(&innerReader, &cipherSuites) ||
   294  		!readUint8LengthPrefixed(&innerReader, &compressionMethods) ||
   295  		!innerReader.ReadUint16LengthPrefixed(&extensions) {
   296  		return nil, errors.New("tls: invalid inner client hello")
   297  	}
   298  
   299  	// The specification says we must verify that the trailing padding is all
   300  	// zeros. This is kind of weird for TLS messages, where we generally just
   301  	// throw away any trailing garbage.
   302  	for _, p := range innerReader {
   303  		if p != 0 {
   304  			return nil, errors.New("tls: invalid inner client hello")
   305  		}
   306  	}
   307  
   308  	rawOuterExts, err := extractRawExtensions(outer)
   309  	if err != nil {
   310  		return nil, err
   311  	}
   312  
   313  	recon := cryptobyte.NewBuilder(nil)
   314  	recon.AddUint8(typeClientHello)
   315  	recon.AddUint24LengthPrefixed(func(recon *cryptobyte.Builder) {
   316  		recon.AddBytes(versionAndRandom)
   317  		recon.AddUint8LengthPrefixed(func(recon *cryptobyte.Builder) {
   318  			recon.AddBytes(outer.sessionId)
   319  		})
   320  		recon.AddUint16LengthPrefixed(func(recon *cryptobyte.Builder) {
   321  			recon.AddBytes(cipherSuites)
   322  		})
   323  		recon.AddUint8LengthPrefixed(func(recon *cryptobyte.Builder) {
   324  			recon.AddBytes(compressionMethods)
   325  		})
   326  		recon.AddUint16LengthPrefixed(func(recon *cryptobyte.Builder) {
   327  			var outerExtensionsSeen bool
   328  			for !extensions.Empty() {
   329  				var extension uint16
   330  				var extData cryptobyte.String
   331  				if !extensions.ReadUint16(&extension) ||
   332  					!extensions.ReadUint16LengthPrefixed(&extData) {
   333  					recon.SetError(errors.New("tls: invalid inner client hello"))
   334  					return
   335  				}
   336  				if extension == extensionECHOuterExtensions {
   337  					if outerExtensionsSeen {
   338  						recon.SetError(errors.New("tls: invalid outer extensions"))
   339  						return
   340  					}
   341  					outerExtensionsSeen = true
   342  					var outerExtensions cryptobyte.String
   343  					if !extData.ReadUint8LengthPrefixed(&outerExtensions) || !extData.Empty() ||
   344  						outerExtensions.Empty() {
   345  						recon.SetError(errors.New("tls: invalid inner client hello"))
   346  						return
   347  					}
   348  					// OuterExtensions reconstruction per RFC 9849, Appendix A.
   349  					// i scans the outer extensions in order and never rewinds,
   350  					// so a referenced type that is out of order or duplicated
   351  					// cannot be found again and is rejected.
   352  					var i int
   353  					for !outerExtensions.Empty() {
   354  						var extType uint16
   355  						if !outerExtensions.ReadUint16(&extType) {
   356  							recon.SetError(errors.New("tls: invalid inner client hello"))
   357  							return
   358  						}
   359  						if extType == extensionEncryptedClientHello ||
   360  							extType == extensionECHOuterExtensions {
   361  							recon.SetError(errors.New("tls: invalid outer extensions"))
   362  							return
   363  						}
   364  						for ; i <= len(rawOuterExts); i++ {
   365  							if i == len(rawOuterExts) {
   366  								recon.SetError(errors.New("tls: invalid outer extensions"))
   367  								return
   368  							}
   369  							if rawOuterExts[i].extType == extType {
   370  								break
   371  							}
   372  						}
   373  						recon.AddUint16(rawOuterExts[i].extType)
   374  						recon.AddUint16LengthPrefixed(func(recon *cryptobyte.Builder) {
   375  							recon.AddBytes(rawOuterExts[i].data)
   376  						})
   377  						i++
   378  					}
   379  				} else {
   380  					recon.AddUint16(extension)
   381  					recon.AddUint16LengthPrefixed(func(recon *cryptobyte.Builder) {
   382  						recon.AddBytes(extData)
   383  					})
   384  				}
   385  			}
   386  		})
   387  	})
   388  
   389  	reconBytes, err := recon.Bytes()
   390  	if err != nil {
   391  		return nil, err
   392  	}
   393  	inner := &clientHelloMsg{}
   394  	if !inner.unmarshal(reconBytes) {
   395  		return nil, errors.New("tls: invalid reconstructed inner client hello")
   396  	}
   397  
   398  	if !bytes.Equal(inner.encryptedClientHello, []byte{uint8(innerECHExt)}) {
   399  		return nil, errInvalidECHExt
   400  	}
   401  
   402  	hasTLS13 := false
   403  	for _, v := range inner.supportedVersions {
   404  		// Skip GREASE values (values of the form 0x?A0A).
   405  		// GREASE (Generate Random Extensions And Sustain Extensibility) is a mechanism used by
   406  		// browsers like Chrome to ensure TLS implementations correctly ignore unknown values.
   407  		// GREASE values follow a specific pattern: 0x?A0A, where ? can be any hex digit.
   408  		// These values should be ignored when processing supported TLS versions.
   409  		if v&0x0F0F == 0x0A0A && v&0xff == v>>8 {
   410  			continue
   411  		}
   412  
   413  		// Ensure at least TLS 1.3 is offered.
   414  		if v == VersionTLS13 {
   415  			hasTLS13 = true
   416  		} else if v < VersionTLS13 {
   417  			// Reject if any non-GREASE value is below TLS 1.3, as ECH requires TLS 1.3+.
   418  			return nil, errors.New("tls: client sent encrypted_client_hello extension with unsupported versions")
   419  		}
   420  	}
   421  
   422  	if !hasTLS13 {
   423  		return nil, errors.New("tls: client sent encrypted_client_hello extension but did not offer TLS 1.3")
   424  	}
   425  
   426  	return inner, nil
   427  }
   428  
   429  func decryptECHPayload(context *hpke.Recipient, hello, payload []byte) ([]byte, error) {
   430  	outerAAD := bytes.Replace(hello[4:], payload, make([]byte, len(payload)), 1)
   431  	return context.Open(outerAAD, payload)
   432  }
   433  
   434  func generateOuterECHExt(id uint8, kdfID, aeadID uint16, encodedKey []byte, payload []byte) ([]byte, error) {
   435  	var b cryptobyte.Builder
   436  	b.AddUint8(0) // outer
   437  	b.AddUint16(kdfID)
   438  	b.AddUint16(aeadID)
   439  	b.AddUint8(id)
   440  	b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { b.AddBytes(encodedKey) })
   441  	b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { b.AddBytes(payload) })
   442  	return b.Bytes()
   443  }
   444  
   445  func computeAndUpdateOuterECHExtension(outer, inner *clientHelloMsg, ech *echClientContext, useKey bool) error {
   446  	// The outer hello must not offer the inner hello's PSK as otherwise an
   447  	// on-path attacker could splice the identity into hellos with guessed
   448  	// SNIs and use the server's accept/reject behavior as an oracle
   449  	// (CVE-2026-42505, see #79282).
   450  	//
   451  	// For that reason we clear it here, crucially before the outer hello is
   452  	// marshaled below as the HPKE AAD, so the AAD and the wire bytes agree.
   453  	outer.pskIdentities = nil
   454  	outer.pskBinders = nil
   455  
   456  	var encapKey []byte
   457  	if useKey {
   458  		encapKey = ech.encapsulatedKey
   459  	}
   460  	encodedInner, err := encodeInnerClientHello(inner, int(ech.config.MaxNameLength))
   461  	if err != nil {
   462  		return err
   463  	}
   464  	encryptedLen := len(encodedInner) + echAEADTagLen
   465  	outer.encryptedClientHello, err = generateOuterECHExt(ech.config.ConfigID, ech.kdfID, ech.aeadID, encapKey, make([]byte, encryptedLen))
   466  	if err != nil {
   467  		return err
   468  	}
   469  	serializedOuter, err := outer.marshal()
   470  	if err != nil {
   471  		return err
   472  	}
   473  	serializedOuter = serializedOuter[4:] // strip the four byte prefix
   474  	encryptedInner, err := ech.hpkeContext.Seal(serializedOuter, encodedInner)
   475  	if err != nil {
   476  		return err
   477  	}
   478  	outer.encryptedClientHello, err = generateOuterECHExt(ech.config.ConfigID, ech.kdfID, ech.aeadID, encapKey, encryptedInner)
   479  	if err != nil {
   480  		return err
   481  	}
   482  	return nil
   483  }
   484  
   485  // validDNSName is a rather rudimentary check for the validity of a DNS name.
   486  // This is used to check if the public_name in a ECHConfig is valid when we are
   487  // picking a config. This can be somewhat lax because even if we pick a
   488  // valid-looking name, the DNS layer will later reject it anyway.
   489  func validDNSName(name string) bool {
   490  	// Reject public names the certificate verifier would interpret as IP addresses.
   491  	// RFC 9849, Section 6.1.7 explicitly rejects IPv4. IPv6 literals, including
   492  	// scoped addresses, are already excluded by the DNS syntax (they contain ':').
   493  	if _, err := netip.ParseAddr(name); err == nil {
   494  		return false
   495  	}
   496  	if len(name) > 253 {
   497  		return false
   498  	}
   499  	labels := strings.Split(name, ".")
   500  	if len(labels) <= 1 {
   501  		return false
   502  	}
   503  	for _, l := range labels {
   504  		labelLen := len(l)
   505  		if labelLen == 0 {
   506  			return false
   507  		}
   508  		for i, r := range l {
   509  			if r == '-' && (i == 0 || i == labelLen-1) {
   510  				return false
   511  			}
   512  			if (r < '0' || r > '9') && (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && r != '-' {
   513  				return false
   514  			}
   515  		}
   516  	}
   517  	return true
   518  }
   519  
   520  // ECHRejectionError is the error type returned when ECH is rejected by a remote
   521  // server. If the server offered a ECHConfigList to use for retries, the
   522  // RetryConfigList field will contain this list.
   523  //
   524  // The client may treat an ECHRejectionError with an empty set of RetryConfigs
   525  // as a secure signal from the server.
   526  type ECHRejectionError struct {
   527  	RetryConfigList []byte
   528  }
   529  
   530  func (e *ECHRejectionError) Error() string {
   531  	return "tls: server rejected ECH"
   532  }
   533  
   534  var errMalformedECHExt = errors.New("tls: malformed encrypted_client_hello extension")
   535  var errInvalidECHExt = errors.New("tls: client sent invalid encrypted_client_hello extension")
   536  
   537  type echExtType uint8
   538  
   539  const (
   540  	innerECHExt echExtType = 1
   541  	outerECHExt echExtType = 0
   542  )
   543  
   544  func parseECHExt(ext []byte) (echType echExtType, cs echCipher, configID uint8, encap []byte, payload []byte, err error) {
   545  	data := make([]byte, len(ext))
   546  	copy(data, ext)
   547  	s := cryptobyte.String(data)
   548  	var echInt uint8
   549  	if !s.ReadUint8(&echInt) {
   550  		err = errMalformedECHExt
   551  		return
   552  	}
   553  	echType = echExtType(echInt)
   554  	if echType == innerECHExt {
   555  		if !s.Empty() {
   556  			err = errMalformedECHExt
   557  			return
   558  		}
   559  		return echType, cs, 0, nil, nil, nil
   560  	}
   561  	if echType != outerECHExt {
   562  		err = errInvalidECHExt
   563  		return
   564  	}
   565  	if !s.ReadUint16(&cs.KDFID) {
   566  		err = errMalformedECHExt
   567  		return
   568  	}
   569  	if !s.ReadUint16(&cs.AEADID) {
   570  		err = errMalformedECHExt
   571  		return
   572  	}
   573  	if !s.ReadUint8(&configID) {
   574  		err = errMalformedECHExt
   575  		return
   576  	}
   577  	if !readUint16LengthPrefixed(&s, &encap) {
   578  		err = errMalformedECHExt
   579  		return
   580  	}
   581  	if !readUint16LengthPrefixed(&s, &payload) {
   582  		err = errMalformedECHExt
   583  		return
   584  	}
   585  
   586  	// NOTE: clone encap and payload so that mutating them does not mutate the
   587  	// raw extension bytes.
   588  	return echType, cs, configID, bytes.Clone(encap), bytes.Clone(payload), nil
   589  }
   590  
   591  func (c *Conn) processECHClientHello(outer *clientHelloMsg, echKeys []EncryptedClientHelloKey) (*clientHelloMsg, *echServerContext, error) {
   592  	echType, echCiphersuite, configID, encap, payload, err := parseECHExt(outer.encryptedClientHello)
   593  	if err != nil {
   594  		if errors.Is(err, errInvalidECHExt) {
   595  			c.sendAlert(alertIllegalParameter)
   596  		} else {
   597  			c.sendAlert(alertDecodeError)
   598  		}
   599  
   600  		return nil, nil, errInvalidECHExt
   601  	}
   602  
   603  	if echType == innerECHExt {
   604  		return outer, &echServerContext{inner: true}, nil
   605  	}
   606  
   607  	if len(echKeys) == 0 {
   608  		return outer, nil, nil
   609  	}
   610  
   611  	for _, echKey := range echKeys {
   612  		skip, config, err := parseECHConfig(echKey.Config)
   613  		if err != nil {
   614  			c.sendAlert(alertInternalError)
   615  			return nil, nil, fmt.Errorf("tls: invalid EncryptedClientHelloKey Config: %s", err)
   616  		}
   617  		if skip {
   618  			continue
   619  		}
   620  		// RFC 9849, Section 7.1 requires trying the next config if the
   621  		// offered cipher suite is not supported by this config.
   622  		if !slices.Contains(config.SymmetricCipherSuite, echCiphersuite) {
   623  			continue
   624  		}
   625  		kem, err := hpke.NewKEM(config.KemID)
   626  		if err != nil {
   627  			c.sendAlert(alertInternalError)
   628  			return nil, nil, fmt.Errorf("tls: invalid EncryptedClientHelloKey Config KEM: %s", err)
   629  		}
   630  		echPriv, err := kem.NewPrivateKey(echKey.PrivateKey)
   631  		if err != nil {
   632  			c.sendAlert(alertInternalError)
   633  			return nil, nil, fmt.Errorf("tls: invalid EncryptedClientHelloKey PrivateKey: %s", err)
   634  		}
   635  		kdf, err := hpke.NewKDF(echCiphersuite.KDFID)
   636  		if err != nil {
   637  			c.sendAlert(alertInternalError)
   638  			return nil, nil, fmt.Errorf("tls: invalid EncryptedClientHelloKey Config KDF: %s", err)
   639  		}
   640  		aead, err := hpke.NewAEAD(echCiphersuite.AEADID)
   641  		if err != nil {
   642  			c.sendAlert(alertInternalError)
   643  			return nil, nil, fmt.Errorf("tls: invalid EncryptedClientHelloKey Config AEAD: %s", err)
   644  		}
   645  		info := append([]byte("tls ech\x00"), echKey.Config...)
   646  		hpkeContext, err := hpke.NewRecipient(encap, echPriv, kdf, aead, info)
   647  		if err != nil {
   648  			// attempt next trial decryption
   649  			continue
   650  		}
   651  
   652  		encodedInner, err := decryptECHPayload(hpkeContext, outer.original, payload)
   653  		if err != nil {
   654  			// attempt next trial decryption
   655  			continue
   656  		}
   657  
   658  		// NOTE: we do not enforce that the sent server_name matches the ECH
   659  		// configs PublicName, since this is not particularly important, and
   660  		// the client already had to know what it was in order to properly
   661  		// encrypt the payload. This is only a MAY in the spec, so we're not
   662  		// doing anything revolutionary.
   663  
   664  		echInner, err := decodeInnerClientHello(outer, encodedInner)
   665  		if err != nil {
   666  			c.sendAlert(alertIllegalParameter)
   667  			return nil, nil, errInvalidECHExt
   668  		}
   669  
   670  		c.echAccepted = true
   671  
   672  		return echInner, &echServerContext{
   673  			hpkeContext: hpkeContext,
   674  			configID:    configID,
   675  			ciphersuite: echCiphersuite,
   676  		}, nil
   677  	}
   678  
   679  	return outer, nil, nil
   680  }
   681  
   682  // newGreaseECHExtension builds a GREASE'd encrypted_client_hello extension.
   683  //
   684  // This extension is placed in the outer ClientHello derived from hello, as
   685  // specified in RFC 9849, Section 6.2.
   686  func newGreaseECHExtension(rand io.Reader, hello *clientHelloMsg, fips140Restrictions bool) ([]byte, error) {
   687  	const echGreaseMaxNameLength = 128
   688  
   689  	kdfID := hpke.HKDFSHA256().ID()
   690  	aeads := []hpke.AEAD{
   691  		hpke.AES128GCM(),
   692  		hpke.AES256GCM(),
   693  		hpke.ChaCha20Poly1305(),
   694  	}
   695  	if fips140Restrictions {
   696  		aeads = aeads[:2]
   697  	}
   698  
   699  	var b [2]byte
   700  	if _, err := io.ReadFull(rand, b[:]); err != nil {
   701  		return nil, err
   702  	}
   703  	aeadID := aeads[int(b[0])%len(aeads)].ID()
   704  	configID := b[1]
   705  
   706  	// For ECH GREASE we only need an encoded ephemeral pubkey to encap to.
   707  	// We generate a throw-away key pair for this purpose.
   708  	curve := ecdh.X25519()
   709  	if fips140Restrictions {
   710  		curve = ecdh.P256()
   711  	}
   712  	priv, err := curve.GenerateKey(rand)
   713  	if err != nil {
   714  		return nil, err
   715  	}
   716  	enc := priv.PublicKey().Bytes()
   717  
   718  	// Size the payload to L+echAEADTagLen, where L is the size of the
   719  	// EncodedClientHelloInner the client would produce if greasing matched a
   720  	// real ECH config with echGreaseMaxNameLength.
   721  	inner := hello.clone()
   722  	inner.encryptedClientHello = []byte{byte(innerECHExt)}
   723  	encoded, err := encodeInnerClientHello(inner, echGreaseMaxNameLength)
   724  	if err != nil {
   725  		return nil, err
   726  	}
   727  	payload := make([]byte, len(encoded)+echAEADTagLen)
   728  	if _, err := io.ReadFull(rand, payload); err != nil {
   729  		return nil, err
   730  	}
   731  
   732  	return generateOuterECHExt(configID, kdfID, aeadID, enc, payload)
   733  }
   734  
   735  func buildRetryConfigList(keys []EncryptedClientHelloKey) ([]byte, error) {
   736  	var atLeastOneRetryConfig bool
   737  	var retryBuilder cryptobyte.Builder
   738  	retryBuilder.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
   739  		for _, c := range keys {
   740  			if !c.SendAsRetry {
   741  				continue
   742  			}
   743  			atLeastOneRetryConfig = true
   744  			b.AddBytes(c.Config)
   745  		}
   746  	})
   747  	if !atLeastOneRetryConfig {
   748  		return nil, nil
   749  	}
   750  	return retryBuilder.Bytes()
   751  }
   752  

View as plain text