github.com/Psiphon-Labs/tls-tris@v0.0.0-20230824155421-58bf6d336a9a/handshake_messages.go (about)

     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  	"bytes"
     9  	"encoding/binary"
    10  	"strings"
    11  
    12  	// [Psiphon]
    13  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
    14  )
    15  
    16  // [Psiphon]
    17  var randomizeClientHello = true
    18  
    19  // signAlgosCertList helper function returns either list of signature algorithms in case
    20  // signature_algorithms_cert extension should be marshalled or nil in the other case.
    21  // signAlgos is a list of algorithms from signature_algorithms extension. signAlgosCert is a list
    22  // of algorithms from signature_algorithms_cert extension.
    23  func signAlgosCertList(signAlgos, signAlgosCert []SignatureScheme) []SignatureScheme {
    24  	if eqSignatureAlgorithms(signAlgos, signAlgosCert) {
    25  		// ensure that only supported_algorithms extension is send if supported_algorithms_cert
    26  		// has identical content
    27  		return nil
    28  	}
    29  	return signAlgosCert
    30  }
    31  
    32  type clientHelloMsg struct {
    33  	raw                              []byte
    34  	rawTruncated                     []byte // for PSK binding
    35  	vers                             uint16
    36  	random                           []byte
    37  	sessionId                        []byte
    38  	cipherSuites                     []uint16
    39  	compressionMethods               []uint8
    40  	nextProtoNeg                     bool
    41  	serverName                       string
    42  	ocspStapling                     bool
    43  	scts                             bool
    44  	supportedCurves                  []CurveID
    45  	supportedPoints                  []uint8
    46  	ticketSupported                  bool
    47  	sessionTicket                    []uint8
    48  	supportedSignatureAlgorithms     []SignatureScheme
    49  	supportedSignatureAlgorithmsCert []SignatureScheme
    50  	secureRenegotiation              []byte
    51  	secureRenegotiationSupported     bool
    52  	alpnProtocols                    []string
    53  	keyShares                        []keyShare
    54  	supportedVersions                []uint16
    55  	psks                             []psk
    56  	pskKeyExchangeModes              []uint8
    57  	earlyData                        bool
    58  	delegatedCredential              bool
    59  	extendedMSSupported              bool // RFC7627
    60  
    61  	// [Psiphon]
    62  	clientHelloPRNGSeed *prng.Seed
    63  }
    64  
    65  // Function used for signature_algorithms and signature_algorithrms_cert
    66  // extensions only (for more details, see TLS 1.3 draft 28, 4.2.3).
    67  //
    68  // It advances data slice and returns it, so that it can be used for further
    69  // processing
    70  func marshalExtensionSignatureAlgorithms(extension uint16, data []byte, schemes []SignatureScheme) []byte {
    71  	algNum := uint16(len(schemes))
    72  	if algNum == 0 {
    73  		return data
    74  	}
    75  
    76  	binary.BigEndian.PutUint16(data, extension)
    77  	data = data[2:]
    78  	binary.BigEndian.PutUint16(data, (2*algNum)+2) // +1 for length
    79  	data = data[2:]
    80  	binary.BigEndian.PutUint16(data, (2 * algNum))
    81  	data = data[2:]
    82  
    83  	for _, algo := range schemes {
    84  		binary.BigEndian.PutUint16(data, uint16(algo))
    85  		data = data[2:]
    86  	}
    87  	return data
    88  }
    89  
    90  // Function used for unmarshalling signature_algorithms or signature_algorithms_cert extensions only
    91  // (for more details, see TLS 1.3 draft 28, 4.2.3)
    92  // In case of error function returns alertDecoderError otherwise filled SignatureScheme slice and alertSuccess
    93  func unmarshalExtensionSignatureAlgorithms(data []byte, length int) ([]SignatureScheme, alert) {
    94  
    95  	if length < 2 || length&1 != 0 {
    96  		return nil, alertDecodeError
    97  	}
    98  
    99  	algLen := binary.BigEndian.Uint16(data)
   100  	idx := 2
   101  
   102  	if int(algLen) != length-2 {
   103  		return nil, alertDecodeError
   104  	}
   105  
   106  	schemes := make([]SignatureScheme, algLen/2)
   107  	for i := range schemes {
   108  		schemes[i] = SignatureScheme(binary.BigEndian.Uint16(data[idx:]))
   109  		idx += 2
   110  	}
   111  	return schemes, alertSuccess
   112  }
   113  
   114  func (m *clientHelloMsg) equal(i interface{}) bool {
   115  	m1, ok := i.(*clientHelloMsg)
   116  	if !ok {
   117  		return false
   118  	}
   119  
   120  	return bytes.Equal(m.raw, m1.raw) &&
   121  		m.vers == m1.vers &&
   122  		bytes.Equal(m.random, m1.random) &&
   123  		bytes.Equal(m.sessionId, m1.sessionId) &&
   124  		eqUint16s(m.cipherSuites, m1.cipherSuites) &&
   125  		bytes.Equal(m.compressionMethods, m1.compressionMethods) &&
   126  		m.nextProtoNeg == m1.nextProtoNeg &&
   127  		m.serverName == m1.serverName &&
   128  		m.ocspStapling == m1.ocspStapling &&
   129  		m.scts == m1.scts &&
   130  		eqCurveIDs(m.supportedCurves, m1.supportedCurves) &&
   131  		bytes.Equal(m.supportedPoints, m1.supportedPoints) &&
   132  		m.ticketSupported == m1.ticketSupported &&
   133  		bytes.Equal(m.sessionTicket, m1.sessionTicket) &&
   134  		eqSignatureAlgorithms(m.supportedSignatureAlgorithms, m1.supportedSignatureAlgorithms) &&
   135  		eqSignatureAlgorithms(m.supportedSignatureAlgorithmsCert, m1.supportedSignatureAlgorithmsCert) &&
   136  		m.secureRenegotiationSupported == m1.secureRenegotiationSupported &&
   137  		bytes.Equal(m.secureRenegotiation, m1.secureRenegotiation) &&
   138  		eqStrings(m.alpnProtocols, m1.alpnProtocols) &&
   139  		eqKeyShares(m.keyShares, m1.keyShares) &&
   140  		eqUint16s(m.supportedVersions, m1.supportedVersions) &&
   141  		m.earlyData == m1.earlyData &&
   142  		m.delegatedCredential == m1.delegatedCredential &&
   143  		m.extendedMSSupported == m1.extendedMSSupported
   144  }
   145  
   146  func (m *clientHelloMsg) marshal() []byte {
   147  
   148  	// [Psiphon]
   149  	// Note: the original marshal function is retained as-is for ease of merging upstream changes.
   150  	if randomizeClientHello {
   151  		return m.randomizedMarshal()
   152  	}
   153  
   154  	if m.raw != nil {
   155  		return m.raw
   156  	}
   157  
   158  	length := 2 + 32 + 1 + len(m.sessionId) + 2 + len(m.cipherSuites)*2 + 1 + len(m.compressionMethods)
   159  	numExtensions := 0
   160  	extensionsLength := 0
   161  
   162  	if m.nextProtoNeg {
   163  		numExtensions++
   164  	}
   165  	if m.ocspStapling {
   166  		extensionsLength += 1 + 2 + 2
   167  		numExtensions++
   168  	}
   169  	if len(m.serverName) > 0 {
   170  		extensionsLength += 5 + len(m.serverName)
   171  		numExtensions++
   172  	}
   173  	if len(m.supportedCurves) > 0 {
   174  		extensionsLength += 2 + 2*len(m.supportedCurves)
   175  		numExtensions++
   176  	}
   177  	if len(m.supportedPoints) > 0 {
   178  		extensionsLength += 1 + len(m.supportedPoints)
   179  		numExtensions++
   180  	}
   181  	if m.ticketSupported {
   182  		extensionsLength += len(m.sessionTicket)
   183  		numExtensions++
   184  	}
   185  	if len(m.supportedSignatureAlgorithms) > 0 {
   186  		extensionsLength += 2 + 2*len(m.supportedSignatureAlgorithms)
   187  		numExtensions++
   188  	}
   189  	if m.getSignatureAlgorithmsCert() != nil {
   190  		extensionsLength += 2 + 2*len(m.getSignatureAlgorithmsCert())
   191  		numExtensions++
   192  	}
   193  	if m.secureRenegotiationSupported {
   194  		extensionsLength += 1 + len(m.secureRenegotiation)
   195  		numExtensions++
   196  	}
   197  	if len(m.alpnProtocols) > 0 {
   198  		extensionsLength += 2
   199  		for _, s := range m.alpnProtocols {
   200  			if l := len(s); l == 0 || l > 255 {
   201  				panic("invalid ALPN protocol")
   202  			}
   203  			extensionsLength++
   204  			extensionsLength += len(s)
   205  		}
   206  		numExtensions++
   207  	}
   208  	if m.scts {
   209  		numExtensions++
   210  	}
   211  	if len(m.keyShares) > 0 {
   212  		extensionsLength += 2
   213  		for _, k := range m.keyShares {
   214  			extensionsLength += 4 + len(k.data)
   215  		}
   216  		numExtensions++
   217  	}
   218  	if len(m.supportedVersions) > 0 {
   219  		extensionsLength += 1 + 2*len(m.supportedVersions)
   220  		numExtensions++
   221  	}
   222  	if m.earlyData {
   223  		numExtensions++
   224  	}
   225  	if m.delegatedCredential {
   226  		numExtensions++
   227  	}
   228  	if m.extendedMSSupported {
   229  		numExtensions++
   230  	}
   231  	if numExtensions > 0 {
   232  		extensionsLength += 4 * numExtensions
   233  		length += 2 + extensionsLength
   234  	}
   235  
   236  	x := make([]byte, 4+length)
   237  	x[0] = typeClientHello
   238  	x[1] = uint8(length >> 16)
   239  	x[2] = uint8(length >> 8)
   240  	x[3] = uint8(length)
   241  	x[4] = uint8(m.vers >> 8)
   242  	x[5] = uint8(m.vers)
   243  	copy(x[6:38], m.random)
   244  	x[38] = uint8(len(m.sessionId))
   245  	copy(x[39:39+len(m.sessionId)], m.sessionId)
   246  	y := x[39+len(m.sessionId):]
   247  	y[0] = uint8(len(m.cipherSuites) >> 7)
   248  	y[1] = uint8(len(m.cipherSuites) << 1)
   249  	for i, suite := range m.cipherSuites {
   250  		y[2+i*2] = uint8(suite >> 8)
   251  		y[3+i*2] = uint8(suite)
   252  	}
   253  	z := y[2+len(m.cipherSuites)*2:]
   254  	z[0] = uint8(len(m.compressionMethods))
   255  	copy(z[1:], m.compressionMethods)
   256  
   257  	z = z[1+len(m.compressionMethods):]
   258  	if numExtensions > 0 {
   259  		z[0] = byte(extensionsLength >> 8)
   260  		z[1] = byte(extensionsLength)
   261  		z = z[2:]
   262  	}
   263  	if m.nextProtoNeg {
   264  		z[0] = byte(extensionNextProtoNeg >> 8)
   265  		z[1] = byte(extensionNextProtoNeg & 0xff)
   266  		// The length is always 0
   267  		z = z[4:]
   268  	}
   269  	if len(m.serverName) > 0 {
   270  		z[0] = byte(extensionServerName >> 8)
   271  		z[1] = byte(extensionServerName & 0xff)
   272  		l := len(m.serverName) + 5
   273  		z[2] = byte(l >> 8)
   274  		z[3] = byte(l)
   275  		z = z[4:]
   276  
   277  		// RFC 3546, section 3.1
   278  		//
   279  		// struct {
   280  		//     NameType name_type;
   281  		//     select (name_type) {
   282  		//         case host_name: HostName;
   283  		//     } name;
   284  		// } ServerName;
   285  		//
   286  		// enum {
   287  		//     host_name(0), (255)
   288  		// } NameType;
   289  		//
   290  		// opaque HostName<1..2^16-1>;
   291  		//
   292  		// struct {
   293  		//     ServerName server_name_list<1..2^16-1>
   294  		// } ServerNameList;
   295  
   296  		z[0] = byte((len(m.serverName) + 3) >> 8)
   297  		z[1] = byte(len(m.serverName) + 3)
   298  		z[3] = byte(len(m.serverName) >> 8)
   299  		z[4] = byte(len(m.serverName))
   300  		copy(z[5:], []byte(m.serverName))
   301  		z = z[l:]
   302  	}
   303  	if m.ocspStapling {
   304  		// RFC 4366, section 3.6
   305  		z[0] = byte(extensionStatusRequest >> 8)
   306  		z[1] = byte(extensionStatusRequest)
   307  		z[2] = 0
   308  		z[3] = 5
   309  		z[4] = 1 // OCSP type
   310  		// Two zero valued uint16s for the two lengths.
   311  		z = z[9:]
   312  	}
   313  	if len(m.supportedCurves) > 0 {
   314  		// http://tools.ietf.org/html/rfc4492#section-5.5.1
   315  		// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.4
   316  		z[0] = byte(extensionSupportedCurves >> 8)
   317  		z[1] = byte(extensionSupportedCurves)
   318  		l := 2 + 2*len(m.supportedCurves)
   319  		z[2] = byte(l >> 8)
   320  		z[3] = byte(l)
   321  		l -= 2
   322  		z[4] = byte(l >> 8)
   323  		z[5] = byte(l)
   324  		z = z[6:]
   325  		for _, curve := range m.supportedCurves {
   326  			z[0] = byte(curve >> 8)
   327  			z[1] = byte(curve)
   328  			z = z[2:]
   329  		}
   330  	}
   331  	if len(m.supportedPoints) > 0 {
   332  		// http://tools.ietf.org/html/rfc4492#section-5.5.2
   333  		z[0] = byte(extensionSupportedPoints >> 8)
   334  		z[1] = byte(extensionSupportedPoints)
   335  		l := 1 + len(m.supportedPoints)
   336  		z[2] = byte(l >> 8)
   337  		z[3] = byte(l)
   338  		l--
   339  		z[4] = byte(l)
   340  		z = z[5:]
   341  		for _, pointFormat := range m.supportedPoints {
   342  			z[0] = pointFormat
   343  			z = z[1:]
   344  		}
   345  	}
   346  	if m.ticketSupported {
   347  		// http://tools.ietf.org/html/rfc5077#section-3.2
   348  		z[0] = byte(extensionSessionTicket >> 8)
   349  		z[1] = byte(extensionSessionTicket)
   350  		l := len(m.sessionTicket)
   351  		z[2] = byte(l >> 8)
   352  		z[3] = byte(l)
   353  		z = z[4:]
   354  		copy(z, m.sessionTicket)
   355  		z = z[len(m.sessionTicket):]
   356  	}
   357  
   358  	if len(m.supportedSignatureAlgorithms) > 0 {
   359  		z = marshalExtensionSignatureAlgorithms(extensionSignatureAlgorithms, z, m.supportedSignatureAlgorithms)
   360  	}
   361  	if m.getSignatureAlgorithmsCert() != nil {
   362  		// Ensure only one list of algorithms is sent if supported_algorithms and supported_algorithms_cert are the same
   363  		z = marshalExtensionSignatureAlgorithms(extensionSignatureAlgorithmsCert, z, m.getSignatureAlgorithmsCert())
   364  	}
   365  
   366  	if m.secureRenegotiationSupported {
   367  		z[0] = byte(extensionRenegotiationInfo >> 8)
   368  		z[1] = byte(extensionRenegotiationInfo & 0xff)
   369  		z[2] = 0
   370  		z[3] = byte(len(m.secureRenegotiation) + 1)
   371  		z[4] = byte(len(m.secureRenegotiation))
   372  		z = z[5:]
   373  		copy(z, m.secureRenegotiation)
   374  		z = z[len(m.secureRenegotiation):]
   375  	}
   376  	if len(m.alpnProtocols) > 0 {
   377  		z[0] = byte(extensionALPN >> 8)
   378  		z[1] = byte(extensionALPN & 0xff)
   379  		lengths := z[2:]
   380  		z = z[6:]
   381  
   382  		stringsLength := 0
   383  		for _, s := range m.alpnProtocols {
   384  			l := len(s)
   385  			z[0] = byte(l)
   386  			copy(z[1:], s)
   387  			z = z[1+l:]
   388  			stringsLength += 1 + l
   389  		}
   390  
   391  		lengths[2] = byte(stringsLength >> 8)
   392  		lengths[3] = byte(stringsLength)
   393  		stringsLength += 2
   394  		lengths[0] = byte(stringsLength >> 8)
   395  		lengths[1] = byte(stringsLength)
   396  	}
   397  	if m.scts {
   398  		// https://tools.ietf.org/html/rfc6962#section-3.3.1
   399  		z[0] = byte(extensionSCT >> 8)
   400  		z[1] = byte(extensionSCT)
   401  		// zero uint16 for the zero-length extension_data
   402  		z = z[4:]
   403  	}
   404  	if len(m.keyShares) > 0 {
   405  		// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.5
   406  		z[0] = byte(extensionKeyShare >> 8)
   407  		z[1] = byte(extensionKeyShare)
   408  		lengths := z[2:]
   409  		z = z[6:]
   410  
   411  		totalLength := 0
   412  		for _, ks := range m.keyShares {
   413  			z[0] = byte(ks.group >> 8)
   414  			z[1] = byte(ks.group)
   415  			z[2] = byte(len(ks.data) >> 8)
   416  			z[3] = byte(len(ks.data))
   417  			copy(z[4:], ks.data)
   418  			z = z[4+len(ks.data):]
   419  			totalLength += 4 + len(ks.data)
   420  		}
   421  
   422  		lengths[2] = byte(totalLength >> 8)
   423  		lengths[3] = byte(totalLength)
   424  		totalLength += 2
   425  		lengths[0] = byte(totalLength >> 8)
   426  		lengths[1] = byte(totalLength)
   427  	}
   428  	if len(m.supportedVersions) > 0 {
   429  		z[0] = byte(extensionSupportedVersions >> 8)
   430  		z[1] = byte(extensionSupportedVersions)
   431  		l := 1 + 2*len(m.supportedVersions)
   432  		z[2] = byte(l >> 8)
   433  		z[3] = byte(l)
   434  		l -= 1
   435  		z[4] = byte(l)
   436  		z = z[5:]
   437  		for _, v := range m.supportedVersions {
   438  			z[0] = byte(v >> 8)
   439  			z[1] = byte(v)
   440  			z = z[2:]
   441  		}
   442  	}
   443  	if m.earlyData {
   444  		z[0] = byte(extensionEarlyData >> 8)
   445  		z[1] = byte(extensionEarlyData)
   446  		z = z[4:]
   447  	}
   448  	if m.delegatedCredential {
   449  		binary.BigEndian.PutUint16(z, extensionDelegatedCredential)
   450  		z = z[4:]
   451  	}
   452  	if m.extendedMSSupported {
   453  		binary.BigEndian.PutUint16(z, extensionEMS)
   454  		z = z[4:]
   455  	}
   456  
   457  	m.raw = x
   458  
   459  	return x
   460  }
   461  
   462  // [Psiphon]
   463  //
   464  // Randomize the ClientHello. The offered algorithms are shuffled and
   465  // truncated (longer lists are selected with higher probability). Extensions
   466  // are shuffled, certain extensions may be omitted, and some additional
   467  // extensions may be added in.
   468  //
   469  // Assumes the Config is using default values for ClientHello algorithm
   470  // configuration.
   471  //
   472  // Inspired by parrotRandomized in utls:
   473  // https://github.com/refraction-networking/utls/blob/db1b65d2300d3a59616a43d2df4ea556b4a7d277/u_parrots.go#L300
   474  func (m *clientHelloMsg) randomizedMarshal() []byte {
   475  	if m.raw != nil {
   476  		return m.raw
   477  	}
   478  
   479  	PRNG := prng.NewPRNGWithSeed(m.clientHelloPRNGSeed)
   480  
   481  	permute := func(n int, swap func(i, j int)) {
   482  		if n < 2 {
   483  			return
   484  		}
   485  		perm := PRNG.Perm(n)
   486  		for i, j := range perm {
   487  			swap(i, j)
   488  		}
   489  	}
   490  
   491  	truncate := func(n int, cut func(i int)) {
   492  		i := n
   493  		for ; i > 1; i-- {
   494  			if !PRNG.FlipCoin() {
   495  				break
   496  			}
   497  		}
   498  		if i < n {
   499  			cut(i)
   500  		}
   501  	}
   502  
   503  	m.cipherSuites = append([]uint16(nil), m.cipherSuites...)
   504  
   505  	// Keep TLS 1.3 cipher suites ordered first, as required.
   506  	numTLS13CipherSuites := 0
   507  	for ; numTLS13CipherSuites < len(m.cipherSuites); numTLS13CipherSuites++ {
   508  		// TODO: check suiteTLS13 flag?
   509  		if m.cipherSuites[numTLS13CipherSuites]>>8 != 0x13 {
   510  			break
   511  		}
   512  	}
   513  	if numTLS13CipherSuites > 1 {
   514  		tls13CipherSuites := m.cipherSuites[:numTLS13CipherSuites]
   515  		permute(
   516  			len(tls13CipherSuites),
   517  			func(i, j int) {
   518  				tls13CipherSuites[i], tls13CipherSuites[j] = tls13CipherSuites[j], tls13CipherSuites[i]
   519  			})
   520  	}
   521  	if numTLS13CipherSuites < len(m.cipherSuites) {
   522  		olderCipherSuites := m.cipherSuites[numTLS13CipherSuites:]
   523  		permute(
   524  			len(olderCipherSuites),
   525  			func(i, j int) {
   526  				olderCipherSuites[i], olderCipherSuites[j] = olderCipherSuites[j], olderCipherSuites[i]
   527  			})
   528  		truncate(
   529  			len(olderCipherSuites),
   530  			func(i int) { m.cipherSuites = m.cipherSuites[:numTLS13CipherSuites+i] })
   531  	}
   532  
   533  	m.supportedCurves = append([]CurveID(nil), m.supportedCurves...)
   534  
   535  	// Following utls, the supported curves extension order is preserved. Note
   536  	// that, in TLS 1.3, the key share extention will include an entry
   537  	// corresponding to the first, default curve.
   538  	truncate(
   539  		len(m.supportedCurves),
   540  		func(i int) { m.supportedCurves = m.supportedCurves[:i] })
   541  
   542  	m.supportedPoints = append([]uint8(nil), m.supportedPoints...)
   543  	permute(
   544  		len(m.supportedPoints),
   545  		func(i, j int) {
   546  			m.supportedPoints[i], m.supportedPoints[j] = m.supportedPoints[j], m.supportedPoints[i]
   547  		})
   548  	truncate(
   549  		len(m.supportedPoints),
   550  		func(i int) { m.supportedPoints = m.supportedPoints[:i] })
   551  
   552  	m.supportedSignatureAlgorithms = append([]SignatureScheme(nil), m.supportedSignatureAlgorithms...)
   553  	permute(
   554  		len(m.supportedSignatureAlgorithms),
   555  		func(i, j int) {
   556  			m.supportedSignatureAlgorithms[i], m.supportedSignatureAlgorithms[j] = m.supportedSignatureAlgorithms[j], m.supportedSignatureAlgorithms[i]
   557  		})
   558  	truncate(
   559  		len(m.supportedSignatureAlgorithms),
   560  		func(i int) { m.supportedSignatureAlgorithms = m.supportedSignatureAlgorithms[:i] })
   561  
   562  	m.supportedSignatureAlgorithmsCert = append([]SignatureScheme(nil), m.supportedSignatureAlgorithmsCert...)
   563  	permute(
   564  		len(m.supportedSignatureAlgorithmsCert),
   565  		func(i, j int) {
   566  			m.supportedSignatureAlgorithmsCert[i], m.supportedSignatureAlgorithmsCert[j] = m.supportedSignatureAlgorithmsCert[j], m.supportedSignatureAlgorithmsCert[i]
   567  		})
   568  	truncate(
   569  		len(m.supportedSignatureAlgorithmsCert),
   570  		func(i int) { m.supportedSignatureAlgorithmsCert = m.supportedSignatureAlgorithmsCert[:i] })
   571  
   572  	m.alpnProtocols = []string{"h2", "http/1.1"}
   573  
   574  	if PRNG.FlipCoin() {
   575  		m.supportedVersions = []uint16{VersionTLS13, VersionTLS12, VersionTLS11, VersionTLS10}
   576  	}
   577  
   578  	numExtensions := 0
   579  	extensionsLength := 0
   580  	extensionMarshalers := make([]func(), 0)
   581  	var z []byte
   582  
   583  	// Indicates whether to send signature_algorithms_cert extension
   584  	if m.nextProtoNeg {
   585  		numExtensions++
   586  		extensionMarshalers = append(extensionMarshalers,
   587  			func() {
   588  				z[0] = byte(extensionNextProtoNeg >> 8)
   589  				z[1] = byte(extensionNextProtoNeg & 0xff)
   590  				// The length is always 0
   591  				z = z[4:]
   592  			})
   593  	}
   594  	if m.ocspStapling && PRNG.FlipCoin() { // May be omitted
   595  		extensionsLength += 1 + 2 + 2
   596  		numExtensions++
   597  		extensionMarshalers = append(extensionMarshalers,
   598  			func() {
   599  				// RFC 4366, section 3.6
   600  				z[0] = byte(extensionStatusRequest >> 8)
   601  				z[1] = byte(extensionStatusRequest)
   602  				z[2] = 0
   603  				z[3] = 5
   604  				z[4] = 1 // OCSP type
   605  				// Two zero valued uint16s for the two lengths.
   606  				z = z[9:]
   607  			})
   608  	}
   609  	if len(m.serverName) > 0 {
   610  		extensionsLength += 5 + len(m.serverName)
   611  		numExtensions++
   612  		extensionMarshalers = append(extensionMarshalers,
   613  			func() {
   614  				z[0] = byte(extensionServerName >> 8)
   615  				z[1] = byte(extensionServerName & 0xff)
   616  				l := len(m.serverName) + 5
   617  				z[2] = byte(l >> 8)
   618  				z[3] = byte(l)
   619  				z = z[4:]
   620  
   621  				// RFC 3546, section 3.1
   622  				//
   623  				// struct {
   624  				//     NameType name_type;
   625  				//     select (name_type) {
   626  				//         case host_name: HostName;
   627  				//     } name;
   628  				// } ServerName;
   629  				//
   630  				// enum {
   631  				//     host_name(0), (255)
   632  				// } NameType;
   633  				//
   634  				// opaque HostName<1..2^16-1>;
   635  				//
   636  				// struct {
   637  				//     ServerName server_name_list<1..2^16-1>
   638  				// } ServerNameList;
   639  
   640  				z[0] = byte((len(m.serverName) + 3) >> 8)
   641  				z[1] = byte(len(m.serverName) + 3)
   642  				z[3] = byte(len(m.serverName) >> 8)
   643  				z[4] = byte(len(m.serverName))
   644  				copy(z[5:], []byte(m.serverName))
   645  				z = z[l:]
   646  			})
   647  	}
   648  	if len(m.supportedCurves) > 0 {
   649  		extensionsLength += 2 + 2*len(m.supportedCurves)
   650  		numExtensions++
   651  		extensionMarshalers = append(extensionMarshalers,
   652  			func() {
   653  				// http://tools.ietf.org/html/rfc4492#section-5.5.1
   654  				// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.4
   655  				z[0] = byte(extensionSupportedCurves >> 8)
   656  				z[1] = byte(extensionSupportedCurves)
   657  				l := 2 + 2*len(m.supportedCurves)
   658  				z[2] = byte(l >> 8)
   659  				z[3] = byte(l)
   660  				l -= 2
   661  				z[4] = byte(l >> 8)
   662  				z[5] = byte(l)
   663  				z = z[6:]
   664  				for _, curve := range m.supportedCurves {
   665  					z[0] = byte(curve >> 8)
   666  					z[1] = byte(curve)
   667  					z = z[2:]
   668  				}
   669  			})
   670  	}
   671  	if len(m.supportedPoints) > 0 {
   672  		extensionsLength += 1 + len(m.supportedPoints)
   673  		numExtensions++
   674  		extensionMarshalers = append(extensionMarshalers,
   675  			func() {
   676  				// http://tools.ietf.org/html/rfc4492#section-5.5.2
   677  				z[0] = byte(extensionSupportedPoints >> 8)
   678  				z[1] = byte(extensionSupportedPoints)
   679  				l := 1 + len(m.supportedPoints)
   680  				z[2] = byte(l >> 8)
   681  				z[3] = byte(l)
   682  				l--
   683  				z[4] = byte(l)
   684  				z = z[5:]
   685  				for _, pointFormat := range m.supportedPoints {
   686  					z[0] = pointFormat
   687  					z = z[1:]
   688  				}
   689  			})
   690  	}
   691  	if m.ticketSupported {
   692  		extensionsLength += len(m.sessionTicket)
   693  		numExtensions++
   694  		extensionMarshalers = append(extensionMarshalers,
   695  			func() {
   696  				// http://tools.ietf.org/html/rfc5077#section-3.2
   697  				z[0] = byte(extensionSessionTicket >> 8)
   698  				z[1] = byte(extensionSessionTicket)
   699  				l := len(m.sessionTicket)
   700  				z[2] = byte(l >> 8)
   701  				z[3] = byte(l)
   702  				z = z[4:]
   703  				copy(z, m.sessionTicket)
   704  				z = z[len(m.sessionTicket):]
   705  			})
   706  	}
   707  	if len(m.supportedSignatureAlgorithms) > 0 {
   708  		extensionsLength += 2 + 2*len(m.supportedSignatureAlgorithms)
   709  		numExtensions++
   710  		extensionMarshalers = append(extensionMarshalers,
   711  			func() {
   712  				z = marshalExtensionSignatureAlgorithms(extensionSignatureAlgorithms, z, m.supportedSignatureAlgorithms)
   713  			})
   714  	}
   715  	if m.getSignatureAlgorithmsCert() != nil {
   716  		extensionsLength += 2 + 2*len(m.getSignatureAlgorithmsCert())
   717  		numExtensions++
   718  		extensionMarshalers = append(extensionMarshalers,
   719  			func() {
   720  				// Ensure only one list of algorithms is sent if supported_algorithms and supported_algorithms_cert are the same
   721  				z = marshalExtensionSignatureAlgorithms(extensionSignatureAlgorithmsCert, z, m.getSignatureAlgorithmsCert())
   722  			})
   723  	}
   724  	if m.secureRenegotiationSupported && PRNG.FlipCoin() { // May be omitted
   725  		extensionsLength += 1 + len(m.secureRenegotiation)
   726  		numExtensions++
   727  		extensionMarshalers = append(extensionMarshalers,
   728  			func() {
   729  				z[0] = byte(extensionRenegotiationInfo >> 8)
   730  				z[1] = byte(extensionRenegotiationInfo & 0xff)
   731  				z[2] = 0
   732  				z[3] = byte(len(m.secureRenegotiation) + 1)
   733  				z[4] = byte(len(m.secureRenegotiation))
   734  				z = z[5:]
   735  				copy(z, m.secureRenegotiation)
   736  				z = z[len(m.secureRenegotiation):]
   737  			})
   738  	}
   739  	if len(m.alpnProtocols) > 0 {
   740  		extensionsLength += 2
   741  		for _, s := range m.alpnProtocols {
   742  			if l := len(s); l == 0 || l > 255 {
   743  				panic("invalid ALPN protocol")
   744  			}
   745  			extensionsLength++
   746  			extensionsLength += len(s)
   747  		}
   748  		numExtensions++
   749  		extensionMarshalers = append(extensionMarshalers,
   750  			func() {
   751  				z[0] = byte(extensionALPN >> 8)
   752  				z[1] = byte(extensionALPN & 0xff)
   753  				lengths := z[2:]
   754  				z = z[6:]
   755  
   756  				stringsLength := 0
   757  				for _, s := range m.alpnProtocols {
   758  					l := len(s)
   759  					z[0] = byte(l)
   760  					copy(z[1:], s)
   761  					z = z[1+l:]
   762  					stringsLength += 1 + l
   763  				}
   764  
   765  				lengths[2] = byte(stringsLength >> 8)
   766  				lengths[3] = byte(stringsLength)
   767  				stringsLength += 2
   768  				lengths[0] = byte(stringsLength >> 8)
   769  				lengths[1] = byte(stringsLength)
   770  			})
   771  	}
   772  	if m.scts && PRNG.FlipCoin() { // May be omitted
   773  		numExtensions++
   774  		extensionMarshalers = append(extensionMarshalers,
   775  			func() {
   776  				// https://tools.ietf.org/html/rfc6962#section-3.3.1
   777  				z[0] = byte(extensionSCT >> 8)
   778  				z[1] = byte(extensionSCT)
   779  				// zero uint16 for the zero-length extension_data
   780  				z = z[4:]
   781  			})
   782  	}
   783  	if len(m.keyShares) > 0 {
   784  		extensionsLength += 2
   785  		for _, k := range m.keyShares {
   786  			extensionsLength += 4 + len(k.data)
   787  		}
   788  		numExtensions++
   789  		extensionMarshalers = append(extensionMarshalers,
   790  			func() {
   791  				// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.5
   792  				z[0] = byte(extensionKeyShare >> 8)
   793  				z[1] = byte(extensionKeyShare)
   794  				lengths := z[2:]
   795  				z = z[6:]
   796  
   797  				totalLength := 0
   798  				for _, ks := range m.keyShares {
   799  					z[0] = byte(ks.group >> 8)
   800  					z[1] = byte(ks.group)
   801  					z[2] = byte(len(ks.data) >> 8)
   802  					z[3] = byte(len(ks.data))
   803  					copy(z[4:], ks.data)
   804  					z = z[4+len(ks.data):]
   805  					totalLength += 4 + len(ks.data)
   806  				}
   807  
   808  				lengths[2] = byte(totalLength >> 8)
   809  				lengths[3] = byte(totalLength)
   810  				totalLength += 2
   811  				lengths[0] = byte(totalLength >> 8)
   812  				lengths[1] = byte(totalLength)
   813  			})
   814  	}
   815  	if len(m.supportedVersions) > 0 {
   816  		extensionsLength += 1 + 2*len(m.supportedVersions)
   817  		numExtensions++
   818  		extensionMarshalers = append(extensionMarshalers,
   819  			func() {
   820  				z[0] = byte(extensionSupportedVersions >> 8)
   821  				z[1] = byte(extensionSupportedVersions)
   822  				l := 1 + 2*len(m.supportedVersions)
   823  				z[2] = byte(l >> 8)
   824  				z[3] = byte(l)
   825  				l -= 1
   826  				z[4] = byte(l)
   827  				z = z[5:]
   828  				for _, v := range m.supportedVersions {
   829  					z[0] = byte(v >> 8)
   830  					z[1] = byte(v)
   831  					z = z[2:]
   832  				}
   833  			})
   834  	}
   835  	if m.earlyData {
   836  		numExtensions++
   837  		extensionMarshalers = append(extensionMarshalers,
   838  			func() {
   839  				z[0] = byte(extensionEarlyData >> 8)
   840  				z[1] = byte(extensionEarlyData)
   841  				z = z[4:]
   842  			})
   843  	}
   844  	if m.delegatedCredential {
   845  		numExtensions++
   846  		extensionMarshalers = append(extensionMarshalers,
   847  			func() {
   848  				binary.BigEndian.PutUint16(z, extensionDelegatedCredential)
   849  				z = z[4:]
   850  			})
   851  	}
   852  	if m.extendedMSSupported && PRNG.FlipCoin() { // May be omitted
   853  		numExtensions++
   854  		extensionMarshalers = append(extensionMarshalers,
   855  			func() {
   856  				binary.BigEndian.PutUint16(z, extensionEMS)
   857  				z = z[4:]
   858  			})
   859  	}
   860  
   861  	// Optional, additional extensions
   862  
   863  	// TODO: GREASE, Extended Master Secret (https://github.com/cloudflare/tls-tris/pull/30)
   864  
   865  	if PRNG.FlipCoin() {
   866  		numExtensions++
   867  		extensionMarshalers = append(extensionMarshalers,
   868  			func() {
   869  				extensionChannelID := uint16(30032)
   870  				z[0] = byte(extensionChannelID >> 8)
   871  				z[1] = byte(extensionChannelID & 0xff)
   872  				z = z[4:]
   873  			})
   874  	}
   875  
   876  	preExtensionLength := 2 + 32 + 1 + len(m.sessionId) + 2 + len(m.cipherSuites)*2 + 1 + len(m.compressionMethods)
   877  
   878  	if PRNG.FlipCoin() {
   879  
   880  		// Padding must be last, since it depends on extensionsLength
   881  
   882  		// Logic from:
   883  		// https://github.com/google/boringssl/blob/46db7af2c998cf8514d606408546d9be9699f03c/ssl/t1_lib.c#L2803
   884  		// https://github.com/google/boringssl/blob/master/LICENSE
   885  
   886  		unpaddedLength := preExtensionLength
   887  		if numExtensions > 0 {
   888  			unpaddedLength += 2 + 4*numExtensions + extensionsLength
   889  		}
   890  		if unpaddedLength > 0xff && unpaddedLength < 0x200 {
   891  			paddingLength := uint16(0x200) - uint16(unpaddedLength)
   892  			if paddingLength >= 4+1 {
   893  				paddingLength -= 4
   894  			} else {
   895  				paddingLength = 1
   896  			}
   897  			extensionsLength += int(paddingLength)
   898  			numExtensions++
   899  			extensionMarshalers = append(extensionMarshalers,
   900  				func() {
   901  					extensionPadding := uint16(21)
   902  					z[0] = byte(extensionPadding >> 8)
   903  					z[1] = byte(extensionPadding & 0xff)
   904  					z[2] = byte(paddingLength >> 8)
   905  					z[3] = byte(paddingLength)
   906  					z = z[4+paddingLength:]
   907  				})
   908  		}
   909  	}
   910  
   911  	permute(
   912  		len(extensionMarshalers),
   913  		func(i, j int) {
   914  			extensionMarshalers[i], extensionMarshalers[j] = extensionMarshalers[j], extensionMarshalers[i]
   915  		})
   916  
   917  	length := preExtensionLength
   918  
   919  	if numExtensions > 0 {
   920  		extensionsLength += 4 * numExtensions
   921  		length += 2 + extensionsLength
   922  	}
   923  
   924  	x := make([]byte, 4+length)
   925  	x[0] = typeClientHello
   926  	x[1] = uint8(length >> 16)
   927  	x[2] = uint8(length >> 8)
   928  	x[3] = uint8(length)
   929  	x[4] = uint8(m.vers >> 8)
   930  	x[5] = uint8(m.vers)
   931  	copy(x[6:38], m.random)
   932  	x[38] = uint8(len(m.sessionId))
   933  	copy(x[39:39+len(m.sessionId)], m.sessionId)
   934  	y := x[39+len(m.sessionId):]
   935  	y[0] = uint8(len(m.cipherSuites) >> 7)
   936  	y[1] = uint8(len(m.cipherSuites) << 1)
   937  	for i, suite := range m.cipherSuites {
   938  		y[2+i*2] = uint8(suite >> 8)
   939  		y[3+i*2] = uint8(suite)
   940  	}
   941  	z = y[2+len(m.cipherSuites)*2:]
   942  	z[0] = uint8(len(m.compressionMethods))
   943  	copy(z[1:], m.compressionMethods)
   944  	z = z[1+len(m.compressionMethods):]
   945  
   946  	if numExtensions > 0 {
   947  		z[0] = byte(extensionsLength >> 8)
   948  		z[1] = byte(extensionsLength)
   949  		z = z[2:]
   950  		for _, extensionMarshaler := range extensionMarshalers {
   951  			extensionMarshaler()
   952  		}
   953  	}
   954  
   955  	m.raw = x
   956  
   957  	return x
   958  }
   959  
   960  func (m *clientHelloMsg) unmarshal(data []byte) alert {
   961  	if len(data) < 42 {
   962  		return alertDecodeError
   963  	}
   964  	m.raw = data
   965  	m.vers = uint16(data[4])<<8 | uint16(data[5])
   966  	m.random = data[6:38]
   967  	sessionIdLen := int(data[38])
   968  	if sessionIdLen > 32 || len(data) < 39+sessionIdLen {
   969  		return alertDecodeError
   970  	}
   971  	m.sessionId = data[39 : 39+sessionIdLen]
   972  	data = data[39+sessionIdLen:]
   973  	bindersOffset := 39 + sessionIdLen
   974  	if len(data) < 2 {
   975  		return alertDecodeError
   976  	}
   977  	// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
   978  	// they are uint16s, the number must be even.
   979  	cipherSuiteLen := int(data[0])<<8 | int(data[1])
   980  	if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
   981  		return alertDecodeError
   982  	}
   983  	numCipherSuites := cipherSuiteLen / 2
   984  	m.cipherSuites = make([]uint16, numCipherSuites)
   985  	for i := 0; i < numCipherSuites; i++ {
   986  		m.cipherSuites[i] = uint16(data[2+2*i])<<8 | uint16(data[3+2*i])
   987  		if m.cipherSuites[i] == scsvRenegotiation {
   988  			m.secureRenegotiationSupported = true
   989  		}
   990  	}
   991  	data = data[2+cipherSuiteLen:]
   992  	bindersOffset += 2 + cipherSuiteLen
   993  	if len(data) < 1 {
   994  		return alertDecodeError
   995  	}
   996  	compressionMethodsLen := int(data[0])
   997  	if len(data) < 1+compressionMethodsLen {
   998  		return alertDecodeError
   999  	}
  1000  	m.compressionMethods = data[1 : 1+compressionMethodsLen]
  1001  
  1002  	data = data[1+compressionMethodsLen:]
  1003  	bindersOffset += 1 + compressionMethodsLen
  1004  
  1005  	m.nextProtoNeg = false
  1006  	m.serverName = ""
  1007  	m.ocspStapling = false
  1008  	m.ticketSupported = false
  1009  	m.sessionTicket = nil
  1010  	m.supportedSignatureAlgorithms = nil
  1011  	m.alpnProtocols = nil
  1012  	m.scts = false
  1013  	m.keyShares = nil
  1014  	m.supportedVersions = nil
  1015  	m.psks = nil
  1016  	m.pskKeyExchangeModes = nil
  1017  	m.earlyData = false
  1018  	m.delegatedCredential = false
  1019  	m.extendedMSSupported = false
  1020  
  1021  	if len(data) == 0 {
  1022  		// ClientHello is optionally followed by extension data
  1023  		return alertSuccess
  1024  	}
  1025  	if len(data) < 2 {
  1026  		return alertDecodeError
  1027  	}
  1028  
  1029  	extensionsLength := int(data[0])<<8 | int(data[1])
  1030  	data = data[2:]
  1031  	bindersOffset += 2
  1032  	if extensionsLength != len(data) {
  1033  		return alertDecodeError
  1034  	}
  1035  
  1036  	for len(data) != 0 {
  1037  		if len(data) < 4 {
  1038  			return alertDecodeError
  1039  		}
  1040  		extension := uint16(data[0])<<8 | uint16(data[1])
  1041  		length := int(data[2])<<8 | int(data[3])
  1042  		data = data[4:]
  1043  		bindersOffset += 4
  1044  		if len(data) < length {
  1045  			return alertDecodeError
  1046  		}
  1047  
  1048  		switch extension {
  1049  		case extensionServerName:
  1050  			d := data[:length]
  1051  			if len(d) < 2 {
  1052  				return alertDecodeError
  1053  			}
  1054  			namesLen := int(d[0])<<8 | int(d[1])
  1055  			d = d[2:]
  1056  			if len(d) != namesLen {
  1057  				return alertDecodeError
  1058  			}
  1059  			for len(d) > 0 {
  1060  				if len(d) < 3 {
  1061  					return alertDecodeError
  1062  				}
  1063  				nameType := d[0]
  1064  				nameLen := int(d[1])<<8 | int(d[2])
  1065  				d = d[3:]
  1066  				if len(d) < nameLen {
  1067  					return alertDecodeError
  1068  				}
  1069  				if nameType == 0 {
  1070  					m.serverName = string(d[:nameLen])
  1071  					// An SNI value may not include a
  1072  					// trailing dot. See
  1073  					// https://tools.ietf.org/html/rfc6066#section-3.
  1074  					if strings.HasSuffix(m.serverName, ".") {
  1075  						// TODO use alertDecodeError?
  1076  						return alertUnexpectedMessage
  1077  					}
  1078  					break
  1079  				}
  1080  				d = d[nameLen:]
  1081  			}
  1082  		case extensionNextProtoNeg:
  1083  			if length > 0 {
  1084  				return alertDecodeError
  1085  			}
  1086  			m.nextProtoNeg = true
  1087  		case extensionStatusRequest:
  1088  			m.ocspStapling = length > 0 && data[0] == statusTypeOCSP
  1089  		case extensionSupportedCurves:
  1090  			// http://tools.ietf.org/html/rfc4492#section-5.5.1
  1091  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.4
  1092  			if length < 2 {
  1093  				return alertDecodeError
  1094  			}
  1095  			l := int(data[0])<<8 | int(data[1])
  1096  			if l%2 == 1 || length != l+2 {
  1097  				return alertDecodeError
  1098  			}
  1099  			numCurves := l / 2
  1100  			m.supportedCurves = make([]CurveID, numCurves)
  1101  			d := data[2:]
  1102  			for i := 0; i < numCurves; i++ {
  1103  				m.supportedCurves[i] = CurveID(d[0])<<8 | CurveID(d[1])
  1104  				d = d[2:]
  1105  			}
  1106  		case extensionSupportedPoints:
  1107  			// http://tools.ietf.org/html/rfc4492#section-5.5.2
  1108  			if length < 1 {
  1109  				return alertDecodeError
  1110  			}
  1111  			l := int(data[0])
  1112  			if length != l+1 {
  1113  				return alertDecodeError
  1114  			}
  1115  			m.supportedPoints = make([]uint8, l)
  1116  			copy(m.supportedPoints, data[1:])
  1117  		case extensionSessionTicket:
  1118  			// http://tools.ietf.org/html/rfc5077#section-3.2
  1119  			m.ticketSupported = true
  1120  			m.sessionTicket = data[:length]
  1121  		case extensionSignatureAlgorithms:
  1122  			// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
  1123  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3
  1124  			if length < 2 || length&1 != 0 {
  1125  				return alertDecodeError
  1126  			}
  1127  			l := int(data[0])<<8 | int(data[1])
  1128  			if l != length-2 {
  1129  				return alertDecodeError
  1130  			}
  1131  			n := l / 2
  1132  			d := data[2:]
  1133  			m.supportedSignatureAlgorithms = make([]SignatureScheme, n)
  1134  			for i := range m.supportedSignatureAlgorithms {
  1135  				m.supportedSignatureAlgorithms[i] = SignatureScheme(d[0])<<8 | SignatureScheme(d[1])
  1136  				d = d[2:]
  1137  			}
  1138  		case extensionRenegotiationInfo:
  1139  			if length == 0 {
  1140  				return alertDecodeError
  1141  			}
  1142  			d := data[:length]
  1143  			l := int(d[0])
  1144  			d = d[1:]
  1145  			if l != len(d) {
  1146  				return alertDecodeError
  1147  			}
  1148  
  1149  			m.secureRenegotiation = d
  1150  			m.secureRenegotiationSupported = true
  1151  		case extensionALPN:
  1152  			if length < 2 {
  1153  				return alertDecodeError
  1154  			}
  1155  			l := int(data[0])<<8 | int(data[1])
  1156  			if l != length-2 {
  1157  				return alertDecodeError
  1158  			}
  1159  			d := data[2:length]
  1160  			for len(d) != 0 {
  1161  				stringLen := int(d[0])
  1162  				d = d[1:]
  1163  				if stringLen == 0 || stringLen > len(d) {
  1164  					return alertDecodeError
  1165  				}
  1166  				m.alpnProtocols = append(m.alpnProtocols, string(d[:stringLen]))
  1167  				d = d[stringLen:]
  1168  			}
  1169  		case extensionSCT:
  1170  			m.scts = true
  1171  			if length != 0 {
  1172  				return alertDecodeError
  1173  			}
  1174  		case extensionKeyShare:
  1175  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.5
  1176  			if length < 2 {
  1177  				return alertDecodeError
  1178  			}
  1179  			l := int(data[0])<<8 | int(data[1])
  1180  			if l != length-2 {
  1181  				return alertDecodeError
  1182  			}
  1183  			d := data[2:length]
  1184  			for len(d) != 0 {
  1185  				if len(d) < 4 {
  1186  					return alertDecodeError
  1187  				}
  1188  				dataLen := int(d[2])<<8 | int(d[3])
  1189  				if dataLen == 0 || 4+dataLen > len(d) {
  1190  					return alertDecodeError
  1191  				}
  1192  				m.keyShares = append(m.keyShares, keyShare{
  1193  					group: CurveID(d[0])<<8 | CurveID(d[1]),
  1194  					data:  d[4 : 4+dataLen],
  1195  				})
  1196  				d = d[4+dataLen:]
  1197  			}
  1198  		case extensionSupportedVersions:
  1199  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.1
  1200  			if length < 1 {
  1201  				return alertDecodeError
  1202  			}
  1203  			l := int(data[0])
  1204  			if l%2 == 1 || length != l+1 {
  1205  				return alertDecodeError
  1206  			}
  1207  			n := l / 2
  1208  			d := data[1:]
  1209  			for i := 0; i < n; i++ {
  1210  				v := uint16(d[0])<<8 + uint16(d[1])
  1211  				m.supportedVersions = append(m.supportedVersions, v)
  1212  				d = d[2:]
  1213  			}
  1214  		case extensionPreSharedKey:
  1215  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.6
  1216  			if length < 2 {
  1217  				return alertDecodeError
  1218  			}
  1219  			// Ensure this extension is the last one in the Client Hello
  1220  			if len(data) != length {
  1221  				return alertIllegalParameter
  1222  			}
  1223  			li := int(data[0])<<8 | int(data[1])
  1224  			if 2+li+2 > length {
  1225  				return alertDecodeError
  1226  			}
  1227  			d := data[2 : 2+li]
  1228  			bindersOffset += 2 + li
  1229  			for len(d) > 0 {
  1230  				if len(d) < 6 {
  1231  					return alertDecodeError
  1232  				}
  1233  				l := int(d[0])<<8 | int(d[1])
  1234  				if len(d) < 2+l+4 {
  1235  					return alertDecodeError
  1236  				}
  1237  				m.psks = append(m.psks, psk{
  1238  					identity: d[2 : 2+l],
  1239  					obfTicketAge: uint32(d[l+2])<<24 | uint32(d[l+3])<<16 |
  1240  						uint32(d[l+4])<<8 | uint32(d[l+5]),
  1241  				})
  1242  				d = d[2+l+4:]
  1243  			}
  1244  			lb := int(data[li+2])<<8 | int(data[li+3])
  1245  			d = data[2+li+2:]
  1246  			if lb != len(d) || lb == 0 {
  1247  				return alertDecodeError
  1248  			}
  1249  			i := 0
  1250  			for len(d) > 0 {
  1251  				if i >= len(m.psks) {
  1252  					return alertIllegalParameter
  1253  				}
  1254  				if len(d) < 1 {
  1255  					return alertDecodeError
  1256  				}
  1257  				l := int(d[0])
  1258  				if l > len(d)-1 {
  1259  					return alertDecodeError
  1260  				}
  1261  				if i >= len(m.psks) {
  1262  					return alertIllegalParameter
  1263  				}
  1264  				m.psks[i].binder = d[1 : 1+l]
  1265  				d = d[1+l:]
  1266  				i++
  1267  			}
  1268  			if i != len(m.psks) {
  1269  				return alertIllegalParameter
  1270  			}
  1271  			m.rawTruncated = m.raw[:bindersOffset]
  1272  		case extensionPSKKeyExchangeModes:
  1273  			if length < 2 {
  1274  				return alertDecodeError
  1275  			}
  1276  			l := int(data[0])
  1277  			if length != l+1 {
  1278  				return alertDecodeError
  1279  			}
  1280  			m.pskKeyExchangeModes = data[1:length]
  1281  		case extensionEarlyData:
  1282  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8
  1283  			m.earlyData = true
  1284  		case extensionDelegatedCredential:
  1285  			// https://tools.ietf.org/html/draft-ietf-tls-subcerts-02
  1286  			m.delegatedCredential = true
  1287  		case extensionEMS:
  1288  			// RFC 7627
  1289  			m.extendedMSSupported = true
  1290  			if length != 0 {
  1291  				return alertDecodeError
  1292  			}
  1293  		}
  1294  		data = data[length:]
  1295  		bindersOffset += length
  1296  	}
  1297  
  1298  	return alertSuccess
  1299  }
  1300  
  1301  func (m *clientHelloMsg) getSignatureAlgorithmsCert() []SignatureScheme {
  1302  	return signAlgosCertList(m.supportedSignatureAlgorithms, m.supportedSignatureAlgorithmsCert)
  1303  }
  1304  
  1305  type serverHelloMsg struct {
  1306  	raw                          []byte
  1307  	vers                         uint16
  1308  	random                       []byte
  1309  	sessionId                    []byte
  1310  	cipherSuite                  uint16
  1311  	compressionMethod            uint8
  1312  	nextProtoNeg                 bool
  1313  	nextProtos                   []string
  1314  	ocspStapling                 bool
  1315  	scts                         [][]byte
  1316  	ticketSupported              bool
  1317  	secureRenegotiation          []byte
  1318  	secureRenegotiationSupported bool
  1319  	alpnProtocol                 string
  1320  
  1321  	// TLS 1.3
  1322  	keyShare    keyShare
  1323  	psk         bool
  1324  	pskIdentity uint16
  1325  
  1326  	// RFC7627
  1327  	extendedMSSupported bool
  1328  
  1329  	// [Psiphon]
  1330  	// https://github.com/golang/go/commit/02a5502ab8d862309aaec3c5ec293b57b913d01d
  1331  	supportedPoints []uint8
  1332  }
  1333  
  1334  func (m *serverHelloMsg) equal(i interface{}) bool {
  1335  	m1, ok := i.(*serverHelloMsg)
  1336  	if !ok {
  1337  		return false
  1338  	}
  1339  
  1340  	if len(m.scts) != len(m1.scts) {
  1341  		return false
  1342  	}
  1343  	for i, sct := range m.scts {
  1344  		if !bytes.Equal(sct, m1.scts[i]) {
  1345  			return false
  1346  		}
  1347  	}
  1348  
  1349  	return bytes.Equal(m.raw, m1.raw) &&
  1350  		m.vers == m1.vers &&
  1351  		bytes.Equal(m.random, m1.random) &&
  1352  		bytes.Equal(m.sessionId, m1.sessionId) &&
  1353  		m.cipherSuite == m1.cipherSuite &&
  1354  		m.compressionMethod == m1.compressionMethod &&
  1355  		m.nextProtoNeg == m1.nextProtoNeg &&
  1356  		eqStrings(m.nextProtos, m1.nextProtos) &&
  1357  		m.ocspStapling == m1.ocspStapling &&
  1358  		m.ticketSupported == m1.ticketSupported &&
  1359  		m.secureRenegotiationSupported == m1.secureRenegotiationSupported &&
  1360  		bytes.Equal(m.secureRenegotiation, m1.secureRenegotiation) &&
  1361  		m.alpnProtocol == m1.alpnProtocol &&
  1362  		m.keyShare.group == m1.keyShare.group &&
  1363  		bytes.Equal(m.keyShare.data, m1.keyShare.data) &&
  1364  		m.psk == m1.psk &&
  1365  		m.pskIdentity == m1.pskIdentity &&
  1366  		m.extendedMSSupported == m1.extendedMSSupported &&
  1367  
  1368  		// [Psiphon]
  1369  		bytes.Equal(m.supportedPoints, m1.supportedPoints)
  1370  }
  1371  
  1372  func (m *serverHelloMsg) marshal() []byte {
  1373  	if m.raw != nil {
  1374  		return m.raw
  1375  	}
  1376  
  1377  	length := 38 + len(m.sessionId)
  1378  	numExtensions := 0
  1379  	extensionsLength := 0
  1380  
  1381  	nextProtoLen := 0
  1382  	if m.nextProtoNeg {
  1383  		numExtensions++
  1384  		for _, v := range m.nextProtos {
  1385  			nextProtoLen += len(v)
  1386  		}
  1387  		nextProtoLen += len(m.nextProtos)
  1388  		extensionsLength += nextProtoLen
  1389  	}
  1390  	if m.ocspStapling {
  1391  		numExtensions++
  1392  	}
  1393  	if m.ticketSupported {
  1394  		numExtensions++
  1395  	}
  1396  	if m.secureRenegotiationSupported {
  1397  		extensionsLength += 1 + len(m.secureRenegotiation)
  1398  		numExtensions++
  1399  	}
  1400  	if m.extendedMSSupported {
  1401  		numExtensions++
  1402  	}
  1403  	if alpnLen := len(m.alpnProtocol); alpnLen > 0 {
  1404  		if alpnLen >= 256 {
  1405  			panic("invalid ALPN protocol")
  1406  		}
  1407  		extensionsLength += 2 + 1 + alpnLen
  1408  		numExtensions++
  1409  	}
  1410  	sctLen := 0
  1411  	if len(m.scts) > 0 {
  1412  		for _, sct := range m.scts {
  1413  			sctLen += len(sct) + 2
  1414  		}
  1415  		extensionsLength += 2 + sctLen
  1416  		numExtensions++
  1417  	}
  1418  	if m.keyShare.group != 0 {
  1419  		extensionsLength += 4 + len(m.keyShare.data)
  1420  		numExtensions++
  1421  	}
  1422  	if m.psk {
  1423  		extensionsLength += 2
  1424  		numExtensions++
  1425  	}
  1426  	// supported_versions extension
  1427  	if m.vers >= VersionTLS13 {
  1428  		extensionsLength += 2
  1429  		numExtensions++
  1430  	}
  1431  
  1432  	// [Psiphon]
  1433  	if len(m.supportedPoints) > 0 {
  1434  		extensionsLength += 1 + len(m.supportedPoints)
  1435  		numExtensions++
  1436  	}
  1437  
  1438  	if numExtensions > 0 {
  1439  		extensionsLength += 4 * numExtensions
  1440  		length += 2 + extensionsLength
  1441  	}
  1442  
  1443  	x := make([]byte, 4+length)
  1444  	x[0] = typeServerHello
  1445  	x[1] = uint8(length >> 16)
  1446  	x[2] = uint8(length >> 8)
  1447  	x[3] = uint8(length)
  1448  	if m.vers >= VersionTLS13 {
  1449  		x[4] = 3
  1450  		x[5] = 3
  1451  	} else {
  1452  		x[4] = uint8(m.vers >> 8)
  1453  		x[5] = uint8(m.vers)
  1454  	}
  1455  	copy(x[6:38], m.random)
  1456  	z := x[38:]
  1457  	x[38] = uint8(len(m.sessionId))
  1458  	copy(x[39:39+len(m.sessionId)], m.sessionId)
  1459  	z = x[39+len(m.sessionId):]
  1460  	z[0] = uint8(m.cipherSuite >> 8)
  1461  	z[1] = uint8(m.cipherSuite)
  1462  	z[2] = m.compressionMethod
  1463  	z = z[3:]
  1464  
  1465  	if numExtensions > 0 {
  1466  		z[0] = byte(extensionsLength >> 8)
  1467  		z[1] = byte(extensionsLength)
  1468  		z = z[2:]
  1469  	}
  1470  
  1471  	// [Psiphon]
  1472  	// Reorder extensions to match OpenSSL order:
  1473  	// https://github.com/openssl/openssl/blob/2a5385511051d33be8d2b20d7669d8b1862fe510/ssl/statem/extensions.c#L119
  1474  
  1475  	if m.secureRenegotiationSupported {
  1476  		z[0] = byte(extensionRenegotiationInfo >> 8)
  1477  		z[1] = byte(extensionRenegotiationInfo & 0xff)
  1478  		z[2] = 0
  1479  		z[3] = byte(len(m.secureRenegotiation) + 1)
  1480  		z[4] = byte(len(m.secureRenegotiation))
  1481  		z = z[5:]
  1482  		copy(z, m.secureRenegotiation)
  1483  		z = z[len(m.secureRenegotiation):]
  1484  	}
  1485  
  1486  	// [Psiphon]
  1487  	// https://github.com/golang/go/commit/02a5502ab8d862309aaec3c5ec293b57b913d01d
  1488  	if len(m.supportedPoints) > 0 {
  1489  		// http://tools.ietf.org/html/rfc4492#section-5.5.2
  1490  		z[0] = byte(extensionSupportedPoints >> 8)
  1491  		z[1] = byte(extensionSupportedPoints)
  1492  		l := 1 + len(m.supportedPoints)
  1493  		z[2] = byte(l >> 8)
  1494  		z[3] = byte(l)
  1495  		l--
  1496  		z[4] = byte(l)
  1497  		z = z[5:]
  1498  		for _, pointFormat := range m.supportedPoints {
  1499  			z[0] = pointFormat
  1500  			z = z[1:]
  1501  		}
  1502  	}
  1503  	if m.ticketSupported {
  1504  		z[0] = byte(extensionSessionTicket >> 8)
  1505  		z[1] = byte(extensionSessionTicket)
  1506  		z = z[4:]
  1507  	}
  1508  	if m.ocspStapling {
  1509  		z[0] = byte(extensionStatusRequest >> 8)
  1510  		z[1] = byte(extensionStatusRequest)
  1511  		z = z[4:]
  1512  	}
  1513  	if m.nextProtoNeg {
  1514  		z[0] = byte(extensionNextProtoNeg >> 8)
  1515  		z[1] = byte(extensionNextProtoNeg & 0xff)
  1516  		z[2] = byte(nextProtoLen >> 8)
  1517  		z[3] = byte(nextProtoLen)
  1518  		z = z[4:]
  1519  
  1520  		for _, v := range m.nextProtos {
  1521  			l := len(v)
  1522  			if l > 255 {
  1523  				l = 255
  1524  			}
  1525  			z[0] = byte(l)
  1526  			copy(z[1:], []byte(v[0:l]))
  1527  			z = z[1+l:]
  1528  		}
  1529  	}
  1530  	if alpnLen := len(m.alpnProtocol); alpnLen > 0 {
  1531  		z[0] = byte(extensionALPN >> 8)
  1532  		z[1] = byte(extensionALPN & 0xff)
  1533  		l := 2 + 1 + alpnLen
  1534  		z[2] = byte(l >> 8)
  1535  		z[3] = byte(l)
  1536  		l -= 2
  1537  		z[4] = byte(l >> 8)
  1538  		z[5] = byte(l)
  1539  		l -= 1
  1540  		z[6] = byte(l)
  1541  		copy(z[7:], []byte(m.alpnProtocol))
  1542  		z = z[7+alpnLen:]
  1543  	}
  1544  	if sctLen > 0 {
  1545  		z[0] = byte(extensionSCT >> 8)
  1546  		z[1] = byte(extensionSCT)
  1547  		l := sctLen + 2
  1548  		z[2] = byte(l >> 8)
  1549  		z[3] = byte(l)
  1550  		z[4] = byte(sctLen >> 8)
  1551  		z[5] = byte(sctLen)
  1552  
  1553  		z = z[6:]
  1554  		for _, sct := range m.scts {
  1555  			z[0] = byte(len(sct) >> 8)
  1556  			z[1] = byte(len(sct))
  1557  			copy(z[2:], sct)
  1558  			z = z[len(sct)+2:]
  1559  		}
  1560  	}
  1561  	if m.extendedMSSupported {
  1562  		binary.BigEndian.PutUint16(z, extensionEMS)
  1563  		z = z[4:]
  1564  	}
  1565  	if m.vers >= VersionTLS13 {
  1566  		z[0] = byte(extensionSupportedVersions >> 8)
  1567  		z[1] = byte(extensionSupportedVersions)
  1568  		z[3] = 2
  1569  		z[4] = uint8(m.vers >> 8)
  1570  		z[5] = uint8(m.vers)
  1571  		z = z[6:]
  1572  	}
  1573  	if m.keyShare.group != 0 {
  1574  		z[0] = uint8(extensionKeyShare >> 8)
  1575  		z[1] = uint8(extensionKeyShare)
  1576  		l := 4 + len(m.keyShare.data)
  1577  		z[2] = uint8(l >> 8)
  1578  		z[3] = uint8(l)
  1579  		z[4] = uint8(m.keyShare.group >> 8)
  1580  		z[5] = uint8(m.keyShare.group)
  1581  		l -= 4
  1582  		z[6] = uint8(l >> 8)
  1583  		z[7] = uint8(l)
  1584  		copy(z[8:], m.keyShare.data)
  1585  		z = z[8+l:]
  1586  	}
  1587  
  1588  	if m.psk {
  1589  		z[0] = byte(extensionPreSharedKey >> 8)
  1590  		z[1] = byte(extensionPreSharedKey)
  1591  		z[3] = 2
  1592  		z[4] = byte(m.pskIdentity >> 8)
  1593  		z[5] = byte(m.pskIdentity)
  1594  		z = z[6:]
  1595  	}
  1596  
  1597  	m.raw = x
  1598  
  1599  	return x
  1600  }
  1601  
  1602  func (m *serverHelloMsg) unmarshal(data []byte) alert {
  1603  	if len(data) < 42 {
  1604  		return alertDecodeError
  1605  	}
  1606  	m.raw = data
  1607  	m.vers = uint16(data[4])<<8 | uint16(data[5])
  1608  	m.random = data[6:38]
  1609  	sessionIdLen := int(data[38])
  1610  	if sessionIdLen > 32 || len(data) < 39+sessionIdLen {
  1611  		return alertDecodeError
  1612  	}
  1613  	m.sessionId = data[39 : 39+sessionIdLen]
  1614  	data = data[39+sessionIdLen:]
  1615  	if len(data) < 3 {
  1616  		return alertDecodeError
  1617  	}
  1618  	m.cipherSuite = uint16(data[0])<<8 | uint16(data[1])
  1619  	m.compressionMethod = data[2]
  1620  	data = data[3:]
  1621  
  1622  	m.nextProtoNeg = false
  1623  	m.nextProtos = nil
  1624  	m.ocspStapling = false
  1625  	m.scts = nil
  1626  	m.ticketSupported = false
  1627  	m.alpnProtocol = ""
  1628  	m.keyShare.group = 0
  1629  	m.keyShare.data = nil
  1630  	m.psk = false
  1631  	m.pskIdentity = 0
  1632  	m.extendedMSSupported = false
  1633  
  1634  	// [Psiphon]
  1635  	m.supportedPoints = nil
  1636  
  1637  	if len(data) == 0 {
  1638  		// ServerHello is optionally followed by extension data
  1639  		return alertSuccess
  1640  	}
  1641  	if len(data) < 2 {
  1642  		return alertDecodeError
  1643  	}
  1644  
  1645  	extensionsLength := int(data[0])<<8 | int(data[1])
  1646  	data = data[2:]
  1647  	if len(data) != extensionsLength {
  1648  		return alertDecodeError
  1649  	}
  1650  
  1651  	svData := findExtension(data, extensionSupportedVersions)
  1652  	if svData != nil {
  1653  		if len(svData) != 2 {
  1654  			return alertDecodeError
  1655  		}
  1656  		if m.vers != VersionTLS12 {
  1657  			return alertDecodeError
  1658  		}
  1659  		rcvVer := binary.BigEndian.Uint16(svData[0:])
  1660  		if rcvVer < VersionTLS13 {
  1661  			return alertIllegalParameter
  1662  		}
  1663  		m.vers = rcvVer
  1664  	}
  1665  
  1666  	for len(data) != 0 {
  1667  		if len(data) < 4 {
  1668  			return alertDecodeError
  1669  		}
  1670  		extension := uint16(data[0])<<8 | uint16(data[1])
  1671  		length := int(data[2])<<8 | int(data[3])
  1672  		data = data[4:]
  1673  		if len(data) < length {
  1674  			return alertDecodeError
  1675  		}
  1676  
  1677  		switch extension {
  1678  		case extensionNextProtoNeg:
  1679  			m.nextProtoNeg = true
  1680  			d := data[:length]
  1681  			for len(d) > 0 {
  1682  				l := int(d[0])
  1683  				d = d[1:]
  1684  				if l == 0 || l > len(d) {
  1685  					return alertDecodeError
  1686  				}
  1687  				m.nextProtos = append(m.nextProtos, string(d[:l]))
  1688  				d = d[l:]
  1689  			}
  1690  		case extensionStatusRequest:
  1691  			if length > 0 {
  1692  				return alertDecodeError
  1693  			}
  1694  			m.ocspStapling = true
  1695  		case extensionSessionTicket:
  1696  			if length > 0 {
  1697  				return alertDecodeError
  1698  			}
  1699  			m.ticketSupported = true
  1700  		case extensionRenegotiationInfo:
  1701  			if length == 0 {
  1702  				return alertDecodeError
  1703  			}
  1704  			d := data[:length]
  1705  			l := int(d[0])
  1706  			d = d[1:]
  1707  			if l != len(d) {
  1708  				return alertDecodeError
  1709  			}
  1710  
  1711  			m.secureRenegotiation = d
  1712  			m.secureRenegotiationSupported = true
  1713  		case extensionALPN:
  1714  			d := data[:length]
  1715  			if len(d) < 3 {
  1716  				return alertDecodeError
  1717  			}
  1718  			l := int(d[0])<<8 | int(d[1])
  1719  			if l != len(d)-2 {
  1720  				return alertDecodeError
  1721  			}
  1722  			d = d[2:]
  1723  			l = int(d[0])
  1724  			if l != len(d)-1 {
  1725  				return alertDecodeError
  1726  			}
  1727  			d = d[1:]
  1728  			if len(d) == 0 {
  1729  				// ALPN protocols must not be empty.
  1730  				return alertDecodeError
  1731  			}
  1732  			m.alpnProtocol = string(d)
  1733  		case extensionSCT:
  1734  			d := data[:length]
  1735  
  1736  			if len(d) < 2 {
  1737  				return alertDecodeError
  1738  			}
  1739  			l := int(d[0])<<8 | int(d[1])
  1740  			d = d[2:]
  1741  			if len(d) != l || l == 0 {
  1742  				return alertDecodeError
  1743  			}
  1744  
  1745  			m.scts = make([][]byte, 0, 3)
  1746  			for len(d) != 0 {
  1747  				if len(d) < 2 {
  1748  					return alertDecodeError
  1749  				}
  1750  				sctLen := int(d[0])<<8 | int(d[1])
  1751  				d = d[2:]
  1752  				if sctLen == 0 || len(d) < sctLen {
  1753  					return alertDecodeError
  1754  				}
  1755  				m.scts = append(m.scts, d[:sctLen])
  1756  				d = d[sctLen:]
  1757  			}
  1758  		case extensionKeyShare:
  1759  			d := data[:length]
  1760  
  1761  			if len(d) < 4 {
  1762  				return alertDecodeError
  1763  			}
  1764  			m.keyShare.group = CurveID(d[0])<<8 | CurveID(d[1])
  1765  			l := int(d[2])<<8 | int(d[3])
  1766  			d = d[4:]
  1767  			if len(d) != l {
  1768  				return alertDecodeError
  1769  			}
  1770  			m.keyShare.data = d[:l]
  1771  		case extensionPreSharedKey:
  1772  			if length != 2 {
  1773  				return alertDecodeError
  1774  			}
  1775  			m.psk = true
  1776  			m.pskIdentity = uint16(data[0])<<8 | uint16(data[1])
  1777  		case extensionEMS:
  1778  			m.extendedMSSupported = true
  1779  
  1780  		// [Psiphon]
  1781  		case extensionSupportedPoints:
  1782  			// http://tools.ietf.org/html/rfc4492#section-5.5.2
  1783  			if length < 1 {
  1784  				return alertDecodeError
  1785  			}
  1786  			l := int(data[0])
  1787  			if length != l+1 {
  1788  				return alertDecodeError
  1789  			}
  1790  			m.supportedPoints = make([]uint8, l)
  1791  			copy(m.supportedPoints, data[1:])
  1792  		}
  1793  		data = data[length:]
  1794  	}
  1795  
  1796  	return alertSuccess
  1797  }
  1798  
  1799  type encryptedExtensionsMsg struct {
  1800  	raw          []byte
  1801  	alpnProtocol string
  1802  	earlyData    bool
  1803  }
  1804  
  1805  func (m *encryptedExtensionsMsg) equal(i interface{}) bool {
  1806  	m1, ok := i.(*encryptedExtensionsMsg)
  1807  	if !ok {
  1808  		return false
  1809  	}
  1810  
  1811  	return bytes.Equal(m.raw, m1.raw) &&
  1812  		m.alpnProtocol == m1.alpnProtocol &&
  1813  		m.earlyData == m1.earlyData
  1814  }
  1815  
  1816  func (m *encryptedExtensionsMsg) marshal() []byte {
  1817  	if m.raw != nil {
  1818  		return m.raw
  1819  	}
  1820  
  1821  	length := 2
  1822  
  1823  	if m.earlyData {
  1824  		length += 4
  1825  	}
  1826  	alpnLen := len(m.alpnProtocol)
  1827  	if alpnLen > 0 {
  1828  		if alpnLen >= 256 {
  1829  			panic("invalid ALPN protocol")
  1830  		}
  1831  		length += 2 + 2 + 2 + 1 + alpnLen
  1832  	}
  1833  
  1834  	x := make([]byte, 4+length)
  1835  	x[0] = typeEncryptedExtensions
  1836  	x[1] = uint8(length >> 16)
  1837  	x[2] = uint8(length >> 8)
  1838  	x[3] = uint8(length)
  1839  	length -= 2
  1840  	x[4] = uint8(length >> 8)
  1841  	x[5] = uint8(length)
  1842  
  1843  	z := x[6:]
  1844  	if alpnLen > 0 {
  1845  		z[0] = byte(extensionALPN >> 8)
  1846  		z[1] = byte(extensionALPN)
  1847  		l := 2 + 1 + alpnLen
  1848  		z[2] = byte(l >> 8)
  1849  		z[3] = byte(l)
  1850  		l -= 2
  1851  		z[4] = byte(l >> 8)
  1852  		z[5] = byte(l)
  1853  		l -= 1
  1854  		z[6] = byte(l)
  1855  		copy(z[7:], []byte(m.alpnProtocol))
  1856  		z = z[7+alpnLen:]
  1857  	}
  1858  
  1859  	if m.earlyData {
  1860  		z[0] = byte(extensionEarlyData >> 8)
  1861  		z[1] = byte(extensionEarlyData)
  1862  		z = z[4:]
  1863  	}
  1864  
  1865  	m.raw = x
  1866  	return x
  1867  }
  1868  
  1869  func (m *encryptedExtensionsMsg) unmarshal(data []byte) alert {
  1870  	if len(data) < 6 {
  1871  		return alertDecodeError
  1872  	}
  1873  	m.raw = data
  1874  
  1875  	m.alpnProtocol = ""
  1876  	m.earlyData = false
  1877  
  1878  	extensionsLength := int(data[4])<<8 | int(data[5])
  1879  	data = data[6:]
  1880  	if len(data) != extensionsLength {
  1881  		return alertDecodeError
  1882  	}
  1883  
  1884  	for len(data) != 0 {
  1885  		if len(data) < 4 {
  1886  			return alertDecodeError
  1887  		}
  1888  		extension := uint16(data[0])<<8 | uint16(data[1])
  1889  		length := int(data[2])<<8 | int(data[3])
  1890  		data = data[4:]
  1891  		if len(data) < length {
  1892  			return alertDecodeError
  1893  		}
  1894  
  1895  		switch extension {
  1896  		case extensionALPN:
  1897  			d := data[:length]
  1898  			if len(d) < 3 {
  1899  				return alertDecodeError
  1900  			}
  1901  			l := int(d[0])<<8 | int(d[1])
  1902  			if l != len(d)-2 {
  1903  				return alertDecodeError
  1904  			}
  1905  			d = d[2:]
  1906  			l = int(d[0])
  1907  			if l != len(d)-1 {
  1908  				return alertDecodeError
  1909  			}
  1910  			d = d[1:]
  1911  			if len(d) == 0 {
  1912  				// ALPN protocols must not be empty.
  1913  				return alertDecodeError
  1914  			}
  1915  			m.alpnProtocol = string(d)
  1916  		case extensionEarlyData:
  1917  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8
  1918  			m.earlyData = true
  1919  		}
  1920  
  1921  		data = data[length:]
  1922  	}
  1923  
  1924  	return alertSuccess
  1925  }
  1926  
  1927  type certificateMsg struct {
  1928  	raw          []byte
  1929  	certificates [][]byte
  1930  }
  1931  
  1932  func (m *certificateMsg) equal(i interface{}) bool {
  1933  	m1, ok := i.(*certificateMsg)
  1934  	if !ok {
  1935  		return false
  1936  	}
  1937  
  1938  	return bytes.Equal(m.raw, m1.raw) &&
  1939  		eqByteSlices(m.certificates, m1.certificates)
  1940  }
  1941  
  1942  func (m *certificateMsg) marshal() (x []byte) {
  1943  	if m.raw != nil {
  1944  		return m.raw
  1945  	}
  1946  
  1947  	var i int
  1948  	for _, slice := range m.certificates {
  1949  		i += len(slice)
  1950  	}
  1951  
  1952  	length := 3 + 3*len(m.certificates) + i
  1953  	x = make([]byte, 4+length)
  1954  	x[0] = typeCertificate
  1955  	x[1] = uint8(length >> 16)
  1956  	x[2] = uint8(length >> 8)
  1957  	x[3] = uint8(length)
  1958  
  1959  	certificateOctets := length - 3
  1960  	x[4] = uint8(certificateOctets >> 16)
  1961  	x[5] = uint8(certificateOctets >> 8)
  1962  	x[6] = uint8(certificateOctets)
  1963  
  1964  	y := x[7:]
  1965  	for _, slice := range m.certificates {
  1966  		y[0] = uint8(len(slice) >> 16)
  1967  		y[1] = uint8(len(slice) >> 8)
  1968  		y[2] = uint8(len(slice))
  1969  		copy(y[3:], slice)
  1970  		y = y[3+len(slice):]
  1971  	}
  1972  
  1973  	m.raw = x
  1974  	return
  1975  }
  1976  
  1977  func (m *certificateMsg) unmarshal(data []byte) alert {
  1978  	if len(data) < 7 {
  1979  		return alertDecodeError
  1980  	}
  1981  
  1982  	m.raw = data
  1983  	certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6])
  1984  	if uint32(len(data)) != certsLen+7 {
  1985  		return alertDecodeError
  1986  	}
  1987  
  1988  	numCerts := 0
  1989  	d := data[7:]
  1990  	for certsLen > 0 {
  1991  		if len(d) < 4 {
  1992  			return alertDecodeError
  1993  		}
  1994  		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
  1995  		if uint32(len(d)) < 3+certLen {
  1996  			return alertDecodeError
  1997  		}
  1998  		d = d[3+certLen:]
  1999  		certsLen -= 3 + certLen
  2000  		numCerts++
  2001  	}
  2002  
  2003  	m.certificates = make([][]byte, numCerts)
  2004  	d = data[7:]
  2005  	for i := 0; i < numCerts; i++ {
  2006  		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
  2007  		m.certificates[i] = d[3 : 3+certLen]
  2008  		d = d[3+certLen:]
  2009  	}
  2010  
  2011  	return alertSuccess
  2012  }
  2013  
  2014  type certificateEntry struct {
  2015  	data                []byte
  2016  	ocspStaple          []byte
  2017  	sctList             [][]byte
  2018  	delegatedCredential []byte
  2019  }
  2020  
  2021  type certificateMsg13 struct {
  2022  	raw            []byte
  2023  	requestContext []byte
  2024  	certificates   []certificateEntry
  2025  }
  2026  
  2027  func (m *certificateMsg13) equal(i interface{}) bool {
  2028  	m1, ok := i.(*certificateMsg13)
  2029  	if !ok {
  2030  		return false
  2031  	}
  2032  
  2033  	if len(m.certificates) != len(m1.certificates) {
  2034  		return false
  2035  	}
  2036  	for i, _ := range m.certificates {
  2037  		ok := bytes.Equal(m.certificates[i].data, m1.certificates[i].data)
  2038  		ok = ok && bytes.Equal(m.certificates[i].ocspStaple, m1.certificates[i].ocspStaple)
  2039  		ok = ok && eqByteSlices(m.certificates[i].sctList, m1.certificates[i].sctList)
  2040  		ok = ok && bytes.Equal(m.certificates[i].delegatedCredential, m1.certificates[i].delegatedCredential)
  2041  		if !ok {
  2042  			return false
  2043  		}
  2044  	}
  2045  
  2046  	return bytes.Equal(m.raw, m1.raw) &&
  2047  		bytes.Equal(m.requestContext, m1.requestContext)
  2048  }
  2049  
  2050  func (m *certificateMsg13) marshal() (x []byte) {
  2051  	if m.raw != nil {
  2052  		return m.raw
  2053  	}
  2054  
  2055  	var i int
  2056  	for _, cert := range m.certificates {
  2057  		i += len(cert.data)
  2058  		if len(cert.ocspStaple) != 0 {
  2059  			i += 8 + len(cert.ocspStaple)
  2060  		}
  2061  		if len(cert.sctList) != 0 {
  2062  			i += 6
  2063  			for _, sct := range cert.sctList {
  2064  				i += 2 + len(sct)
  2065  			}
  2066  		}
  2067  		if len(cert.delegatedCredential) != 0 {
  2068  			i += 4 + len(cert.delegatedCredential)
  2069  		}
  2070  	}
  2071  
  2072  	length := 3 + 3*len(m.certificates) + i
  2073  	length += 2 * len(m.certificates) // extensions
  2074  	length += 1 + len(m.requestContext)
  2075  	x = make([]byte, 4+length)
  2076  	x[0] = typeCertificate
  2077  	x[1] = uint8(length >> 16)
  2078  	x[2] = uint8(length >> 8)
  2079  	x[3] = uint8(length)
  2080  
  2081  	z := x[4:]
  2082  
  2083  	z[0] = byte(len(m.requestContext))
  2084  	copy(z[1:], m.requestContext)
  2085  	z = z[1+len(m.requestContext):]
  2086  
  2087  	certificateOctets := len(z) - 3
  2088  	z[0] = uint8(certificateOctets >> 16)
  2089  	z[1] = uint8(certificateOctets >> 8)
  2090  	z[2] = uint8(certificateOctets)
  2091  
  2092  	z = z[3:]
  2093  	for _, cert := range m.certificates {
  2094  		z[0] = uint8(len(cert.data) >> 16)
  2095  		z[1] = uint8(len(cert.data) >> 8)
  2096  		z[2] = uint8(len(cert.data))
  2097  		copy(z[3:], cert.data)
  2098  		z = z[3+len(cert.data):]
  2099  
  2100  		extLenPos := z[:2]
  2101  		z = z[2:]
  2102  
  2103  		extensionLen := 0
  2104  		if len(cert.ocspStaple) != 0 {
  2105  			stapleLen := 4 + len(cert.ocspStaple)
  2106  			z[0] = uint8(extensionStatusRequest >> 8)
  2107  			z[1] = uint8(extensionStatusRequest)
  2108  			z[2] = uint8(stapleLen >> 8)
  2109  			z[3] = uint8(stapleLen)
  2110  
  2111  			stapleLen -= 4
  2112  			z[4] = statusTypeOCSP
  2113  			z[5] = uint8(stapleLen >> 16)
  2114  			z[6] = uint8(stapleLen >> 8)
  2115  			z[7] = uint8(stapleLen)
  2116  			copy(z[8:], cert.ocspStaple)
  2117  			z = z[8+stapleLen:]
  2118  
  2119  			extensionLen += 8 + stapleLen
  2120  		}
  2121  		if len(cert.sctList) != 0 {
  2122  			z[0] = uint8(extensionSCT >> 8)
  2123  			z[1] = uint8(extensionSCT)
  2124  			sctLenPos := z[2:6]
  2125  			z = z[6:]
  2126  			extensionLen += 6
  2127  
  2128  			sctLen := 2
  2129  			for _, sct := range cert.sctList {
  2130  				z[0] = uint8(len(sct) >> 8)
  2131  				z[1] = uint8(len(sct))
  2132  				copy(z[2:], sct)
  2133  				z = z[2+len(sct):]
  2134  
  2135  				extensionLen += 2 + len(sct)
  2136  				sctLen += 2 + len(sct)
  2137  			}
  2138  			sctLenPos[0] = uint8(sctLen >> 8)
  2139  			sctLenPos[1] = uint8(sctLen)
  2140  			sctLen -= 2
  2141  			sctLenPos[2] = uint8(sctLen >> 8)
  2142  			sctLenPos[3] = uint8(sctLen)
  2143  		}
  2144  		if len(cert.delegatedCredential) != 0 {
  2145  			binary.BigEndian.PutUint16(z, extensionDelegatedCredential)
  2146  			binary.BigEndian.PutUint16(z[2:], uint16(len(cert.delegatedCredential)))
  2147  			z = z[4:]
  2148  			copy(z, cert.delegatedCredential)
  2149  			z = z[len(cert.delegatedCredential):]
  2150  			extensionLen += 4 + len(cert.delegatedCredential)
  2151  		}
  2152  
  2153  		extLenPos[0] = uint8(extensionLen >> 8)
  2154  		extLenPos[1] = uint8(extensionLen)
  2155  	}
  2156  
  2157  	m.raw = x
  2158  	return
  2159  }
  2160  
  2161  func (m *certificateMsg13) unmarshal(data []byte) alert {
  2162  	if len(data) < 5 {
  2163  		return alertDecodeError
  2164  	}
  2165  
  2166  	m.raw = data
  2167  
  2168  	ctxLen := data[4]
  2169  	if len(data) < int(ctxLen)+5+3 {
  2170  		return alertDecodeError
  2171  	}
  2172  	m.requestContext = data[5 : 5+ctxLen]
  2173  
  2174  	d := data[5+ctxLen:]
  2175  	certsLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
  2176  	if uint32(len(d)) != certsLen+3 {
  2177  		return alertDecodeError
  2178  	}
  2179  
  2180  	numCerts := 0
  2181  	d = d[3:]
  2182  	for certsLen > 0 {
  2183  		if len(d) < 4 {
  2184  			return alertDecodeError
  2185  		}
  2186  		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
  2187  		if uint32(len(d)) < 3+certLen {
  2188  			return alertDecodeError
  2189  		}
  2190  		d = d[3+certLen:]
  2191  
  2192  		if len(d) < 2 {
  2193  			return alertDecodeError
  2194  		}
  2195  		extLen := uint16(d[0])<<8 | uint16(d[1])
  2196  		if uint16(len(d)) < 2+extLen {
  2197  			return alertDecodeError
  2198  		}
  2199  		d = d[2+extLen:]
  2200  
  2201  		certsLen -= 3 + certLen + 2 + uint32(extLen)
  2202  		numCerts++
  2203  	}
  2204  
  2205  	m.certificates = make([]certificateEntry, numCerts)
  2206  	d = data[8+ctxLen:]
  2207  	for i := 0; i < numCerts; i++ {
  2208  		certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2])
  2209  		m.certificates[i].data = d[3 : 3+certLen]
  2210  		d = d[3+certLen:]
  2211  
  2212  		extLen := uint16(d[0])<<8 | uint16(d[1])
  2213  		d = d[2:]
  2214  		for extLen > 0 {
  2215  			if extLen < 4 {
  2216  				return alertDecodeError
  2217  			}
  2218  			typ := uint16(d[0])<<8 | uint16(d[1])
  2219  			bodyLen := uint16(d[2])<<8 | uint16(d[3])
  2220  			if extLen < 4+bodyLen {
  2221  				return alertDecodeError
  2222  			}
  2223  			body := d[4 : 4+bodyLen]
  2224  			d = d[4+bodyLen:]
  2225  			extLen -= 4 + bodyLen
  2226  
  2227  			switch typ {
  2228  			case extensionStatusRequest:
  2229  				if len(body) < 4 || body[0] != 0x01 {
  2230  					return alertDecodeError
  2231  				}
  2232  				ocspLen := int(body[1])<<16 | int(body[2])<<8 | int(body[3])
  2233  				if len(body) != 4+ocspLen {
  2234  					return alertDecodeError
  2235  				}
  2236  				m.certificates[i].ocspStaple = body[4:]
  2237  
  2238  			case extensionSCT:
  2239  				if len(body) < 2 {
  2240  					return alertDecodeError
  2241  				}
  2242  				listLen := int(body[0])<<8 | int(body[1])
  2243  				body = body[2:]
  2244  				if len(body) != listLen {
  2245  					return alertDecodeError
  2246  				}
  2247  				for len(body) > 0 {
  2248  					if len(body) < 2 {
  2249  						return alertDecodeError
  2250  					}
  2251  					sctLen := int(body[0])<<8 | int(body[1])
  2252  					if len(body) < 2+sctLen {
  2253  						return alertDecodeError
  2254  					}
  2255  					m.certificates[i].sctList = append(m.certificates[i].sctList, body[2:2+sctLen])
  2256  					body = body[2+sctLen:]
  2257  				}
  2258  			case extensionDelegatedCredential:
  2259  				m.certificates[i].delegatedCredential = body
  2260  			}
  2261  		}
  2262  	}
  2263  
  2264  	return alertSuccess
  2265  }
  2266  
  2267  type serverKeyExchangeMsg struct {
  2268  	raw []byte
  2269  	key []byte
  2270  }
  2271  
  2272  func (m *serverKeyExchangeMsg) equal(i interface{}) bool {
  2273  	m1, ok := i.(*serverKeyExchangeMsg)
  2274  	if !ok {
  2275  		return false
  2276  	}
  2277  
  2278  	return bytes.Equal(m.raw, m1.raw) &&
  2279  		bytes.Equal(m.key, m1.key)
  2280  }
  2281  
  2282  func (m *serverKeyExchangeMsg) marshal() []byte {
  2283  	if m.raw != nil {
  2284  		return m.raw
  2285  	}
  2286  	length := len(m.key)
  2287  	x := make([]byte, length+4)
  2288  	x[0] = typeServerKeyExchange
  2289  	x[1] = uint8(length >> 16)
  2290  	x[2] = uint8(length >> 8)
  2291  	x[3] = uint8(length)
  2292  	copy(x[4:], m.key)
  2293  
  2294  	m.raw = x
  2295  	return x
  2296  }
  2297  
  2298  func (m *serverKeyExchangeMsg) unmarshal(data []byte) alert {
  2299  	m.raw = data
  2300  	if len(data) < 4 {
  2301  		return alertDecodeError
  2302  	}
  2303  	m.key = data[4:]
  2304  	return alertSuccess
  2305  }
  2306  
  2307  type certificateStatusMsg struct {
  2308  	raw        []byte
  2309  	statusType uint8
  2310  	response   []byte
  2311  }
  2312  
  2313  func (m *certificateStatusMsg) equal(i interface{}) bool {
  2314  	m1, ok := i.(*certificateStatusMsg)
  2315  	if !ok {
  2316  		return false
  2317  	}
  2318  
  2319  	return bytes.Equal(m.raw, m1.raw) &&
  2320  		m.statusType == m1.statusType &&
  2321  		bytes.Equal(m.response, m1.response)
  2322  }
  2323  
  2324  func (m *certificateStatusMsg) marshal() []byte {
  2325  	if m.raw != nil {
  2326  		return m.raw
  2327  	}
  2328  
  2329  	var x []byte
  2330  	if m.statusType == statusTypeOCSP {
  2331  		x = make([]byte, 4+4+len(m.response))
  2332  		x[0] = typeCertificateStatus
  2333  		l := len(m.response) + 4
  2334  		x[1] = byte(l >> 16)
  2335  		x[2] = byte(l >> 8)
  2336  		x[3] = byte(l)
  2337  		x[4] = statusTypeOCSP
  2338  
  2339  		l -= 4
  2340  		x[5] = byte(l >> 16)
  2341  		x[6] = byte(l >> 8)
  2342  		x[7] = byte(l)
  2343  		copy(x[8:], m.response)
  2344  	} else {
  2345  		x = []byte{typeCertificateStatus, 0, 0, 1, m.statusType}
  2346  	}
  2347  
  2348  	m.raw = x
  2349  	return x
  2350  }
  2351  
  2352  func (m *certificateStatusMsg) unmarshal(data []byte) alert {
  2353  	m.raw = data
  2354  	if len(data) < 5 {
  2355  		return alertDecodeError
  2356  	}
  2357  	m.statusType = data[4]
  2358  
  2359  	m.response = nil
  2360  	if m.statusType == statusTypeOCSP {
  2361  		if len(data) < 8 {
  2362  			return alertDecodeError
  2363  		}
  2364  		respLen := uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])
  2365  		if uint32(len(data)) != 4+4+respLen {
  2366  			return alertDecodeError
  2367  		}
  2368  		m.response = data[8:]
  2369  	}
  2370  	return alertSuccess
  2371  }
  2372  
  2373  type serverHelloDoneMsg struct{}
  2374  
  2375  func (m *serverHelloDoneMsg) equal(i interface{}) bool {
  2376  	_, ok := i.(*serverHelloDoneMsg)
  2377  	return ok
  2378  }
  2379  
  2380  func (m *serverHelloDoneMsg) marshal() []byte {
  2381  	x := make([]byte, 4)
  2382  	x[0] = typeServerHelloDone
  2383  	return x
  2384  }
  2385  
  2386  func (m *serverHelloDoneMsg) unmarshal(data []byte) alert {
  2387  	if len(data) != 4 {
  2388  		return alertDecodeError
  2389  	}
  2390  	return alertSuccess
  2391  }
  2392  
  2393  type clientKeyExchangeMsg struct {
  2394  	raw        []byte
  2395  	ciphertext []byte
  2396  }
  2397  
  2398  func (m *clientKeyExchangeMsg) equal(i interface{}) bool {
  2399  	m1, ok := i.(*clientKeyExchangeMsg)
  2400  	if !ok {
  2401  		return false
  2402  	}
  2403  
  2404  	return bytes.Equal(m.raw, m1.raw) &&
  2405  		bytes.Equal(m.ciphertext, m1.ciphertext)
  2406  }
  2407  
  2408  func (m *clientKeyExchangeMsg) marshal() []byte {
  2409  	if m.raw != nil {
  2410  		return m.raw
  2411  	}
  2412  	length := len(m.ciphertext)
  2413  	x := make([]byte, length+4)
  2414  	x[0] = typeClientKeyExchange
  2415  	x[1] = uint8(length >> 16)
  2416  	x[2] = uint8(length >> 8)
  2417  	x[3] = uint8(length)
  2418  	copy(x[4:], m.ciphertext)
  2419  
  2420  	m.raw = x
  2421  	return x
  2422  }
  2423  
  2424  func (m *clientKeyExchangeMsg) unmarshal(data []byte) alert {
  2425  	m.raw = data
  2426  	if len(data) < 4 {
  2427  		return alertDecodeError
  2428  	}
  2429  	l := int(data[1])<<16 | int(data[2])<<8 | int(data[3])
  2430  	if l != len(data)-4 {
  2431  		return alertDecodeError
  2432  	}
  2433  	m.ciphertext = data[4:]
  2434  	return alertSuccess
  2435  }
  2436  
  2437  type finishedMsg struct {
  2438  	raw        []byte
  2439  	verifyData []byte
  2440  }
  2441  
  2442  func (m *finishedMsg) equal(i interface{}) bool {
  2443  	m1, ok := i.(*finishedMsg)
  2444  	if !ok {
  2445  		return false
  2446  	}
  2447  
  2448  	return bytes.Equal(m.raw, m1.raw) &&
  2449  		bytes.Equal(m.verifyData, m1.verifyData)
  2450  }
  2451  
  2452  func (m *finishedMsg) marshal() (x []byte) {
  2453  	if m.raw != nil {
  2454  		return m.raw
  2455  	}
  2456  
  2457  	x = make([]byte, 4+len(m.verifyData))
  2458  	x[0] = typeFinished
  2459  	x[3] = byte(len(m.verifyData))
  2460  	copy(x[4:], m.verifyData)
  2461  	m.raw = x
  2462  	return
  2463  }
  2464  
  2465  func (m *finishedMsg) unmarshal(data []byte) alert {
  2466  	m.raw = data
  2467  	if len(data) < 4 {
  2468  		return alertDecodeError
  2469  	}
  2470  	m.verifyData = data[4:]
  2471  	return alertSuccess
  2472  }
  2473  
  2474  type nextProtoMsg struct {
  2475  	raw   []byte
  2476  	proto string
  2477  }
  2478  
  2479  func (m *nextProtoMsg) equal(i interface{}) bool {
  2480  	m1, ok := i.(*nextProtoMsg)
  2481  	if !ok {
  2482  		return false
  2483  	}
  2484  
  2485  	return bytes.Equal(m.raw, m1.raw) &&
  2486  		m.proto == m1.proto
  2487  }
  2488  
  2489  func (m *nextProtoMsg) marshal() []byte {
  2490  	if m.raw != nil {
  2491  		return m.raw
  2492  	}
  2493  	l := len(m.proto)
  2494  	if l > 255 {
  2495  		l = 255
  2496  	}
  2497  
  2498  	padding := 32 - (l+2)%32
  2499  	length := l + padding + 2
  2500  	x := make([]byte, length+4)
  2501  	x[0] = typeNextProtocol
  2502  	x[1] = uint8(length >> 16)
  2503  	x[2] = uint8(length >> 8)
  2504  	x[3] = uint8(length)
  2505  
  2506  	y := x[4:]
  2507  	y[0] = byte(l)
  2508  	copy(y[1:], []byte(m.proto[0:l]))
  2509  	y = y[1+l:]
  2510  	y[0] = byte(padding)
  2511  
  2512  	m.raw = x
  2513  
  2514  	return x
  2515  }
  2516  
  2517  func (m *nextProtoMsg) unmarshal(data []byte) alert {
  2518  	m.raw = data
  2519  
  2520  	if len(data) < 5 {
  2521  		return alertDecodeError
  2522  	}
  2523  	data = data[4:]
  2524  	protoLen := int(data[0])
  2525  	data = data[1:]
  2526  	if len(data) < protoLen {
  2527  		return alertDecodeError
  2528  	}
  2529  	m.proto = string(data[0:protoLen])
  2530  	data = data[protoLen:]
  2531  
  2532  	if len(data) < 1 {
  2533  		return alertDecodeError
  2534  	}
  2535  	paddingLen := int(data[0])
  2536  	data = data[1:]
  2537  	if len(data) != paddingLen {
  2538  		return alertDecodeError
  2539  	}
  2540  
  2541  	return alertSuccess
  2542  }
  2543  
  2544  type certificateRequestMsg struct {
  2545  	raw []byte
  2546  	// hasSignatureAndHash indicates whether this message includes a list
  2547  	// of signature and hash functions. This change was introduced with TLS
  2548  	// 1.2.
  2549  	hasSignatureAndHash bool
  2550  
  2551  	certificateTypes             []byte
  2552  	supportedSignatureAlgorithms []SignatureScheme
  2553  	certificateAuthorities       [][]byte
  2554  }
  2555  
  2556  func (m *certificateRequestMsg) equal(i interface{}) bool {
  2557  	m1, ok := i.(*certificateRequestMsg)
  2558  	if !ok {
  2559  		return false
  2560  	}
  2561  
  2562  	return bytes.Equal(m.raw, m1.raw) &&
  2563  		bytes.Equal(m.certificateTypes, m1.certificateTypes) &&
  2564  		eqByteSlices(m.certificateAuthorities, m1.certificateAuthorities) &&
  2565  		eqSignatureAlgorithms(m.supportedSignatureAlgorithms, m1.supportedSignatureAlgorithms)
  2566  }
  2567  
  2568  func (m *certificateRequestMsg) marshal() (x []byte) {
  2569  	if m.raw != nil {
  2570  		return m.raw
  2571  	}
  2572  
  2573  	// See http://tools.ietf.org/html/rfc4346#section-7.4.4
  2574  	length := 1 + len(m.certificateTypes) + 2
  2575  	casLength := 0
  2576  	for _, ca := range m.certificateAuthorities {
  2577  		casLength += 2 + len(ca)
  2578  	}
  2579  	length += casLength
  2580  
  2581  	if m.hasSignatureAndHash {
  2582  		length += 2 + 2*len(m.supportedSignatureAlgorithms)
  2583  	}
  2584  
  2585  	x = make([]byte, 4+length)
  2586  	x[0] = typeCertificateRequest
  2587  	x[1] = uint8(length >> 16)
  2588  	x[2] = uint8(length >> 8)
  2589  	x[3] = uint8(length)
  2590  
  2591  	x[4] = uint8(len(m.certificateTypes))
  2592  
  2593  	copy(x[5:], m.certificateTypes)
  2594  	y := x[5+len(m.certificateTypes):]
  2595  
  2596  	if m.hasSignatureAndHash {
  2597  		n := len(m.supportedSignatureAlgorithms) * 2
  2598  		y[0] = uint8(n >> 8)
  2599  		y[1] = uint8(n)
  2600  		y = y[2:]
  2601  		for _, sigAlgo := range m.supportedSignatureAlgorithms {
  2602  			y[0] = uint8(sigAlgo >> 8)
  2603  			y[1] = uint8(sigAlgo)
  2604  			y = y[2:]
  2605  		}
  2606  	}
  2607  
  2608  	y[0] = uint8(casLength >> 8)
  2609  	y[1] = uint8(casLength)
  2610  	y = y[2:]
  2611  	for _, ca := range m.certificateAuthorities {
  2612  		y[0] = uint8(len(ca) >> 8)
  2613  		y[1] = uint8(len(ca))
  2614  		y = y[2:]
  2615  		copy(y, ca)
  2616  		y = y[len(ca):]
  2617  	}
  2618  
  2619  	m.raw = x
  2620  	return
  2621  }
  2622  
  2623  func (m *certificateRequestMsg) unmarshal(data []byte) alert {
  2624  	m.raw = data
  2625  
  2626  	if len(data) < 5 {
  2627  		return alertDecodeError
  2628  	}
  2629  
  2630  	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
  2631  	if uint32(len(data))-4 != length {
  2632  		return alertDecodeError
  2633  	}
  2634  
  2635  	numCertTypes := int(data[4])
  2636  	data = data[5:]
  2637  	if numCertTypes == 0 || len(data) <= numCertTypes {
  2638  		return alertDecodeError
  2639  	}
  2640  
  2641  	m.certificateTypes = make([]byte, numCertTypes)
  2642  	if copy(m.certificateTypes, data) != numCertTypes {
  2643  		return alertDecodeError
  2644  	}
  2645  
  2646  	data = data[numCertTypes:]
  2647  
  2648  	if m.hasSignatureAndHash {
  2649  		if len(data) < 2 {
  2650  			return alertDecodeError
  2651  		}
  2652  		sigAndHashLen := uint16(data[0])<<8 | uint16(data[1])
  2653  		data = data[2:]
  2654  		if sigAndHashLen&1 != 0 {
  2655  			return alertDecodeError
  2656  		}
  2657  		if len(data) < int(sigAndHashLen) {
  2658  			return alertDecodeError
  2659  		}
  2660  		numSigAlgos := sigAndHashLen / 2
  2661  		m.supportedSignatureAlgorithms = make([]SignatureScheme, numSigAlgos)
  2662  		for i := range m.supportedSignatureAlgorithms {
  2663  			m.supportedSignatureAlgorithms[i] = SignatureScheme(data[0])<<8 | SignatureScheme(data[1])
  2664  			data = data[2:]
  2665  		}
  2666  	}
  2667  
  2668  	if len(data) < 2 {
  2669  		return alertDecodeError
  2670  	}
  2671  	casLength := uint16(data[0])<<8 | uint16(data[1])
  2672  	data = data[2:]
  2673  	if len(data) < int(casLength) {
  2674  		return alertDecodeError
  2675  	}
  2676  	cas := make([]byte, casLength)
  2677  	copy(cas, data)
  2678  	data = data[casLength:]
  2679  
  2680  	m.certificateAuthorities = nil
  2681  	for len(cas) > 0 {
  2682  		if len(cas) < 2 {
  2683  			return alertDecodeError
  2684  		}
  2685  		caLen := uint16(cas[0])<<8 | uint16(cas[1])
  2686  		cas = cas[2:]
  2687  
  2688  		if len(cas) < int(caLen) {
  2689  			return alertDecodeError
  2690  		}
  2691  
  2692  		m.certificateAuthorities = append(m.certificateAuthorities, cas[:caLen])
  2693  		cas = cas[caLen:]
  2694  	}
  2695  
  2696  	if len(data) != 0 {
  2697  		return alertDecodeError
  2698  	}
  2699  
  2700  	return alertSuccess
  2701  }
  2702  
  2703  type certificateRequestMsg13 struct {
  2704  	raw []byte
  2705  
  2706  	requestContext                   []byte
  2707  	supportedSignatureAlgorithms     []SignatureScheme
  2708  	supportedSignatureAlgorithmsCert []SignatureScheme
  2709  	certificateAuthorities           [][]byte
  2710  }
  2711  
  2712  func (m *certificateRequestMsg13) equal(i interface{}) bool {
  2713  	m1, ok := i.(*certificateRequestMsg13)
  2714  	return ok &&
  2715  		bytes.Equal(m.raw, m1.raw) &&
  2716  		bytes.Equal(m.requestContext, m1.requestContext) &&
  2717  		eqByteSlices(m.certificateAuthorities, m1.certificateAuthorities) &&
  2718  		eqSignatureAlgorithms(m.supportedSignatureAlgorithms, m1.supportedSignatureAlgorithms) &&
  2719  		eqSignatureAlgorithms(m.supportedSignatureAlgorithmsCert, m1.supportedSignatureAlgorithmsCert)
  2720  }
  2721  
  2722  func (m *certificateRequestMsg13) marshal() (x []byte) {
  2723  	if m.raw != nil {
  2724  		return m.raw
  2725  	}
  2726  
  2727  	// See https://tools.ietf.org/html/draft-ietf-tls-tls13-21#section-4.3.2
  2728  	length := 1 + len(m.requestContext)
  2729  	numExtensions := 1
  2730  	extensionsLength := 2 + 2*len(m.supportedSignatureAlgorithms)
  2731  
  2732  	if m.getSignatureAlgorithmsCert() != nil {
  2733  		numExtensions += 1
  2734  		extensionsLength += 2 + 2*len(m.getSignatureAlgorithmsCert())
  2735  	}
  2736  
  2737  	casLength := 0
  2738  	if len(m.certificateAuthorities) > 0 {
  2739  		for _, ca := range m.certificateAuthorities {
  2740  			casLength += 2 + len(ca)
  2741  		}
  2742  		extensionsLength += 2 + casLength
  2743  		numExtensions++
  2744  	}
  2745  
  2746  	extensionsLength += 4 * numExtensions
  2747  	length += 2 + extensionsLength
  2748  
  2749  	x = make([]byte, 4+length)
  2750  	x[0] = typeCertificateRequest
  2751  	x[1] = uint8(length >> 16)
  2752  	x[2] = uint8(length >> 8)
  2753  	x[3] = uint8(length)
  2754  
  2755  	x[4] = uint8(len(m.requestContext))
  2756  	copy(x[5:], m.requestContext)
  2757  	z := x[5+len(m.requestContext):]
  2758  
  2759  	z[0] = byte(extensionsLength >> 8)
  2760  	z[1] = byte(extensionsLength)
  2761  	z = z[2:]
  2762  
  2763  	// TODO: this function should be reused by CH
  2764  	z = marshalExtensionSignatureAlgorithms(extensionSignatureAlgorithms, z, m.supportedSignatureAlgorithms)
  2765  
  2766  	if m.getSignatureAlgorithmsCert() != nil {
  2767  		z = marshalExtensionSignatureAlgorithms(extensionSignatureAlgorithmsCert, z, m.getSignatureAlgorithmsCert())
  2768  	}
  2769  	// certificate_authorities
  2770  	if casLength > 0 {
  2771  		z[0] = byte(extensionCAs >> 8)
  2772  		z[1] = byte(extensionCAs)
  2773  		l := 2 + casLength
  2774  		z[2] = byte(l >> 8)
  2775  		z[3] = byte(l)
  2776  		z = z[4:]
  2777  
  2778  		z[0] = uint8(casLength >> 8)
  2779  		z[1] = uint8(casLength)
  2780  		z = z[2:]
  2781  		for _, ca := range m.certificateAuthorities {
  2782  			z[0] = uint8(len(ca) >> 8)
  2783  			z[1] = uint8(len(ca))
  2784  			z = z[2:]
  2785  			copy(z, ca)
  2786  			z = z[len(ca):]
  2787  		}
  2788  	}
  2789  
  2790  	m.raw = x
  2791  	return
  2792  }
  2793  
  2794  func (m *certificateRequestMsg13) unmarshal(data []byte) alert {
  2795  	m.raw = data
  2796  	m.supportedSignatureAlgorithms = nil
  2797  	m.certificateAuthorities = nil
  2798  
  2799  	if len(data) < 5 {
  2800  		return alertDecodeError
  2801  	}
  2802  
  2803  	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
  2804  	if uint32(len(data))-4 != length {
  2805  		return alertDecodeError
  2806  	}
  2807  
  2808  	ctxLen := data[4]
  2809  	if len(data) < 5+int(ctxLen)+2 {
  2810  		return alertDecodeError
  2811  	}
  2812  	m.requestContext = data[5 : 5+ctxLen]
  2813  	data = data[5+ctxLen:]
  2814  
  2815  	extensionsLength := int(data[0])<<8 | int(data[1])
  2816  	data = data[2:]
  2817  	if len(data) != extensionsLength {
  2818  		return alertDecodeError
  2819  	}
  2820  
  2821  	for len(data) != 0 {
  2822  		if len(data) < 4 {
  2823  			return alertDecodeError
  2824  		}
  2825  		extension := uint16(data[0])<<8 | uint16(data[1])
  2826  		length := int(data[2])<<8 | int(data[3])
  2827  		data = data[4:]
  2828  		if len(data) < length {
  2829  			return alertDecodeError
  2830  		}
  2831  
  2832  		switch extension {
  2833  		case extensionSignatureAlgorithms:
  2834  			// TODO: unmarshalExtensionSignatureAlgorithms should be shared with CH and pre-1.3 CV
  2835  			// https://tools.ietf.org/html/draft-ietf-tls-tls13-21#section-4.2.3
  2836  			var err alert
  2837  			m.supportedSignatureAlgorithms, err = unmarshalExtensionSignatureAlgorithms(data, length)
  2838  			if err != alertSuccess {
  2839  				return err
  2840  			}
  2841  		case extensionSignatureAlgorithmsCert:
  2842  			var err alert
  2843  			m.supportedSignatureAlgorithmsCert, err = unmarshalExtensionSignatureAlgorithms(data, length)
  2844  			if err != alertSuccess {
  2845  				return err
  2846  			}
  2847  		case extensionCAs:
  2848  			// TODO DRY: share code with CH
  2849  			if length < 2 {
  2850  				return alertDecodeError
  2851  			}
  2852  			l := int(data[0])<<8 | int(data[1])
  2853  			if l != length-2 || l < 3 {
  2854  				return alertDecodeError
  2855  			}
  2856  			cas := make([]byte, l)
  2857  			copy(cas, data[2:])
  2858  			m.certificateAuthorities = nil
  2859  			for len(cas) > 0 {
  2860  				if len(cas) < 2 {
  2861  					return alertDecodeError
  2862  				}
  2863  				caLen := uint16(cas[0])<<8 | uint16(cas[1])
  2864  				cas = cas[2:]
  2865  
  2866  				if len(cas) < int(caLen) {
  2867  					return alertDecodeError
  2868  				}
  2869  
  2870  				m.certificateAuthorities = append(m.certificateAuthorities, cas[:caLen])
  2871  				cas = cas[caLen:]
  2872  			}
  2873  		}
  2874  		data = data[length:]
  2875  	}
  2876  
  2877  	if len(m.supportedSignatureAlgorithms) == 0 {
  2878  		return alertDecodeError
  2879  	}
  2880  	return alertSuccess
  2881  }
  2882  
  2883  func (m *certificateRequestMsg13) getSignatureAlgorithmsCert() []SignatureScheme {
  2884  	return signAlgosCertList(m.supportedSignatureAlgorithms, m.supportedSignatureAlgorithmsCert)
  2885  }
  2886  
  2887  type certificateVerifyMsg struct {
  2888  	raw                 []byte
  2889  	hasSignatureAndHash bool
  2890  	signatureAlgorithm  SignatureScheme
  2891  	signature           []byte
  2892  }
  2893  
  2894  func (m *certificateVerifyMsg) equal(i interface{}) bool {
  2895  	m1, ok := i.(*certificateVerifyMsg)
  2896  	if !ok {
  2897  		return false
  2898  	}
  2899  
  2900  	return bytes.Equal(m.raw, m1.raw) &&
  2901  		m.hasSignatureAndHash == m1.hasSignatureAndHash &&
  2902  		m.signatureAlgorithm == m1.signatureAlgorithm &&
  2903  		bytes.Equal(m.signature, m1.signature)
  2904  }
  2905  
  2906  func (m *certificateVerifyMsg) marshal() (x []byte) {
  2907  	if m.raw != nil {
  2908  		return m.raw
  2909  	}
  2910  
  2911  	// See http://tools.ietf.org/html/rfc4346#section-7.4.8
  2912  	siglength := len(m.signature)
  2913  	length := 2 + siglength
  2914  	if m.hasSignatureAndHash {
  2915  		length += 2
  2916  	}
  2917  	x = make([]byte, 4+length)
  2918  	x[0] = typeCertificateVerify
  2919  	x[1] = uint8(length >> 16)
  2920  	x[2] = uint8(length >> 8)
  2921  	x[3] = uint8(length)
  2922  	y := x[4:]
  2923  	if m.hasSignatureAndHash {
  2924  		y[0] = uint8(m.signatureAlgorithm >> 8)
  2925  		y[1] = uint8(m.signatureAlgorithm)
  2926  		y = y[2:]
  2927  	}
  2928  	y[0] = uint8(siglength >> 8)
  2929  	y[1] = uint8(siglength)
  2930  	copy(y[2:], m.signature)
  2931  
  2932  	m.raw = x
  2933  
  2934  	return
  2935  }
  2936  
  2937  func (m *certificateVerifyMsg) unmarshal(data []byte) alert {
  2938  	m.raw = data
  2939  
  2940  	if len(data) < 6 {
  2941  		return alertDecodeError
  2942  	}
  2943  
  2944  	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
  2945  	if uint32(len(data))-4 != length {
  2946  		return alertDecodeError
  2947  	}
  2948  
  2949  	data = data[4:]
  2950  	if m.hasSignatureAndHash {
  2951  		m.signatureAlgorithm = SignatureScheme(data[0])<<8 | SignatureScheme(data[1])
  2952  		data = data[2:]
  2953  	}
  2954  
  2955  	if len(data) < 2 {
  2956  		return alertDecodeError
  2957  	}
  2958  	siglength := int(data[0])<<8 + int(data[1])
  2959  	data = data[2:]
  2960  	if len(data) != siglength {
  2961  		return alertDecodeError
  2962  	}
  2963  
  2964  	m.signature = data
  2965  
  2966  	return alertSuccess
  2967  }
  2968  
  2969  type newSessionTicketMsg struct {
  2970  	raw    []byte
  2971  	ticket []byte
  2972  }
  2973  
  2974  func (m *newSessionTicketMsg) equal(i interface{}) bool {
  2975  	m1, ok := i.(*newSessionTicketMsg)
  2976  	if !ok {
  2977  		return false
  2978  	}
  2979  
  2980  	return bytes.Equal(m.raw, m1.raw) &&
  2981  		bytes.Equal(m.ticket, m1.ticket)
  2982  }
  2983  
  2984  func (m *newSessionTicketMsg) marshal() (x []byte) {
  2985  	if m.raw != nil {
  2986  		return m.raw
  2987  	}
  2988  
  2989  	// See http://tools.ietf.org/html/rfc5077#section-3.3
  2990  	ticketLen := len(m.ticket)
  2991  	length := 2 + 4 + ticketLen
  2992  	x = make([]byte, 4+length)
  2993  	x[0] = typeNewSessionTicket
  2994  	x[1] = uint8(length >> 16)
  2995  	x[2] = uint8(length >> 8)
  2996  	x[3] = uint8(length)
  2997  	x[8] = uint8(ticketLen >> 8)
  2998  	x[9] = uint8(ticketLen)
  2999  	copy(x[10:], m.ticket)
  3000  
  3001  	// [Psiphon]
  3002  	// Set lifetime hint to a more typical value.
  3003  	if obfuscateSessionTickets {
  3004  		hints := []int{300, 1200, 7200, 10800, 64800, 100800, 129600}
  3005  		index := prng.Intn(len(hints))
  3006  		hint := hints[index]
  3007  		x[4] = uint8(hint >> 24)
  3008  		x[5] = uint8(hint >> 16)
  3009  		x[6] = uint8(hint >> 8)
  3010  		x[7] = uint8(hint)
  3011  	}
  3012  
  3013  	m.raw = x
  3014  
  3015  	return
  3016  }
  3017  
  3018  func (m *newSessionTicketMsg) unmarshal(data []byte) alert {
  3019  	m.raw = data
  3020  
  3021  	if len(data) < 10 {
  3022  		return alertDecodeError
  3023  	}
  3024  
  3025  	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
  3026  	if uint32(len(data))-4 != length {
  3027  		return alertDecodeError
  3028  	}
  3029  
  3030  	ticketLen := int(data[8])<<8 + int(data[9])
  3031  	if len(data)-10 != ticketLen {
  3032  		return alertDecodeError
  3033  	}
  3034  
  3035  	m.ticket = data[10:]
  3036  
  3037  	return alertSuccess
  3038  }
  3039  
  3040  type newSessionTicketMsg13 struct {
  3041  	raw                []byte
  3042  	lifetime           uint32
  3043  	ageAdd             uint32
  3044  	nonce              []byte
  3045  	ticket             []byte
  3046  	withEarlyDataInfo  bool
  3047  	maxEarlyDataLength uint32
  3048  }
  3049  
  3050  func (m *newSessionTicketMsg13) equal(i interface{}) bool {
  3051  	m1, ok := i.(*newSessionTicketMsg13)
  3052  	if !ok {
  3053  		return false
  3054  	}
  3055  
  3056  	return bytes.Equal(m.raw, m1.raw) &&
  3057  		m.lifetime == m1.lifetime &&
  3058  		m.ageAdd == m1.ageAdd &&
  3059  		bytes.Equal(m.nonce, m1.nonce) &&
  3060  		bytes.Equal(m.ticket, m1.ticket) &&
  3061  		m.withEarlyDataInfo == m1.withEarlyDataInfo &&
  3062  		m.maxEarlyDataLength == m1.maxEarlyDataLength
  3063  }
  3064  
  3065  func (m *newSessionTicketMsg13) marshal() (x []byte) {
  3066  	if m.raw != nil {
  3067  		return m.raw
  3068  	}
  3069  
  3070  	// See https://tools.ietf.org/html/draft-ietf-tls-tls13-21#section-4.6.1
  3071  	nonceLen := len(m.nonce)
  3072  	ticketLen := len(m.ticket)
  3073  	length := 13 + nonceLen + ticketLen
  3074  	if m.withEarlyDataInfo {
  3075  		length += 8
  3076  	}
  3077  	x = make([]byte, 4+length)
  3078  	x[0] = typeNewSessionTicket
  3079  	x[1] = uint8(length >> 16)
  3080  	x[2] = uint8(length >> 8)
  3081  	x[3] = uint8(length)
  3082  
  3083  	x[4] = uint8(m.lifetime >> 24)
  3084  	x[5] = uint8(m.lifetime >> 16)
  3085  	x[6] = uint8(m.lifetime >> 8)
  3086  	x[7] = uint8(m.lifetime)
  3087  	x[8] = uint8(m.ageAdd >> 24)
  3088  	x[9] = uint8(m.ageAdd >> 16)
  3089  	x[10] = uint8(m.ageAdd >> 8)
  3090  	x[11] = uint8(m.ageAdd)
  3091  
  3092  	x[12] = uint8(nonceLen)
  3093  	copy(x[13:13+nonceLen], m.nonce)
  3094  
  3095  	y := x[13+nonceLen:]
  3096  	y[0] = uint8(ticketLen >> 8)
  3097  	y[1] = uint8(ticketLen)
  3098  	copy(y[2:2+ticketLen], m.ticket)
  3099  
  3100  	if m.withEarlyDataInfo {
  3101  		z := y[2+ticketLen:]
  3102  		// z[0] is already 0, this is the extensions vector length.
  3103  		z[1] = 8
  3104  		z[2] = uint8(extensionEarlyData >> 8)
  3105  		z[3] = uint8(extensionEarlyData)
  3106  		z[5] = 4
  3107  		z[6] = uint8(m.maxEarlyDataLength >> 24)
  3108  		z[7] = uint8(m.maxEarlyDataLength >> 16)
  3109  		z[8] = uint8(m.maxEarlyDataLength >> 8)
  3110  		z[9] = uint8(m.maxEarlyDataLength)
  3111  	}
  3112  
  3113  	m.raw = x
  3114  
  3115  	return
  3116  }
  3117  
  3118  func (m *newSessionTicketMsg13) unmarshal(data []byte) alert {
  3119  	m.raw = data
  3120  	m.maxEarlyDataLength = 0
  3121  	m.withEarlyDataInfo = false
  3122  
  3123  	if len(data) < 17 {
  3124  		return alertDecodeError
  3125  	}
  3126  
  3127  	length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
  3128  	if uint32(len(data))-4 != length {
  3129  		return alertDecodeError
  3130  	}
  3131  
  3132  	m.lifetime = uint32(data[4])<<24 | uint32(data[5])<<16 |
  3133  		uint32(data[6])<<8 | uint32(data[7])
  3134  	m.ageAdd = uint32(data[8])<<24 | uint32(data[9])<<16 |
  3135  		uint32(data[10])<<8 | uint32(data[11])
  3136  
  3137  	nonceLen := int(data[12])
  3138  	if nonceLen == 0 || 13+nonceLen+2 > len(data) {
  3139  		return alertDecodeError
  3140  	}
  3141  	m.nonce = data[13 : 13+nonceLen]
  3142  
  3143  	data = data[13+nonceLen:]
  3144  	ticketLen := int(data[0])<<8 + int(data[1])
  3145  	if ticketLen == 0 || 2+ticketLen+2 > len(data) {
  3146  		return alertDecodeError
  3147  	}
  3148  	m.ticket = data[2 : 2+ticketLen]
  3149  
  3150  	data = data[2+ticketLen:]
  3151  	extLen := int(data[0])<<8 + int(data[1])
  3152  	if extLen != len(data)-2 {
  3153  		return alertDecodeError
  3154  	}
  3155  
  3156  	data = data[2:]
  3157  	for len(data) > 0 {
  3158  		if len(data) < 4 {
  3159  			return alertDecodeError
  3160  		}
  3161  		extType := uint16(data[0])<<8 + uint16(data[1])
  3162  		length := int(data[2])<<8 + int(data[3])
  3163  		data = data[4:]
  3164  
  3165  		switch extType {
  3166  		case extensionEarlyData:
  3167  			if length != 4 {
  3168  				return alertDecodeError
  3169  			}
  3170  			m.withEarlyDataInfo = true
  3171  			m.maxEarlyDataLength = uint32(data[0])<<24 | uint32(data[1])<<16 |
  3172  				uint32(data[2])<<8 | uint32(data[3])
  3173  		}
  3174  		data = data[length:]
  3175  	}
  3176  
  3177  	return alertSuccess
  3178  }
  3179  
  3180  type endOfEarlyDataMsg struct {
  3181  }
  3182  
  3183  func (*endOfEarlyDataMsg) marshal() []byte {
  3184  	return []byte{typeEndOfEarlyData, 0, 0, 0}
  3185  }
  3186  
  3187  func (*endOfEarlyDataMsg) unmarshal(data []byte) alert {
  3188  	if len(data) != 4 {
  3189  		return alertDecodeError
  3190  	}
  3191  	return alertSuccess
  3192  }
  3193  
  3194  type helloRequestMsg struct {
  3195  }
  3196  
  3197  func (*helloRequestMsg) marshal() []byte {
  3198  	return []byte{typeHelloRequest, 0, 0, 0}
  3199  }
  3200  
  3201  func (*helloRequestMsg) unmarshal(data []byte) alert {
  3202  	if len(data) != 4 {
  3203  		return alertDecodeError
  3204  	}
  3205  	return alertSuccess
  3206  }
  3207  
  3208  func eqUint16s(x, y []uint16) bool {
  3209  	if len(x) != len(y) {
  3210  		return false
  3211  	}
  3212  	for i, v := range x {
  3213  		if y[i] != v {
  3214  			return false
  3215  		}
  3216  	}
  3217  	return true
  3218  }
  3219  
  3220  func eqCurveIDs(x, y []CurveID) bool {
  3221  	if len(x) != len(y) {
  3222  		return false
  3223  	}
  3224  	for i, v := range x {
  3225  		if y[i] != v {
  3226  			return false
  3227  		}
  3228  	}
  3229  	return true
  3230  }
  3231  
  3232  func eqStrings(x, y []string) bool {
  3233  	if len(x) != len(y) {
  3234  		return false
  3235  	}
  3236  	for i, v := range x {
  3237  		if y[i] != v {
  3238  			return false
  3239  		}
  3240  	}
  3241  	return true
  3242  }
  3243  
  3244  func eqByteSlices(x, y [][]byte) bool {
  3245  	if len(x) != len(y) {
  3246  		return false
  3247  	}
  3248  	for i, v := range x {
  3249  		if !bytes.Equal(v, y[i]) {
  3250  			return false
  3251  		}
  3252  	}
  3253  	return true
  3254  }
  3255  
  3256  func eqSignatureAlgorithms(x, y []SignatureScheme) bool {
  3257  	if len(x) != len(y) {
  3258  		return false
  3259  	}
  3260  	for i, v := range x {
  3261  		if v != y[i] {
  3262  			return false
  3263  		}
  3264  	}
  3265  	return true
  3266  }
  3267  
  3268  func eqKeyShares(x, y []keyShare) bool {
  3269  	if len(x) != len(y) {
  3270  		return false
  3271  	}
  3272  	for i := range x {
  3273  		if x[i].group != y[i].group {
  3274  			return false
  3275  		}
  3276  		if !bytes.Equal(x[i].data, y[i].data) {
  3277  			return false
  3278  		}
  3279  	}
  3280  	return true
  3281  }
  3282  
  3283  func findExtension(data []byte, extensionType uint16) []byte {
  3284  	for len(data) != 0 {
  3285  		if len(data) < 4 {
  3286  			return nil
  3287  		}
  3288  		extension := uint16(data[0])<<8 | uint16(data[1])
  3289  		length := int(data[2])<<8 | int(data[3])
  3290  		data = data[4:]
  3291  		if len(data) < length {
  3292  			return nil
  3293  		}
  3294  		if extension == extensionType {
  3295  			return data[:length]
  3296  		}
  3297  		data = data[length:]
  3298  	}
  3299  	return nil
  3300  }