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