-
Notifications
You must be signed in to change notification settings - Fork 3
/
u_tls_extensions.go
2067 lines (1786 loc) · 57.5 KB
/
u_tls_extensions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tls
import (
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"github.com/gaukas/godicttls"
"golang.org/x/crypto/cryptobyte"
)
// ExtensionFromID returns a TLSExtension for the given extension ID.
func ExtensionFromID(id uint16) TLSExtension {
// deep copy
switch id {
case extensionServerName:
return &SNIExtension{}
case extensionStatusRequest:
return &StatusRequestExtension{}
case extensionSupportedCurves:
return &SupportedCurvesExtension{}
case extensionSupportedPoints:
return &SupportedPointsExtension{}
case extensionSignatureAlgorithms:
return &SignatureAlgorithmsExtension{}
case extensionALPN:
return &ALPNExtension{}
case extensionStatusRequestV2:
return &StatusRequestV2Extension{}
case extensionSCT:
return &SCTExtension{}
case utlsExtensionPadding:
return &UtlsPaddingExtension{}
case extensionExtendedMasterSecret:
return &ExtendedMasterSecretExtension{}
case fakeExtensionTokenBinding:
return &FakeTokenBindingExtension{}
case utlsExtensionCompressCertificate:
return &UtlsCompressCertExtension{}
case fakeExtensionDelegatedCredentials:
return &FakeDelegatedCredentialsExtension{}
case extensionSessionTicket:
return &SessionTicketExtension{}
case extensionPreSharedKey:
return &FakePreSharedKeyExtension{}
// case extensionEarlyData:
// return &EarlyDataExtension{}
case extensionSupportedVersions:
return &SupportedVersionsExtension{}
// case extensionCookie:
// return &CookieExtension{}
case extensionPSKModes:
return &PSKKeyExchangeModesExtension{}
// case extensionCertificateAuthorities:
// return &CertificateAuthoritiesExtension{}
case extensionSignatureAlgorithmsCert:
return &SignatureAlgorithmsCertExtension{}
case extensionKeyShare:
return &KeyShareExtension{}
case extensionQUICTransportParameters:
return &QUICTransportParametersExtension{}
case extensionNextProtoNeg:
return &NPNExtension{}
case utlsExtensionApplicationSettings:
return &ApplicationSettingsExtension{}
case fakeOldExtensionChannelID:
return &FakeChannelIDExtension{true}
case fakeExtensionChannelID:
return &FakeChannelIDExtension{}
case fakeRecordSizeLimit:
return &FakeRecordSizeLimitExtension{}
case extensionRenegotiationInfo:
return &RenegotiationInfoExtension{}
default:
if isGREASEUint16(id) {
return &UtlsGREASEExtension{}
}
return nil // not returning GenericExtension, it should be handled by caller
}
}
type TLSExtension interface {
writeToUConn(*UConn) error
Len() int // includes header
// Read reads up to len(p) bytes into p.
// It returns the number of bytes read (0 <= n <= len(p)) and any error encountered.
Read(p []byte) (n int, err error) // implements io.Reader
}
// TLSExtensionWriter is an interface allowing a TLS extension to be
// auto-constucted/recovered by reading in a byte stream.
type TLSExtensionWriter interface {
TLSExtension
// Write writes the extension data as a byte slice, up to len(b) bytes from b.
// It returns the number of bytes written (0 <= n <= len(b)) and any error encountered.
//
// The implementation MUST NOT silently drop data if consumed less than len(b) bytes,
// instead, it MUST return an error.
Write(b []byte) (n int, err error)
}
type TLSExtensionJSON interface {
TLSExtension
// UnmarshalJSON unmarshals the JSON-encoded data into the extension.
UnmarshalJSON([]byte) error
}
// SNIExtension implements server_name (0)
type SNIExtension struct {
ServerName string // not an array because go crypto/tls doesn't support multiple SNIs
}
func (e *SNIExtension) Len() int {
// Literal IP addresses, absolute FQDNs, and empty strings are not permitted as SNI values.
// See RFC 6066, Section 3.
hostName := hostnameInSNI(e.ServerName)
if len(hostName) == 0 {
return 0
}
return 4 + 2 + 1 + 2 + len(hostName)
}
func (e *SNIExtension) Read(b []byte) (int, error) {
// Literal IP addresses, absolute FQDNs, and empty strings are not permitted as SNI values.
// See RFC 6066, Section 3.
hostName := hostnameInSNI(e.ServerName)
if len(hostName) == 0 {
return 0, io.EOF
}
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// RFC 3546, section 3.1
b[0] = byte(extensionServerName >> 8)
b[1] = byte(extensionServerName)
b[2] = byte((len(hostName) + 5) >> 8)
b[3] = byte(len(hostName) + 5)
b[4] = byte((len(hostName) + 3) >> 8)
b[5] = byte(len(hostName) + 3)
// b[6] Server Name Type: host_name (0)
b[7] = byte(len(hostName) >> 8)
b[8] = byte(len(hostName))
copy(b[9:], []byte(hostName))
return e.Len(), io.EOF
}
func (e *SNIExtension) UnmarshalJSON(_ []byte) error {
return nil // no-op
}
// Write is a no-op for StatusRequestExtension.
// SNI should not be fingerprinted and is user controlled.
func (e *SNIExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 6066, Section 3
var nameList cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&nameList) || nameList.Empty() {
return fullLen, errors.New("unable to read server name extension data")
}
var serverName string
for !nameList.Empty() {
var nameType uint8
var serverNameBytes cryptobyte.String
if !nameList.ReadUint8(&nameType) ||
!nameList.ReadUint16LengthPrefixed(&serverNameBytes) ||
serverNameBytes.Empty() {
return fullLen, errors.New("unable to read server name extension data")
}
if nameType != 0 {
continue
}
if len(serverName) != 0 {
return fullLen, errors.New("multiple names of the same name_type in server name extension are prohibited")
}
serverName = string(serverNameBytes)
if strings.HasSuffix(serverName, ".") {
return fullLen, errors.New("SNI value may not include a trailing dot")
}
}
// clientHelloSpec.Extensions = append(clientHelloSpec.Extensions, &SNIExtension{}) // gaukas moved this line out from the loop.
// don't copy SNI from ClientHello to ClientHelloSpec!
return fullLen, nil
}
func (e *SNIExtension) writeToUConn(uc *UConn) error {
uc.config.ServerName = e.ServerName
hostName := hostnameInSNI(e.ServerName)
uc.HandshakeState.Hello.ServerName = hostName
return nil
}
// StatusRequestExtension implements status_request (5)
type StatusRequestExtension struct {
}
func (e *StatusRequestExtension) Len() int {
return 9
}
func (e *StatusRequestExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// RFC 4366, section 3.6
b[0] = byte(extensionStatusRequest >> 8)
b[1] = byte(extensionStatusRequest)
b[2] = 0
b[3] = 5
b[4] = 1 // OCSP type
// Two zero valued uint16s for the two lengths.
return e.Len(), io.EOF
}
func (e *StatusRequestExtension) UnmarshalJSON(_ []byte) error {
return nil // no-op
}
// Write is a no-op for StatusRequestExtension. No data for this extension.
func (e *StatusRequestExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 4366, Section 3.6
var statusType uint8
var ignored cryptobyte.String
if !extData.ReadUint8(&statusType) ||
!extData.ReadUint16LengthPrefixed(&ignored) ||
!extData.ReadUint16LengthPrefixed(&ignored) {
return fullLen, errors.New("unable to read status request extension data")
}
if statusType != statusTypeOCSP {
return fullLen, errors.New("status request extension statusType is not statusTypeOCSP(1)")
}
return fullLen, nil
}
func (e *StatusRequestExtension) writeToUConn(uc *UConn) error {
uc.HandshakeState.Hello.OcspStapling = true
return nil
}
// SupportedCurvesExtension implements supported_groups (renamed from "elliptic_curves") (10)
type SupportedCurvesExtension struct {
Curves []CurveID
}
func (e *SupportedCurvesExtension) Len() int {
return 6 + 2*len(e.Curves)
}
func (e *SupportedCurvesExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// http://tools.ietf.org/html/rfc4492#section-5.5.1
b[0] = byte(extensionSupportedCurves >> 8)
b[1] = byte(extensionSupportedCurves)
b[2] = byte((2 + 2*len(e.Curves)) >> 8)
b[3] = byte(2 + 2*len(e.Curves))
b[4] = byte((2 * len(e.Curves)) >> 8)
b[5] = byte(2 * len(e.Curves))
for i, curve := range e.Curves {
b[6+2*i] = byte(curve >> 8)
b[7+2*i] = byte(curve)
}
return e.Len(), io.EOF
}
func (e *SupportedCurvesExtension) UnmarshalJSON(data []byte) error {
var namedGroups struct {
NamedGroupList []string `json:"named_group_list"`
}
if err := json.Unmarshal(data, &namedGroups); err != nil {
return err
}
for _, namedGroup := range namedGroups.NamedGroupList {
if namedGroup == "GREASE" {
e.Curves = append(e.Curves, GREASE_PLACEHOLDER)
continue
}
if group, ok := godicttls.DictSupportedGroupsNameIndexed[namedGroup]; ok {
e.Curves = append(e.Curves, CurveID(group))
} else {
return fmt.Errorf("unknown named group: %s", namedGroup)
}
}
return nil
}
func (e *SupportedCurvesExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7
var curvesBytes cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&curvesBytes) || curvesBytes.Empty() {
return 0, errors.New("unable to read supported curves extension data")
}
curves := []CurveID{}
for !curvesBytes.Empty() {
var curve uint16
if !curvesBytes.ReadUint16(&curve) {
return 0, errors.New("unable to read supported curves extension data")
}
curves = append(curves, CurveID(unGREASEUint16(curve)))
}
e.Curves = curves
return fullLen, nil
}
func (e *SupportedCurvesExtension) writeToUConn(uc *UConn) error {
// uc.config.CurvePreferences = e.Curves // #Restls# Remove
uc.HandshakeState.Hello.SupportedCurves = e.Curves
return nil
}
// SupportedPointsExtension implements ec_point_formats (11)
type SupportedPointsExtension struct {
SupportedPoints []uint8
}
func (e *SupportedPointsExtension) Len() int {
return 5 + len(e.SupportedPoints)
}
func (e *SupportedPointsExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// http://tools.ietf.org/html/rfc4492#section-5.5.2
b[0] = byte(extensionSupportedPoints >> 8)
b[1] = byte(extensionSupportedPoints)
b[2] = byte((1 + len(e.SupportedPoints)) >> 8)
b[3] = byte(1 + len(e.SupportedPoints))
b[4] = byte(len(e.SupportedPoints))
for i, pointFormat := range e.SupportedPoints {
b[5+i] = pointFormat
}
return e.Len(), io.EOF
}
func (e *SupportedPointsExtension) UnmarshalJSON(data []byte) error {
var pointFormatList struct {
ECPointFormatList []string `json:"ec_point_format_list"`
}
if err := json.Unmarshal(data, &pointFormatList); err != nil {
return err
}
for _, pointFormat := range pointFormatList.ECPointFormatList {
if format, ok := godicttls.DictECPointFormatNameIndexed[pointFormat]; ok {
e.SupportedPoints = append(e.SupportedPoints, format)
} else {
return fmt.Errorf("unknown point format: %s", pointFormat)
}
}
return nil
}
func (e *SupportedPointsExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 4492, Section 5.1.2
supportedPoints := []uint8{}
if !readUint8LengthPrefixed(&extData, &supportedPoints) ||
len(supportedPoints) == 0 {
return 0, errors.New("unable to read supported points extension data")
}
e.SupportedPoints = supportedPoints
return fullLen, nil
}
func (e *SupportedPointsExtension) writeToUConn(uc *UConn) error {
uc.HandshakeState.Hello.SupportedPoints = e.SupportedPoints
return nil
}
// SignatureAlgorithmsExtension implements signature_algorithms (13)
type SignatureAlgorithmsExtension struct {
SupportedSignatureAlgorithms []SignatureScheme
}
func (e *SignatureAlgorithmsExtension) Len() int {
return 6 + 2*len(e.SupportedSignatureAlgorithms)
}
func (e *SignatureAlgorithmsExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
b[0] = byte(extensionSignatureAlgorithms >> 8)
b[1] = byte(extensionSignatureAlgorithms)
b[2] = byte((2 + 2*len(e.SupportedSignatureAlgorithms)) >> 8)
b[3] = byte(2 + 2*len(e.SupportedSignatureAlgorithms))
b[4] = byte((2 * len(e.SupportedSignatureAlgorithms)) >> 8)
b[5] = byte(2 * len(e.SupportedSignatureAlgorithms))
for i, sigScheme := range e.SupportedSignatureAlgorithms {
b[6+2*i] = byte(sigScheme >> 8)
b[7+2*i] = byte(sigScheme)
}
return e.Len(), io.EOF
}
func (e *SignatureAlgorithmsExtension) UnmarshalJSON(data []byte) error {
var signatureAlgorithms struct {
Algorithms []string `json:"supported_signature_algorithms"`
}
if err := json.Unmarshal(data, &signatureAlgorithms); err != nil {
return err
}
for _, sigScheme := range signatureAlgorithms.Algorithms {
if sigScheme == "GREASE" {
e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, GREASE_PLACEHOLDER)
continue
}
if scheme, ok := godicttls.DictSignatureSchemeNameIndexed[sigScheme]; ok {
e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, SignatureScheme(scheme))
} else {
return fmt.Errorf("unknown signature scheme: %s", sigScheme)
}
}
return nil
}
func (e *SignatureAlgorithmsExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 5246, Section 7.4.1.4.1
var sigAndAlgs cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
return 0, errors.New("unable to read signature algorithms extension data")
}
supportedSignatureAlgorithms := []SignatureScheme{}
for !sigAndAlgs.Empty() {
var sigAndAlg uint16
if !sigAndAlgs.ReadUint16(&sigAndAlg) {
return 0, errors.New("unable to read signature algorithms extension data")
}
supportedSignatureAlgorithms = append(
supportedSignatureAlgorithms, SignatureScheme(sigAndAlg))
}
e.SupportedSignatureAlgorithms = supportedSignatureAlgorithms
return fullLen, nil
}
func (e *SignatureAlgorithmsExtension) writeToUConn(uc *UConn) error {
uc.HandshakeState.Hello.SupportedSignatureAlgorithms = e.SupportedSignatureAlgorithms
return nil
}
// StatusRequestV2Extension implements status_request_v2 (17)
type StatusRequestV2Extension struct {
}
func (e *StatusRequestV2Extension) writeToUConn(uc *UConn) error {
uc.HandshakeState.Hello.OcspStapling = true
return nil
}
func (e *StatusRequestV2Extension) Len() int {
return 13
}
func (e *StatusRequestV2Extension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// RFC 4366, section 3.6
b[0] = byte(extensionStatusRequestV2 >> 8)
b[1] = byte(extensionStatusRequestV2)
b[2] = 0
b[3] = 9
b[4] = 0
b[5] = 7
b[6] = 2 // OCSP type
b[7] = 0
b[8] = 4
// Two zero valued uint16s for the two lengths.
return e.Len(), io.EOF
}
// Write is a no-op for StatusRequestV2Extension. No data for this extension.
func (e *StatusRequestV2Extension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 4366, Section 3.6
var statusType uint8
var ignored cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&ignored) ||
!extData.ReadUint8(&statusType) ||
!extData.ReadUint16LengthPrefixed(&ignored) ||
!extData.ReadUint16LengthPrefixed(&ignored) ||
!extData.ReadUint16LengthPrefixed(&ignored) {
return fullLen, errors.New("unable to read status request v2 extension data")
}
if statusType != statusV2TypeOCSP {
return fullLen, errors.New("status request v2 extension statusType is not statusV2TypeOCSP(2)")
}
return fullLen, nil
}
func (e *StatusRequestV2Extension) UnmarshalJSON(_ []byte) error {
return nil // no-op
}
// SignatureAlgorithmsCertExtension implements signature_algorithms_cert (50)
type SignatureAlgorithmsCertExtension struct {
SupportedSignatureAlgorithms []SignatureScheme
}
func (e *SignatureAlgorithmsCertExtension) Len() int {
return 6 + 2*len(e.SupportedSignatureAlgorithms)
}
func (e *SignatureAlgorithmsCertExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
b[0] = byte(extensionSignatureAlgorithmsCert >> 8)
b[1] = byte(extensionSignatureAlgorithmsCert)
b[2] = byte((2 + 2*len(e.SupportedSignatureAlgorithms)) >> 8)
b[3] = byte(2 + 2*len(e.SupportedSignatureAlgorithms))
b[4] = byte((2 * len(e.SupportedSignatureAlgorithms)) >> 8)
b[5] = byte(2 * len(e.SupportedSignatureAlgorithms))
for i, sigAndHash := range e.SupportedSignatureAlgorithms {
b[6+2*i] = byte(sigAndHash >> 8)
b[7+2*i] = byte(sigAndHash)
}
return e.Len(), io.EOF
}
// Copied from SignatureAlgorithmsExtension.UnmarshalJSON
func (e *SignatureAlgorithmsCertExtension) UnmarshalJSON(data []byte) error {
var signatureAlgorithms struct {
Algorithms []string `json:"supported_signature_algorithms"`
}
if err := json.Unmarshal(data, &signatureAlgorithms); err != nil {
return err
}
for _, sigScheme := range signatureAlgorithms.Algorithms {
if sigScheme == "GREASE" {
e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, GREASE_PLACEHOLDER)
continue
}
if scheme, ok := godicttls.DictSignatureSchemeNameIndexed[sigScheme]; ok {
e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, SignatureScheme(scheme))
} else {
return fmt.Errorf("unknown cert signature scheme: %s", sigScheme)
}
}
return nil
}
// Write implementation copied from SignatureAlgorithmsExtension.Write
//
// Warning: not tested.
func (e *SignatureAlgorithmsCertExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 8446, Section 4.2.3
var sigAndAlgs cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() {
return 0, errors.New("unable to read signature algorithms extension data")
}
supportedSignatureAlgorithms := []SignatureScheme{}
for !sigAndAlgs.Empty() {
var sigAndAlg uint16
if !sigAndAlgs.ReadUint16(&sigAndAlg) {
return 0, errors.New("unable to read signature algorithms extension data")
}
supportedSignatureAlgorithms = append(
supportedSignatureAlgorithms, SignatureScheme(sigAndAlg))
}
e.SupportedSignatureAlgorithms = supportedSignatureAlgorithms
return fullLen, nil
}
func (e *SignatureAlgorithmsCertExtension) writeToUConn(uc *UConn) error {
uc.HandshakeState.Hello.SupportedSignatureAlgorithms = e.SupportedSignatureAlgorithms
return nil
}
// ALPNExtension implements application_layer_protocol_negotiation (16)
type ALPNExtension struct {
AlpnProtocols []string
}
func (e *ALPNExtension) writeToUConn(uc *UConn) error {
uc.config.NextProtos = e.AlpnProtocols
uc.HandshakeState.Hello.AlpnProtocols = e.AlpnProtocols
return nil
}
func (e *ALPNExtension) Len() int {
bLen := 2 + 2 + 2
for _, s := range e.AlpnProtocols {
bLen += 1 + len(s)
}
return bLen
}
func (e *ALPNExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
b[0] = byte(extensionALPN >> 8)
b[1] = byte(extensionALPN & 0xff)
lengths := b[2:]
b = b[6:]
stringsLength := 0
for _, s := range e.AlpnProtocols {
l := len(s)
b[0] = byte(l)
copy(b[1:], s)
b = b[1+l:]
stringsLength += 1 + l
}
lengths[2] = byte(stringsLength >> 8)
lengths[3] = byte(stringsLength)
stringsLength += 2
lengths[0] = byte(stringsLength >> 8)
lengths[1] = byte(stringsLength)
return e.Len(), io.EOF
}
func (e *ALPNExtension) UnmarshalJSON(b []byte) error {
var protocolNames struct {
ProtocolNameList []string `json:"protocol_name_list"`
}
if err := json.Unmarshal(b, &protocolNames); err != nil {
return err
}
e.AlpnProtocols = protocolNames.ProtocolNameList
return nil
}
func (e *ALPNExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// RFC 7301, Section 3.1
var protoList cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
return 0, errors.New("unable to read ALPN extension data")
}
alpnProtocols := []string{}
for !protoList.Empty() {
var proto cryptobyte.String
if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() {
return 0, errors.New("unable to read ALPN extension data")
}
alpnProtocols = append(alpnProtocols, string(proto))
}
e.AlpnProtocols = alpnProtocols
return fullLen, nil
}
// ApplicationSettingsExtension represents the TLS ALPS extension.
// At the time of this writing, this extension is currently a draft:
// https://datatracker.ietf.org/doc/html/draft-vvv-tls-alps-01
type ApplicationSettingsExtension struct {
SupportedProtocols []string
}
func (e *ApplicationSettingsExtension) writeToUConn(uc *UConn) error {
return nil
}
func (e *ApplicationSettingsExtension) Len() int {
bLen := 2 + 2 + 2 // Type + Length + ALPS Extension length
for _, s := range e.SupportedProtocols {
bLen += 1 + len(s) // Supported ALPN Length + actual length of protocol
}
return bLen
}
func (e *ApplicationSettingsExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// Read Type.
b[0] = byte(utlsExtensionApplicationSettings >> 8) // hex: 44 dec: 68
b[1] = byte(utlsExtensionApplicationSettings & 0xff) // hex: 69 dec: 105
lengths := b[2:] // get the remaining buffer without Type
b = b[6:] // set the buffer to the buffer without Type, Length and ALPS Extension Length (so only the Supported ALPN list remains)
stringsLength := 0
for _, s := range e.SupportedProtocols {
l := len(s) // Supported ALPN Length
b[0] = byte(l) // Supported ALPN Length in bytes hex: 02 dec: 2
copy(b[1:], s) // copy the Supported ALPN as bytes to the buffer
b = b[1+l:] // set the buffer to the buffer without the Supported ALPN Length and Supported ALPN (so we can continue to the next protocol in this loop)
stringsLength += 1 + l // Supported ALPN Length (the field itself) + Supported ALPN Length (the value)
}
lengths[2] = byte(stringsLength >> 8) // ALPS Extension Length hex: 00 dec: 0
lengths[3] = byte(stringsLength) // ALPS Extension Length hex: 03 dec: 3
stringsLength += 2 // plus ALPS Extension Length field length
lengths[0] = byte(stringsLength >> 8) // Length hex:00 dec: 0
lengths[1] = byte(stringsLength) // Length hex: 05 dec: 5
return e.Len(), io.EOF
}
func (e *ApplicationSettingsExtension) UnmarshalJSON(b []byte) error {
var applicationSettingsSupport struct {
SupportedProtocols []string `json:"supported_protocols"`
}
if err := json.Unmarshal(b, &applicationSettingsSupport); err != nil {
return err
}
e.SupportedProtocols = applicationSettingsSupport.SupportedProtocols
return nil
}
// Write implementation copied from ALPNExtension.Write
func (e *ApplicationSettingsExtension) Write(b []byte) (int, error) {
fullLen := len(b)
extData := cryptobyte.String(b)
// https://datatracker.ietf.org/doc/html/draft-vvv-tls-alps-01
var protoList cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
return 0, errors.New("unable to read ALPN extension data")
}
alpnProtocols := []string{}
for !protoList.Empty() {
var proto cryptobyte.String
if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() {
return 0, errors.New("unable to read ALPN extension data")
}
alpnProtocols = append(alpnProtocols, string(proto))
}
e.SupportedProtocols = alpnProtocols
return fullLen, nil
}
// SCTExtension implements signed_certificate_timestamp (18)
type SCTExtension struct {
}
func (e *SCTExtension) writeToUConn(uc *UConn) error {
uc.HandshakeState.Hello.Scts = true
return nil
}
func (e *SCTExtension) Len() int {
return 4
}
func (e *SCTExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// https://tools.ietf.org/html/rfc6962#section-3.3.1
b[0] = byte(extensionSCT >> 8)
b[1] = byte(extensionSCT)
// zero uint16 for the zero-length extension_data
return e.Len(), io.EOF
}
func (e *SCTExtension) UnmarshalJSON(_ []byte) error {
return nil // no-op
}
func (e *SCTExtension) Write(_ []byte) (int, error) {
return 0, nil
}
// SessionTicketExtension implements session_ticket (35)
type SessionTicketExtension struct {
Session *ClientSessionState
}
func (e *SessionTicketExtension) writeToUConn(uc *UConn) error {
if e.Session != nil {
uc.HandshakeState.Session = e.Session.session
uc.HandshakeState.Hello.SessionTicket = e.Session.ticket
}
return nil
}
func (e *SessionTicketExtension) Len() int {
if e.Session != nil {
return 4 + len(e.Session.ticket)
}
return 4
}
func (e *SessionTicketExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
extBodyLen := e.Len() - 4
b[0] = byte(extensionSessionTicket >> 8)
b[1] = byte(extensionSessionTicket)
b[2] = byte(extBodyLen >> 8)
b[3] = byte(extBodyLen)
if extBodyLen > 0 {
copy(b[4:], e.Session.ticket)
}
return e.Len(), io.EOF
}
func (e *SessionTicketExtension) UnmarshalJSON(_ []byte) error {
return nil // no-op
}
func (e *SessionTicketExtension) Write(_ []byte) (int, error) {
// RFC 5077, Section 3.2
return 0, nil
}
// GenericExtension allows to include in ClientHello arbitrary unsupported extensions.
// It is not defined in TLS RFCs nor by IANA.
// If a server echoes this extension back, the handshake will likely fail due to no further support.
type GenericExtension struct {
Id uint16
Data []byte
}
func (e *GenericExtension) writeToUConn(uc *UConn) error {
return nil
}
func (e *GenericExtension) Len() int {
return 4 + len(e.Data)
}
func (e *GenericExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
b[0] = byte(e.Id >> 8)
b[1] = byte(e.Id)
b[2] = byte(len(e.Data) >> 8)
b[3] = byte(len(e.Data))
if len(e.Data) > 0 {
copy(b[4:], e.Data)
}
return e.Len(), io.EOF
}
func (e *GenericExtension) UnmarshalJSON(b []byte) error {
var genericExtension struct {
Name string `json:"name"`
Data []byte `json:"data"`
}
if err := json.Unmarshal(b, &genericExtension); err != nil {
return err
}
// lookup extension ID by name
if id, ok := godicttls.DictExtTypeNameIndexed[genericExtension.Name]; ok {
e.Id = id
} else {
return fmt.Errorf("unknown extension name %s", genericExtension.Name)
}
e.Data = genericExtension.Data
return nil
}
// ExtendedMasterSecretExtension implements extended_master_secret (23)
//
// Was named as ExtendedMasterSecretExtension, renamed due to crypto/tls
// implemented this extension's support.
type ExtendedMasterSecretExtension struct {
}
// TODO: update when this extension is implemented in crypto/tls
// but we probably won't have to enable it in Config
func (e *ExtendedMasterSecretExtension) writeToUConn(uc *UConn) error {
uc.HandshakeState.Hello.Ems = true
return nil
}
func (e *ExtendedMasterSecretExtension) Len() int {
return 4
}
func (e *ExtendedMasterSecretExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
// https://tools.ietf.org/html/rfc7627
b[0] = byte(extensionExtendedMasterSecret >> 8)
b[1] = byte(extensionExtendedMasterSecret)
// The length is 0
return e.Len(), io.EOF
}
func (e *ExtendedMasterSecretExtension) UnmarshalJSON(_ []byte) error {
return nil // no-op
}
func (e *ExtendedMasterSecretExtension) Write(_ []byte) (int, error) {
// https://tools.ietf.org/html/rfc7627
return 0, nil
}
// var extendedMasterSecretLabel = []byte("extended master secret")
// extendedMasterFromPreMasterSecret generates the master secret from the pre-master
// secret and session hash. See https://tools.ietf.org/html/rfc7627#section-4
func extendedMasterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret []byte, sessionHash []byte) []byte {
masterSecret := make([]byte, masterSecretLength)
prfForVersion(version, suite)(masterSecret, preMasterSecret, extendedMasterSecretLabel, sessionHash)
return masterSecret
}
// GREASE stinks with dead parrots, have to be super careful, and, if possible, not include GREASE
// https://github.com/google/boringssl/blob/1c68fa2350936ca5897a66b430ebaf333a0e43f5/ssl/internal.h
const (
ssl_grease_cipher = iota
ssl_grease_group
ssl_grease_extension1
ssl_grease_extension2
ssl_grease_version
ssl_grease_ticket_extension
ssl_grease_last_index = ssl_grease_ticket_extension
)
// it is responsibility of user not to generate multiple grease extensions with same value
type UtlsGREASEExtension struct {
Value uint16
Body []byte // in Chrome first grease has empty body, second grease has a single zero byte
}
func (e *UtlsGREASEExtension) writeToUConn(uc *UConn) error {
return nil
}
// will panic if ssl_grease_last_index[index] is out of bounds.
func GetBoringGREASEValue(greaseSeed [ssl_grease_last_index]uint16, index int) uint16 {
// GREASE value is back from deterministic to random.
// https://github.com/google/boringssl/blob/a365138ac60f38b64bfc608b493e0f879845cb88/ssl/handshake_client.c#L530
ret := uint16(greaseSeed[index])
/* This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16. */
ret = (ret & 0xf0) | 0x0a
ret |= ret << 8
return ret
}
func (e *UtlsGREASEExtension) Len() int {
return 4 + len(e.Body)
}
func (e *UtlsGREASEExtension) Read(b []byte) (int, error) {
if len(b) < e.Len() {
return 0, io.ErrShortBuffer
}
b[0] = byte(e.Value >> 8)
b[1] = byte(e.Value)
b[2] = byte(len(e.Body) >> 8)
b[3] = byte(len(e.Body))
if len(e.Body) > 0 {
copy(b[4:], e.Body)
}
return e.Len(), io.EOF
}
func (e *UtlsGREASEExtension) Write(b []byte) (int, error) {
e.Value = GREASE_PLACEHOLDER