Source file src/crypto/tls/handshake_messages.go

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

View as plain text