]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_messages_test.go
85efacf4cb1bc800a58005eac26756904d2e8650
[gostls13.git] / 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
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                         m.marshal() // to fill any marshal cache in the message
75
76                         if m, ok := m.(*SessionState); ok {
77                                 m.activeCertHandles = nil
78                         }
79
80                         if !reflect.DeepEqual(m1, m) {
81                                 t.Errorf("#%d got:%#v want:%#v %x", i, m, m1, marshaled)
82                                 break
83                         }
84
85                         if i >= 3 {
86                                 // The first three message types (ClientHello,
87                                 // ServerHello and Finished) are allowed to
88                                 // have parsable prefixes because the extension
89                                 // data is optional and the length of the
90                                 // Finished varies across versions.
91                                 for j := 0; j < len(marshaled); j++ {
92                                         if m.unmarshal(marshaled[0:j]) {
93                                                 t.Errorf("#%d unmarshaled a prefix of length %d of %#v", i, j, m1)
94                                                 break
95                                         }
96                                 }
97                         }
98                 }
99         }
100 }
101
102 func TestFuzz(t *testing.T) {
103         rand := rand.New(rand.NewSource(0))
104         for _, m := range tests {
105                 for j := 0; j < 1000; j++ {
106                         len := rand.Intn(1000)
107                         bytes := randomBytes(len, rand)
108                         // This just looks for crashes due to bounds errors etc.
109                         m.unmarshal(bytes)
110                 }
111         }
112 }
113
114 func randomBytes(n int, rand *rand.Rand) []byte {
115         r := make([]byte, n)
116         if _, err := rand.Read(r); err != nil {
117                 panic("rand.Read failed: " + err.Error())
118         }
119         return r
120 }
121
122 func randomString(n int, rand *rand.Rand) string {
123         b := randomBytes(n, rand)
124         return string(b)
125 }
126
127 func (*clientHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
128         m := &clientHelloMsg{}
129         m.vers = uint16(rand.Intn(65536))
130         m.random = randomBytes(32, rand)
131         m.sessionId = randomBytes(rand.Intn(32), rand)
132         m.cipherSuites = make([]uint16, rand.Intn(63)+1)
133         for i := 0; i < len(m.cipherSuites); i++ {
134                 cs := uint16(rand.Int31())
135                 if cs == scsvRenegotiation {
136                         cs += 1
137                 }
138                 m.cipherSuites[i] = cs
139         }
140         m.compressionMethods = randomBytes(rand.Intn(63)+1, rand)
141         if rand.Intn(10) > 5 {
142                 m.serverName = randomString(rand.Intn(255), rand)
143                 for strings.HasSuffix(m.serverName, ".") {
144                         m.serverName = m.serverName[:len(m.serverName)-1]
145                 }
146         }
147         m.ocspStapling = rand.Intn(10) > 5
148         m.supportedPoints = randomBytes(rand.Intn(5)+1, rand)
149         m.supportedCurves = make([]CurveID, rand.Intn(5)+1)
150         for i := range m.supportedCurves {
151                 m.supportedCurves[i] = CurveID(rand.Intn(30000) + 1)
152         }
153         if rand.Intn(10) > 5 {
154                 m.ticketSupported = true
155                 if rand.Intn(10) > 5 {
156                         m.sessionTicket = randomBytes(rand.Intn(300), rand)
157                 } else {
158                         m.sessionTicket = make([]byte, 0)
159                 }
160         }
161         if rand.Intn(10) > 5 {
162                 m.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
163         }
164         if rand.Intn(10) > 5 {
165                 m.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithms()
166         }
167         for i := 0; i < rand.Intn(5); i++ {
168                 m.alpnProtocols = append(m.alpnProtocols, randomString(rand.Intn(20)+1, rand))
169         }
170         if rand.Intn(10) > 5 {
171                 m.scts = true
172         }
173         if rand.Intn(10) > 5 {
174                 m.secureRenegotiationSupported = true
175                 m.secureRenegotiation = randomBytes(rand.Intn(50)+1, rand)
176         }
177         for i := 0; i < rand.Intn(5); i++ {
178                 m.supportedVersions = append(m.supportedVersions, uint16(rand.Intn(0xffff)+1))
179         }
180         if rand.Intn(10) > 5 {
181                 m.cookie = randomBytes(rand.Intn(500)+1, rand)
182         }
183         for i := 0; i < rand.Intn(5); i++ {
184                 var ks keyShare
185                 ks.group = CurveID(rand.Intn(30000) + 1)
186                 ks.data = randomBytes(rand.Intn(200)+1, rand)
187                 m.keyShares = append(m.keyShares, ks)
188         }
189         switch rand.Intn(3) {
190         case 1:
191                 m.pskModes = []uint8{pskModeDHE}
192         case 2:
193                 m.pskModes = []uint8{pskModeDHE, pskModePlain}
194         }
195         for i := 0; i < rand.Intn(5); i++ {
196                 var psk pskIdentity
197                 psk.obfuscatedTicketAge = uint32(rand.Intn(500000))
198                 psk.label = randomBytes(rand.Intn(500)+1, rand)
199                 m.pskIdentities = append(m.pskIdentities, psk)
200                 m.pskBinders = append(m.pskBinders, randomBytes(rand.Intn(50)+32, rand))
201         }
202         if rand.Intn(10) > 5 {
203                 m.quicTransportParameters = randomBytes(rand.Intn(500), rand)
204         }
205         if rand.Intn(10) > 5 {
206                 m.earlyData = true
207         }
208
209         return reflect.ValueOf(m)
210 }
211
212 func (*serverHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
213         m := &serverHelloMsg{}
214         m.vers = uint16(rand.Intn(65536))
215         m.random = randomBytes(32, rand)
216         m.sessionId = randomBytes(rand.Intn(32), rand)
217         m.cipherSuite = uint16(rand.Int31())
218         m.compressionMethod = uint8(rand.Intn(256))
219         m.supportedPoints = randomBytes(rand.Intn(5)+1, rand)
220
221         if rand.Intn(10) > 5 {
222                 m.ocspStapling = true
223         }
224         if rand.Intn(10) > 5 {
225                 m.ticketSupported = true
226         }
227         if rand.Intn(10) > 5 {
228                 m.alpnProtocol = randomString(rand.Intn(32)+1, rand)
229         }
230
231         for i := 0; i < rand.Intn(4); i++ {
232                 m.scts = append(m.scts, randomBytes(rand.Intn(500)+1, rand))
233         }
234
235         if rand.Intn(10) > 5 {
236                 m.secureRenegotiationSupported = true
237                 m.secureRenegotiation = randomBytes(rand.Intn(50)+1, rand)
238         }
239         if rand.Intn(10) > 5 {
240                 m.supportedVersion = uint16(rand.Intn(0xffff) + 1)
241         }
242         if rand.Intn(10) > 5 {
243                 m.cookie = randomBytes(rand.Intn(500)+1, rand)
244         }
245         if rand.Intn(10) > 5 {
246                 for i := 0; i < rand.Intn(5); i++ {
247                         m.serverShare.group = CurveID(rand.Intn(30000) + 1)
248                         m.serverShare.data = randomBytes(rand.Intn(200)+1, rand)
249                 }
250         } else if rand.Intn(10) > 5 {
251                 m.selectedGroup = CurveID(rand.Intn(30000) + 1)
252         }
253         if rand.Intn(10) > 5 {
254                 m.selectedIdentityPresent = true
255                 m.selectedIdentity = uint16(rand.Intn(0xffff))
256         }
257
258         return reflect.ValueOf(m)
259 }
260
261 func (*encryptedExtensionsMsg) Generate(rand *rand.Rand, size int) reflect.Value {
262         m := &encryptedExtensionsMsg{}
263
264         if rand.Intn(10) > 5 {
265                 m.alpnProtocol = randomString(rand.Intn(32)+1, rand)
266         }
267
268         return reflect.ValueOf(m)
269 }
270
271 func (*certificateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
272         m := &certificateMsg{}
273         numCerts := rand.Intn(20)
274         m.certificates = make([][]byte, numCerts)
275         for i := 0; i < numCerts; i++ {
276                 m.certificates[i] = randomBytes(rand.Intn(10)+1, rand)
277         }
278         return reflect.ValueOf(m)
279 }
280
281 func (*certificateRequestMsg) Generate(rand *rand.Rand, size int) reflect.Value {
282         m := &certificateRequestMsg{}
283         m.certificateTypes = randomBytes(rand.Intn(5)+1, rand)
284         for i := 0; i < rand.Intn(100); i++ {
285                 m.certificateAuthorities = append(m.certificateAuthorities, randomBytes(rand.Intn(15)+1, rand))
286         }
287         return reflect.ValueOf(m)
288 }
289
290 func (*certificateVerifyMsg) Generate(rand *rand.Rand, size int) reflect.Value {
291         m := &certificateVerifyMsg{}
292         m.hasSignatureAlgorithm = true
293         m.signatureAlgorithm = SignatureScheme(rand.Intn(30000))
294         m.signature = randomBytes(rand.Intn(15)+1, rand)
295         return reflect.ValueOf(m)
296 }
297
298 func (*certificateStatusMsg) Generate(rand *rand.Rand, size int) reflect.Value {
299         m := &certificateStatusMsg{}
300         m.response = randomBytes(rand.Intn(10)+1, rand)
301         return reflect.ValueOf(m)
302 }
303
304 func (*clientKeyExchangeMsg) Generate(rand *rand.Rand, size int) reflect.Value {
305         m := &clientKeyExchangeMsg{}
306         m.ciphertext = randomBytes(rand.Intn(1000)+1, rand)
307         return reflect.ValueOf(m)
308 }
309
310 func (*finishedMsg) Generate(rand *rand.Rand, size int) reflect.Value {
311         m := &finishedMsg{}
312         m.verifyData = randomBytes(12, rand)
313         return reflect.ValueOf(m)
314 }
315
316 func (*newSessionTicketMsg) Generate(rand *rand.Rand, size int) reflect.Value {
317         m := &newSessionTicketMsg{}
318         m.ticket = randomBytes(rand.Intn(4), rand)
319         return reflect.ValueOf(m)
320 }
321
322 var sessionTestCerts []*x509.Certificate
323
324 func init() {
325         cert, err := x509.ParseCertificate(testRSACertificate)
326         if err != nil {
327                 panic(err)
328         }
329         sessionTestCerts = append(sessionTestCerts, cert)
330         cert, err = x509.ParseCertificate(testRSACertificateIssuer)
331         if err != nil {
332                 panic(err)
333         }
334         sessionTestCerts = append(sessionTestCerts, cert)
335 }
336
337 func (*SessionState) Generate(rand *rand.Rand, size int) reflect.Value {
338         s := &SessionState{}
339         isTLS13 := rand.Intn(10) > 5
340         if isTLS13 {
341                 s.version = VersionTLS13
342         } else {
343                 s.version = uint16(rand.Intn(VersionTLS13))
344         }
345         s.isClient = rand.Intn(10) > 5
346         s.cipherSuite = uint16(rand.Intn(math.MaxUint16))
347         s.createdAt = uint64(rand.Int63())
348         s.secret = randomBytes(rand.Intn(100)+1, rand)
349         if s.isClient || rand.Intn(10) > 5 {
350                 if rand.Intn(10) > 5 {
351                         s.peerCertificates = sessionTestCerts
352                 } else {
353                         s.peerCertificates = sessionTestCerts[:1]
354                 }
355         }
356         if rand.Intn(10) > 5 && s.peerCertificates != nil {
357                 s.ocspResponse = randomBytes(rand.Intn(100)+1, rand)
358         }
359         if rand.Intn(10) > 5 && s.peerCertificates != nil {
360                 for i := 0; i < rand.Intn(2)+1; i++ {
361                         s.scts = append(s.scts, randomBytes(rand.Intn(500)+1, rand))
362                 }
363         }
364         if s.isClient {
365                 for i := 0; i < rand.Intn(3); i++ {
366                         if rand.Intn(10) > 5 {
367                                 s.verifiedChains = append(s.verifiedChains, s.peerCertificates)
368                         } else {
369                                 s.verifiedChains = append(s.verifiedChains, s.peerCertificates[:1])
370                         }
371                 }
372                 if isTLS13 {
373                         s.useBy = uint64(rand.Int63())
374                         s.ageAdd = uint32(rand.Int63() & math.MaxUint32)
375                 }
376         }
377         return reflect.ValueOf(s)
378 }
379
380 func (s *SessionState) marshal() ([]byte, error) { return s.Bytes() }
381 func (s *SessionState) unmarshal(b []byte) bool {
382         ss, err := ParseSessionState(b)
383         if err != nil {
384                 return false
385         }
386         *s = *ss
387         return true
388 }
389
390 func (*endOfEarlyDataMsg) Generate(rand *rand.Rand, size int) reflect.Value {
391         m := &endOfEarlyDataMsg{}
392         return reflect.ValueOf(m)
393 }
394
395 func (*keyUpdateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
396         m := &keyUpdateMsg{}
397         m.updateRequested = rand.Intn(10) > 5
398         return reflect.ValueOf(m)
399 }
400
401 func (*newSessionTicketMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
402         m := &newSessionTicketMsgTLS13{}
403         m.lifetime = uint32(rand.Intn(500000))
404         m.ageAdd = uint32(rand.Intn(500000))
405         m.nonce = randomBytes(rand.Intn(100), rand)
406         m.label = randomBytes(rand.Intn(1000), rand)
407         if rand.Intn(10) > 5 {
408                 m.maxEarlyData = uint32(rand.Intn(500000))
409         }
410         return reflect.ValueOf(m)
411 }
412
413 func (*certificateRequestMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
414         m := &certificateRequestMsgTLS13{}
415         if rand.Intn(10) > 5 {
416                 m.ocspStapling = true
417         }
418         if rand.Intn(10) > 5 {
419                 m.scts = true
420         }
421         if rand.Intn(10) > 5 {
422                 m.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
423         }
424         if rand.Intn(10) > 5 {
425                 m.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithms()
426         }
427         if rand.Intn(10) > 5 {
428                 m.certificateAuthorities = make([][]byte, 3)
429                 for i := 0; i < 3; i++ {
430                         m.certificateAuthorities[i] = randomBytes(rand.Intn(10)+1, rand)
431                 }
432         }
433         return reflect.ValueOf(m)
434 }
435
436 func (*certificateMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
437         m := &certificateMsgTLS13{}
438         for i := 0; i < rand.Intn(2)+1; i++ {
439                 m.certificate.Certificate = append(
440                         m.certificate.Certificate, randomBytes(rand.Intn(500)+1, rand))
441         }
442         if rand.Intn(10) > 5 {
443                 m.ocspStapling = true
444                 m.certificate.OCSPStaple = randomBytes(rand.Intn(100)+1, rand)
445         }
446         if rand.Intn(10) > 5 {
447                 m.scts = true
448                 for i := 0; i < rand.Intn(2)+1; i++ {
449                         m.certificate.SignedCertificateTimestamps = append(
450                                 m.certificate.SignedCertificateTimestamps, randomBytes(rand.Intn(500)+1, rand))
451                 }
452         }
453         return reflect.ValueOf(m)
454 }
455
456 func TestRejectEmptySCTList(t *testing.T) {
457         // RFC 6962, Section 3.3.1 specifies that empty SCT lists are invalid.
458
459         var random [32]byte
460         sct := []byte{0x42, 0x42, 0x42, 0x42}
461         serverHello := &serverHelloMsg{
462                 vers:   VersionTLS12,
463                 random: random[:],
464                 scts:   [][]byte{sct},
465         }
466         serverHelloBytes := mustMarshal(t, serverHello)
467
468         var serverHelloCopy serverHelloMsg
469         if !serverHelloCopy.unmarshal(serverHelloBytes) {
470                 t.Fatal("Failed to unmarshal initial message")
471         }
472
473         // Change serverHelloBytes so that the SCT list is empty
474         i := bytes.Index(serverHelloBytes, sct)
475         if i < 0 {
476                 t.Fatal("Cannot find SCT in ServerHello")
477         }
478
479         var serverHelloEmptySCT []byte
480         serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[:i-6]...)
481         // Append the extension length and SCT list length for an empty list.
482         serverHelloEmptySCT = append(serverHelloEmptySCT, []byte{0, 2, 0, 0}...)
483         serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[i+4:]...)
484
485         // Update the handshake message length.
486         serverHelloEmptySCT[1] = byte((len(serverHelloEmptySCT) - 4) >> 16)
487         serverHelloEmptySCT[2] = byte((len(serverHelloEmptySCT) - 4) >> 8)
488         serverHelloEmptySCT[3] = byte(len(serverHelloEmptySCT) - 4)
489
490         // Update the extensions length
491         serverHelloEmptySCT[42] = byte((len(serverHelloEmptySCT) - 44) >> 8)
492         serverHelloEmptySCT[43] = byte((len(serverHelloEmptySCT) - 44))
493
494         if serverHelloCopy.unmarshal(serverHelloEmptySCT) {
495                 t.Fatal("Unmarshaled ServerHello with empty SCT list")
496         }
497 }
498
499 func TestRejectEmptySCT(t *testing.T) {
500         // Not only must the SCT list be non-empty, but the SCT elements must
501         // not be zero length.
502
503         var random [32]byte
504         serverHello := &serverHelloMsg{
505                 vers:   VersionTLS12,
506                 random: random[:],
507                 scts:   [][]byte{nil},
508         }
509         serverHelloBytes := mustMarshal(t, serverHello)
510
511         var serverHelloCopy serverHelloMsg
512         if serverHelloCopy.unmarshal(serverHelloBytes) {
513                 t.Fatal("Unmarshaled ServerHello with zero-length SCT")
514         }
515 }
516
517 func TestRejectDuplicateExtensions(t *testing.T) {
518         clientHelloBytes, err := hex.DecodeString("010000440303000000000000000000000000000000000000000000000000000000000000000000000000001c0000000a000800000568656c6c6f0000000a000800000568656c6c6f")
519         if err != nil {
520                 t.Fatalf("failed to decode test ClientHello: %s", err)
521         }
522         var clientHelloCopy clientHelloMsg
523         if clientHelloCopy.unmarshal(clientHelloBytes) {
524                 t.Error("Unmarshaled ClientHello with duplicate extensions")
525         }
526
527         serverHelloBytes, err := hex.DecodeString("02000030030300000000000000000000000000000000000000000000000000000000000000000000000000080005000000050000")
528         if err != nil {
529                 t.Fatalf("failed to decode test ServerHello: %s", err)
530         }
531         var serverHelloCopy serverHelloMsg
532         if serverHelloCopy.unmarshal(serverHelloBytes) {
533                 t.Fatal("Unmarshaled ServerHello with duplicate extensions")
534         }
535 }