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)
   183  	}
   184  	if rand.Intn(10) > 5 {
   185  		m.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithms(VersionTLS12)
   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  	cert, err := x509.ParseCertificate(testRSACertificate)
   370  	if err != nil {
   371  		panic(err)
   372  	}
   373  	sessionTestCerts = append(sessionTestCerts, cert)
   374  	cert, err = x509.ParseCertificate(testRSACertificateIssuer)
   375  	if err != nil {
   376  		panic(err)
   377  	}
   378  	sessionTestCerts = append(sessionTestCerts, cert)
   379  }
   380  
   381  func (*SessionState) Generate(rand *rand.Rand, size int) reflect.Value {
   382  	s := &SessionState{}
   383  	isTLS13 := rand.Intn(10) > 5
   384  	if isTLS13 {
   385  		s.version = VersionTLS13
   386  	} else {
   387  		s.version = uint16(rand.Intn(VersionTLS13))
   388  	}
   389  	s.isClient = rand.Intn(10) > 5
   390  	s.cipherSuite = uint16(rand.Intn(math.MaxUint16))
   391  	s.createdAt = uint64(rand.Int63())
   392  	s.secret = randomBytes(rand.Intn(100)+1, rand)
   393  	for n, i := rand.Intn(3), 0; i < n; i++ {
   394  		s.Extra = append(s.Extra, randomBytes(rand.Intn(100), rand))
   395  	}
   396  	if rand.Intn(10) > 5 {
   397  		s.EarlyData = true
   398  	}
   399  	if rand.Intn(10) > 5 {
   400  		s.extMasterSecret = true
   401  	}
   402  	if s.isClient || rand.Intn(10) > 5 {
   403  		if rand.Intn(10) > 5 {
   404  			s.peerCertificates = sessionTestCerts
   405  		} else {
   406  			s.peerCertificates = sessionTestCerts[:1]
   407  		}
   408  	}
   409  	if rand.Intn(10) > 5 && s.peerCertificates != nil {
   410  		s.ocspResponse = randomBytes(rand.Intn(100)+1, rand)
   411  	}
   412  	if rand.Intn(10) > 5 && s.peerCertificates != nil {
   413  		for i := 0; i < rand.Intn(2)+1; i++ {
   414  			s.scts = append(s.scts, randomBytes(rand.Intn(500)+1, rand))
   415  		}
   416  	}
   417  	if len(s.peerCertificates) > 0 {
   418  		for i := 0; i < rand.Intn(3); i++ {
   419  			if rand.Intn(10) > 5 {
   420  				s.verifiedChains = append(s.verifiedChains, s.peerCertificates)
   421  			} else {
   422  				s.verifiedChains = append(s.verifiedChains, s.peerCertificates[:1])
   423  			}
   424  		}
   425  	}
   426  	if rand.Intn(10) > 5 && s.EarlyData {
   427  		s.alpnProtocol = string(randomBytes(rand.Intn(10), rand))
   428  	}
   429  	if isTLS13 {
   430  		if s.isClient {
   431  			s.useBy = uint64(rand.Int63())
   432  			s.ageAdd = uint32(rand.Int63() & math.MaxUint32)
   433  		}
   434  	} else {
   435  		s.curveID = CurveID(rand.Intn(30000) + 1)
   436  	}
   437  	return reflect.ValueOf(s)
   438  }
   439  
   440  func (s *SessionState) marshal() ([]byte, error) { return s.Bytes() }
   441  func (s *SessionState) unmarshal(b []byte) bool {
   442  	ss, err := ParseSessionState(b)
   443  	if err != nil {
   444  		return false
   445  	}
   446  	*s = *ss
   447  	return true
   448  }
   449  
   450  func (*endOfEarlyDataMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   451  	m := &endOfEarlyDataMsg{}
   452  	return reflect.ValueOf(m)
   453  }
   454  
   455  func (*keyUpdateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
   456  	m := &keyUpdateMsg{}
   457  	m.updateRequested = rand.Intn(10) > 5
   458  	return reflect.ValueOf(m)
   459  }
   460  
   461  func (*newSessionTicketMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
   462  	m := &newSessionTicketMsgTLS13{}
   463  	m.lifetime = uint32(rand.Intn(500000))
   464  	m.ageAdd = uint32(rand.Intn(500000))
   465  	m.nonce = randomBytes(rand.Intn(100), rand)
   466  	m.label = randomBytes(rand.Intn(1000), rand)
   467  	if rand.Intn(10) > 5 {
   468  		m.maxEarlyData = uint32(rand.Intn(500000))
   469  	}
   470  	return reflect.ValueOf(m)
   471  }
   472  
   473  func (*certificateRequestMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
   474  	m := &certificateRequestMsgTLS13{}
   475  	if rand.Intn(10) > 5 {
   476  		m.ocspStapling = true
   477  	}
   478  	if rand.Intn(10) > 5 {
   479  		m.scts = true
   480  	}
   481  	if rand.Intn(10) > 5 {
   482  		m.supportedSignatureAlgorithms = supportedSignatureAlgorithms(VersionTLS12)
   483  	}
   484  	if rand.Intn(10) > 5 {
   485  		m.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithms(VersionTLS12)
   486  	}
   487  	if rand.Intn(10) > 5 {
   488  		m.certificateAuthorities = make([][]byte, 3)
   489  		for i := 0; i < 3; i++ {
   490  			m.certificateAuthorities[i] = randomBytes(rand.Intn(10)+1, rand)
   491  		}
   492  	}
   493  	return reflect.ValueOf(m)
   494  }
   495  
   496  func (*certificateMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
   497  	m := &certificateMsgTLS13{}
   498  	for i := 0; i < rand.Intn(2)+1; i++ {
   499  		m.certificate.Certificate = append(
   500  			m.certificate.Certificate, randomBytes(rand.Intn(500)+1, rand))
   501  	}
   502  	if rand.Intn(10) > 5 {
   503  		m.ocspStapling = true
   504  		m.certificate.OCSPStaple = randomBytes(rand.Intn(100)+1, rand)
   505  	}
   506  	if rand.Intn(10) > 5 {
   507  		m.scts = true
   508  		for i := 0; i < rand.Intn(2)+1; i++ {
   509  			m.certificate.SignedCertificateTimestamps = append(
   510  				m.certificate.SignedCertificateTimestamps, randomBytes(rand.Intn(500)+1, rand))
   511  		}
   512  	}
   513  	return reflect.ValueOf(m)
   514  }
   515  
   516  func TestRejectEmptySCTList(t *testing.T) {
   517  	// RFC 6962, Section 3.3.1 specifies that empty SCT lists are invalid.
   518  
   519  	var random [32]byte
   520  	sct := []byte{0x42, 0x42, 0x42, 0x42}
   521  	serverHello := &serverHelloMsg{
   522  		vers:   VersionTLS12,
   523  		random: random[:],
   524  		scts:   [][]byte{sct},
   525  	}
   526  	serverHelloBytes := mustMarshal(t, serverHello)
   527  
   528  	var serverHelloCopy serverHelloMsg
   529  	if !serverHelloCopy.unmarshal(serverHelloBytes) {
   530  		t.Fatal("Failed to unmarshal initial message")
   531  	}
   532  
   533  	// Change serverHelloBytes so that the SCT list is empty
   534  	i := bytes.Index(serverHelloBytes, sct)
   535  	if i < 0 {
   536  		t.Fatal("Cannot find SCT in ServerHello")
   537  	}
   538  
   539  	var serverHelloEmptySCT []byte
   540  	serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[:i-6]...)
   541  	// Append the extension length and SCT list length for an empty list.
   542  	serverHelloEmptySCT = append(serverHelloEmptySCT, []byte{0, 2, 0, 0}...)
   543  	serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[i+4:]...)
   544  
   545  	// Update the handshake message length.
   546  	serverHelloEmptySCT[1] = byte((len(serverHelloEmptySCT) - 4) >> 16)
   547  	serverHelloEmptySCT[2] = byte((len(serverHelloEmptySCT) - 4) >> 8)
   548  	serverHelloEmptySCT[3] = byte(len(serverHelloEmptySCT) - 4)
   549  
   550  	// Update the extensions length
   551  	serverHelloEmptySCT[42] = byte((len(serverHelloEmptySCT) - 44) >> 8)
   552  	serverHelloEmptySCT[43] = byte((len(serverHelloEmptySCT) - 44))
   553  
   554  	if serverHelloCopy.unmarshal(serverHelloEmptySCT) {
   555  		t.Fatal("Unmarshaled ServerHello with empty SCT list")
   556  	}
   557  }
   558  
   559  func TestRejectEmptySCT(t *testing.T) {
   560  	// Not only must the SCT list be non-empty, but the SCT elements must
   561  	// not be zero length.
   562  
   563  	var random [32]byte
   564  	serverHello := &serverHelloMsg{
   565  		vers:   VersionTLS12,
   566  		random: random[:],
   567  		scts:   [][]byte{nil},
   568  	}
   569  	serverHelloBytes := mustMarshal(t, serverHello)
   570  
   571  	var serverHelloCopy serverHelloMsg
   572  	if serverHelloCopy.unmarshal(serverHelloBytes) {
   573  		t.Fatal("Unmarshaled ServerHello with zero-length SCT")
   574  	}
   575  }
   576  
   577  func TestRejectDuplicateExtensions(t *testing.T) {
   578  	clientHelloBytes, err := hex.DecodeString("010000440303000000000000000000000000000000000000000000000000000000000000000000000000001c0000000a000800000568656c6c6f0000000a000800000568656c6c6f")
   579  	if err != nil {
   580  		t.Fatalf("failed to decode test ClientHello: %s", err)
   581  	}
   582  	var clientHelloCopy clientHelloMsg
   583  	if clientHelloCopy.unmarshal(clientHelloBytes) {
   584  		t.Error("Unmarshaled ClientHello with duplicate extensions")
   585  	}
   586  
   587  	serverHelloBytes, err := hex.DecodeString("02000030030300000000000000000000000000000000000000000000000000000000000000000000000000080005000000050000")
   588  	if err != nil {
   589  		t.Fatalf("failed to decode test ServerHello: %s", err)
   590  	}
   591  	var serverHelloCopy serverHelloMsg
   592  	if serverHelloCopy.unmarshal(serverHelloBytes) {
   593  		t.Fatal("Unmarshaled ServerHello with duplicate extensions")
   594  	}
   595  }
   596  
   597  func TestECHRemoveOuterPSK(t *testing.T) {
   598  	r := rand.New(rand.NewSource(0))
   599  
   600  	for _, tc := range []struct {
   601  		name          string
   602  		echInner      bool
   603  		echExt        []byte
   604  		expectRemoved bool
   605  	}{
   606  		{
   607  			name:          "echInner true",
   608  			echInner:      true,
   609  			expectRemoved: false,
   610  		},
   611  		{
   612  			name:          "echInner true, no ech ext",
   613  			echInner:      true,
   614  			expectRemoved: false,
   615  		},
   616  		{
   617  			name:          "echInner true, ech ext present",
   618  			echInner:      true,
   619  			echExt:        []byte{254},
   620  			expectRemoved: false,
   621  		},
   622  		{
   623  			name:          "echInner true, ech ext present, inner ech sentinel",
   624  			echInner:      true,
   625  			echExt:        []byte{byte(innerECHExt)},
   626  			expectRemoved: false,
   627  		},
   628  		{
   629  			name:          "echInner false, no ech ext",
   630  			echInner:      false,
   631  			expectRemoved: false,
   632  		},
   633  		{
   634  			name:          "echInner false, ech ext present",
   635  			echInner:      false,
   636  			echExt:        []byte{254},
   637  			expectRemoved: true,
   638  		},
   639  		{
   640  			name:          "echInner false, ech ext present, inner ech sentinel",
   641  			echInner:      false,
   642  			echExt:        []byte{byte(innerECHExt)},
   643  			expectRemoved: false,
   644  		},
   645  	} {
   646  		t.Run(tc.name, func(t *testing.T) {
   647  			ch := (&clientHelloMsg{}).Generate(r, 0).Interface().(*clientHelloMsg)
   648  
   649  			ch.pskBinders = [][]byte{[]byte("test")}
   650  			ch.pskIdentities = []pskIdentity{{label: []byte("test")}}
   651  			ch.encryptedClientHello = tc.echExt
   652  
   653  			b, err := ch.marshalMsg(tc.echInner)
   654  			if err != nil {
   655  				t.Fatal(err)
   656  			}
   657  			var rch clientHelloMsg
   658  			if !rch.unmarshal(b) {
   659  				t.Fatal("Failed to unmarshal ClientHello")
   660  			}
   661  
   662  			if tc.expectRemoved {
   663  				if rch.pskIdentities != nil {
   664  					t.Error("expected PSK identities to be removed")
   665  				}
   666  				if rch.pskBinders != nil {
   667  					t.Error("expected PSK binders to be removed")
   668  				}
   669  			} else {
   670  				if rch.pskIdentities == nil {
   671  					t.Error("expected PSK identities to be present")
   672  				}
   673  				if rch.pskBinders == nil {
   674  					t.Error("expected PSK binders to be present")
   675  				}
   676  			}
   677  		})
   678  	}
   679  
   680  }
   681  

View as plain text