Source file src/crypto/tls/handshake_messages_test.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  	"bytes"
     9  	"crypto/x509"
    10  	"encoding/hex"
    11  	"math"
    12  	"math/rand"
    13  	"reflect"
    14  	"strings"
    15  	"testing"
    16  	"testing/quick"
    17  	"time"
    18  )
    19  
    20  var tests = []handshakeMessage{
    21  	&clientHelloMsg{},
    22  	&serverHelloMsg{},
    23  	&finishedMsg{},
    24  
    25  	&certificateMsg{},
    26  	&certificateRequestMsg{},
    27  	&certificateVerifyMsg{
    28  		hasSignatureAlgorithm: true,
    29  	},
    30  	&certificateStatusMsg{},
    31  	&clientKeyExchangeMsg{},
    32  	&newSessionTicketMsg{},
    33  	&encryptedExtensionsMsg{},
    34  	&endOfEarlyDataMsg{},
    35  	&keyUpdateMsg{},
    36  	&newSessionTicketMsgTLS13{},
    37  	&certificateRequestMsgTLS13{},
    38  	&certificateMsgTLS13{},
    39  	&SessionState{},
    40  }
    41  
    42  func mustMarshal(t *testing.T, msg handshakeMessage) []byte {
    43  	t.Helper()
    44  	b, err := msg.marshal()
    45  	if err != nil {
    46  		t.Fatal(err)
    47  	}
    48  	return b
    49  }
    50  
    51  func TestMarshalUnmarshal(t *testing.T) {
    52  	rand := rand.New(rand.NewSource(time.Now().UnixNano()))
    53  
    54  	for i, m := range tests {
    55  		ty := reflect.ValueOf(m).Type()
    56  		t.Run(ty.String(), func(t *testing.T) {
    57  			n := 100
    58  			if testing.Short() {
    59  				n = 5
    60  			}
    61  			for j := 0; j < n; j++ {
    62  				v, ok := quick.Value(ty, rand)
    63  				if !ok {
    64  					t.Errorf("#%d: failed to create value", i)
    65  					break
    66  				}
    67  
    68  				m1 := v.Interface().(handshakeMessage)
    69  				marshaled := mustMarshal(t, m1)
    70  				if !m.unmarshal(marshaled) {
    71  					t.Errorf("#%d failed to unmarshal %#v %x", i, m1, marshaled)
    72  					break
    73  				}
    74  
    75  				if ch, ok := m.(*clientHelloMsg); ok {
    76  					// extensions is special cased, as it is only populated by the
    77  					// server-side of a handshake and is not expected to roundtrip
    78  					// through marshal + unmarshal.  m ends up with the list of
    79  					// extensions necessary to serialize the other fields of
    80  					// clientHelloMsg, so check that it is non-empty, then clear it.
    81  					if len(ch.extensions) == 0 {
    82  						t.Errorf("expected ch.extensions to be populated on unmarshal")
    83  					}
    84  					ch.extensions = nil
    85  				}
    86  
    87  				// clientHelloMsg and serverHelloMsg, when unmarshalled, store
    88  				// their original representation, for later use in the handshake
    89  				// transcript. In order to prevent DeepEqual from failing since
    90  				// we didn't create the original message via unmarshalling, nil
    91  				// the field.
    92  				switch t := m.(type) {
    93  				case *clientHelloMsg:
    94  					t.original = nil
    95  				case *serverHelloMsg:
    96  					t.original = nil
    97  				}
    98  
    99  				if !reflect.DeepEqual(m1, m) {
   100  					t.Errorf("#%d got:%#v want:%#v %x", i, m, m1, marshaled)
   101  					break
   102  				}
   103  
   104  				if i >= 3 {
   105  					// The first three message types (ClientHello,
   106  					// ServerHello and Finished) are allowed to
   107  					// have parsable prefixes because the extension
   108  					// data is optional and the length of the
   109  					// Finished varies across versions.
   110  					for j := 0; j < len(marshaled); j++ {
   111  						if m.unmarshal(marshaled[0:j]) {
   112  							t.Errorf("#%d unmarshaled a prefix of length %d of %#v", i, j, m1)
   113  							break
   114  						}
   115  					}
   116  				}
   117  			}
   118  		})
   119  	}
   120  }
   121  
   122  func TestFuzz(t *testing.T) {
   123  	rand := rand.New(rand.NewSource(0))
   124  	for _, m := range tests {
   125  		for j := 0; j < 1000; j++ {
   126  			len := rand.Intn(1000)
   127  			bytes := randomBytes(len, rand)
   128  			// This just looks for crashes due to bounds errors etc.
   129  			m.unmarshal(bytes)
   130  		}
   131  	}
   132  }
   133  
   134  func randomBytes(n int, rand *rand.Rand) []byte {
   135  	r := make([]byte, n)
   136  	if _, err := rand.Read(r); err != nil {
   137  		panic("rand.Read failed: " + err.Error())
   138  	}
   139  	return r
   140  }
   141  
   142  func randomString(n int, rand *rand.Rand) string {
   143  	b := randomBytes(n, rand)
   144  	return string(b)
   145  }
   146  
   147  func (*clientHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   148  	m := &clientHelloMsg{}
   149  	m.vers = uint16(rand.Intn(65536))
   150  	m.random = randomBytes(32, rand)
   151  	m.sessionId = randomBytes(rand.Intn(32), rand)
   152  	m.cipherSuites = make([]uint16, rand.Intn(63)+1)
   153  	for i := 0; i < len(m.cipherSuites); i++ {
   154  		cs := uint16(rand.Int31())
   155  		if cs == scsvRenegotiation {
   156  			cs += 1
   157  		}
   158  		m.cipherSuites[i] = cs
   159  	}
   160  	m.compressionMethods = randomBytes(rand.Intn(63)+1, rand)
   161  	if rand.Intn(10) > 5 {
   162  		m.serverName = randomString(rand.Intn(255), rand)
   163  		for strings.HasSuffix(m.serverName, ".") {
   164  			m.serverName = m.serverName[:len(m.serverName)-1]
   165  		}
   166  	}
   167  	m.ocspStapling = rand.Intn(10) > 5
   168  	m.supportedPoints = randomBytes(rand.Intn(5)+1, rand)
   169  	m.supportedCurves = make([]CurveID, rand.Intn(5)+1)
   170  	for i := range m.supportedCurves {
   171  		m.supportedCurves[i] = CurveID(rand.Intn(30000) + 1)
   172  	}
   173  	if rand.Intn(10) > 5 {
   174  		m.ticketSupported = true
   175  		if rand.Intn(10) > 5 {
   176  			m.sessionTicket = randomBytes(rand.Intn(300), rand)
   177  		} else {
   178  			m.sessionTicket = make([]byte, 0)
   179  		}
   180  	}
   181  	if rand.Intn(10) > 5 {
   182  		m.supportedSignatureAlgorithms = supportedSignatureAlgorithms(VersionTLS12, VersionTLS13)
   183  	}
   184  	if rand.Intn(10) > 5 {
   185  		m.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithms(VersionTLS12, VersionTLS13)
   186  	}
   187  	for i := 0; i < rand.Intn(5); i++ {
   188  		m.alpnProtocols = append(m.alpnProtocols, randomString(rand.Intn(20)+1, rand))
   189  	}
   190  	if rand.Intn(10) > 5 {
   191  		m.scts = true
   192  	}
   193  	if rand.Intn(10) > 5 {
   194  		m.secureRenegotiationSupported = true
   195  		m.secureRenegotiation = randomBytes(rand.Intn(50)+1, rand)
   196  	}
   197  	if rand.Intn(10) > 5 {
   198  		m.extendedMasterSecret = true
   199  	}
   200  	for i := 0; i < rand.Intn(5); i++ {
   201  		m.supportedVersions = append(m.supportedVersions, uint16(rand.Intn(0xffff)+1))
   202  	}
   203  	if rand.Intn(10) > 5 {
   204  		m.cookie = randomBytes(rand.Intn(500)+1, rand)
   205  	}
   206  	for i := 0; i < rand.Intn(5); i++ {
   207  		var ks keyShare
   208  		ks.group = CurveID(rand.Intn(30000) + 1)
   209  		ks.data = randomBytes(rand.Intn(200)+1, rand)
   210  		m.keyShares = append(m.keyShares, ks)
   211  	}
   212  	switch rand.Intn(3) {
   213  	case 1:
   214  		m.pskModes = []uint8{pskModeDHE}
   215  	case 2:
   216  		m.pskModes = []uint8{pskModeDHE, pskModePlain}
   217  	}
   218  	// clientHelloMsg.marshal uses echInner == false. If m.encryptedClientHello > 0 and
   219  	// does not equal []byte{innerECHExt}, then the psk extension will be omitted,
   220  	// so either only emit empty encryptedClientHello and psk, encryptedClientHello with
   221  	// []byte{innerECHExt} and psk, or random encryptedClientHello and no psk.
   222  	if rand.Intn(10) > 5 {
   223  		m.encryptedClientHello = randomBytes(rand.Intn(50)+1, rand)
   224  	} else {
   225  		if rand.Intn(10) > 5 {
   226  			m.encryptedClientHello = []byte{byte(innerECHExt)}
   227  		}
   228  		var psk pskIdentity
   229  		psk.obfuscatedTicketAge = uint32(rand.Intn(500000))
   230  		psk.label = randomBytes(rand.Intn(500)+1, rand)
   231  		m.pskIdentities = append(m.pskIdentities, psk)
   232  		m.pskBinders = append(m.pskBinders, randomBytes(rand.Intn(50)+32, rand))
   233  	}
   234  	if rand.Intn(10) > 5 {
   235  		m.quicTransportParameters = randomBytes(rand.Intn(500), rand)
   236  	}
   237  	if rand.Intn(10) > 5 {
   238  		m.earlyData = true
   239  	}
   240  
   241  	return reflect.ValueOf(m)
   242  }
   243  
   244  func (*serverHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   245  	m := &serverHelloMsg{}
   246  	m.vers = uint16(rand.Intn(65536))
   247  	m.random = randomBytes(32, rand)
   248  	m.sessionId = randomBytes(rand.Intn(32), rand)
   249  	m.cipherSuite = uint16(rand.Int31())
   250  	m.compressionMethod = uint8(rand.Intn(256))
   251  	m.supportedPoints = randomBytes(rand.Intn(5)+1, rand)
   252  
   253  	if rand.Intn(10) > 5 {
   254  		m.ocspStapling = true
   255  	}
   256  	if rand.Intn(10) > 5 {
   257  		m.ticketSupported = true
   258  	}
   259  	if rand.Intn(10) > 5 {
   260  		m.alpnProtocol = randomString(rand.Intn(32)+1, rand)
   261  	}
   262  
   263  	for i := 0; i < rand.Intn(4); i++ {
   264  		m.scts = append(m.scts, randomBytes(rand.Intn(500)+1, rand))
   265  	}
   266  
   267  	if rand.Intn(10) > 5 {
   268  		m.secureRenegotiationSupported = true
   269  		m.secureRenegotiation = randomBytes(rand.Intn(50)+1, rand)
   270  	}
   271  	if rand.Intn(10) > 5 {
   272  		m.extendedMasterSecret = true
   273  	}
   274  	if rand.Intn(10) > 5 {
   275  		m.supportedVersion = uint16(rand.Intn(0xffff) + 1)
   276  	}
   277  	if rand.Intn(10) > 5 {
   278  		m.cookie = randomBytes(rand.Intn(500)+1, rand)
   279  	}
   280  	if rand.Intn(10) > 5 {
   281  		for i := 0; i < rand.Intn(5); i++ {
   282  			m.serverShare.group = CurveID(rand.Intn(30000) + 1)
   283  			m.serverShare.data = randomBytes(rand.Intn(200)+1, rand)
   284  		}
   285  	} else if rand.Intn(10) > 5 {
   286  		m.selectedGroup = CurveID(rand.Intn(30000) + 1)
   287  	}
   288  	if rand.Intn(10) > 5 {
   289  		m.selectedIdentityPresent = true
   290  		m.selectedIdentity = uint16(rand.Intn(0xffff))
   291  	}
   292  	if rand.Intn(10) > 5 {
   293  		m.encryptedClientHello = randomBytes(rand.Intn(50)+1, rand)
   294  	}
   295  	if rand.Intn(10) > 5 {
   296  		m.serverNameAck = rand.Intn(2) == 1
   297  	}
   298  
   299  	return reflect.ValueOf(m)
   300  }
   301  
   302  func (*encryptedExtensionsMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   303  	m := &encryptedExtensionsMsg{}
   304  
   305  	if rand.Intn(10) > 5 {
   306  		m.alpnProtocol = randomString(rand.Intn(32)+1, rand)
   307  	}
   308  	if rand.Intn(10) > 5 {
   309  		m.earlyData = true
   310  	}
   311  
   312  	return reflect.ValueOf(m)
   313  }
   314  
   315  func (*certificateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   316  	m := &certificateMsg{}
   317  	numCerts := rand.Intn(20)
   318  	m.certificates = make([][]byte, numCerts)
   319  	for i := 0; i < numCerts; i++ {
   320  		m.certificates[i] = randomBytes(rand.Intn(10)+1, rand)
   321  	}
   322  	return reflect.ValueOf(m)
   323  }
   324  
   325  func (*certificateRequestMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   326  	m := &certificateRequestMsg{}
   327  	m.certificateTypes = randomBytes(rand.Intn(5)+1, rand)
   328  	for i := 0; i < rand.Intn(100); i++ {
   329  		m.certificateAuthorities = append(m.certificateAuthorities, randomBytes(rand.Intn(15)+1, rand))
   330  	}
   331  	return reflect.ValueOf(m)
   332  }
   333  
   334  func (*certificateVerifyMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   335  	m := &certificateVerifyMsg{}
   336  	m.hasSignatureAlgorithm = true
   337  	m.signatureAlgorithm = SignatureScheme(rand.Intn(30000))
   338  	m.signature = randomBytes(rand.Intn(15)+1, rand)
   339  	return reflect.ValueOf(m)
   340  }
   341  
   342  func (*certificateStatusMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   343  	m := &certificateStatusMsg{}
   344  	m.response = randomBytes(rand.Intn(10)+1, rand)
   345  	return reflect.ValueOf(m)
   346  }
   347  
   348  func (*clientKeyExchangeMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   349  	m := &clientKeyExchangeMsg{}
   350  	m.ciphertext = randomBytes(rand.Intn(1000)+1, rand)
   351  	return reflect.ValueOf(m)
   352  }
   353  
   354  func (*finishedMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   355  	m := &finishedMsg{}
   356  	m.verifyData = randomBytes(12, rand)
   357  	return reflect.ValueOf(m)
   358  }
   359  
   360  func (*newSessionTicketMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   361  	m := &newSessionTicketMsg{}
   362  	m.ticket = randomBytes(rand.Intn(4), rand)
   363  	return reflect.ValueOf(m)
   364  }
   365  
   366  var sessionTestCerts []*x509.Certificate
   367  
   368  func init() {
   369  	sessionTestCerts = append(sessionTestCerts, testRSA2048Cert.Leaf)
   370  	sessionTestCerts = append(sessionTestCerts, testRootCert.Leaf)
   371  }
   372  
   373  func (*SessionState) Generate(rand *rand.Rand, size int) reflect.Value {
   374  	s := &SessionState{}
   375  	isTLS13 := rand.Intn(10) > 5
   376  	if isTLS13 {
   377  		s.version = VersionTLS13
   378  	} else {
   379  		s.version = uint16(rand.Intn(VersionTLS13))
   380  	}
   381  	s.isClient = rand.Intn(10) > 5
   382  	s.cipherSuite = uint16(rand.Intn(math.MaxUint16))
   383  	s.createdAt = uint64(rand.Int63())
   384  	s.secret = randomBytes(rand.Intn(100)+1, rand)
   385  	for n, i := rand.Intn(3), 0; i < n; i++ {
   386  		s.Extra = append(s.Extra, randomBytes(rand.Intn(100), rand))
   387  	}
   388  	if rand.Intn(10) > 5 {
   389  		s.EarlyData = true
   390  	}
   391  	if rand.Intn(10) > 5 {
   392  		s.extMasterSecret = true
   393  	}
   394  	if s.isClient || rand.Intn(10) > 5 {
   395  		if rand.Intn(10) > 5 {
   396  			s.peerCertificates = sessionTestCerts
   397  		} else {
   398  			s.peerCertificates = sessionTestCerts[:1]
   399  		}
   400  	}
   401  	if rand.Intn(10) > 5 && s.peerCertificates != nil {
   402  		s.ocspResponse = randomBytes(rand.Intn(100)+1, rand)
   403  	}
   404  	if rand.Intn(10) > 5 && s.peerCertificates != nil {
   405  		for i := 0; i < rand.Intn(2)+1; i++ {
   406  			s.scts = append(s.scts, randomBytes(rand.Intn(500)+1, rand))
   407  		}
   408  	}
   409  	if len(s.peerCertificates) > 0 {
   410  		for i := 0; i < rand.Intn(3); i++ {
   411  			if rand.Intn(10) > 5 {
   412  				s.verifiedChains = append(s.verifiedChains, s.peerCertificates)
   413  			} else {
   414  				s.verifiedChains = append(s.verifiedChains, s.peerCertificates[:1])
   415  			}
   416  		}
   417  	}
   418  	if rand.Intn(10) > 5 && s.EarlyData {
   419  		s.alpnProtocol = string(randomBytes(rand.Intn(10), rand))
   420  	}
   421  	if isTLS13 {
   422  		if s.isClient {
   423  			s.useBy = uint64(rand.Int63())
   424  			s.ageAdd = uint32(rand.Int63() & math.MaxUint32)
   425  		}
   426  	} else {
   427  		s.curveID = CurveID(rand.Intn(30000) + 1)
   428  	}
   429  	return reflect.ValueOf(s)
   430  }
   431  
   432  func (s *SessionState) marshal() ([]byte, error) { return s.Bytes() }
   433  func (s *SessionState) unmarshal(b []byte) bool {
   434  	ss, err := ParseSessionState(b)
   435  	if err != nil {
   436  		return false
   437  	}
   438  	*s = *ss
   439  	return true
   440  }
   441  
   442  func (*endOfEarlyDataMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   443  	m := &endOfEarlyDataMsg{}
   444  	return reflect.ValueOf(m)
   445  }
   446  
   447  func (*keyUpdateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   448  	m := &keyUpdateMsg{}
   449  	m.updateRequested = rand.Intn(10) > 5
   450  	return reflect.ValueOf(m)
   451  }
   452  
   453  func (*newSessionTicketMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
   454  	m := &newSessionTicketMsgTLS13{}
   455  	m.lifetime = uint32(rand.Intn(500000))
   456  	m.ageAdd = uint32(rand.Intn(500000))
   457  	m.nonce = randomBytes(rand.Intn(100), rand)
   458  	m.label = randomBytes(rand.Intn(1000), rand)
   459  	if rand.Intn(10) > 5 {
   460  		m.maxEarlyData = uint32(rand.Intn(500000))
   461  	}
   462  	return reflect.ValueOf(m)
   463  }
   464  
   465  func (*certificateRequestMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
   466  	m := &certificateRequestMsgTLS13{}
   467  	if rand.Intn(10) > 5 {
   468  		m.ocspStapling = true
   469  	}
   470  	if rand.Intn(10) > 5 {
   471  		m.scts = true
   472  	}
   473  	if rand.Intn(10) > 5 {
   474  		m.supportedSignatureAlgorithms = supportedSignatureAlgorithms(VersionTLS12, VersionTLS13)
   475  	}
   476  	if rand.Intn(10) > 5 {
   477  		m.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithms(VersionTLS12, VersionTLS13)
   478  	}
   479  	if rand.Intn(10) > 5 {
   480  		m.certificateAuthorities = make([][]byte, 3)
   481  		for i := 0; i < 3; i++ {
   482  			m.certificateAuthorities[i] = randomBytes(rand.Intn(10)+1, rand)
   483  		}
   484  	}
   485  	return reflect.ValueOf(m)
   486  }
   487  
   488  func (*certificateMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
   489  	m := &certificateMsgTLS13{}
   490  	for i := 0; i < rand.Intn(2)+1; i++ {
   491  		m.certificate.Certificate = append(
   492  			m.certificate.Certificate, randomBytes(rand.Intn(500)+1, rand))
   493  	}
   494  	if rand.Intn(10) > 5 {
   495  		m.ocspStapling = true
   496  		m.certificate.OCSPStaple = randomBytes(rand.Intn(100)+1, rand)
   497  	}
   498  	if rand.Intn(10) > 5 {
   499  		m.scts = true
   500  		for i := 0; i < rand.Intn(2)+1; i++ {
   501  			m.certificate.SignedCertificateTimestamps = append(
   502  				m.certificate.SignedCertificateTimestamps, randomBytes(rand.Intn(500)+1, rand))
   503  		}
   504  	}
   505  	return reflect.ValueOf(m)
   506  }
   507  
   508  func TestRejectEmptySCTList(t *testing.T) {
   509  	// RFC 6962, Section 3.3.1 specifies that empty SCT lists are invalid.
   510  
   511  	var random [32]byte
   512  	sct := []byte{0x42, 0x42, 0x42, 0x42}
   513  	serverHello := &serverHelloMsg{
   514  		vers:   VersionTLS12,
   515  		random: random[:],
   516  		scts:   [][]byte{sct},
   517  	}
   518  	serverHelloBytes := mustMarshal(t, serverHello)
   519  
   520  	var serverHelloCopy serverHelloMsg
   521  	if !serverHelloCopy.unmarshal(serverHelloBytes) {
   522  		t.Fatal("Failed to unmarshal initial message")
   523  	}
   524  
   525  	// Change serverHelloBytes so that the SCT list is empty
   526  	i := bytes.Index(serverHelloBytes, sct)
   527  	if i < 0 {
   528  		t.Fatal("Cannot find SCT in ServerHello")
   529  	}
   530  
   531  	var serverHelloEmptySCT []byte
   532  	serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[:i-6]...)
   533  	// Append the extension length and SCT list length for an empty list.
   534  	serverHelloEmptySCT = append(serverHelloEmptySCT, []byte{0, 2, 0, 0}...)
   535  	serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[i+4:]...)
   536  
   537  	// Update the handshake message length.
   538  	serverHelloEmptySCT[1] = byte((len(serverHelloEmptySCT) - 4) >> 16)
   539  	serverHelloEmptySCT[2] = byte((len(serverHelloEmptySCT) - 4) >> 8)
   540  	serverHelloEmptySCT[3] = byte(len(serverHelloEmptySCT) - 4)
   541  
   542  	// Update the extensions length
   543  	serverHelloEmptySCT[42] = byte((len(serverHelloEmptySCT) - 44) >> 8)
   544  	serverHelloEmptySCT[43] = byte((len(serverHelloEmptySCT) - 44))
   545  
   546  	if serverHelloCopy.unmarshal(serverHelloEmptySCT) {
   547  		t.Fatal("Unmarshaled ServerHello with empty SCT list")
   548  	}
   549  }
   550  
   551  func TestRejectEmptySCT(t *testing.T) {
   552  	// Not only must the SCT list be non-empty, but the SCT elements must
   553  	// not be zero length.
   554  
   555  	var random [32]byte
   556  	serverHello := &serverHelloMsg{
   557  		vers:   VersionTLS12,
   558  		random: random[:],
   559  		scts:   [][]byte{nil},
   560  	}
   561  	serverHelloBytes := mustMarshal(t, serverHello)
   562  
   563  	var serverHelloCopy serverHelloMsg
   564  	if serverHelloCopy.unmarshal(serverHelloBytes) {
   565  		t.Fatal("Unmarshaled ServerHello with zero-length SCT")
   566  	}
   567  }
   568  
   569  func TestRejectDuplicateExtensions(t *testing.T) {
   570  	clientHelloBytes, err := hex.DecodeString("010000440303000000000000000000000000000000000000000000000000000000000000000000000000001c0000000a000800000568656c6c6f0000000a000800000568656c6c6f")
   571  	if err != nil {
   572  		t.Fatalf("failed to decode test ClientHello: %s", err)
   573  	}
   574  	var clientHelloCopy clientHelloMsg
   575  	if clientHelloCopy.unmarshal(clientHelloBytes) {
   576  		t.Error("Unmarshaled ClientHello with duplicate extensions")
   577  	}
   578  
   579  	serverHelloBytes, err := hex.DecodeString("02000030030300000000000000000000000000000000000000000000000000000000000000000000000000080005000000050000")
   580  	if err != nil {
   581  		t.Fatalf("failed to decode test ServerHello: %s", err)
   582  	}
   583  	var serverHelloCopy serverHelloMsg
   584  	if serverHelloCopy.unmarshal(serverHelloBytes) {
   585  		t.Fatal("Unmarshaled ServerHello with duplicate extensions")
   586  	}
   587  }
   588  
   589  func TestECHRemoveOuterPSK(t *testing.T) {
   590  	r := rand.New(rand.NewSource(0))
   591  
   592  	for _, tc := range []struct {
   593  		name          string
   594  		echInner      bool
   595  		echExt        []byte
   596  		expectRemoved bool
   597  	}{
   598  		{
   599  			name:          "echInner true",
   600  			echInner:      true,
   601  			expectRemoved: false,
   602  		},
   603  		{
   604  			name:          "echInner true, no ech ext",
   605  			echInner:      true,
   606  			expectRemoved: false,
   607  		},
   608  		{
   609  			name:          "echInner true, ech ext present",
   610  			echInner:      true,
   611  			echExt:        []byte{254},
   612  			expectRemoved: false,
   613  		},
   614  		{
   615  			name:          "echInner true, ech ext present, inner ech sentinel",
   616  			echInner:      true,
   617  			echExt:        []byte{byte(innerECHExt)},
   618  			expectRemoved: false,
   619  		},
   620  		{
   621  			name:          "echInner false, no ech ext",
   622  			echInner:      false,
   623  			expectRemoved: false,
   624  		},
   625  		{
   626  			name:          "echInner false, ech ext present",
   627  			echInner:      false,
   628  			echExt:        []byte{254},
   629  			expectRemoved: true,
   630  		},
   631  		{
   632  			name:          "echInner false, ech ext present, inner ech sentinel",
   633  			echInner:      false,
   634  			echExt:        []byte{byte(innerECHExt)},
   635  			expectRemoved: false,
   636  		},
   637  	} {
   638  		t.Run(tc.name, func(t *testing.T) {
   639  			ch := (&clientHelloMsg{}).Generate(r, 0).Interface().(*clientHelloMsg)
   640  
   641  			ch.pskBinders = [][]byte{[]byte("test")}
   642  			ch.pskIdentities = []pskIdentity{{label: []byte("test")}}
   643  			ch.encryptedClientHello = tc.echExt
   644  
   645  			b, err := ch.marshalMsg(tc.echInner)
   646  			if err != nil {
   647  				t.Fatal(err)
   648  			}
   649  			var rch clientHelloMsg
   650  			if !rch.unmarshal(b) {
   651  				t.Fatal("Failed to unmarshal ClientHello")
   652  			}
   653  
   654  			if tc.expectRemoved {
   655  				if rch.pskIdentities != nil {
   656  					t.Error("expected PSK identities to be removed")
   657  				}
   658  				if rch.pskBinders != nil {
   659  					t.Error("expected PSK binders to be removed")
   660  				}
   661  			} else {
   662  				if rch.pskIdentities == nil {
   663  					t.Error("expected PSK identities to be present")
   664  				}
   665  				if rch.pskBinders == nil {
   666  					t.Error("expected PSK binders to be present")
   667  				}
   668  			}
   669  		})
   670  	}
   671  
   672  }
   673  

View as plain text