]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_messages_test.go
crypto/tls: add SessionState.Extra
[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         s.Extra = randomBytes(rand.Intn(100), rand)
350         if s.isClient || rand.Intn(10) > 5 {
351                 if rand.Intn(10) > 5 {
352                         s.peerCertificates = sessionTestCerts
353                 } else {
354                         s.peerCertificates = sessionTestCerts[:1]
355                 }
356         }
357         if rand.Intn(10) > 5 && s.peerCertificates != nil {
358                 s.ocspResponse = randomBytes(rand.Intn(100)+1, rand)
359         }
360         if rand.Intn(10) > 5 && s.peerCertificates != nil {
361                 for i := 0; i < rand.Intn(2)+1; i++ {
362                         s.scts = append(s.scts, randomBytes(rand.Intn(500)+1, rand))
363                 }
364         }
365         if s.isClient {
366                 for i := 0; i < rand.Intn(3); i++ {
367                         if rand.Intn(10) > 5 {
368                                 s.verifiedChains = append(s.verifiedChains, s.peerCertificates)
369                         } else {
370                                 s.verifiedChains = append(s.verifiedChains, s.peerCertificates[:1])
371                         }
372                 }
373                 if isTLS13 {
374                         s.useBy = uint64(rand.Int63())
375                         s.ageAdd = uint32(rand.Int63() & math.MaxUint32)
376                 }
377         }
378         return reflect.ValueOf(s)
379 }
380
381 func (s *SessionState) marshal() ([]byte, error) { return s.Bytes() }
382 func (s *SessionState) unmarshal(b []byte) bool {
383         ss, err := ParseSessionState(b)
384         if err != nil {
385                 return false
386         }
387         *s = *ss
388         return true
389 }
390
391 func (*endOfEarlyDataMsg) Generate(rand *rand.Rand, size int) reflect.Value {
392         m := &endOfEarlyDataMsg{}
393         return reflect.ValueOf(m)
394 }
395
396 func (*keyUpdateMsg) Generate(rand *rand.Rand, size int) reflect.Value {
397         m := &keyUpdateMsg{}
398         m.updateRequested = rand.Intn(10) > 5
399         return reflect.ValueOf(m)
400 }
401
402 func (*newSessionTicketMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
403         m := &newSessionTicketMsgTLS13{}
404         m.lifetime = uint32(rand.Intn(500000))
405         m.ageAdd = uint32(rand.Intn(500000))
406         m.nonce = randomBytes(rand.Intn(100), rand)
407         m.label = randomBytes(rand.Intn(1000), rand)
408         if rand.Intn(10) > 5 {
409                 m.maxEarlyData = uint32(rand.Intn(500000))
410         }
411         return reflect.ValueOf(m)
412 }
413
414 func (*certificateRequestMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
415         m := &certificateRequestMsgTLS13{}
416         if rand.Intn(10) > 5 {
417                 m.ocspStapling = true
418         }
419         if rand.Intn(10) > 5 {
420                 m.scts = true
421         }
422         if rand.Intn(10) > 5 {
423                 m.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
424         }
425         if rand.Intn(10) > 5 {
426                 m.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithms()
427         }
428         if rand.Intn(10) > 5 {
429                 m.certificateAuthorities = make([][]byte, 3)
430                 for i := 0; i < 3; i++ {
431                         m.certificateAuthorities[i] = randomBytes(rand.Intn(10)+1, rand)
432                 }
433         }
434         return reflect.ValueOf(m)
435 }
436
437 func (*certificateMsgTLS13) Generate(rand *rand.Rand, size int) reflect.Value {
438         m := &certificateMsgTLS13{}
439         for i := 0; i < rand.Intn(2)+1; i++ {
440                 m.certificate.Certificate = append(
441                         m.certificate.Certificate, randomBytes(rand.Intn(500)+1, rand))
442         }
443         if rand.Intn(10) > 5 {
444                 m.ocspStapling = true
445                 m.certificate.OCSPStaple = randomBytes(rand.Intn(100)+1, rand)
446         }
447         if rand.Intn(10) > 5 {
448                 m.scts = true
449                 for i := 0; i < rand.Intn(2)+1; i++ {
450                         m.certificate.SignedCertificateTimestamps = append(
451                                 m.certificate.SignedCertificateTimestamps, randomBytes(rand.Intn(500)+1, rand))
452                 }
453         }
454         return reflect.ValueOf(m)
455 }
456
457 func TestRejectEmptySCTList(t *testing.T) {
458         // RFC 6962, Section 3.3.1 specifies that empty SCT lists are invalid.
459
460         var random [32]byte
461         sct := []byte{0x42, 0x42, 0x42, 0x42}
462         serverHello := &serverHelloMsg{
463                 vers:   VersionTLS12,
464                 random: random[:],
465                 scts:   [][]byte{sct},
466         }
467         serverHelloBytes := mustMarshal(t, serverHello)
468
469         var serverHelloCopy serverHelloMsg
470         if !serverHelloCopy.unmarshal(serverHelloBytes) {
471                 t.Fatal("Failed to unmarshal initial message")
472         }
473
474         // Change serverHelloBytes so that the SCT list is empty
475         i := bytes.Index(serverHelloBytes, sct)
476         if i < 0 {
477                 t.Fatal("Cannot find SCT in ServerHello")
478         }
479
480         var serverHelloEmptySCT []byte
481         serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[:i-6]...)
482         // Append the extension length and SCT list length for an empty list.
483         serverHelloEmptySCT = append(serverHelloEmptySCT, []byte{0, 2, 0, 0}...)
484         serverHelloEmptySCT = append(serverHelloEmptySCT, serverHelloBytes[i+4:]...)
485
486         // Update the handshake message length.
487         serverHelloEmptySCT[1] = byte((len(serverHelloEmptySCT) - 4) >> 16)
488         serverHelloEmptySCT[2] = byte((len(serverHelloEmptySCT) - 4) >> 8)
489         serverHelloEmptySCT[3] = byte(len(serverHelloEmptySCT) - 4)
490
491         // Update the extensions length
492         serverHelloEmptySCT[42] = byte((len(serverHelloEmptySCT) - 44) >> 8)
493         serverHelloEmptySCT[43] = byte((len(serverHelloEmptySCT) - 44))
494
495         if serverHelloCopy.unmarshal(serverHelloEmptySCT) {
496                 t.Fatal("Unmarshaled ServerHello with empty SCT list")
497         }
498 }
499
500 func TestRejectEmptySCT(t *testing.T) {
501         // Not only must the SCT list be non-empty, but the SCT elements must
502         // not be zero length.
503
504         var random [32]byte
505         serverHello := &serverHelloMsg{
506                 vers:   VersionTLS12,
507                 random: random[:],
508                 scts:   [][]byte{nil},
509         }
510         serverHelloBytes := mustMarshal(t, serverHello)
511
512         var serverHelloCopy serverHelloMsg
513         if serverHelloCopy.unmarshal(serverHelloBytes) {
514                 t.Fatal("Unmarshaled ServerHello with zero-length SCT")
515         }
516 }
517
518 func TestRejectDuplicateExtensions(t *testing.T) {
519         clientHelloBytes, err := hex.DecodeString("010000440303000000000000000000000000000000000000000000000000000000000000000000000000001c0000000a000800000568656c6c6f0000000a000800000568656c6c6f")
520         if err != nil {
521                 t.Fatalf("failed to decode test ClientHello: %s", err)
522         }
523         var clientHelloCopy clientHelloMsg
524         if clientHelloCopy.unmarshal(clientHelloBytes) {
525                 t.Error("Unmarshaled ClientHello with duplicate extensions")
526         }
527
528         serverHelloBytes, err := hex.DecodeString("02000030030300000000000000000000000000000000000000000000000000000000000000000000000000080005000000050000")
529         if err != nil {
530                 t.Fatalf("failed to decode test ServerHello: %s", err)
531         }
532         var serverHelloCopy serverHelloMsg
533         if serverHelloCopy.unmarshal(serverHelloBytes) {
534                 t.Fatal("Unmarshaled ServerHello with duplicate extensions")
535         }
536 }