...

Source file src/crypto/tls/handshake_messages.go

Documentation: crypto/tls

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

View as plain text