Source file src/crypto/tls/handshake_messages.go

     1  // Copyright 2009 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  	"errors"
     9  	"fmt"
    10  	"slices"
    11  	"strings"
    12  
    13  	"golang.org/x/crypto/cryptobyte"
    14  )
    15  
    16  // The marshalingFunction type is an adapter to allow the use of ordinary
    17  // functions as cryptobyte.MarshalingValue.
    18  type marshalingFunction func(b *cryptobyte.Builder) error
    19  
    20  func (f marshalingFunction) Marshal(b *cryptobyte.Builder) error {
    21  	return f(b)
    22  }
    23  
    24  // addBytesWithLength appends a sequence of bytes to the cryptobyte.Builder. If
    25  // the length of the sequence is not the value specified, it produces an error.
    26  func addBytesWithLength(b *cryptobyte.Builder, v []byte, n int) {
    27  	b.AddValue(marshalingFunction(func(b *cryptobyte.Builder) error {
    28  		if len(v) != n {
    29  			return fmt.Errorf("invalid value length: expected %d, got %d", n, len(v))
    30  		}
    31  		b.AddBytes(v)
    32  		return nil
    33  	}))
    34  }
    35  
    36  // addUint64 appends a big-endian, 64-bit value to the cryptobyte.Builder.
    37  func addUint64(b *cryptobyte.Builder, v uint64) {
    38  	b.AddUint32(uint32(v >> 32))
    39  	b.AddUint32(uint32(v))
    40  }
    41  
    42  // readUint64 decodes a big-endian, 64-bit value into out and advances over it.
    43  // It reports whether the read was successful.
    44  func readUint64(s *cryptobyte.String, out *uint64) bool {
    45  	var hi, lo uint32
    46  	if !s.ReadUint32(&hi) || !s.ReadUint32(&lo) {
    47  		return false
    48  	}
    49  	*out = uint64(hi)<<32 | uint64(lo)
    50  	return true
    51  }
    52  
    53  // readUint8LengthPrefixed acts like s.ReadUint8LengthPrefixed, but targets a
    54  // []byte instead of a cryptobyte.String.
    55  func readUint8LengthPrefixed(s *cryptobyte.String, out *[]byte) bool {
    56  	return s.ReadUint8LengthPrefixed((*cryptobyte.String)(out))
    57  }
    58  
    59  // readUint16LengthPrefixed acts like s.ReadUint16LengthPrefixed, but targets a
    60  // []byte instead of a cryptobyte.String.
    61  func readUint16LengthPrefixed(s *cryptobyte.String, out *[]byte) bool {
    62  	return s.ReadUint16LengthPrefixed((*cryptobyte.String)(out))
    63  }
    64  
    65  // readUint24LengthPrefixed acts like s.ReadUint24LengthPrefixed, but targets a
    66  // []byte instead of a cryptobyte.String.
    67  func readUint24LengthPrefixed(s *cryptobyte.String, out *[]byte) bool {
    68  	return s.ReadUint24LengthPrefixed((*cryptobyte.String)(out))
    69  }
    70  
    71  type clientHelloMsg struct {
    72  	original                         []byte
    73  	vers                             uint16
    74  	random                           []byte
    75  	sessionId                        []byte
    76  	cipherSuites                     []uint16
    77  	compressionMethods               []uint8
    78  	serverName                       string
    79  	ocspStapling                     bool
    80  	supportedCurves                  []CurveID
    81  	supportedPoints                  []uint8
    82  	ticketSupported                  bool
    83  	sessionTicket                    []uint8
    84  	supportedSignatureAlgorithms     []SignatureScheme
    85  	supportedSignatureAlgorithmsCert []SignatureScheme
    86  	secureRenegotiationSupported     bool
    87  	secureRenegotiation              []byte
    88  	extendedMasterSecret             bool
    89  	alpnProtocols                    []string
    90  	scts                             bool
    91  	supportedVersions                []uint16
    92  	cookie                           []byte
    93  	keyShares                        []keyShare
    94  	earlyData                        bool
    95  	pskModes                         []uint8
    96  	pskIdentities                    []pskIdentity
    97  	pskBinders                       [][]byte
    98  	quicTransportParameters          []byte
    99  	encryptedClientHello             []byte
   100  	// extensions are only populated on the server-side of a handshake
   101  	extensions []uint16
   102  }
   103  
   104  func (m *clientHelloMsg) marshalMsg(echInner bool) ([]byte, error) {
   105  	var exts cryptobyte.Builder
   106  	if len(m.serverName) > 0 {
   107  		// RFC 6066, Section 3
   108  		exts.AddUint16(extensionServerName)
   109  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   110  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   111  				exts.AddUint8(0) // name_type = host_name
   112  				exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   113  					exts.AddBytes([]byte(m.serverName))
   114  				})
   115  			})
   116  		})
   117  	}
   118  	if len(m.supportedPoints) > 0 && !echInner {
   119  		// RFC 4492, Section 5.1.2
   120  		exts.AddUint16(extensionSupportedPoints)
   121  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   122  			exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   123  				exts.AddBytes(m.supportedPoints)
   124  			})
   125  		})
   126  	}
   127  	if m.ticketSupported && !echInner {
   128  		// RFC 5077, Section 3.2
   129  		exts.AddUint16(extensionSessionTicket)
   130  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   131  			exts.AddBytes(m.sessionTicket)
   132  		})
   133  	}
   134  	if m.secureRenegotiationSupported && !echInner {
   135  		// RFC 5746, Section 3.2
   136  		exts.AddUint16(extensionRenegotiationInfo)
   137  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   138  			exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   139  				exts.AddBytes(m.secureRenegotiation)
   140  			})
   141  		})
   142  	}
   143  	if m.extendedMasterSecret && !echInner {
   144  		// RFC 7627
   145  		exts.AddUint16(extensionExtendedMasterSecret)
   146  		exts.AddUint16(0) // empty extension_data
   147  	}
   148  	if m.scts {
   149  		// RFC 6962, Section 3.3.1
   150  		exts.AddUint16(extensionSCT)
   151  		exts.AddUint16(0) // empty extension_data
   152  	}
   153  	if m.earlyData {
   154  		// RFC 8446, Section 4.2.10
   155  		exts.AddUint16(extensionEarlyData)
   156  		exts.AddUint16(0) // empty extension_data
   157  	}
   158  	if m.quicTransportParameters != nil { // marshal zero-length parameters when present
   159  		// RFC 9001, Section 8.2
   160  		exts.AddUint16(extensionQUICTransportParameters)
   161  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   162  			exts.AddBytes(m.quicTransportParameters)
   163  		})
   164  	}
   165  	if len(m.encryptedClientHello) > 0 {
   166  		exts.AddUint16(extensionEncryptedClientHello)
   167  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   168  			exts.AddBytes(m.encryptedClientHello)
   169  		})
   170  	}
   171  	// Note that any extension that can be compressed during ECH must be
   172  	// contiguous. If any additional extensions are to be compressed they must
   173  	// be added to the following block, so that they can be properly
   174  	// decompressed on the other side.
   175  	var echOuterExts []uint16
   176  	if m.ocspStapling {
   177  		// RFC 4366, Section 3.6
   178  		if echInner {
   179  			echOuterExts = append(echOuterExts, extensionStatusRequest)
   180  		} else {
   181  			exts.AddUint16(extensionStatusRequest)
   182  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   183  				exts.AddUint8(1)  // status_type = ocsp
   184  				exts.AddUint16(0) // empty responder_id_list
   185  				exts.AddUint16(0) // empty request_extensions
   186  			})
   187  		}
   188  	}
   189  	if len(m.supportedCurves) > 0 {
   190  		// RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7
   191  		if echInner {
   192  			echOuterExts = append(echOuterExts, extensionSupportedCurves)
   193  		} else {
   194  			exts.AddUint16(extensionSupportedCurves)
   195  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   196  				exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   197  					for _, curve := range m.supportedCurves {
   198  						exts.AddUint16(uint16(curve))
   199  					}
   200  				})
   201  			})
   202  		}
   203  	}
   204  	if len(m.supportedSignatureAlgorithms) > 0 {
   205  		// RFC 5246, Section 7.4.1.4.1
   206  		if echInner {
   207  			echOuterExts = append(echOuterExts, extensionSignatureAlgorithms)
   208  		} else {
   209  			exts.AddUint16(extensionSignatureAlgorithms)
   210  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   211  				exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   212  					for _, sigAlgo := range m.supportedSignatureAlgorithms {
   213  						exts.AddUint16(uint16(sigAlgo))
   214  					}
   215  				})
   216  			})
   217  		}
   218  	}
   219  	if len(m.supportedSignatureAlgorithmsCert) > 0 {
   220  		// RFC 8446, Section 4.2.3
   221  		if echInner {
   222  			echOuterExts = append(echOuterExts, extensionSignatureAlgorithmsCert)
   223  		} else {
   224  			exts.AddUint16(extensionSignatureAlgorithmsCert)
   225  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   226  				exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   227  					for _, sigAlgo := range m.supportedSignatureAlgorithmsCert {
   228  						exts.AddUint16(uint16(sigAlgo))
   229  					}
   230  				})
   231  			})
   232  		}
   233  	}
   234  	if len(m.alpnProtocols) > 0 {
   235  		// RFC 7301, Section 3.1
   236  		if echInner {
   237  			echOuterExts = append(echOuterExts, extensionALPN)
   238  		} else {
   239  			exts.AddUint16(extensionALPN)
   240  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   241  				exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   242  					for _, proto := range m.alpnProtocols {
   243  						exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   244  							exts.AddBytes([]byte(proto))
   245  						})
   246  					}
   247  				})
   248  			})
   249  		}
   250  	}
   251  	if len(m.supportedVersions) > 0 {
   252  		// RFC 8446, Section 4.2.1
   253  		if echInner {
   254  			echOuterExts = append(echOuterExts, extensionSupportedVersions)
   255  		} else {
   256  			exts.AddUint16(extensionSupportedVersions)
   257  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   258  				exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   259  					for _, vers := range m.supportedVersions {
   260  						exts.AddUint16(vers)
   261  					}
   262  				})
   263  			})
   264  		}
   265  	}
   266  	if len(m.cookie) > 0 {
   267  		// RFC 8446, Section 4.2.2
   268  		if echInner {
   269  			echOuterExts = append(echOuterExts, extensionCookie)
   270  		} else {
   271  			exts.AddUint16(extensionCookie)
   272  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   273  				exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   274  					exts.AddBytes(m.cookie)
   275  				})
   276  			})
   277  		}
   278  	}
   279  	if len(m.keyShares) > 0 {
   280  		// RFC 8446, Section 4.2.8
   281  		if echInner {
   282  			echOuterExts = append(echOuterExts, extensionKeyShare)
   283  		} else {
   284  			exts.AddUint16(extensionKeyShare)
   285  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   286  				exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   287  					for _, ks := range m.keyShares {
   288  						exts.AddUint16(uint16(ks.group))
   289  						exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   290  							exts.AddBytes(ks.data)
   291  						})
   292  					}
   293  				})
   294  			})
   295  		}
   296  	}
   297  	if len(m.pskModes) > 0 {
   298  		// RFC 8446, Section 4.2.9
   299  		if echInner {
   300  			echOuterExts = append(echOuterExts, extensionPSKModes)
   301  		} else {
   302  			exts.AddUint16(extensionPSKModes)
   303  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   304  				exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   305  					exts.AddBytes(m.pskModes)
   306  				})
   307  			})
   308  		}
   309  	}
   310  	if len(echOuterExts) > 0 && echInner {
   311  		exts.AddUint16(extensionECHOuterExtensions)
   312  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   313  			exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   314  				for _, e := range echOuterExts {
   315  					exts.AddUint16(e)
   316  				}
   317  			})
   318  		})
   319  	}
   320  	if len(m.pskIdentities) > 0 { // pre_shared_key must be the last extension
   321  		// RFC 8446, Section 4.2.11
   322  		exts.AddUint16(extensionPreSharedKey)
   323  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   324  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   325  				for _, psk := range m.pskIdentities {
   326  					exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   327  						exts.AddBytes(psk.label)
   328  					})
   329  					exts.AddUint32(psk.obfuscatedTicketAge)
   330  				}
   331  			})
   332  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   333  				for _, binder := range m.pskBinders {
   334  					exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   335  						exts.AddBytes(binder)
   336  					})
   337  				}
   338  			})
   339  		})
   340  	}
   341  	extBytes, err := exts.Bytes()
   342  	if err != nil {
   343  		return nil, err
   344  	}
   345  
   346  	var b cryptobyte.Builder
   347  	b.AddUint8(typeClientHello)
   348  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
   349  		b.AddUint16(m.vers)
   350  		addBytesWithLength(b, m.random, 32)
   351  		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
   352  			if !echInner {
   353  				b.AddBytes(m.sessionId)
   354  			}
   355  		})
   356  		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
   357  			for _, suite := range m.cipherSuites {
   358  				b.AddUint16(suite)
   359  			}
   360  		})
   361  		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
   362  			b.AddBytes(m.compressionMethods)
   363  		})
   364  
   365  		if len(extBytes) > 0 {
   366  			b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
   367  				b.AddBytes(extBytes)
   368  			})
   369  		}
   370  	})
   371  
   372  	return b.Bytes()
   373  }
   374  
   375  func (m *clientHelloMsg) marshal() ([]byte, error) {
   376  	return m.marshalMsg(false)
   377  }
   378  
   379  // marshalWithoutBinders returns the ClientHello through the
   380  // PreSharedKeyExtension.identities field, according to RFC 8446, Section
   381  // 4.2.11.2. Note that m.pskBinders must be set to slices of the correct length.
   382  func (m *clientHelloMsg) marshalWithoutBinders() ([]byte, error) {
   383  	bindersLen := 2 // uint16 length prefix
   384  	for _, binder := range m.pskBinders {
   385  		bindersLen += 1 // uint8 length prefix
   386  		bindersLen += len(binder)
   387  	}
   388  
   389  	var fullMessage []byte
   390  	if m.original != nil {
   391  		fullMessage = m.original
   392  	} else {
   393  		var err error
   394  		fullMessage, err = m.marshal()
   395  		if err != nil {
   396  			return nil, err
   397  		}
   398  	}
   399  	return fullMessage[:len(fullMessage)-bindersLen], nil
   400  }
   401  
   402  // updateBinders updates the m.pskBinders field. The supplied binders must have
   403  // the same length as the current m.pskBinders.
   404  func (m *clientHelloMsg) updateBinders(pskBinders [][]byte) error {
   405  	if len(pskBinders) != len(m.pskBinders) {
   406  		return errors.New("tls: internal error: pskBinders length mismatch")
   407  	}
   408  	for i := range m.pskBinders {
   409  		if len(pskBinders[i]) != len(m.pskBinders[i]) {
   410  			return errors.New("tls: internal error: pskBinders length mismatch")
   411  		}
   412  	}
   413  	m.pskBinders = pskBinders
   414  
   415  	return nil
   416  }
   417  
   418  func (m *clientHelloMsg) unmarshal(data []byte) bool {
   419  	*m = clientHelloMsg{original: data}
   420  	s := cryptobyte.String(data)
   421  
   422  	if !s.Skip(4) || // message type and uint24 length field
   423  		!s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) ||
   424  		!readUint8LengthPrefixed(&s, &m.sessionId) {
   425  		return false
   426  	}
   427  
   428  	var cipherSuites cryptobyte.String
   429  	if !s.ReadUint16LengthPrefixed(&cipherSuites) {
   430  		return false
   431  	}
   432  	m.cipherSuites = []uint16{}
   433  	m.secureRenegotiationSupported = false
   434  	for !cipherSuites.Empty() {
   435  		var suite uint16
   436  		if !cipherSuites.ReadUint16(&suite) {
   437  			return false
   438  		}
   439  		if suite == scsvRenegotiation {
   440  			m.secureRenegotiationSupported = true
   441  		}
   442  		m.cipherSuites = append(m.cipherSuites, suite)
   443  	}
   444  
   445  	if !readUint8LengthPrefixed(&s, &m.compressionMethods) {
   446  		return false
   447  	}
   448  
   449  	if s.Empty() {
   450  		// ClientHello is optionally followed by extension data
   451  		return true
   452  	}
   453  
   454  	var extensions cryptobyte.String
   455  	if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {
   456  		return false
   457  	}
   458  
   459  	seenExts := make(map[uint16]bool)
   460  	for !extensions.Empty() {
   461  		var extension uint16
   462  		var extData cryptobyte.String
   463  		if !extensions.ReadUint16(&extension) ||
   464  			!extensions.ReadUint16LengthPrefixed(&extData) {
   465  			return false
   466  		}
   467  
   468  		if seenExts[extension] {
   469  			return false
   470  		}
   471  		seenExts[extension] = true
   472  		m.extensions = append(m.extensions, extension)
   473  
   474  		switch extension {
   475  		case extensionServerName:
   476  			// RFC 6066, Section 3
   477  			var nameList cryptobyte.String
   478  			if !extData.ReadUint16LengthPrefixed(&nameList) || nameList.Empty() {
   479  				return false
   480  			}
   481  			for !nameList.Empty() {
   482  				var nameType uint8
   483  				var serverName cryptobyte.String
   484  				if !nameList.ReadUint8(&nameType) ||
   485  					!nameList.ReadUint16LengthPrefixed(&serverName) ||
   486  					serverName.Empty() {
   487  					return false
   488  				}
   489  				if nameType != 0 {
   490  					continue
   491  				}
   492  				if len(m.serverName) != 0 {
   493  					// Multiple names of the same name_type are prohibited.
   494  					return false
   495  				}
   496  				m.serverName = string(serverName)
   497  				// An SNI value may not include a trailing dot.
   498  				if strings.HasSuffix(m.serverName, ".") {
   499  					return false
   500  				}
   501  			}
   502  		case extensionStatusRequest:
   503  			// RFC 4366, Section 3.6
   504  			var statusType uint8
   505  			var ignored cryptobyte.String
   506  			if !extData.ReadUint8(&statusType) ||
   507  				!extData.ReadUint16LengthPrefixed(&ignored) ||
   508  				!extData.ReadUint16LengthPrefixed(&ignored) {
   509  				return false
   510  			}
   511  			m.ocspStapling = statusType == statusTypeOCSP
   512  		case extensionSupportedCurves:
   513  			// RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7
   514  			var curves cryptobyte.String
   515  			if !extData.ReadUint16LengthPrefixed(&curves) || curves.Empty() {
   516  				return false
   517  			}
   518  			for !curves.Empty() {
   519  				var curve uint16
   520  				if !curves.ReadUint16(&curve) {
   521  					return false
   522  				}
   523  				m.supportedCurves = append(m.supportedCurves, CurveID(curve))
   524  			}
   525  		case extensionSupportedPoints:
   526  			// RFC 4492, Section 5.1.2
   527  			if !readUint8LengthPrefixed(&extData, &m.supportedPoints) ||
   528  				len(m.supportedPoints) == 0 {
   529  				return false
   530  			}
   531  		case extensionSessionTicket:
   532  			// RFC 5077, Section 3.2
   533  			m.ticketSupported = true
   534  			extData.ReadBytes(&m.sessionTicket, len(extData))
   535  		case extensionSignatureAlgorithms:
   536  			// RFC 5246, Section 7.4.1.4.1
   537  			var sigAndAlgs cryptobyte.String
   538  			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
   539  				return false
   540  			}
   541  			for !sigAndAlgs.Empty() {
   542  				var sigAndAlg uint16
   543  				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
   544  					return false
   545  				}
   546  				m.supportedSignatureAlgorithms = append(
   547  					m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg))
   548  			}
   549  		case extensionSignatureAlgorithmsCert:
   550  			// RFC 8446, Section 4.2.3
   551  			var sigAndAlgs cryptobyte.String
   552  			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
   553  				return false
   554  			}
   555  			for !sigAndAlgs.Empty() {
   556  				var sigAndAlg uint16
   557  				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
   558  					return false
   559  				}
   560  				m.supportedSignatureAlgorithmsCert = append(
   561  					m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg))
   562  			}
   563  		case extensionRenegotiationInfo:
   564  			// RFC 5746, Section 3.2
   565  			if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) {
   566  				return false
   567  			}
   568  			m.secureRenegotiationSupported = true
   569  		case extensionExtendedMasterSecret:
   570  			// RFC 7627
   571  			m.extendedMasterSecret = true
   572  		case extensionALPN:
   573  			// RFC 7301, Section 3.1
   574  			var protoList cryptobyte.String
   575  			if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
   576  				return false
   577  			}
   578  			for !protoList.Empty() {
   579  				var proto cryptobyte.String
   580  				if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() {
   581  					return false
   582  				}
   583  				m.alpnProtocols = append(m.alpnProtocols, string(proto))
   584  			}
   585  		case extensionSCT:
   586  			// RFC 6962, Section 3.3.1
   587  			m.scts = true
   588  		case extensionSupportedVersions:
   589  			// RFC 8446, Section 4.2.1
   590  			var versList cryptobyte.String
   591  			if !extData.ReadUint8LengthPrefixed(&versList) || versList.Empty() {
   592  				return false
   593  			}
   594  			for !versList.Empty() {
   595  				var vers uint16
   596  				if !versList.ReadUint16(&vers) {
   597  					return false
   598  				}
   599  				m.supportedVersions = append(m.supportedVersions, vers)
   600  			}
   601  		case extensionCookie:
   602  			// RFC 8446, Section 4.2.2
   603  			if !readUint16LengthPrefixed(&extData, &m.cookie) ||
   604  				len(m.cookie) == 0 {
   605  				return false
   606  			}
   607  		case extensionKeyShare:
   608  			// RFC 8446, Section 4.2.8
   609  			var clientShares cryptobyte.String
   610  			if !extData.ReadUint16LengthPrefixed(&clientShares) {
   611  				return false
   612  			}
   613  			for !clientShares.Empty() {
   614  				var ks keyShare
   615  				if !clientShares.ReadUint16((*uint16)(&ks.group)) ||
   616  					!readUint16LengthPrefixed(&clientShares, &ks.data) ||
   617  					len(ks.data) == 0 {
   618  					return false
   619  				}
   620  				m.keyShares = append(m.keyShares, ks)
   621  			}
   622  		case extensionEarlyData:
   623  			// RFC 8446, Section 4.2.10
   624  			m.earlyData = true
   625  		case extensionPSKModes:
   626  			// RFC 8446, Section 4.2.9
   627  			if !readUint8LengthPrefixed(&extData, &m.pskModes) {
   628  				return false
   629  			}
   630  		case extensionQUICTransportParameters:
   631  			m.quicTransportParameters = make([]byte, len(extData))
   632  			if !extData.CopyBytes(m.quicTransportParameters) {
   633  				return false
   634  			}
   635  		case extensionPreSharedKey:
   636  			// RFC 8446, Section 4.2.11
   637  			if !extensions.Empty() {
   638  				return false // pre_shared_key must be the last extension
   639  			}
   640  			var identities cryptobyte.String
   641  			if !extData.ReadUint16LengthPrefixed(&identities) || identities.Empty() {
   642  				return false
   643  			}
   644  			for !identities.Empty() {
   645  				var psk pskIdentity
   646  				if !readUint16LengthPrefixed(&identities, &psk.label) ||
   647  					!identities.ReadUint32(&psk.obfuscatedTicketAge) ||
   648  					len(psk.label) == 0 {
   649  					return false
   650  				}
   651  				m.pskIdentities = append(m.pskIdentities, psk)
   652  			}
   653  			var binders cryptobyte.String
   654  			if !extData.ReadUint16LengthPrefixed(&binders) || binders.Empty() {
   655  				return false
   656  			}
   657  			for !binders.Empty() {
   658  				var binder []byte
   659  				if !readUint8LengthPrefixed(&binders, &binder) ||
   660  					len(binder) == 0 {
   661  					return false
   662  				}
   663  				m.pskBinders = append(m.pskBinders, binder)
   664  			}
   665  		default:
   666  			// Ignore unknown extensions.
   667  			continue
   668  		}
   669  
   670  		if !extData.Empty() {
   671  			return false
   672  		}
   673  	}
   674  
   675  	return true
   676  }
   677  
   678  func (m *clientHelloMsg) originalBytes() []byte {
   679  	return m.original
   680  }
   681  
   682  func (m *clientHelloMsg) clone() *clientHelloMsg {
   683  	return &clientHelloMsg{
   684  		original:                         slices.Clone(m.original),
   685  		vers:                             m.vers,
   686  		random:                           slices.Clone(m.random),
   687  		sessionId:                        slices.Clone(m.sessionId),
   688  		cipherSuites:                     slices.Clone(m.cipherSuites),
   689  		compressionMethods:               slices.Clone(m.compressionMethods),
   690  		serverName:                       m.serverName,
   691  		ocspStapling:                     m.ocspStapling,
   692  		supportedCurves:                  slices.Clone(m.supportedCurves),
   693  		supportedPoints:                  slices.Clone(m.supportedPoints),
   694  		ticketSupported:                  m.ticketSupported,
   695  		sessionTicket:                    slices.Clone(m.sessionTicket),
   696  		supportedSignatureAlgorithms:     slices.Clone(m.supportedSignatureAlgorithms),
   697  		supportedSignatureAlgorithmsCert: slices.Clone(m.supportedSignatureAlgorithmsCert),
   698  		secureRenegotiationSupported:     m.secureRenegotiationSupported,
   699  		secureRenegotiation:              slices.Clone(m.secureRenegotiation),
   700  		extendedMasterSecret:             m.extendedMasterSecret,
   701  		alpnProtocols:                    slices.Clone(m.alpnProtocols),
   702  		scts:                             m.scts,
   703  		supportedVersions:                slices.Clone(m.supportedVersions),
   704  		cookie:                           slices.Clone(m.cookie),
   705  		keyShares:                        slices.Clone(m.keyShares),
   706  		earlyData:                        m.earlyData,
   707  		pskModes:                         slices.Clone(m.pskModes),
   708  		pskIdentities:                    slices.Clone(m.pskIdentities),
   709  		pskBinders:                       slices.Clone(m.pskBinders),
   710  		quicTransportParameters:          slices.Clone(m.quicTransportParameters),
   711  		encryptedClientHello:             slices.Clone(m.encryptedClientHello),
   712  	}
   713  }
   714  
   715  type serverHelloMsg struct {
   716  	original                     []byte
   717  	vers                         uint16
   718  	random                       []byte
   719  	sessionId                    []byte
   720  	cipherSuite                  uint16
   721  	compressionMethod            uint8
   722  	ocspStapling                 bool
   723  	ticketSupported              bool
   724  	secureRenegotiationSupported bool
   725  	secureRenegotiation          []byte
   726  	extendedMasterSecret         bool
   727  	alpnProtocol                 string
   728  	scts                         [][]byte
   729  	supportedVersion             uint16
   730  	serverShare                  keyShare
   731  	selectedIdentityPresent      bool
   732  	selectedIdentity             uint16
   733  	supportedPoints              []uint8
   734  	encryptedClientHello         []byte
   735  	serverNameAck                bool
   736  
   737  	// HelloRetryRequest extensions
   738  	cookie        []byte
   739  	selectedGroup CurveID
   740  }
   741  
   742  func (m *serverHelloMsg) marshal() ([]byte, error) {
   743  	var exts cryptobyte.Builder
   744  	if m.ocspStapling {
   745  		exts.AddUint16(extensionStatusRequest)
   746  		exts.AddUint16(0) // empty extension_data
   747  	}
   748  	if m.ticketSupported {
   749  		exts.AddUint16(extensionSessionTicket)
   750  		exts.AddUint16(0) // empty extension_data
   751  	}
   752  	if m.secureRenegotiationSupported {
   753  		exts.AddUint16(extensionRenegotiationInfo)
   754  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   755  			exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   756  				exts.AddBytes(m.secureRenegotiation)
   757  			})
   758  		})
   759  	}
   760  	if m.extendedMasterSecret {
   761  		exts.AddUint16(extensionExtendedMasterSecret)
   762  		exts.AddUint16(0) // empty extension_data
   763  	}
   764  	if len(m.alpnProtocol) > 0 {
   765  		exts.AddUint16(extensionALPN)
   766  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   767  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   768  				exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   769  					exts.AddBytes([]byte(m.alpnProtocol))
   770  				})
   771  			})
   772  		})
   773  	}
   774  	if len(m.scts) > 0 {
   775  		exts.AddUint16(extensionSCT)
   776  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   777  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   778  				for _, sct := range m.scts {
   779  					exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   780  						exts.AddBytes(sct)
   781  					})
   782  				}
   783  			})
   784  		})
   785  	}
   786  	if m.supportedVersion != 0 {
   787  		exts.AddUint16(extensionSupportedVersions)
   788  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   789  			exts.AddUint16(m.supportedVersion)
   790  		})
   791  	}
   792  	if m.serverShare.group != 0 {
   793  		exts.AddUint16(extensionKeyShare)
   794  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   795  			exts.AddUint16(uint16(m.serverShare.group))
   796  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   797  				exts.AddBytes(m.serverShare.data)
   798  			})
   799  		})
   800  	}
   801  	if m.selectedIdentityPresent {
   802  		exts.AddUint16(extensionPreSharedKey)
   803  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   804  			exts.AddUint16(m.selectedIdentity)
   805  		})
   806  	}
   807  
   808  	if len(m.cookie) > 0 {
   809  		exts.AddUint16(extensionCookie)
   810  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   811  			exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   812  				exts.AddBytes(m.cookie)
   813  			})
   814  		})
   815  	}
   816  	if m.selectedGroup != 0 {
   817  		exts.AddUint16(extensionKeyShare)
   818  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   819  			exts.AddUint16(uint16(m.selectedGroup))
   820  		})
   821  	}
   822  	if len(m.supportedPoints) > 0 {
   823  		exts.AddUint16(extensionSupportedPoints)
   824  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   825  			exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) {
   826  				exts.AddBytes(m.supportedPoints)
   827  			})
   828  		})
   829  	}
   830  	if len(m.encryptedClientHello) > 0 {
   831  		exts.AddUint16(extensionEncryptedClientHello)
   832  		exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) {
   833  			exts.AddBytes(m.encryptedClientHello)
   834  		})
   835  	}
   836  	if m.serverNameAck {
   837  		exts.AddUint16(extensionServerName)
   838  		exts.AddUint16(0)
   839  	}
   840  
   841  	extBytes, err := exts.Bytes()
   842  	if err != nil {
   843  		return nil, err
   844  	}
   845  
   846  	var b cryptobyte.Builder
   847  	b.AddUint8(typeServerHello)
   848  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
   849  		b.AddUint16(m.vers)
   850  		addBytesWithLength(b, m.random, 32)
   851  		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
   852  			b.AddBytes(m.sessionId)
   853  		})
   854  		b.AddUint16(m.cipherSuite)
   855  		b.AddUint8(m.compressionMethod)
   856  
   857  		if len(extBytes) > 0 {
   858  			b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
   859  				b.AddBytes(extBytes)
   860  			})
   861  		}
   862  	})
   863  
   864  	return b.Bytes()
   865  }
   866  
   867  func (m *serverHelloMsg) unmarshal(data []byte) bool {
   868  	*m = serverHelloMsg{original: data}
   869  	s := cryptobyte.String(data)
   870  
   871  	if !s.Skip(4) || // message type and uint24 length field
   872  		!s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) ||
   873  		!readUint8LengthPrefixed(&s, &m.sessionId) ||
   874  		!s.ReadUint16(&m.cipherSuite) ||
   875  		!s.ReadUint8(&m.compressionMethod) {
   876  		return false
   877  	}
   878  
   879  	if s.Empty() {
   880  		// ServerHello is optionally followed by extension data
   881  		return true
   882  	}
   883  
   884  	var extensions cryptobyte.String
   885  	if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {
   886  		return false
   887  	}
   888  
   889  	seenExts := make(map[uint16]bool)
   890  	for !extensions.Empty() {
   891  		var extension uint16
   892  		var extData cryptobyte.String
   893  		if !extensions.ReadUint16(&extension) ||
   894  			!extensions.ReadUint16LengthPrefixed(&extData) {
   895  			return false
   896  		}
   897  
   898  		if seenExts[extension] {
   899  			return false
   900  		}
   901  		seenExts[extension] = true
   902  
   903  		switch extension {
   904  		case extensionStatusRequest:
   905  			m.ocspStapling = true
   906  		case extensionSessionTicket:
   907  			m.ticketSupported = true
   908  		case extensionRenegotiationInfo:
   909  			if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) {
   910  				return false
   911  			}
   912  			m.secureRenegotiationSupported = true
   913  		case extensionExtendedMasterSecret:
   914  			m.extendedMasterSecret = true
   915  		case extensionALPN:
   916  			var protoList cryptobyte.String
   917  			if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
   918  				return false
   919  			}
   920  			var proto cryptobyte.String
   921  			if !protoList.ReadUint8LengthPrefixed(&proto) ||
   922  				proto.Empty() || !protoList.Empty() {
   923  				return false
   924  			}
   925  			m.alpnProtocol = string(proto)
   926  		case extensionSCT:
   927  			var sctList cryptobyte.String
   928  			if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() {
   929  				return false
   930  			}
   931  			for !sctList.Empty() {
   932  				var sct []byte
   933  				if !readUint16LengthPrefixed(&sctList, &sct) ||
   934  					len(sct) == 0 {
   935  					return false
   936  				}
   937  				m.scts = append(m.scts, sct)
   938  			}
   939  		case extensionSupportedVersions:
   940  			if !extData.ReadUint16(&m.supportedVersion) {
   941  				return false
   942  			}
   943  		case extensionCookie:
   944  			if !readUint16LengthPrefixed(&extData, &m.cookie) ||
   945  				len(m.cookie) == 0 {
   946  				return false
   947  			}
   948  		case extensionKeyShare:
   949  			// This extension has different formats in SH and HRR, accept either
   950  			// and let the handshake logic decide. See RFC 8446, Section 4.2.8.
   951  			if len(extData) == 2 {
   952  				if !extData.ReadUint16((*uint16)(&m.selectedGroup)) {
   953  					return false
   954  				}
   955  			} else {
   956  				if !extData.ReadUint16((*uint16)(&m.serverShare.group)) ||
   957  					!readUint16LengthPrefixed(&extData, &m.serverShare.data) {
   958  					return false
   959  				}
   960  			}
   961  		case extensionPreSharedKey:
   962  			m.selectedIdentityPresent = true
   963  			if !extData.ReadUint16(&m.selectedIdentity) {
   964  				return false
   965  			}
   966  		case extensionSupportedPoints:
   967  			// RFC 4492, Section 5.1.2
   968  			if !readUint8LengthPrefixed(&extData, &m.supportedPoints) ||
   969  				len(m.supportedPoints) == 0 {
   970  				return false
   971  			}
   972  		case extensionEncryptedClientHello: // encrypted_client_hello
   973  			m.encryptedClientHello = make([]byte, len(extData))
   974  			if !extData.CopyBytes(m.encryptedClientHello) {
   975  				return false
   976  			}
   977  		case extensionServerName:
   978  			if len(extData) != 0 {
   979  				return false
   980  			}
   981  			m.serverNameAck = true
   982  		default:
   983  			// Ignore unknown extensions.
   984  			continue
   985  		}
   986  
   987  		if !extData.Empty() {
   988  			return false
   989  		}
   990  	}
   991  
   992  	return true
   993  }
   994  
   995  func (m *serverHelloMsg) originalBytes() []byte {
   996  	return m.original
   997  }
   998  
   999  type encryptedExtensionsMsg struct {
  1000  	alpnProtocol            string
  1001  	quicTransportParameters []byte
  1002  	earlyData               bool
  1003  	echRetryConfigs         []byte
  1004  }
  1005  
  1006  func (m *encryptedExtensionsMsg) marshal() ([]byte, error) {
  1007  	var b cryptobyte.Builder
  1008  	b.AddUint8(typeEncryptedExtensions)
  1009  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1010  		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1011  			if len(m.alpnProtocol) > 0 {
  1012  				b.AddUint16(extensionALPN)
  1013  				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1014  					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1015  						b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  1016  							b.AddBytes([]byte(m.alpnProtocol))
  1017  						})
  1018  					})
  1019  				})
  1020  			}
  1021  			if m.quicTransportParameters != nil { // marshal zero-length parameters when present
  1022  				// draft-ietf-quic-tls-32, Section 8.2
  1023  				b.AddUint16(extensionQUICTransportParameters)
  1024  				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1025  					b.AddBytes(m.quicTransportParameters)
  1026  				})
  1027  			}
  1028  			if m.earlyData {
  1029  				// RFC 8446, Section 4.2.10
  1030  				b.AddUint16(extensionEarlyData)
  1031  				b.AddUint16(0) // empty extension_data
  1032  			}
  1033  			if len(m.echRetryConfigs) > 0 {
  1034  				b.AddUint16(extensionEncryptedClientHello)
  1035  				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1036  					b.AddBytes(m.echRetryConfigs)
  1037  				})
  1038  			}
  1039  		})
  1040  	})
  1041  
  1042  	return b.Bytes()
  1043  }
  1044  
  1045  func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool {
  1046  	*m = encryptedExtensionsMsg{}
  1047  	s := cryptobyte.String(data)
  1048  
  1049  	var extensions cryptobyte.String
  1050  	if !s.Skip(4) || // message type and uint24 length field
  1051  		!s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() {
  1052  		return false
  1053  	}
  1054  
  1055  	for !extensions.Empty() {
  1056  		var extension uint16
  1057  		var extData cryptobyte.String
  1058  		if !extensions.ReadUint16(&extension) ||
  1059  			!extensions.ReadUint16LengthPrefixed(&extData) {
  1060  			return false
  1061  		}
  1062  
  1063  		switch extension {
  1064  		case extensionALPN:
  1065  			var protoList cryptobyte.String
  1066  			if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
  1067  				return false
  1068  			}
  1069  			var proto cryptobyte.String
  1070  			if !protoList.ReadUint8LengthPrefixed(&proto) ||
  1071  				proto.Empty() || !protoList.Empty() {
  1072  				return false
  1073  			}
  1074  			m.alpnProtocol = string(proto)
  1075  		case extensionQUICTransportParameters:
  1076  			m.quicTransportParameters = make([]byte, len(extData))
  1077  			if !extData.CopyBytes(m.quicTransportParameters) {
  1078  				return false
  1079  			}
  1080  		case extensionEarlyData:
  1081  			// RFC 8446, Section 4.2.10
  1082  			m.earlyData = true
  1083  		case extensionEncryptedClientHello:
  1084  			m.echRetryConfigs = make([]byte, len(extData))
  1085  			if !extData.CopyBytes(m.echRetryConfigs) {
  1086  				return false
  1087  			}
  1088  		default:
  1089  			// Ignore unknown extensions.
  1090  			continue
  1091  		}
  1092  
  1093  		if !extData.Empty() {
  1094  			return false
  1095  		}
  1096  	}
  1097  
  1098  	return true
  1099  }
  1100  
  1101  type endOfEarlyDataMsg struct{}
  1102  
  1103  func (m *endOfEarlyDataMsg) marshal() ([]byte, error) {
  1104  	x := make([]byte, 4)
  1105  	x[0] = typeEndOfEarlyData
  1106  	return x, nil
  1107  }
  1108  
  1109  func (m *endOfEarlyDataMsg) unmarshal(data []byte) bool {
  1110  	return len(data) == 4
  1111  }
  1112  
  1113  type keyUpdateMsg struct {
  1114  	updateRequested bool
  1115  }
  1116  
  1117  func (m *keyUpdateMsg) marshal() ([]byte, error) {
  1118  	var b cryptobyte.Builder
  1119  	b.AddUint8(typeKeyUpdate)
  1120  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1121  		if m.updateRequested {
  1122  			b.AddUint8(1)
  1123  		} else {
  1124  			b.AddUint8(0)
  1125  		}
  1126  	})
  1127  
  1128  	return b.Bytes()
  1129  }
  1130  
  1131  func (m *keyUpdateMsg) unmarshal(data []byte) bool {
  1132  	s := cryptobyte.String(data)
  1133  
  1134  	var updateRequested uint8
  1135  	if !s.Skip(4) || // message type and uint24 length field
  1136  		!s.ReadUint8(&updateRequested) || !s.Empty() {
  1137  		return false
  1138  	}
  1139  	switch updateRequested {
  1140  	case 0:
  1141  		m.updateRequested = false
  1142  	case 1:
  1143  		m.updateRequested = true
  1144  	default:
  1145  		return false
  1146  	}
  1147  	return true
  1148  }
  1149  
  1150  type newSessionTicketMsgTLS13 struct {
  1151  	lifetime     uint32
  1152  	ageAdd       uint32
  1153  	nonce        []byte
  1154  	label        []byte
  1155  	maxEarlyData uint32
  1156  }
  1157  
  1158  func (m *newSessionTicketMsgTLS13) marshal() ([]byte, error) {
  1159  	var b cryptobyte.Builder
  1160  	b.AddUint8(typeNewSessionTicket)
  1161  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1162  		b.AddUint32(m.lifetime)
  1163  		b.AddUint32(m.ageAdd)
  1164  		b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  1165  			b.AddBytes(m.nonce)
  1166  		})
  1167  		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1168  			b.AddBytes(m.label)
  1169  		})
  1170  
  1171  		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1172  			if m.maxEarlyData > 0 {
  1173  				b.AddUint16(extensionEarlyData)
  1174  				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1175  					b.AddUint32(m.maxEarlyData)
  1176  				})
  1177  			}
  1178  		})
  1179  	})
  1180  
  1181  	return b.Bytes()
  1182  }
  1183  
  1184  func (m *newSessionTicketMsgTLS13) unmarshal(data []byte) bool {
  1185  	*m = newSessionTicketMsgTLS13{}
  1186  	s := cryptobyte.String(data)
  1187  
  1188  	var extensions cryptobyte.String
  1189  	if !s.Skip(4) || // message type and uint24 length field
  1190  		!s.ReadUint32(&m.lifetime) ||
  1191  		!s.ReadUint32(&m.ageAdd) ||
  1192  		!readUint8LengthPrefixed(&s, &m.nonce) ||
  1193  		!readUint16LengthPrefixed(&s, &m.label) ||
  1194  		!s.ReadUint16LengthPrefixed(&extensions) ||
  1195  		!s.Empty() {
  1196  		return false
  1197  	}
  1198  
  1199  	for !extensions.Empty() {
  1200  		var extension uint16
  1201  		var extData cryptobyte.String
  1202  		if !extensions.ReadUint16(&extension) ||
  1203  			!extensions.ReadUint16LengthPrefixed(&extData) {
  1204  			return false
  1205  		}
  1206  
  1207  		switch extension {
  1208  		case extensionEarlyData:
  1209  			if !extData.ReadUint32(&m.maxEarlyData) {
  1210  				return false
  1211  			}
  1212  		default:
  1213  			// Ignore unknown extensions.
  1214  			continue
  1215  		}
  1216  
  1217  		if !extData.Empty() {
  1218  			return false
  1219  		}
  1220  	}
  1221  
  1222  	return true
  1223  }
  1224  
  1225  type certificateRequestMsgTLS13 struct {
  1226  	ocspStapling                     bool
  1227  	scts                             bool
  1228  	supportedSignatureAlgorithms     []SignatureScheme
  1229  	supportedSignatureAlgorithmsCert []SignatureScheme
  1230  	certificateAuthorities           [][]byte
  1231  }
  1232  
  1233  func (m *certificateRequestMsgTLS13) marshal() ([]byte, error) {
  1234  	var b cryptobyte.Builder
  1235  	b.AddUint8(typeCertificateRequest)
  1236  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1237  		// certificate_request_context (SHALL be zero length unless used for
  1238  		// post-handshake authentication)
  1239  		b.AddUint8(0)
  1240  
  1241  		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1242  			if m.ocspStapling {
  1243  				b.AddUint16(extensionStatusRequest)
  1244  				b.AddUint16(0) // empty extension_data
  1245  			}
  1246  			if m.scts {
  1247  				// RFC 8446, Section 4.4.2.1 makes no mention of
  1248  				// signed_certificate_timestamp in CertificateRequest, but
  1249  				// "Extensions in the Certificate message from the client MUST
  1250  				// correspond to extensions in the CertificateRequest message
  1251  				// from the server." and it appears in the table in Section 4.2.
  1252  				b.AddUint16(extensionSCT)
  1253  				b.AddUint16(0) // empty extension_data
  1254  			}
  1255  			if len(m.supportedSignatureAlgorithms) > 0 {
  1256  				b.AddUint16(extensionSignatureAlgorithms)
  1257  				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1258  					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1259  						for _, sigAlgo := range m.supportedSignatureAlgorithms {
  1260  							b.AddUint16(uint16(sigAlgo))
  1261  						}
  1262  					})
  1263  				})
  1264  			}
  1265  			if len(m.supportedSignatureAlgorithmsCert) > 0 {
  1266  				b.AddUint16(extensionSignatureAlgorithmsCert)
  1267  				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1268  					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1269  						for _, sigAlgo := range m.supportedSignatureAlgorithmsCert {
  1270  							b.AddUint16(uint16(sigAlgo))
  1271  						}
  1272  					})
  1273  				})
  1274  			}
  1275  			if len(m.certificateAuthorities) > 0 {
  1276  				b.AddUint16(extensionCertificateAuthorities)
  1277  				b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1278  					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1279  						for _, ca := range m.certificateAuthorities {
  1280  							b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1281  								b.AddBytes(ca)
  1282  							})
  1283  						}
  1284  					})
  1285  				})
  1286  			}
  1287  		})
  1288  	})
  1289  
  1290  	return b.Bytes()
  1291  }
  1292  
  1293  func (m *certificateRequestMsgTLS13) unmarshal(data []byte) bool {
  1294  	*m = certificateRequestMsgTLS13{}
  1295  	s := cryptobyte.String(data)
  1296  
  1297  	var context, extensions cryptobyte.String
  1298  	if !s.Skip(4) || // message type and uint24 length field
  1299  		!s.ReadUint8LengthPrefixed(&context) || !context.Empty() ||
  1300  		!s.ReadUint16LengthPrefixed(&extensions) ||
  1301  		!s.Empty() {
  1302  		return false
  1303  	}
  1304  
  1305  	for !extensions.Empty() {
  1306  		var extension uint16
  1307  		var extData cryptobyte.String
  1308  		if !extensions.ReadUint16(&extension) ||
  1309  			!extensions.ReadUint16LengthPrefixed(&extData) {
  1310  			return false
  1311  		}
  1312  
  1313  		switch extension {
  1314  		case extensionStatusRequest:
  1315  			m.ocspStapling = true
  1316  		case extensionSCT:
  1317  			m.scts = true
  1318  		case extensionSignatureAlgorithms:
  1319  			var sigAndAlgs cryptobyte.String
  1320  			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
  1321  				return false
  1322  			}
  1323  			for !sigAndAlgs.Empty() {
  1324  				var sigAndAlg uint16
  1325  				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
  1326  					return false
  1327  				}
  1328  				m.supportedSignatureAlgorithms = append(
  1329  					m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg))
  1330  			}
  1331  		case extensionSignatureAlgorithmsCert:
  1332  			var sigAndAlgs cryptobyte.String
  1333  			if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
  1334  				return false
  1335  			}
  1336  			for !sigAndAlgs.Empty() {
  1337  				var sigAndAlg uint16
  1338  				if !sigAndAlgs.ReadUint16(&sigAndAlg) {
  1339  					return false
  1340  				}
  1341  				m.supportedSignatureAlgorithmsCert = append(
  1342  					m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg))
  1343  			}
  1344  		case extensionCertificateAuthorities:
  1345  			var auths cryptobyte.String
  1346  			if !extData.ReadUint16LengthPrefixed(&auths) || auths.Empty() {
  1347  				return false
  1348  			}
  1349  			for !auths.Empty() {
  1350  				var ca []byte
  1351  				if !readUint16LengthPrefixed(&auths, &ca) || len(ca) == 0 {
  1352  					return false
  1353  				}
  1354  				m.certificateAuthorities = append(m.certificateAuthorities, ca)
  1355  			}
  1356  		default:
  1357  			// Ignore unknown extensions.
  1358  			continue
  1359  		}
  1360  
  1361  		if !extData.Empty() {
  1362  			return false
  1363  		}
  1364  	}
  1365  
  1366  	return true
  1367  }
  1368  
  1369  type certificateMsg struct {
  1370  	certificates [][]byte
  1371  }
  1372  
  1373  func (m *certificateMsg) marshal() ([]byte, error) {
  1374  	var i int
  1375  	for _, slice := range m.certificates {
  1376  		i += len(slice)
  1377  	}
  1378  
  1379  	length := 3 + 3*len(m.certificates) + i
  1380  	x := make([]byte, 4+length)
  1381  	x[0] = typeCertificate
  1382  	x[1] = uint8(length >> 16)
  1383  	x[2] = uint8(length >> 8)
  1384  	x[3] = uint8(length)
  1385  
  1386  	certificateOctets := length - 3
  1387  	x[4] = uint8(certificateOctets >> 16)
  1388  	x[5] = uint8(certificateOctets >> 8)
  1389  	x[6] = uint8(certificateOctets)
  1390  
  1391  	y := x[7:]
  1392  	for _, slice := range m.certificates {
  1393  		y[0] = uint8(len(slice) >> 16)
  1394  		y[1] = uint8(len(slice) >> 8)
  1395  		y[2] = uint8(len(slice))
  1396  		copy(y[3:], slice)
  1397  		y = y[3+len(slice):]
  1398  	}
  1399  
  1400  	return x, nil
  1401  }
  1402  
  1403  func (m *certificateMsg) unmarshal(data []byte) bool {
  1404  	if len(data) < 7 {
  1405  		return false
  1406  	}
  1407  
  1408  	certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6])
  1409  	if uint32(len(data)) != certsLen+7 {
  1410  		return false
  1411  	}
  1412  
  1413  	numCerts := 0
  1414  	d := data[7:]
  1415  	for certsLen > 0 {
  1416  		if len(d) < 4 {
  1417  			return false
  1418  		}
  1419  		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
  1420  		if uint32(len(d)) < 3+certLen {
  1421  			return false
  1422  		}
  1423  		d = d[3+certLen:]
  1424  		certsLen -= 3 + certLen
  1425  		numCerts++
  1426  	}
  1427  
  1428  	m.certificates = make([][]byte, numCerts)
  1429  	d = data[7:]
  1430  	for i := 0; i < numCerts; i++ {
  1431  		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
  1432  		m.certificates[i] = d[3 : 3+certLen]
  1433  		d = d[3+certLen:]
  1434  	}
  1435  
  1436  	return true
  1437  }
  1438  
  1439  type certificateMsgTLS13 struct {
  1440  	certificate  Certificate
  1441  	ocspStapling bool
  1442  	scts         bool
  1443  }
  1444  
  1445  func (m *certificateMsgTLS13) marshal() ([]byte, error) {
  1446  	var b cryptobyte.Builder
  1447  	b.AddUint8(typeCertificate)
  1448  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1449  		b.AddUint8(0) // certificate_request_context
  1450  
  1451  		certificate := m.certificate
  1452  		if !m.ocspStapling {
  1453  			certificate.OCSPStaple = nil
  1454  		}
  1455  		if !m.scts {
  1456  			certificate.SignedCertificateTimestamps = nil
  1457  		}
  1458  		marshalCertificate(b, certificate)
  1459  	})
  1460  
  1461  	return b.Bytes()
  1462  }
  1463  
  1464  func marshalCertificate(b *cryptobyte.Builder, certificate Certificate) {
  1465  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1466  		for i, cert := range certificate.Certificate {
  1467  			b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1468  				b.AddBytes(cert)
  1469  			})
  1470  			b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1471  				if i > 0 {
  1472  					// This library only supports OCSP and SCT for leaf certificates.
  1473  					return
  1474  				}
  1475  				if certificate.OCSPStaple != nil {
  1476  					b.AddUint16(extensionStatusRequest)
  1477  					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1478  						b.AddUint8(statusTypeOCSP)
  1479  						b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1480  							b.AddBytes(certificate.OCSPStaple)
  1481  						})
  1482  					})
  1483  				}
  1484  				if certificate.SignedCertificateTimestamps != nil {
  1485  					b.AddUint16(extensionSCT)
  1486  					b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1487  						b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1488  							for _, sct := range certificate.SignedCertificateTimestamps {
  1489  								b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1490  									b.AddBytes(sct)
  1491  								})
  1492  							}
  1493  						})
  1494  					})
  1495  				}
  1496  			})
  1497  		}
  1498  	})
  1499  }
  1500  
  1501  func (m *certificateMsgTLS13) unmarshal(data []byte) bool {
  1502  	*m = certificateMsgTLS13{}
  1503  	s := cryptobyte.String(data)
  1504  
  1505  	var context cryptobyte.String
  1506  	if !s.Skip(4) || // message type and uint24 length field
  1507  		!s.ReadUint8LengthPrefixed(&context) || !context.Empty() ||
  1508  		!unmarshalCertificate(&s, &m.certificate) ||
  1509  		!s.Empty() {
  1510  		return false
  1511  	}
  1512  
  1513  	m.scts = m.certificate.SignedCertificateTimestamps != nil
  1514  	m.ocspStapling = m.certificate.OCSPStaple != nil
  1515  
  1516  	return true
  1517  }
  1518  
  1519  func unmarshalCertificate(s *cryptobyte.String, certificate *Certificate) bool {
  1520  	var certList cryptobyte.String
  1521  	if !s.ReadUint24LengthPrefixed(&certList) {
  1522  		return false
  1523  	}
  1524  	for !certList.Empty() {
  1525  		var cert []byte
  1526  		var extensions cryptobyte.String
  1527  		if !readUint24LengthPrefixed(&certList, &cert) ||
  1528  			!certList.ReadUint16LengthPrefixed(&extensions) {
  1529  			return false
  1530  		}
  1531  		certificate.Certificate = append(certificate.Certificate, cert)
  1532  		for !extensions.Empty() {
  1533  			var extension uint16
  1534  			var extData cryptobyte.String
  1535  			if !extensions.ReadUint16(&extension) ||
  1536  				!extensions.ReadUint16LengthPrefixed(&extData) {
  1537  				return false
  1538  			}
  1539  			if len(certificate.Certificate) > 1 {
  1540  				// This library only supports OCSP and SCT for leaf certificates.
  1541  				continue
  1542  			}
  1543  
  1544  			switch extension {
  1545  			case extensionStatusRequest:
  1546  				var statusType uint8
  1547  				if !extData.ReadUint8(&statusType) || statusType != statusTypeOCSP ||
  1548  					!readUint24LengthPrefixed(&extData, &certificate.OCSPStaple) ||
  1549  					len(certificate.OCSPStaple) == 0 {
  1550  					return false
  1551  				}
  1552  			case extensionSCT:
  1553  				var sctList cryptobyte.String
  1554  				if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() {
  1555  					return false
  1556  				}
  1557  				for !sctList.Empty() {
  1558  					var sct []byte
  1559  					if !readUint16LengthPrefixed(&sctList, &sct) ||
  1560  						len(sct) == 0 {
  1561  						return false
  1562  					}
  1563  					certificate.SignedCertificateTimestamps = append(
  1564  						certificate.SignedCertificateTimestamps, sct)
  1565  				}
  1566  			default:
  1567  				// Ignore unknown extensions.
  1568  				continue
  1569  			}
  1570  
  1571  			if !extData.Empty() {
  1572  				return false
  1573  			}
  1574  		}
  1575  	}
  1576  	return true
  1577  }
  1578  
  1579  type serverKeyExchangeMsg struct {
  1580  	key []byte
  1581  }
  1582  
  1583  func (m *serverKeyExchangeMsg) marshal() ([]byte, error) {
  1584  	length := len(m.key)
  1585  	x := make([]byte, length+4)
  1586  	x[0] = typeServerKeyExchange
  1587  	x[1] = uint8(length >> 16)
  1588  	x[2] = uint8(length >> 8)
  1589  	x[3] = uint8(length)
  1590  	copy(x[4:], m.key)
  1591  
  1592  	return x, nil
  1593  }
  1594  
  1595  func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool {
  1596  	if len(data) < 4 {
  1597  		return false
  1598  	}
  1599  	m.key = data[4:]
  1600  	return true
  1601  }
  1602  
  1603  type certificateStatusMsg struct {
  1604  	response []byte
  1605  }
  1606  
  1607  func (m *certificateStatusMsg) marshal() ([]byte, error) {
  1608  	var b cryptobyte.Builder
  1609  	b.AddUint8(typeCertificateStatus)
  1610  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1611  		b.AddUint8(statusTypeOCSP)
  1612  		b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1613  			b.AddBytes(m.response)
  1614  		})
  1615  	})
  1616  
  1617  	return b.Bytes()
  1618  }
  1619  
  1620  func (m *certificateStatusMsg) unmarshal(data []byte) bool {
  1621  	s := cryptobyte.String(data)
  1622  
  1623  	var statusType uint8
  1624  	if !s.Skip(4) || // message type and uint24 length field
  1625  		!s.ReadUint8(&statusType) || statusType != statusTypeOCSP ||
  1626  		!readUint24LengthPrefixed(&s, &m.response) ||
  1627  		len(m.response) == 0 || !s.Empty() {
  1628  		return false
  1629  	}
  1630  	return true
  1631  }
  1632  
  1633  type serverHelloDoneMsg struct{}
  1634  
  1635  func (m *serverHelloDoneMsg) marshal() ([]byte, error) {
  1636  	x := make([]byte, 4)
  1637  	x[0] = typeServerHelloDone
  1638  	return x, nil
  1639  }
  1640  
  1641  func (m *serverHelloDoneMsg) unmarshal(data []byte) bool {
  1642  	return len(data) == 4
  1643  }
  1644  
  1645  type clientKeyExchangeMsg struct {
  1646  	ciphertext []byte
  1647  }
  1648  
  1649  func (m *clientKeyExchangeMsg) marshal() ([]byte, error) {
  1650  	length := len(m.ciphertext)
  1651  	x := make([]byte, length+4)
  1652  	x[0] = typeClientKeyExchange
  1653  	x[1] = uint8(length >> 16)
  1654  	x[2] = uint8(length >> 8)
  1655  	x[3] = uint8(length)
  1656  	copy(x[4:], m.ciphertext)
  1657  
  1658  	return x, nil
  1659  }
  1660  
  1661  func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool {
  1662  	if len(data) < 4 {
  1663  		return false
  1664  	}
  1665  	l := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  1666  	if l != len(data)-4 {
  1667  		return false
  1668  	}
  1669  	m.ciphertext = data[4:]
  1670  	return true
  1671  }
  1672  
  1673  type finishedMsg struct {
  1674  	verifyData []byte
  1675  }
  1676  
  1677  func (m *finishedMsg) marshal() ([]byte, error) {
  1678  	var b cryptobyte.Builder
  1679  	b.AddUint8(typeFinished)
  1680  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1681  		b.AddBytes(m.verifyData)
  1682  	})
  1683  
  1684  	return b.Bytes()
  1685  }
  1686  
  1687  func (m *finishedMsg) unmarshal(data []byte) bool {
  1688  	s := cryptobyte.String(data)
  1689  	return s.Skip(1) &&
  1690  		readUint24LengthPrefixed(&s, &m.verifyData) &&
  1691  		s.Empty()
  1692  }
  1693  
  1694  type certificateRequestMsg struct {
  1695  	// hasSignatureAlgorithm indicates whether this message includes a list of
  1696  	// supported signature algorithms. This change was introduced with TLS 1.2.
  1697  	hasSignatureAlgorithm bool
  1698  
  1699  	certificateTypes             []byte
  1700  	supportedSignatureAlgorithms []SignatureScheme
  1701  	certificateAuthorities       [][]byte
  1702  }
  1703  
  1704  func (m *certificateRequestMsg) marshal() ([]byte, error) {
  1705  	// See RFC 4346, Section 7.4.4.
  1706  	length := 1 + len(m.certificateTypes) + 2
  1707  	casLength := 0
  1708  	for _, ca := range m.certificateAuthorities {
  1709  		casLength += 2 + len(ca)
  1710  	}
  1711  	length += casLength
  1712  
  1713  	if m.hasSignatureAlgorithm {
  1714  		length += 2 + 2*len(m.supportedSignatureAlgorithms)
  1715  	}
  1716  
  1717  	x := make([]byte, 4+length)
  1718  	x[0] = typeCertificateRequest
  1719  	x[1] = uint8(length >> 16)
  1720  	x[2] = uint8(length >> 8)
  1721  	x[3] = uint8(length)
  1722  
  1723  	x[4] = uint8(len(m.certificateTypes))
  1724  
  1725  	copy(x[5:], m.certificateTypes)
  1726  	y := x[5+len(m.certificateTypes):]
  1727  
  1728  	if m.hasSignatureAlgorithm {
  1729  		n := len(m.supportedSignatureAlgorithms) * 2
  1730  		y[0] = uint8(n >> 8)
  1731  		y[1] = uint8(n)
  1732  		y = y[2:]
  1733  		for _, sigAlgo := range m.supportedSignatureAlgorithms {
  1734  			y[0] = uint8(sigAlgo >> 8)
  1735  			y[1] = uint8(sigAlgo)
  1736  			y = y[2:]
  1737  		}
  1738  	}
  1739  
  1740  	y[0] = uint8(casLength >> 8)
  1741  	y[1] = uint8(casLength)
  1742  	y = y[2:]
  1743  	for _, ca := range m.certificateAuthorities {
  1744  		y[0] = uint8(len(ca) >> 8)
  1745  		y[1] = uint8(len(ca))
  1746  		y = y[2:]
  1747  		copy(y, ca)
  1748  		y = y[len(ca):]
  1749  	}
  1750  
  1751  	return x, nil
  1752  }
  1753  
  1754  func (m *certificateRequestMsg) unmarshal(data []byte) bool {
  1755  	if len(data) < 5 {
  1756  		return false
  1757  	}
  1758  
  1759  	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
  1760  	if uint32(len(data))-4 != length {
  1761  		return false
  1762  	}
  1763  
  1764  	numCertTypes := int(data[4])
  1765  	data = data[5:]
  1766  	if numCertTypes == 0 || len(data) <= numCertTypes {
  1767  		return false
  1768  	}
  1769  
  1770  	m.certificateTypes = make([]byte, numCertTypes)
  1771  	if copy(m.certificateTypes, data) != numCertTypes {
  1772  		return false
  1773  	}
  1774  
  1775  	data = data[numCertTypes:]
  1776  
  1777  	if m.hasSignatureAlgorithm {
  1778  		if len(data) < 2 {
  1779  			return false
  1780  		}
  1781  		sigAndHashLen := uint16(data[0])<<8 | uint16(data[1])
  1782  		data = data[2:]
  1783  		if sigAndHashLen&1 != 0 {
  1784  			return false
  1785  		}
  1786  		if len(data) < int(sigAndHashLen) {
  1787  			return false
  1788  		}
  1789  		numSigAlgos := sigAndHashLen / 2
  1790  		m.supportedSignatureAlgorithms = make([]SignatureScheme, numSigAlgos)
  1791  		for i := range m.supportedSignatureAlgorithms {
  1792  			m.supportedSignatureAlgorithms[i] = SignatureScheme(data[0])<<8 | SignatureScheme(data[1])
  1793  			data = data[2:]
  1794  		}
  1795  	}
  1796  
  1797  	if len(data) < 2 {
  1798  		return false
  1799  	}
  1800  	casLength := uint16(data[0])<<8 | uint16(data[1])
  1801  	data = data[2:]
  1802  	if len(data) < int(casLength) {
  1803  		return false
  1804  	}
  1805  	cas := make([]byte, casLength)
  1806  	copy(cas, data)
  1807  	data = data[casLength:]
  1808  
  1809  	m.certificateAuthorities = nil
  1810  	for len(cas) > 0 {
  1811  		if len(cas) < 2 {
  1812  			return false
  1813  		}
  1814  		caLen := uint16(cas[0])<<8 | uint16(cas[1])
  1815  		cas = cas[2:]
  1816  
  1817  		if len(cas) < int(caLen) {
  1818  			return false
  1819  		}
  1820  
  1821  		m.certificateAuthorities = append(m.certificateAuthorities, cas[:caLen])
  1822  		cas = cas[caLen:]
  1823  	}
  1824  
  1825  	return len(data) == 0
  1826  }
  1827  
  1828  type certificateVerifyMsg struct {
  1829  	hasSignatureAlgorithm bool // format change introduced in TLS 1.2
  1830  	signatureAlgorithm    SignatureScheme
  1831  	signature             []byte
  1832  }
  1833  
  1834  func (m *certificateVerifyMsg) marshal() ([]byte, error) {
  1835  	var b cryptobyte.Builder
  1836  	b.AddUint8(typeCertificateVerify)
  1837  	b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) {
  1838  		if m.hasSignatureAlgorithm {
  1839  			b.AddUint16(uint16(m.signatureAlgorithm))
  1840  		}
  1841  		b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
  1842  			b.AddBytes(m.signature)
  1843  		})
  1844  	})
  1845  
  1846  	return b.Bytes()
  1847  }
  1848  
  1849  func (m *certificateVerifyMsg) unmarshal(data []byte) bool {
  1850  	s := cryptobyte.String(data)
  1851  
  1852  	if !s.Skip(4) { // message type and uint24 length field
  1853  		return false
  1854  	}
  1855  	if m.hasSignatureAlgorithm {
  1856  		if !s.ReadUint16((*uint16)(&m.signatureAlgorithm)) {
  1857  			return false
  1858  		}
  1859  	}
  1860  	return readUint16LengthPrefixed(&s, &m.signature) && s.Empty()
  1861  }
  1862  
  1863  type newSessionTicketMsg struct {
  1864  	ticket []byte
  1865  }
  1866  
  1867  func (m *newSessionTicketMsg) marshal() ([]byte, error) {
  1868  	// See RFC 5077, Section 3.3.
  1869  	ticketLen := len(m.ticket)
  1870  	length := 2 + 4 + ticketLen
  1871  	x := make([]byte, 4+length)
  1872  	x[0] = typeNewSessionTicket
  1873  	x[1] = uint8(length >> 16)
  1874  	x[2] = uint8(length >> 8)
  1875  	x[3] = uint8(length)
  1876  	x[8] = uint8(ticketLen >> 8)
  1877  	x[9] = uint8(ticketLen)
  1878  	copy(x[10:], m.ticket)
  1879  
  1880  	return x, nil
  1881  }
  1882  
  1883  func (m *newSessionTicketMsg) unmarshal(data []byte) bool {
  1884  	if len(data) < 10 {
  1885  		return false
  1886  	}
  1887  
  1888  	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
  1889  	if uint32(len(data))-4 != length {
  1890  		return false
  1891  	}
  1892  
  1893  	ticketLen := int(data[8])<<8 + int(data[9])
  1894  	if len(data)-10 != ticketLen {
  1895  		return false
  1896  	}
  1897  
  1898  	m.ticket = data[10:]
  1899  
  1900  	return true
  1901  }
  1902  
  1903  type helloRequestMsg struct {
  1904  }
  1905  
  1906  func (*helloRequestMsg) marshal() ([]byte, error) {
  1907  	return []byte{typeHelloRequest, 0, 0, 0}, nil
  1908  }
  1909  
  1910  func (*helloRequestMsg) unmarshal(data []byte) bool {
  1911  	return len(data) == 4
  1912  }
  1913  
  1914  type transcriptHash interface {
  1915  	Write([]byte) (int, error)
  1916  }
  1917  
  1918  // transcriptMsg is a helper used to hash messages which are not hashed when
  1919  // they are read from, or written to, the wire. This is typically the case for
  1920  // messages which are either not sent, or need to be hashed out of order from
  1921  // when they are read/written.
  1922  //
  1923  // For most messages, the message is marshalled using their marshal method,
  1924  // since their wire representation is idempotent. For clientHelloMsg and
  1925  // serverHelloMsg, we store the original wire representation of the message and
  1926  // use that for hashing, since unmarshal/marshal are not idempotent due to
  1927  // extension ordering and other malleable fields, which may cause differences
  1928  // between what was received and what we marshal.
  1929  func transcriptMsg(msg handshakeMessage, h transcriptHash) error {
  1930  	if msgWithOrig, ok := msg.(handshakeMessageWithOriginalBytes); ok {
  1931  		if orig := msgWithOrig.originalBytes(); orig != nil {
  1932  			h.Write(msgWithOrig.originalBytes())
  1933  			return nil
  1934  		}
  1935  	}
  1936  
  1937  	data, err := msg.marshal()
  1938  	if err != nil {
  1939  		return err
  1940  	}
  1941  	h.Write(data)
  1942  	return nil
  1943  }
  1944  

View as plain text