-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtls.go
1493 lines (1275 loc) · 46.1 KB
/
tls.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
package packemon
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/binary"
"encoding/hex"
"fmt"
"log"
"strconv"
"golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/curve25519"
)
func ParsedTLSToPassive(tcp *TCP, p *Passive) {
// 以下、tcp.Data[1:3] にある(Record Layer) version あてにならないかも。tls version 1.0 の値でも wireshark 上で、tls1.2 or 1.3 の record という表示になってる
// なので、HandshakeProtocol 内の、Version でも確認する.
// が、これもあてにならない。TLS1.3のつもりでリクエストして(curl -s -v --tls-max 1.3 https://192.168.10.112:10443)、Client Hello みると、Version 1.0 / Handshake Protocol Version 1.2
// if bytes.Equal(TLS_VERSION_1_2, tcp.Data[1:3]) {
// TODO: support TLSv1.3
// ref: https://zenn.dev/satoken/articles/golang-tls1_3
if bytes.Equal(TLS_VERSION_1_0, tcp.Data[1:3]) || // 1.0 / 1.1 とか含めちゃってるのは、そういうのが1.2 / 1.3 でも入ってき得るから
bytes.Equal(TLS_VERSION_1_1, tcp.Data[1:3]) ||
bytes.Equal(TLS_VERSION_1_2, tcp.Data[1:3]) ||
bytes.Equal(TLS_VERSION_1_3, tcp.Data[1:3]) ||
bytes.Equal(TLS_VERSION_1_2, tcp.Data[9:11]) {
// TLS の 先頭の Content Type をチェック
// TODO: あくまで先頭の、なので、パケットが分割されて例えば、ChangeChiperSpec のみ来たりする可能性はあるかも
switch tcp.Data[0] {
case TLS_CONTENT_TYPE_HANDSHAKE:
if tcp.Data[5] == TLS_HANDSHAKE_TYPE_CLIENT_HELLO {
tlsClientHello := ParsedTLSClientHello(tcp.Data)
p.TLSClientHello = tlsClientHello
return
}
if tcp.Data[5] == TLS_HANDSHAKE_TYPE_SERVER_HELLO {
// Server Hello の、Extension.supported_versions に、TLS1.3(0x0304) が含まれていれば、それ用のパースをする
serverHello, _ := ParsedTLSServerHelloOnly(tcp.Data) // 以下のParsedTLSServerHelloでもこれ呼んでるからなんとかする
for _, e := range serverHello.HandshakeProtocol.Extentions {
if e.IsTLS13() {
tlsServerHelloFor1_3 := ParsedTLSServerHelloFor1_3(tcp.Data)
p.TLSServerHelloFor1_3 = tlsServerHelloFor1_3
return
}
}
tlsServerHello := ParsedTLSServerHello(tcp.Data)
p.TLSServerHello = tlsServerHello
return
}
if tcp.Data[5] == TLS_HANDSHAKE_TYPE_CLIENT_KEY_EXCHANGE {
tlsClientKeyExchange := ParsedTLSClientKeyexchange(tcp.Data)
p.TLSClientKeyExchange = tlsClientKeyExchange
return
}
case TLS_HANDSHAKE_TYPE_CHANGE_CIPHER_SPEC:
tlsChangeCipherSpecAndEncryptedHandshakeMessage := ParsedTLSChangeCipherSpecAndEncryptedHandshakeMessage(tcp.Data)
p.TLSChangeCipherSpecAndEncryptedHandshakeMessage = tlsChangeCipherSpecAndEncryptedHandshakeMessage
return
case TLS_CONTENT_TYPE_APPLICATION_DATA:
tlsApplicationData := ParsedTLSApplicationData(tcp.Data)
p.TLSApplicationData = tlsApplicationData
return
case TLS_CONTENT_TYPE_ALERT:
tlsEncryptedAlert := ParsedTLSEncryptedAlert(tcp.Data)
p.TLSEncryptedAlert = tlsEncryptedAlert
return
default:
}
}
}
const TLS_CONTENT_TYPE_HANDSHAKE = 0x16
const TLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC = 0x14
const TLS_CONTENT_TYPE_APPLICATION_DATA = 0x17
// ref: https://tls12.xargs.org/#client-hello/annotated
// 以降のstructのフィールドはWiresharkを見つつ補完
type TLSRecordLayer struct {
ContentType []byte
Version []byte
Length []byte
}
func (l *TLSRecordLayer) Bytes() []byte {
buf := []byte{}
buf = append(buf, l.ContentType...)
buf = append(buf, l.Version...)
buf = append(buf, l.Length...)
return buf
}
type TLSHandshakeProtocol struct {
HandshakeType []byte
Length []byte
Version []byte
Random []byte
SessionIDLength []byte
SessionID []byte
CipherSuitesLength []byte
CipherSuites []uint16 // ref: https://tls12.xargs.org/#client-hello/annotated [Ciper Suites]
CompressionMethodsLength []byte
CompressionMethods []byte
ExtensionsLength []byte
Extentions TLSExtensions
}
var TLS_EXTENSION_TYPE_KEY_SHARE = []byte{0x0, 0x33}
type TLSExtension struct {
Type []byte
Length []byte
Data []byte
}
func (e *TLSExtension) Bytes() []byte {
buf := &bytes.Buffer{}
buf.Write(e.Type)
buf.Write(e.Length)
buf.Write(e.Data)
return buf.Bytes()
}
var TLS_EXTENSION_SUPPORTED_VERSIONS = []byte{0x00, 0x2b}
func (e *TLSExtension) IsTLS13() bool {
if !bytes.Equal(e.Type, TLS_EXTENSION_SUPPORTED_VERSIONS) {
return false
}
for i := 0; i < bytesToInt(e.Length); i += 2 {
supportedVersion := e.Data[i : i+2]
if bytes.Equal(supportedVersion, TLS_VERSION_1_3) {
return true
}
}
return false
}
type TLSExtensions []*TLSExtension
func (es TLSExtensions) Bytes() []byte {
buf := &bytes.Buffer{}
for _, e := range es {
buf.Write(e.Bytes())
}
return buf.Bytes()
}
func ParsedTLSExtensions(extensionsLength int, b []byte) TLSExtensions {
if extensionsLength == 0 {
return TLSExtensions{}
}
es := []*TLSExtension{}
for i := 0; i < extensionsLength; {
typ := b[i : i+2]
length := b[i+2 : i+4]
lengthInt := bytesToInt(length)
data := b[i+4 : i+4+lengthInt]
e := &TLSExtension{
Type: typ,
Length: length,
Data: data,
}
es = append(es, e)
i = i + 4 + lengthInt
}
return es
}
func (p *TLSHandshakeProtocol) Bytes(isFromServer bool) []byte {
buf := []byte{}
buf = append(buf, p.HandshakeType...)
buf = append(buf, p.Length...)
buf = append(buf, p.Version...)
buf = append(buf, p.Random...)
buf = append(buf, p.SessionIDLength...)
if !(p.SessionIDLength == nil || bytes.Equal(p.SessionIDLength, []byte{0x00})) {
buf = append(buf, p.SessionID...)
}
if clength := p.lengthCipherSuites(isFromServer); clength != nil {
buf = append(buf, p.lengthCipherSuites(isFromServer)...)
}
buf = append(buf, p.bytesCipherSuites()...)
buf = append(buf, p.CompressionMethodsLength...)
buf = append(buf, p.CompressionMethods...)
buf = append(buf, p.ExtensionsLength...)
buf = append(buf, p.Extentions.Bytes()...)
return buf
}
func (p *TLSHandshakeProtocol) bytesCipherSuites() []byte {
if len(p.CipherSuites) == 0 {
return nil
}
buf := []byte{}
for i := range p.CipherSuites {
buf = binary.BigEndian.AppendUint16(buf, p.CipherSuites[i])
}
return buf
}
func (p *TLSHandshakeProtocol) lengthCipherSuites(isFromServer bool) []byte {
if len(p.CipherSuites) == 0 || isFromServer {
return nil
}
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, uint16(len(p.CipherSuites)*2)) // 2byteなため×2
return buf
}
type TLSClientHello struct {
RecordLayer *TLSRecordLayer
HandshakeProtocol *TLSHandshakeProtocol
// TODO: これがこのstruct内にあるのはおかしく、一旦実装を簡単にするため置いてるだけ。要リファクタ
ECDHEKeys *ECDHEKeys
}
const TLS_HANDSHAKE_TYPE_CLIENT_HELLO = 0x01
const TLS_HANDSHAKE_TYPE_SERVER_HELLO = 0x02
const COMPRESSION_METHOD_NULL = 0x00
var TLS_VERSION_1_0 = []byte{0x03, 0x01}
var TLS_VERSION_1_1 = []byte{0x03, 0x02}
var TLS_VERSION_1_2 = []byte{0x03, 0x03}
var TLS_VERSION_1_3 = []byte{0x03, 0x04}
type ECDHEKeys struct {
PrivateKey []byte
PublicKey []byte
SharedKey []byte
}
// TODO: tls1.3 用のと汎用的に
func NewTLSClientHello(tlsVersion []byte, cipherSuites ...uint16) *TLSClientHello {
random := make([]byte, 32)
if _, err := rand.Read(random); err != nil {
panic(err)
}
handshake := &TLSHandshakeProtocol{
HandshakeType: []byte{TLS_HANDSHAKE_TYPE_CLIENT_HELLO},
Length: []byte{0x00, 0x00, 0x00}, // 後で計算して求めるが、初期化のため
Version: TLS_VERSION_1_2,
// TODO: debug 環境の https-server あてにリクエストするときは、以下を使う。復号される
// Random: make([]byte, 32), // 000000....
Random: random,
SessionIDLength: []byte{0x00},
// SessionID: make([]byte, 32),
CipherSuitesLength: []byte{0x00, 0x02}, // 一旦固定
// CipherSuitesLength: []byte{0x00, 0x04}, // 一旦固定
CipherSuites: cipherSuites, // TODO: 外から指定するようにしたので、CipherSuitesLength を計算して求めないといけない
CompressionMethodsLength: []byte{0x00}, // 後で計算して求めるが、初期化のため
CompressionMethods: []byte{COMPRESSION_METHOD_NULL},
ExtensionsLength: []byte{0x00, 0x00}, // 後で計算して求めるが、初期化のため
}
handshake.CompressionMethodsLength = []byte{byte(len(handshake.CompressionMethods))}
tmp := &bytes.Buffer{}
ecdheKeys := &ECDHEKeys{}
if bytes.Equal(tlsVersion, TLS_VERSION_1_3) {
// ref: https://github.com/sat0ken/go-tcpip/blob/7dd5085f8aa25747a6098cc7d8d8e336ec5fcadd/tls1_3.go#L16
clientPrivateKey := make([]byte, 32)
rand.Read(clientPrivateKey)
// clientPrivateKey := noRandomByte(32)
clientPublicKey, err := curve25519.X25519(clientPrivateKey, curve25519.Basepoint)
if err != nil {
panic(err)
}
ecdheKeys.PrivateKey = clientPrivateKey
ecdheKeys.PublicKey = clientPublicKey
handshake.Extentions = []*TLSExtension{
{
// supported_groups
Type: []byte{0x00, 0x0a},
Length: []byte{0x00, 0x04},
Data: []byte{
/*Supported Groups List Length: 2*/ 0x00, 0x02,
/*Supported Groups (1 groups): x25519*/ 0x0, 0x1d,
},
},
{
// ec_point_formats
Type: []byte{0x0, 0x0b},
Length: []byte{0x0, 0x02},
Data: []byte{
0x01, 0x00,
},
},
{
// signature_algorithms
Type: []byte{0x0, 0x0d},
Length: []byte{0x0, 0x1a},
Data: append(
[]byte{0x0, 0x18},
[]byte{
0x08, 0x04,
0x04, 0x03, 0x08, 0x07, 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x05, 0x03, 0x06, 0x03, 0x02, 0x01, 0x02, 0x03,
}...,
),
},
{
// renagotiation_info
Type: []byte{0xff, 0x01},
Length: []byte{0x00, 0x01},
Data: []byte{0x00},
},
{
// supported_versions
Type: []byte{0x0, 0x2b},
Length: []byte{0x0, 0x03},
Data: append([]byte{0x02}, TLS_VERSION_1_3...),
},
{
// key_share
Type: []byte{0x0, 0x33},
Length: []byte{0x0, 0x26},
Data: append(
[]byte{
/* Client Key Share Length: 36 */ 0x0, 0x24,
// 以降、Key Share Entry:
/* Group: x25519 (29) */ 0x0, 0x1d,
/* Key Exchange Length: 32 */ 0x0, 0x20,
},
/* Key Exchange: */ ecdheKeys.PublicKey...),
},
// {
// // http2 実装するときに使う
// // application_layer_protocol_negotiation
// },
}
}
WriteUint16(tmp, uint16(len(handshake.Extentions.Bytes())))
handshake.ExtensionsLength = tmp.Bytes()
lengthAll := &bytes.Buffer{}
isFromServer := false
WriteUint16(lengthAll, uint16(len(handshake.Bytes(isFromServer))))
// 全体の長さ - 4 でいいはず
handshake.Length = uintTo3byte(uint32(len(handshake.Bytes(isFromServer))) - 4)
return &TLSClientHello{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{TLS_CONTENT_TYPE_HANDSHAKE},
Version: TLS_VERSION_1_2,
Length: lengthAll.Bytes(),
},
HandshakeProtocol: handshake,
ECDHEKeys: ecdheKeys,
}
}
func ParsedTLSClientHello(b []byte) *TLSClientHello {
sessionIDLength := b[43]
sessionIDLengthInt := int(sessionIDLength)
var sessionID []byte
nextPoint := 44
if sessionIDLengthInt > 0 {
sessionID = b[nextPoint : nextPoint+sessionIDLengthInt]
nextPoint += sessionIDLengthInt
}
cipherSuitesLength := b[nextPoint : nextPoint+2]
nextPoint += 2
cipherSuites := []uint16{}
// たぶん、2byteずつ増えていくでokと思うけど
sum := 0
for i := 0; i < (bytesToInt(cipherSuitesLength) / 2); i++ {
point := i * 2
cipherSuite := binary.BigEndian.Uint16(b[nextPoint+point : nextPoint+point+2])
cipherSuites = append(cipherSuites, cipherSuite)
sum += 2
}
nextPoint += sum
compressionMethodsLength := b[nextPoint]
compressionMethodsLengthInt := int(compressionMethodsLength)
compressionMethods := []byte{}
if compressionMethodsLengthInt > 0 {
compressionMethods = b[nextPoint+1 : nextPoint+1+compressionMethodsLengthInt]
nextPoint = nextPoint + 1 + compressionMethodsLengthInt
}
extensionsLength := b[nextPoint : nextPoint+2]
extensionsLengthInt := bytesToInt(extensionsLength)
nextPoint += 2
var extensions TLSExtensions
if extensionsLengthInt > 0 {
extensions = ParsedTLSExtensions(extensionsLengthInt, b[nextPoint:nextPoint+extensionsLengthInt])
}
return &TLSClientHello{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{b[0]},
Version: b[1:3],
Length: b[3:5],
},
HandshakeProtocol: &TLSHandshakeProtocol{
HandshakeType: []byte{b[5]},
Length: b[6:9],
Version: b[9:11],
Random: b[11:43],
SessionIDLength: []byte{sessionIDLength},
SessionID: sessionID,
CipherSuitesLength: cipherSuitesLength,
CipherSuites: cipherSuites,
CompressionMethodsLength: []byte{compressionMethodsLength},
CompressionMethods: compressionMethods,
ExtensionsLength: extensionsLength,
Extentions: extensions,
},
}
}
// 2byteをintへ変換
func bytesToInt(b []byte) int {
return int(b[0])<<8 + int(b[1])
}
// 3byteをintへ変換
func bytesToInt2(b []byte) int {
return int(b[0])<<16 + int(b[1])<<8 + int(b[2])
}
func (tch *TLSClientHello) Bytes() []byte {
buf := []byte{}
buf = append(buf, tch.RecordLayer.Bytes()...)
isFromServer := false
buf = append(buf, tch.HandshakeProtocol.Bytes(isFromServer)...)
return buf
}
type TLSServerHello struct {
ServerHello *ServerHello
Certificate *Certificate
ServerHelloDone *ServerHelloDone
}
func (tlsserverhello *TLSServerHello) Bytes() []byte {
b := []byte{}
b = append(b, tlsserverhello.ServerHello.Bytes()...)
b = append(b, tlsserverhello.Certificate.Bytes()...)
b = append(b, tlsserverhello.ServerHelloDone.Bytes()...)
return b
}
type ServerHello struct {
RecordLayer *TLSRecordLayer
HandshakeProtocol *TLSHandshakeProtocol
}
func (s *ServerHello) Bytes() []byte {
b := []byte{}
b = append(b, s.RecordLayer.Bytes()...)
isFromServer := true
b = append(b, s.HandshakeProtocol.Bytes(isFromServer)...)
return b
}
type Certificate struct {
RecordLayer *TLSRecordLayer
HandshakeProtocol *TLSHandshakeProtocol
CertificatesLength []byte
Certificates []byte // TODO: ここ更にフィールドあった
certs []*x509.Certificate // parse成功した証明書を格納する
}
func (c *Certificate) Bytes() []byte {
b := []byte{}
b = append(b, c.RecordLayer.Bytes()...)
isFromServer := true
b = append(b, c.HandshakeProtocol.Bytes(isFromServer)...)
b = append(b, c.CertificatesLength...)
b = append(b, c.Certificates...)
return b
}
// ref: https://zenn.dev/satoken/articles/golang-tls1_2#serverhello%2C-certificate%2C-serverhellodone
func (c *Certificate) Validate() error {
// log.Printf("validation cert: \n%x\n", c.Certificates[3:])
length, _ := strconv.ParseUint(fmt.Sprintf("%x", c.Certificates[:3]), 16, 16)
certs, err := x509.ParseCertificates(c.Certificates[3 : 3+length])
if err != nil {
return err
}
// log.Printf("certificate num: %d\n", len(certs))
c.certs = certs
ospool, err := x509.SystemCertPool()
if err != nil {
return err
}
// log.Println("start verify server certificate")
for i := len(c.certs) - 1; i >= 0; i-- {
opts := x509.VerifyOptions{}
if len(c.certs[i].DNSNames) == 0 {
opts.Roots = ospool
} else {
opts.Roots = ospool
opts.DNSName = c.certs[i].DNSNames[0]
// log.Printf("\tDNS name in server certificate: %s\n", c.certs[i].DNSNames[0])
}
if _, err := c.certs[i].Verify(opts); err != nil {
// TODO: 以下対応までエラーとしないようにする
// https://github.com/ddddddO/packemon/issues/63
// log.Printf("\tfailed to verify server certificate: %s\n", err)
return err
}
if i > 0 {
ospool.AddCert(c.certs[1])
}
}
// log.Println("finish verify server certificate")
return nil
}
func (c *Certificate) ServerPublicKey() *rsa.PublicKey {
if len(c.certs) == 0 {
// log.Println("nil ServerPublicKey")
return nil
}
pub, ok := c.certs[0].PublicKey.(*rsa.PublicKey)
if !ok {
// log.Printf("not public key")
return nil
}
return pub
}
type ServerHelloDone struct {
RecordLayer *TLSRecordLayer
HandshakeProtocol *TLSHandshakeProtocol
}
func (sd *ServerHelloDone) Bytes() []byte {
b := []byte{}
b = append(b, sd.RecordLayer.Bytes()...)
isFromServer := true
b = append(b, sd.HandshakeProtocol.Bytes(isFromServer)...)
return b
}
// TLS1.2/1.3 共通
func ParsedTLSServerHelloOnly(b []byte) (*ServerHello, int) {
sessionIDLength := b[43]
sessionIDLengthInt := int(sessionIDLength)
nextPosition := 44
sessionID := []byte{}
if sessionIDLengthInt != 0 {
sessionID = b[nextPosition : nextPosition+sessionIDLengthInt]
nextPosition += sessionIDLengthInt
}
slength := b[3:5]
serverHello := &ServerHello{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{b[0]},
Version: b[1:3],
Length: slength,
},
HandshakeProtocol: &TLSHandshakeProtocol{
HandshakeType: []byte{b[5]},
Length: b[6:9],
Version: b[9:11],
Random: b[11:43],
SessionIDLength: []byte{sessionIDLength},
SessionID: sessionID,
CipherSuites: []uint16{parsedCipherSuites(b[nextPosition : nextPosition+2])},
CompressionMethods: []byte{b[nextPosition+2]},
},
}
nextPosition = nextPosition + 3
if bytesToInt(slength) > 47 {
extentionsLength := b[nextPosition : nextPosition+2]
serverHello.HandshakeProtocol.ExtensionsLength = extentionsLength
nextPosition += 2
serverHello.HandshakeProtocol.Extentions = ParsedTLSExtensions(bytesToInt(extentionsLength), b[nextPosition:nextPosition+bytesToInt(extentionsLength)])
nextPosition += bytesToInt(extentionsLength)
}
return serverHello, nextPosition
}
// tls1.2用
func ParsedTLSServerHello(b []byte) *TLSServerHello {
serverHello, nextPosition := ParsedTLSServerHelloOnly(b)
certificate := &Certificate{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{b[nextPosition]},
Version: b[nextPosition+1 : nextPosition+3],
Length: b[nextPosition+3 : nextPosition+5],
},
HandshakeProtocol: &TLSHandshakeProtocol{
HandshakeType: []byte{b[nextPosition+5]},
Length: b[nextPosition+6 : nextPosition+9],
},
CertificatesLength: b[nextPosition+9 : nextPosition+12],
}
certificateLength := parsedCertificatesLength(b[nextPosition+9 : nextPosition+12])
certificate.Certificates = b[nextPosition+12 : nextPosition+12+certificateLength]
nextPosition += 12 + certificateLength
serverHelloDone := &ServerHelloDone{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{b[nextPosition]},
Version: b[nextPosition+1 : nextPosition+3],
Length: b[nextPosition+3 : nextPosition+5],
},
HandshakeProtocol: &TLSHandshakeProtocol{
HandshakeType: []byte{b[nextPosition+5]},
Length: b[nextPosition+6 : nextPosition+9],
},
}
return &TLSServerHello{
ServerHello: serverHello,
Certificate: certificate,
ServerHelloDone: serverHelloDone,
}
}
type TLSServerHelloFor1_3 struct {
ServerHello *ServerHello
ChangeCipherSpecProtocol *ChangeCipherSpecProtocol
ApplicationDataProtocols []*TLSApplicationData
}
func (t *TLSServerHelloFor1_3) Bytes() []byte {
b := &bytes.Buffer{}
b.Write(t.ServerHello.Bytes())
b.Write(t.ChangeCipherSpecProtocol.Bytes())
for _, app := range t.ApplicationDataProtocols {
b.Write(app.Bytes())
}
return b.Bytes()
}
func (t *TLSServerHelloFor1_3) GetServerKeyShare() []byte {
for _, extension := range t.ServerHello.HandshakeProtocol.Extentions {
if bytes.Equal(TLS_EXTENSION_TYPE_KEY_SHARE, extension.Type) {
return extension.Data[4:]
}
}
return nil
}
// tls1.3用
func ParsedTLSServerHelloFor1_3(b []byte) *TLSServerHelloFor1_3 {
serverHello, nextPosition := ParsedTLSServerHelloOnly(b)
b = b[nextPosition:]
changeCipherSpec, nextPosition := ParsedChangeCipherSpec(b)
b = b[nextPosition:]
as := []*TLSApplicationData{}
// TODO: 多分、パケット2つ結合してからでないとダメかもしれん
// ただ、1パケットでも大丈夫なときがありそう
// ip header の total length が 1500 超えてるとき、連結するようにすればよさそう(そういうパケットでも、Don't fragment なのはそういうものなの?)
// これは確か、Monitor の話
for {
applicationData := ParsedTLSApplicationData(b)
if applicationData == nil || applicationData.RecordLayer.ContentType[0] != TLS_CONTENT_TYPE_APPLICATION_DATA {
break
}
as = append(as, applicationData)
nextPosition = 5 + bytesToInt(applicationData.RecordLayer.Length)
b = b[nextPosition:]
}
return &TLSServerHelloFor1_3{
ServerHello: serverHello,
ChangeCipherSpecProtocol: changeCipherSpec,
ApplicationDataProtocols: as,
}
}
// こちらも拝借させてもらってる
// ref: https://github.com/sat0ken/go-tcpip/blob/7dd5085f8aa25747a6098cc7d8d8e336ec5fcadd/tls1_3.go#L88
func DecryptChacha20(header []byte, chipertext []byte, tlsConn *TLSv12Connection) []byte {
// header := message[0:5]
// chipertext := message[5:]
// chipertext := message
var key, iv, nonce []byte
if tlsConn.currentHandshake {
key = tlsConn.KeyBlockForTLSv13.serverHandshakeKey
iv = tlsConn.KeyBlockForTLSv13.serverHandshakeIV
nonce = getNonce(tlsConn.ServerHandshakeSeq, 8)
} else {
key = tlsConn.KeyBlockForTLSv13.serverAppKey
iv = tlsConn.KeyBlockForTLSv13.serverAppIV
nonce = getNonce(tlsConn.ServerAppSeq, 8)
}
//fmt.Printf("key is %x, iv is %x\n", key, iv)
aead, err := chacha20poly1305.New(key)
if err != nil {
panic(err)
}
xornonce := getXORNonce(nonce, iv)
//fmt.Printf("decrypt nonce is %x xornonce is %x, chipertext is %x, add is %x\n", nonce, xornonce, chipertext, header)
plaintext, err := aead.Open(nil, xornonce, chipertext, header)
if err != nil {
panic(err)
}
// fmt.Printf("plaintext is : %x\n", plaintext)
return plaintext
}
func EncryptChacha20(message []byte, tlsConn *TLSv12Connection) []byte {
var key, iv, nonce []byte
// Finishedメッセージを送るとき
if tlsConn.currentHandshake {
key = tlsConn.KeyBlockForTLSv13.clientHandshakeKey
iv = tlsConn.KeyBlockForTLSv13.clientHandshakeIV
nonce = getNonce(tlsConn.ClientHandshakeSeq, 8)
} else {
// Application Dataを送る時
key = tlsConn.KeyBlockForTLSv13.clientAppKey
iv = tlsConn.KeyBlockForTLSv13.clientAppIV
nonce = getNonce(tlsConn.ClientAppSeq, 8)
}
// fmt.Printf("key is %x, iv is %x\n", key, iv)
aead, err := chacha20poly1305.New(key)
if err != nil {
log.Fatal(err)
}
// ivとnonceをxorのbit演算をする
// 5.3. レコードごとのノンス
// 2.埋め込まれたシーケンス番号は、静的なclient_write_ivまたはserver_write_iv(役割に応じて)とXORされます。
xornonce := getXORNonce(nonce, iv)
header := strtoByte("170303")
// 平文→暗号化したときのOverHeadを足す
totalLength := len(message) + 16
b := &bytes.Buffer{}
WriteUint16(b, uint16(totalLength))
header = append(header, b.Bytes()...)
// fmt.Printf("encrypt now nonce is %x xornonce is %x, plaintext is %x, add is %x\n", nonce, xornonce, message, header)
ciphertext := aead.Seal(header, xornonce, message, header)
return ciphertext
}
type CertificateVerify struct {
HandshakeType byte
Length []byte
SignatureHashAlgorithms []byte
SignatureLength []byte
Signature []byte
}
const str0x20x64 = "20202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020"
var serverCertificateContextString = []byte(`TLS 1.3, server CertificateVerify`)
// ref: https://github.com/sat0ken/go-tcpip/blob/7dd5085f8aa25747a6098cc7d8d8e336ec5fcadd/tls1_3.go#L285
func (c *CertificateVerify) VerifyServerCertificate(pubkey *rsa.PublicKey, handshake_messages []byte) error {
hash_messages := WriteHash(handshake_messages)
hasher := sha256.New()
// 64回繰り返されるオクテット32(0x20)で構成される文字列
hasher.Write(strtoByte(str0x20x64))
// コンテキスト文字列 = "TLS 1.3, server CertificateVerify"
hasher.Write(serverCertificateContextString)
// セパレータとして機能する単一の0バイト
hasher.Write([]byte{0x00})
hasher.Write(hash_messages)
signed := hasher.Sum(nil)
// fmt.Printf("hash_messages is %x\n, signed is %x\n", hash_messages, signed)
signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}
if err := rsa.VerifyPSS(pubkey, crypto.SHA256, signed, c.Signature, signOpts); err != nil {
return err
}
return nil
}
type FinishedMessage struct {
HandshakeType byte
Length []byte
VerifyData []byte
}
func (f *FinishedMessage) Bytes() []byte {
b := &bytes.Buffer{}
b.WriteByte(f.HandshakeType)
b.Write(f.Length)
b.Write(f.VerifyData)
return b.Bytes()
}
// TLS1.3用
// https://tex2e.github.io/rfc-translater/html/rfc8446.html
// シーケンス番号とwrite_ivをxorした値がnonceになる
func getXORNonce(seqnum, writeiv []byte) []byte {
nonce := make([]byte, len(writeiv))
copy(nonce, writeiv)
for i, b := range seqnum {
nonce[4+i] ^= b
}
return nonce
}
func strtoByte(str string) []byte {
b, _ := hex.DecodeString(str)
return b
}
func parsedCipherSuites(b []byte) uint16 {
return binary.BigEndian.Uint16(b)
}
func parsedCertificatesLength(b []byte) int {
b = append([]byte{0x00}, b...)
return int(binary.BigEndian.Uint32(b))
}
type TLSClientKeyExchange struct {
ClientKeyExchange *ClientKeyExchange
ChangeCipherSpecProtocol *ChangeCipherSpecProtocol
EncryptedHandshakeMessage []byte
}
func ParsedTLSClientKeyexchange(b []byte) *TLSClientKeyExchange {
encryptedPreMasterLength := b[9:11]
clientKeyExchange := &ClientKeyExchange{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{b[0]},
Version: b[1:3],
Length: b[3:5],
},
HandshakeProtocol: &TLSHandshakeProtocol{
HandshakeType: []byte{b[5]},
Length: b[6:9],
},
RSAEncryptedPreMasterSecret: &RSAEncryptedPreMasterSecret{
EncryptedPreMasterLength: encryptedPreMasterLength,
},
}
nextPosition := 11
clientKeyExchange.RSAEncryptedPreMasterSecret.EncryptedPreMaster = b[nextPosition : nextPosition+bytesToInt(encryptedPreMasterLength)]
nextPosition += bytesToInt(encryptedPreMasterLength)
lengthOfChangeCipherSpecProtocol := b[nextPosition+3 : nextPosition+5]
changeCipherSpecProtocol := &ChangeCipherSpecProtocol{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{b[nextPosition]},
Version: b[nextPosition+1 : nextPosition+3],
Length: lengthOfChangeCipherSpecProtocol,
},
ChangeCipherSpecMessage: b[nextPosition+5 : nextPosition+5+bytesToInt(lengthOfChangeCipherSpecProtocol)],
}
nextPosition += 5 + bytesToInt(lengthOfChangeCipherSpecProtocol)
lengthOfEncryptedHandshakeMessage := b[nextPosition+3 : nextPosition+5]
encryptedHandshakeMessage := &EncryptedHandshakeMessage{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{b[nextPosition]},
Version: b[nextPosition+1 : nextPosition+3],
Length: lengthOfEncryptedHandshakeMessage,
},
EncryptedHandshakeMessage_: b[nextPosition+5 : nextPosition+5+bytesToInt(lengthOfEncryptedHandshakeMessage)],
}
return &TLSClientKeyExchange{
ClientKeyExchange: clientKeyExchange,
ChangeCipherSpecProtocol: changeCipherSpecProtocol,
EncryptedHandshakeMessage: encryptedHandshakeMessage.Bytes(),
}
}
func (tlsclientkeyexchange *TLSClientKeyExchange) Bytes() []byte {
b := []byte{}
b = append(b, tlsclientkeyexchange.ClientKeyExchange.Bytes()...)
b = append(b, tlsclientkeyexchange.ChangeCipherSpecProtocol.Bytes()...)
b = append(b, tlsclientkeyexchange.EncryptedHandshakeMessage...)
return b
}
type ClientKeyExchange struct {
RecordLayer *TLSRecordLayer
HandshakeProtocol *TLSHandshakeProtocol
RSAEncryptedPreMasterSecret *RSAEncryptedPreMasterSecret
}
type RSAEncryptedPreMasterSecret struct {
EncryptedPreMasterLength []byte
EncryptedPreMaster []byte
}
func (r *RSAEncryptedPreMasterSecret) Bytes() []byte {
b := []byte{}
b = append(b, r.EncryptedPreMasterLength...)
b = append(b, r.EncryptedPreMaster...)
return b
}
func (c *ClientKeyExchange) Bytes() []byte {
b := []byte{}
b = append(b, c.RecordLayer.Bytes()...)
isFromServer := false
b = append(b, c.HandshakeProtocol.Bytes(isFromServer)...)
b = append(b, c.RSAEncryptedPreMasterSecret.Bytes()...)
return b
}
type ChangeCipherSpecProtocol struct {
RecordLayer *TLSRecordLayer
ChangeCipherSpecMessage []byte
}
func (cc *ChangeCipherSpecProtocol) Bytes() []byte {
b := []byte{}
b = append(b, cc.RecordLayer.Bytes()...)
b = append(b, cc.ChangeCipherSpecMessage...)
return b
}
type EncryptedHandshakeMessage struct {
RecordLayer *TLSRecordLayer
EncryptedHandshakeMessage_ []byte
}
func (e *EncryptedHandshakeMessage) Bytes() []byte {
b := []byte{}
b = append(b, e.RecordLayer.Bytes()...)
b = append(b, e.EncryptedHandshakeMessage_...)
return b
}
const TLS_HANDSHAKE_TYPE_CLIENT_KEY_EXCHANGE = 0x10
const TLS_HANDSHAKE_TYPE_CHANGE_CIPHER_SPEC = 0x14
const TLS_HANDSHAKE_TYPE_FINISHED = 0x14
func NewTLSClientKeyExchangeAndChangeCipherSpecAndFinished(clientHello *TLSClientHello, serverHello *TLSServerHello) (*TLSClientKeyExchange, *KeyBlock, int, []byte, []byte) {
publicKey := serverHello.Certificate.ServerPublicKey()
preMastersecret, encryptedPreMastersecret := generatePreMasterSecret(publicKey)
// log.Printf("pre master secret:\n%x\n", preMastersecret)
// log.Printf("encryptedPreMastersecret:\n%x\n", encryptedPreMastersecret)
encryptedPreMasterLength := &bytes.Buffer{}
WriteUint16(encryptedPreMasterLength, uint16(len(encryptedPreMastersecret)))
rsaEncryptedPreMasterSecret := &RSAEncryptedPreMasterSecret{
EncryptedPreMasterLength: encryptedPreMasterLength.Bytes(),
EncryptedPreMaster: encryptedPreMastersecret,
}
clientKeyExchange := &ClientKeyExchange{
RecordLayer: &TLSRecordLayer{
ContentType: []byte{TLS_CONTENT_TYPE_HANDSHAKE},
Version: TLS_VERSION_1_2,
Length: []byte{0x00, 0x00}, // 後で計算するが、初期化のため
},
HandshakeProtocol: &TLSHandshakeProtocol{