/
automaton_srv.py
1401 lines (1196 loc) · 51.9 KB
/
automaton_srv.py
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
# SPDX-License-Identifier: GPL-2.0-only
# This file is part of Scapy
# See https://scapy.net/ for more information
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
# 2015, 2016, 2017 Maxence Tury
# 2019 Romain Perez
"""
TLS server automaton. This makes for a primitive TLS stack.
Obviously you need rights for network access.
We support versions SSLv2 to TLS 1.3, along with many features.
In order to run a server listening on tcp/4433::
from scapy.layers.tls import *
t = TLSServerAutomaton(mycert='<cert.pem>', mykey='<key.pem>')
t.run()
"""
import socket
import binascii
import struct
import time
from scapy.config import conf
from scapy.packet import Raw
from scapy.pton_ntop import inet_pton
from scapy.utils import get_temp_file, randstring, repr_hex
from scapy.automaton import ATMT
from scapy.error import warning
from scapy.layers.tls.automaton import _TLSAutomaton
from scapy.layers.tls.cert import PrivKeyRSA, PrivKeyECDSA
from scapy.layers.tls.basefields import _tls_version
from scapy.layers.tls.session import tlsSession
from scapy.layers.tls.crypto.groups import _tls_named_groups
from scapy.layers.tls.extensions import TLS_Ext_SupportedVersion_SH, \
TLS_Ext_SupportedGroups, TLS_Ext_Cookie, \
TLS_Ext_SignatureAlgorithms, TLS_Ext_PSKKeyExchangeModes, \
TLS_Ext_EarlyDataIndicationTicket
from scapy.layers.tls.keyexchange_tls13 import TLS_Ext_KeyShare_SH, \
KeyShareEntry, TLS_Ext_KeyShare_HRR, TLS_Ext_PreSharedKey_CH, \
TLS_Ext_PreSharedKey_SH
from scapy.layers.tls.handshake import TLSCertificate, TLSCertificateRequest, \
TLSCertificateVerify, TLSClientHello, TLSClientKeyExchange, TLSFinished, \
TLSServerHello, TLSServerHelloDone, TLSServerKeyExchange, \
_ASN1CertAndExt, TLS13ServerHello, TLS13Certificate, TLS13ClientHello, \
TLSEncryptedExtensions, TLS13HelloRetryRequest, TLS13CertificateRequest, \
TLS13KeyUpdate, TLS13NewSessionTicket
from scapy.layers.tls.handshake_sslv2 import SSLv2ClientCertificate, \
SSLv2ClientFinished, SSLv2ClientHello, SSLv2ClientMasterKey, \
SSLv2RequestCertificate, SSLv2ServerFinished, SSLv2ServerHello, \
SSLv2ServerVerify
from scapy.layers.tls.record import TLSAlert, TLSChangeCipherSpec, \
TLSApplicationData
from scapy.layers.tls.record_tls13 import TLS13
from scapy.layers.tls.crypto.hkdf import TLS13_HKDF
from scapy.layers.tls.crypto.suites import _tls_cipher_suites_cls, \
get_usable_ciphersuites
if conf.crypto_valid:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
class TLSServerAutomaton(_TLSAutomaton):
"""
A simple TLS test server automaton. Try to overload some states or
conditions and see what happens on the other side.
Because of socket and automaton limitations, for now, the best way to
interrupt the server is by sending him 'stop_server'. Interruptions with
Ctrl-Z should work, but this might leave a loose listening socket behind.
In case the server receives a TLSAlert (whatever its type), or a 'goodbye'
message in a SSLv2 version, he will close the client session with a
similar message, and start waiting for new client connections.
_'mycert' and 'mykey' may be provided as filenames. They are needed for any
server authenticated handshake.
_'preferred_ciphersuite' allows the automaton to choose a cipher suite when
offered in the ClientHello. If absent, another one will be chosen.
_'client_auth' means the client has to provide a certificate.
_'is_echo_server' means that everything received will be sent back.
_'max_client_idle_time' is the maximum silence duration from the client.
Once this limit has been reached, the client (if still here) is dropped,
and we wait for a new connection.
"""
def parse_args(self, server="127.0.0.1", sport=4433,
mycert=None, mykey=None,
preferred_ciphersuite=None,
client_auth=False,
is_echo_server=True,
max_client_idle_time=60,
handle_session_ticket=None,
session_ticket_file=None,
curve=None,
cookie=False,
psk=None,
psk_mode=None,
**kargs):
super(TLSServerAutomaton, self).parse_args(mycert=mycert,
mykey=mykey,
**kargs)
try:
if ':' in server:
inet_pton(socket.AF_INET6, server)
else:
inet_pton(socket.AF_INET, server)
tmp = socket.getaddrinfo(server, sport)
except Exception:
tmp = socket.getaddrinfo(socket.getfqdn(server), sport)
self.serversocket = None
self.ip_family = tmp[0][0]
self.local_ip = tmp[0][4][0]
self.local_port = sport
self.remote_ip = None
self.remote_port = None
self.preferred_ciphersuite = preferred_ciphersuite
self.client_auth = client_auth
self.is_echo_server = is_echo_server
self.max_client_idle_time = max_client_idle_time
self.curve = None
self.cookie = cookie
self.psk_secret = psk
self.psk_mode = psk_mode
if handle_session_ticket is None:
handle_session_ticket = session_ticket_file is not None
if handle_session_ticket:
session_ticket_file = session_ticket_file or get_temp_file()
self.handle_session_ticket = handle_session_ticket
self.session_ticket_file = session_ticket_file
for (group_id, ng) in _tls_named_groups.items():
if ng == curve:
self.curve = group_id
def vprint_sessioninfo(self):
if self.verbose:
s = self.cur_session
v = _tls_version[s.tls_version]
self.vprint("Version : %s" % v)
cs = s.wcs.ciphersuite.name
self.vprint("Cipher suite : %s" % cs)
if s.tls_version < 0x0304:
ms = s.master_secret
else:
ms = s.tls13_master_secret
self.vprint("Master secret : %s" % repr_hex(ms))
if s.client_certs:
self.vprint("Client certificate chain: %r" % s.client_certs)
if s.tls_version >= 0x0304:
res_secret = s.tls13_derived_secrets["resumption_secret"]
self.vprint("Resumption master secret : %s" %
repr_hex(res_secret))
self.vprint()
def http_sessioninfo(self):
header = "HTTP/1.1 200 OK\r\n"
header += "Server: Scapy TLS Extension\r\n"
header += "Content-type: text/html\r\n"
header += "Content-length: %d\r\n\r\n"
s = "----- Scapy TLS Server Automaton -----\n\n"
s += "Information on current TLS session:\n\n"
s += "Local end : %s:%d\n" % (self.local_ip, self.local_port)
s += "Remote end : %s:%d\n" % (self.remote_ip, self.remote_port)
v = _tls_version[self.cur_session.tls_version]
s += "Version : %s\n" % v
cs = self.cur_session.wcs.ciphersuite.name
s += "Cipher suite : %s\n" % cs
if self.cur_session.tls_version < 0x0304:
ms = self.cur_session.master_secret
else:
ms = self.cur_session.tls13_master_secret
s += "Master secret : %s\n" % repr_hex(ms)
body = "<html><body><pre>%s</pre></body></html>\r\n\r\n" % s
answer = (header + body) % len(body)
return answer
@ATMT.state(initial=True)
def INITIAL(self):
self.vprint("Starting TLS server automaton.")
self.vprint("Receiving 'stop_server' will cause a graceful exit.")
self.vprint("Interrupting with Ctrl-Z might leave a loose socket hanging.") # noqa: E501
raise self.BIND()
@ATMT.state()
def BIND(self):
s = socket.socket(self.ip_family, socket.SOCK_STREAM)
self.serversocket = s
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.bind((self.local_ip, self.local_port))
s.listen(1)
except Exception as e:
m = "Unable to bind on %s:%d! (%s)" % (
self.local_ip,
self.local_port,
e
)
self.vprint()
self.vprint(m)
self.vprint("Maybe some server is already listening there?")
self.vprint()
raise self.FINAL()
raise self.WAITING_CLIENT()
@ATMT.state()
def SOCKET_CLOSED(self):
self.socket.close()
raise self.WAITING_CLIENT()
@ATMT.state()
def WAITING_CLIENT(self):
self.buffer_out = []
self.buffer_in = []
self.vprint()
self.vprint("Waiting for a new client on %s:%d" % (self.local_ip,
self.local_port))
self.socket, addr = self.serversocket.accept()
if not isinstance(addr, tuple):
addr = self.socket.getpeername()
if len(addr) > 2:
addr = (addr[0], addr[1])
self.remote_ip, self.remote_port = addr
self.vprint("Accepted connection from %s:%d" % (self.remote_ip,
self.remote_port))
self.vprint()
raise self.INIT_TLS_SESSION()
@ATMT.state()
def INIT_TLS_SESSION(self):
"""
XXX We should offer the right key according to the client's suites. For
now server_rsa_key is only used for RSAkx, but we should try to replace
every server_key with both server_rsa_key and server_ecdsa_key.
"""
self.cur_session = tlsSession(connection_end="server")
self.cur_session.server_certs = [self.mycert]
self.cur_session.server_key = self.mykey
if isinstance(self.mykey, PrivKeyRSA):
self.cur_session.server_rsa_key = self.mykey
# elif isinstance(self.mykey, PrivKeyECDSA):
# self.cur_session.server_ecdsa_key = self.mykey
raise self.WAITING_CLIENTFLIGHT1()
@ATMT.state()
def WAITING_CLIENTFLIGHT1(self):
self.get_next_msg()
raise self.RECEIVED_CLIENTFLIGHT1()
@ATMT.state()
def RECEIVED_CLIENTFLIGHT1(self):
pass
# TLS handshake #
@ATMT.condition(RECEIVED_CLIENTFLIGHT1, prio=1)
def tls13_should_handle_ClientHello(self):
self.raise_on_packet(TLS13ClientHello,
self.tls13_HANDLED_CLIENTHELLO)
if self.cur_session.advertised_tls_version == 0x0304:
self.raise_on_packet(TLSClientHello,
self.tls13_HANDLED_CLIENTHELLO)
@ATMT.condition(RECEIVED_CLIENTFLIGHT1, prio=2)
def should_handle_ClientHello(self):
self.raise_on_packet(TLSClientHello,
self.HANDLED_CLIENTHELLO)
@ATMT.state()
def HANDLED_CLIENTHELLO(self):
"""
We extract cipher suites candidates from the client's proposition.
"""
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
if get_usable_ciphersuites(self.cur_pkt.ciphers, kx):
raise self.PREPARE_SERVERFLIGHT1()
raise self.NO_USABLE_CIPHERSUITE()
@ATMT.state()
def NO_USABLE_CIPHERSUITE(self):
self.vprint("No usable cipher suite!")
raise self.CLOSE_NOTIFY()
@ATMT.condition(RECEIVED_CLIENTFLIGHT1, prio=3)
def missing_ClientHello(self):
raise self.MISSING_CLIENTHELLO()
@ATMT.state(final=True)
def MISSING_CLIENTHELLO(self):
self.vprint("Missing ClientHello message!")
raise self.CLOSE_NOTIFY()
@ATMT.state()
def PREPARE_SERVERFLIGHT1(self):
self.add_record()
@ATMT.condition(PREPARE_SERVERFLIGHT1)
def should_add_ServerHello(self):
"""
Selecting a cipher suite should be no trouble as we already caught
the None case previously.
Also, we do not manage extensions at all.
"""
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
usable_suites = get_usable_ciphersuites(self.cur_pkt.ciphers, kx)
c = usable_suites[0]
if self.preferred_ciphersuite in usable_suites:
c = self.preferred_ciphersuite
self.add_msg(TLSServerHello(cipher=c))
raise self.ADDED_SERVERHELLO()
@ATMT.state()
def ADDED_SERVERHELLO(self):
pass
@ATMT.condition(ADDED_SERVERHELLO)
def should_add_Certificate(self):
c = self.buffer_out[-1].msg[0].cipher
if not _tls_cipher_suites_cls[c].kx_alg.anonymous:
self.add_msg(TLSCertificate(certs=self.cur_session.server_certs))
raise self.ADDED_CERTIFICATE()
@ATMT.state()
def ADDED_CERTIFICATE(self):
pass
@ATMT.condition(ADDED_CERTIFICATE)
def should_add_ServerKeyExchange(self):
c = self.buffer_out[-1].msg[0].cipher
if not _tls_cipher_suites_cls[c].kx_alg.no_ske:
self.add_msg(TLSServerKeyExchange())
raise self.ADDED_SERVERKEYEXCHANGE()
@ATMT.state()
def ADDED_SERVERKEYEXCHANGE(self):
pass
@ATMT.condition(ADDED_SERVERKEYEXCHANGE)
def should_add_CertificateRequest(self):
if self.client_auth:
self.add_msg(TLSCertificateRequest())
raise self.ADDED_CERTIFICATEREQUEST()
@ATMT.state()
def ADDED_CERTIFICATEREQUEST(self):
pass
@ATMT.condition(ADDED_CERTIFICATEREQUEST)
def should_add_ServerHelloDone(self):
self.add_msg(TLSServerHelloDone())
raise self.ADDED_SERVERHELLODONE()
@ATMT.state()
def ADDED_SERVERHELLODONE(self):
pass
@ATMT.condition(ADDED_SERVERHELLODONE)
def should_send_ServerFlight1(self):
self.flush_records()
raise self.WAITING_CLIENTFLIGHT2()
@ATMT.state()
def WAITING_CLIENTFLIGHT2(self):
self.get_next_msg()
raise self.RECEIVED_CLIENTFLIGHT2()
@ATMT.state()
def RECEIVED_CLIENTFLIGHT2(self):
pass
@ATMT.condition(RECEIVED_CLIENTFLIGHT2, prio=1)
def should_handle_ClientCertificate(self):
self.raise_on_packet(TLSCertificate,
self.HANDLED_CLIENTCERTIFICATE)
@ATMT.condition(RECEIVED_CLIENTFLIGHT2, prio=2)
def no_ClientCertificate(self):
if self.client_auth:
raise self.MISSING_CLIENTCERTIFICATE()
raise self.HANDLED_CLIENTCERTIFICATE()
@ATMT.state()
def MISSING_CLIENTCERTIFICATE(self):
self.vprint("Missing ClientCertificate!")
raise self.CLOSE_NOTIFY()
@ATMT.state()
def HANDLED_CLIENTCERTIFICATE(self):
if self.client_auth:
self.vprint("Received client certificate chain...")
@ATMT.condition(HANDLED_CLIENTCERTIFICATE, prio=1)
def should_handle_ClientKeyExchange(self):
self.raise_on_packet(TLSClientKeyExchange,
self.HANDLED_CLIENTKEYEXCHANGE)
@ATMT.state()
def HANDLED_CLIENTKEYEXCHANGE(self):
pass
@ATMT.condition(HANDLED_CLIENTCERTIFICATE, prio=2)
def should_handle_Alert_from_ClientCertificate(self):
self.raise_on_packet(TLSAlert,
self.HANDLED_ALERT_FROM_CLIENTCERTIFICATE)
@ATMT.state()
def HANDLED_ALERT_FROM_CLIENTCERTIFICATE(self):
self.vprint("Received Alert message instead of ClientKeyExchange!")
self.vprint(self.cur_pkt.mysummary())
raise self.CLOSE_NOTIFY()
@ATMT.condition(HANDLED_CLIENTCERTIFICATE, prio=3)
def missing_ClientKeyExchange(self):
raise self.MISSING_CLIENTKEYEXCHANGE()
@ATMT.state()
def MISSING_CLIENTKEYEXCHANGE(self):
self.vprint("Missing ClientKeyExchange!")
raise self.CLOSE_NOTIFY()
@ATMT.condition(HANDLED_CLIENTKEYEXCHANGE, prio=1)
def should_handle_CertificateVerify(self):
self.raise_on_packet(TLSCertificateVerify,
self.HANDLED_CERTIFICATEVERIFY)
@ATMT.condition(HANDLED_CLIENTKEYEXCHANGE, prio=2)
def no_CertificateVerify(self):
if self.client_auth:
raise self.MISSING_CERTIFICATEVERIFY()
raise self.HANDLED_CERTIFICATEVERIFY()
@ATMT.state()
def MISSING_CERTIFICATEVERIFY(self):
self.vprint("Missing CertificateVerify!")
raise self.CLOSE_NOTIFY()
@ATMT.state()
def HANDLED_CERTIFICATEVERIFY(self):
pass
@ATMT.condition(HANDLED_CERTIFICATEVERIFY, prio=1)
def should_handle_ChangeCipherSpec(self):
self.raise_on_packet(TLSChangeCipherSpec,
self.HANDLED_CHANGECIPHERSPEC)
@ATMT.state()
def HANDLED_CHANGECIPHERSPEC(self):
pass
@ATMT.condition(HANDLED_CERTIFICATEVERIFY, prio=2)
def should_handle_Alert_from_ClientKeyExchange(self):
self.raise_on_packet(TLSAlert,
self.HANDLED_ALERT_FROM_CLIENTKEYEXCHANGE)
@ATMT.state()
def HANDLED_ALERT_FROM_CLIENTKEYEXCHANGE(self):
self.vprint("Received Alert message instead of ChangeCipherSpec!")
self.vprint(self.cur_pkt.mysummary())
raise self.CLOSE_NOTIFY()
@ATMT.condition(HANDLED_CERTIFICATEVERIFY, prio=3)
def missing_ChangeCipherSpec(self):
raise self.MISSING_CHANGECIPHERSPEC()
@ATMT.state()
def MISSING_CHANGECIPHERSPEC(self):
self.vprint("Missing ChangeCipherSpec!")
raise self.CLOSE_NOTIFY()
@ATMT.condition(HANDLED_CHANGECIPHERSPEC, prio=1)
def should_handle_ClientFinished(self):
self.raise_on_packet(TLSFinished,
self.HANDLED_CLIENTFINISHED)
@ATMT.state()
def HANDLED_CLIENTFINISHED(self):
raise self.PREPARE_SERVERFLIGHT2()
@ATMT.condition(HANDLED_CHANGECIPHERSPEC, prio=2)
def should_handle_Alert_from_ClientFinished(self):
self.raise_on_packet(TLSAlert,
self.HANDLED_ALERT_FROM_CHANGECIPHERSPEC)
@ATMT.state()
def HANDLED_ALERT_FROM_CHANGECIPHERSPEC(self):
self.vprint("Received Alert message instead of Finished!")
raise self.CLOSE_NOTIFY()
@ATMT.condition(HANDLED_CHANGECIPHERSPEC, prio=3)
def missing_ClientFinished(self):
raise self.MISSING_CLIENTFINISHED()
@ATMT.state()
def MISSING_CLIENTFINISHED(self):
self.vprint("Missing Finished!")
raise self.CLOSE_NOTIFY()
@ATMT.state()
def PREPARE_SERVERFLIGHT2(self):
self.add_record()
@ATMT.condition(PREPARE_SERVERFLIGHT2)
def should_add_ChangeCipherSpec(self):
self.add_msg(TLSChangeCipherSpec())
raise self.ADDED_CHANGECIPHERSPEC()
@ATMT.state()
def ADDED_CHANGECIPHERSPEC(self):
pass
@ATMT.condition(ADDED_CHANGECIPHERSPEC)
def should_add_ServerFinished(self):
self.add_record()
self.add_msg(TLSFinished())
raise self.ADDED_SERVERFINISHED()
@ATMT.state()
def ADDED_SERVERFINISHED(self):
pass
@ATMT.condition(ADDED_SERVERFINISHED)
def should_send_ServerFlight2(self):
self.flush_records()
raise self.SENT_SERVERFLIGHT2()
@ATMT.state()
def SENT_SERVERFLIGHT2(self):
self.vprint("TLS handshake completed!")
self.vprint_sessioninfo()
if self.is_echo_server:
self.vprint("Will now act as a simple echo server.")
raise self.WAITING_CLIENTDATA()
# end of TLS handshake #
# TLS 1.3 handshake #
@ATMT.state()
def tls13_HANDLED_CLIENTHELLO(self):
"""
Check if we have to send an HelloRetryRequest
XXX check also with non ECC groups
"""
s = self.cur_session
m = s.handshake_messages_parsed[-1]
# Check if we have to send an HelloRetryRequest
# XXX check also with non ECC groups
if self.curve:
# We first look for a KeyShareEntry with same group as self.curve
if not _tls_named_groups[self.curve] in s.tls13_client_pubshares:
# We then check if self.curve was advertised in SupportedGroups
# extension
for e in m.ext:
if isinstance(e, TLS_Ext_SupportedGroups):
if self.curve in e.groups:
# Here, we need to send an HelloRetryRequest
raise self.tls13_PREPARE_HELLORETRYREQUEST()
raise self.tls13_PREPARE_SERVERFLIGHT1()
@ATMT.state()
def tls13_PREPARE_HELLORETRYREQUEST(self):
pass
@ATMT.condition(tls13_PREPARE_HELLORETRYREQUEST)
def tls13_should_add_HelloRetryRequest(self):
self.add_record(is_tls13=False)
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
usable_suites = get_usable_ciphersuites(self.cur_pkt.ciphers, kx)
c = usable_suites[0]
ext = [TLS_Ext_SupportedVersion_SH(version="TLS 1.3"),
TLS_Ext_KeyShare_HRR(selected_group=_tls_named_groups[self.curve])] # noqa: E501
if self.cookie:
ext += TLS_Ext_Cookie()
p = TLS13HelloRetryRequest(cipher=c, ext=ext)
self.add_msg(p)
self.flush_records()
raise self.tls13_HANDLED_HELLORETRYREQUEST()
@ATMT.state()
def tls13_HANDLED_HELLORETRYREQUEST(self):
pass
@ATMT.condition(tls13_HANDLED_HELLORETRYREQUEST)
def tls13_should_add_ServerHello_from_HRR(self):
raise self.WAITING_CLIENTFLIGHT1()
@ATMT.state()
def tls13_PREPARE_SERVERFLIGHT1(self):
self.add_record(is_tls13=False)
def verify_psk_binder(self, psk_identity, obfuscated_age, binder):
"""
This function verifies the binder received in the 'pre_shared_key'
extension and return the resumption PSK associated with those
values.
The arguments psk_identity, obfuscated_age and binder are taken
from 'pre_shared_key' in the ClientHello.
"""
with open(self.session_ticket_file, "rb") as f:
for line in f:
s = line.strip().split(b';')
if len(s) < 8:
continue
ticket_label = binascii.unhexlify(s[0])
ticket_nonce = binascii.unhexlify(s[1])
tmp = binascii.unhexlify(s[2])
ticket_lifetime = struct.unpack("!I", tmp)[0]
tmp = binascii.unhexlify(s[3])
ticket_age_add = struct.unpack("!I", tmp)[0]
tmp = binascii.unhexlify(s[4])
ticket_start_time = struct.unpack("!I", tmp)[0]
resumption_secret = binascii.unhexlify(s[5])
tmp = binascii.unhexlify(s[6])
res_ciphersuite = struct.unpack("!H", tmp)[0]
tmp = binascii.unhexlify(s[7])
max_early_data_size = struct.unpack("!I", tmp)[0]
# Here psk_identity is a Ticket type but ticket_label is bytes,
# we need to convert psk_identiy to bytes in order to compare
# both strings
if psk_identity.__bytes__() == ticket_label:
# We compute the resumed PSK associated the resumption
# secret
self.vprint("Ticket found in database !")
if res_ciphersuite not in _tls_cipher_suites_cls:
warning("Unknown cipher suite %d", res_ciphersuite)
# we do not try to set a default nor stop the execution
else:
cs_cls = _tls_cipher_suites_cls[res_ciphersuite]
hkdf = TLS13_HKDF(cs_cls.hash_alg.name.lower())
hash_len = hkdf.hash.digest_size
tls13_psk_secret = hkdf.expand_label(resumption_secret,
b"resumption",
ticket_nonce,
hash_len)
# We verify that ticket age is not expired
agesec = int((time.time() - ticket_start_time))
# agems = agesec * 1000
ticket_age = (obfuscated_age - ticket_age_add) % 0xffffffff # noqa: F841, E501
# We verify the PSK binder
s = self.cur_session
if s.tls13_retry:
handshake_context = struct.pack("B", 254)
handshake_context += struct.pack("B", 0)
handshake_context += struct.pack("B", 0)
handshake_context += struct.pack("B", hash_len)
digest = hashes.Hash(hkdf.hash, backend=default_backend()) # noqa: E501
digest.update(s.handshake_messages[0])
handshake_context += digest.finalize()
for m in s.handshake_messages[1:]:
if (isinstance(TLS13ClientHello) or
isinstance(TLSClientHello)):
handshake_context += m[:-hash_len - 3]
else:
handshake_context += m
else:
handshake_context = s.handshake_messages[0][:-hash_len - 3] # noqa: E501
# We compute the binder key
# XXX use the compute_tls13_early_secrets() function
tls13_early_secret = hkdf.extract(None, tls13_psk_secret)
binder_key = hkdf.derive_secret(tls13_early_secret,
b"res binder",
b"")
computed_binder = hkdf.compute_verify_data(binder_key,
handshake_context) # noqa: E501
if (agesec < ticket_lifetime and
computed_binder == binder):
self.vprint("Ticket has been accepted ! ")
self.max_early_data_size = max_early_data_size
self.resumed_ciphersuite = res_ciphersuite
return tls13_psk_secret
self.vprint("Ticket has not been accepted ! Fallback to a complete handshake") # noqa: E501
return None
@ATMT.condition(tls13_PREPARE_SERVERFLIGHT1)
def tls13_should_add_ServerHello(self):
psk_identity = None
psk_key_exchange_mode = None
obfuscated_age = None
# XXX check ClientHello extensions...
for m in reversed(self.cur_session.handshake_messages_parsed):
if isinstance(m, (TLS13ClientHello, TLSClientHello)):
for e in m.ext:
if isinstance(e, TLS_Ext_PreSharedKey_CH):
psk_identity = e.identities[0].identity
obfuscated_age = e.identities[0].obfuscated_ticket_age
binder = e.binders[0].binder
# For out-of-bound PSK, obfuscated_ticket_age should be
# 0. We use this field to distinguish between out-of-
# bound PSK and resumed PSK
is_out_of_band_psk = (obfuscated_age == 0)
if isinstance(e, TLS_Ext_PSKKeyExchangeModes):
psk_key_exchange_mode = e.kxmodes[0]
if isinstance(self.mykey, PrivKeyRSA):
kx = "RSA"
elif isinstance(self.mykey, PrivKeyECDSA):
kx = "ECDSA"
usable_suites = get_usable_ciphersuites(self.cur_pkt.ciphers, kx)
c = usable_suites[0]
group = next(iter(self.cur_session.tls13_client_pubshares))
ext = [TLS_Ext_SupportedVersion_SH(version="TLS 1.3")]
if (psk_identity and obfuscated_age and psk_key_exchange_mode):
s = self.cur_session
if is_out_of_band_psk:
# Handshake with external PSK authentication
# XXX test that self.psk_secret is set
s.tls13_psk_secret = binascii.unhexlify(self.psk_secret)
# 0: "psk_ke"
# 1: "psk_dhe_ke"
if psk_key_exchange_mode == 1:
server_kse = KeyShareEntry(group=group)
ext += TLS_Ext_KeyShare_SH(server_share=server_kse)
ext += TLS_Ext_PreSharedKey_SH(selected_identity=0)
else:
resumption_psk = self.verify_psk_binder(psk_identity,
obfuscated_age,
binder)
if resumption_psk is None:
# We did not find a ticket matching the one provided in the
# ClientHello. We fallback to a regular 1-RTT handshake
server_kse = KeyShareEntry(group=group)
ext += [TLS_Ext_KeyShare_SH(server_share=server_kse)]
else:
# 0: "psk_ke"
# 1: "psk_dhe_ke"
if psk_key_exchange_mode == 1:
server_kse = KeyShareEntry(group=group)
ext += [TLS_Ext_KeyShare_SH(server_share=server_kse)]
ext += [TLS_Ext_PreSharedKey_SH(selected_identity=0)]
self.cur_session.tls13_psk_secret = resumption_psk
else:
# Standard Handshake
ext += TLS_Ext_KeyShare_SH(server_share=KeyShareEntry(group=group))
if self.cur_session.sid is not None:
p = TLS13ServerHello(cipher=c, sid=self.cur_session.sid, ext=ext)
else:
p = TLS13ServerHello(cipher=c, ext=ext)
self.add_msg(p)
raise self.tls13_ADDED_SERVERHELLO()
@ATMT.state()
def tls13_ADDED_SERVERHELLO(self):
# If the client proposed a non-empty session ID in his ClientHello
# he requested the middlebox compatibility mode (RFC8446, appendix D.4)
# In this case, the server should send a dummy ChangeCipherSpec in
# between the ServerHello and the encrypted handshake messages
if self.cur_session.sid is not None:
self.add_record(is_tls12=True)
self.add_msg(TLSChangeCipherSpec())
@ATMT.condition(tls13_ADDED_SERVERHELLO)
def tls13_should_add_EncryptedExtensions(self):
self.add_record(is_tls13=True)
self.add_msg(TLSEncryptedExtensions(extlen=0))
raise self.tls13_ADDED_ENCRYPTEDEXTENSIONS()
@ATMT.state()
def tls13_ADDED_ENCRYPTEDEXTENSIONS(self):
pass
@ATMT.condition(tls13_ADDED_ENCRYPTEDEXTENSIONS)
def tls13_should_add_CertificateRequest(self):
if self.client_auth:
ext = [TLS_Ext_SignatureAlgorithms(sig_algs=["sha256+rsaepss"])]
p = TLS13CertificateRequest(ext=ext)
self.add_msg(p)
raise self.tls13_ADDED_CERTIFICATEREQUEST()
@ATMT.state()
def tls13_ADDED_CERTIFICATEREQUEST(self):
pass
@ATMT.condition(tls13_ADDED_CERTIFICATEREQUEST)
def tls13_should_add_Certificate(self):
# If a PSK is set, an extension pre_shared_key
# was send in the ServerHello. No certificate should
# be send here
if not self.cur_session.tls13_psk_secret:
certs = []
for c in self.cur_session.server_certs:
certs += _ASN1CertAndExt(cert=c)
self.add_msg(TLS13Certificate(certs=certs))
raise self.tls13_ADDED_CERTIFICATE()
@ATMT.state()
def tls13_ADDED_CERTIFICATE(self):
pass
@ATMT.condition(tls13_ADDED_CERTIFICATE)
def tls13_should_add_CertificateVerifiy(self):
if not self.cur_session.tls13_psk_secret:
self.add_msg(TLSCertificateVerify())
raise self.tls13_ADDED_CERTIFICATEVERIFY()
@ATMT.state()
def tls13_ADDED_CERTIFICATEVERIFY(self):
pass
@ATMT.condition(tls13_ADDED_CERTIFICATEVERIFY)
def tls13_should_add_Finished(self):
self.add_msg(TLSFinished())
raise self.tls13_ADDED_SERVERFINISHED()
@ATMT.state()
def tls13_ADDED_SERVERFINISHED(self):
pass
@ATMT.condition(tls13_ADDED_SERVERFINISHED)
def tls13_should_send_ServerFlight1(self):
self.flush_records()
raise self.tls13_WAITING_CLIENTFLIGHT2()
@ATMT.state()
def tls13_WAITING_CLIENTFLIGHT2(self):
self.get_next_msg()
raise self.tls13_RECEIVED_CLIENTFLIGHT2()
@ATMT.state()
def tls13_RECEIVED_CLIENTFLIGHT2(self):
pass
@ATMT.condition(tls13_RECEIVED_CLIENTFLIGHT2, prio=1)
def tls13_should_handle_ClientFlight2(self):
self.raise_on_packet(TLS13Certificate,
self.TLS13_HANDLED_CLIENTCERTIFICATE)
@ATMT.condition(tls13_RECEIVED_CLIENTFLIGHT2, prio=2)
def tls13_should_handle_Alert_from_ClientCertificate(self):
self.raise_on_packet(TLSAlert,
self.TLS13_HANDLED_ALERT_FROM_CLIENTCERTIFICATE)
@ATMT.state()
def TLS13_HANDLED_ALERT_FROM_CLIENTCERTIFICATE(self):
self.vprint("Received Alert message instead of ClientKeyExchange!")
self.vprint(self.cur_pkt.mysummary())
raise self.CLOSE_NOTIFY()
# For Middlebox compatibility (see RFC8446, appendix D.4)
# a dummy ChangeCipherSpec record can be send. In this case,
# this function just read the ChangeCipherSpec message and
# go back in a previous state continuing with the next TLS 1.3
# record
@ATMT.condition(tls13_RECEIVED_CLIENTFLIGHT2, prio=3)
def tls13_should_handle_ClientCCS(self):
self.raise_on_packet(TLSChangeCipherSpec,
self.tls13_RECEIVED_CLIENTFLIGHT2)
@ATMT.condition(tls13_RECEIVED_CLIENTFLIGHT2, prio=4)
def tls13_no_ClientCertificate(self):
if self.client_auth:
raise self.TLS13_MISSING_CLIENTCERTIFICATE()
self.raise_on_packet(TLSFinished,
self.TLS13_HANDLED_CLIENTFINISHED)
# RFC8446, section 4.4.2.4 :
# "If the client does not send any certificates (i.e., it sends an empty
# Certificate message), the server MAY at its discretion either
# continue the handshake without client authentication or abort the
# handshake with a "certificate_required" alert."
# Here, we abort the handshake.
@ATMT.state()
def TLS13_HANDLED_CLIENTCERTIFICATE(self):
if self.client_auth:
self.vprint("Received client certificate chain...")
if isinstance(self.cur_pkt, TLS13Certificate):
if self.cur_pkt.certslen == 0:
self.vprint("but it's empty !")
raise self.TLS13_MISSING_CLIENTCERTIFICATE()
@ATMT.condition(TLS13_HANDLED_CLIENTCERTIFICATE)
def tls13_should_handle_ClientCertificateVerify(self):
self.raise_on_packet(TLSCertificateVerify,
self.TLS13_HANDLED_CLIENT_CERTIFICATEVERIFY)
@ATMT.condition(TLS13_HANDLED_CLIENTCERTIFICATE, prio=2)
def tls13_no_Client_CertificateVerify(self):
if self.client_auth:
raise self.TLS13_MISSING_CLIENTCERTIFICATE()
raise self.TLS13_HANDLED_CLIENT_CERTIFICATEVERIFY()
@ATMT.state()
def TLS13_HANDLED_CLIENT_CERTIFICATEVERIFY(self):
pass
@ATMT.condition(TLS13_HANDLED_CLIENT_CERTIFICATEVERIFY)
def tls13_should_handle_ClientFinished(self):
self.raise_on_packet(TLSFinished,
self.TLS13_HANDLED_CLIENTFINISHED)
@ATMT.state()
def TLS13_MISSING_CLIENTCERTIFICATE(self):
self.vprint("Missing ClientCertificate!")
self.add_record()
self.add_msg(TLSAlert(level=2, descr=0x74))
self.flush_records()
self.vprint("Sending TLSAlert 116")
self.socket.close()
raise self.WAITING_CLIENT()
@ATMT.state()
def TLS13_HANDLED_CLIENTFINISHED(self):
self.vprint("TLS handshake completed!")
self.vprint_sessioninfo()
if self.is_echo_server:
self.vprint("Will now act as a simple echo server.")
raise self.WAITING_CLIENTDATA()
# end of TLS 1.3 handshake #
@ATMT.state()
def WAITING_CLIENTDATA(self):
self.get_next_msg(self.max_client_idle_time, 1)
raise self.RECEIVED_CLIENTDATA()
@ATMT.state()
def RECEIVED_CLIENTDATA(self):
pass
def save_ticket(self, ticket):
"""
This function save a ticket and others parameters in the
file given as argument to the automaton
Warning : The file is not protected and contains sensitive
information. It should be used only for testing purpose.
"""
if (not isinstance(ticket, TLS13NewSessionTicket) or
self.session_ticket_file is None):
return
s = self.cur_session
with open(self.session_ticket_file, "ab") as f:
# ticket;ticket_nonce;obfuscated_age;start_time;resumption_secret
line = binascii.hexlify(ticket.ticket)
line += b";"
line += binascii.hexlify(ticket.ticket_nonce)
line += b";"
line += binascii.hexlify(struct.pack("!I", ticket.ticket_lifetime))
line += b";"
line += binascii.hexlify(struct.pack("!I", ticket.ticket_age_add))
line += b";"
line += binascii.hexlify(struct.pack("!I", int(time.time())))
line += b";"
line += binascii.hexlify(s.tls13_derived_secrets["resumption_secret"]) # noqa: E501
line += b";"
line += binascii.hexlify(struct.pack("!H", s.wcs.ciphersuite.val))
line += b";"
if (ticket.ext is None or ticket.extlen is None or
ticket.extlen == 0):
line += binascii.hexlify(struct.pack("!I", 0))
else:
for e in ticket.ext:
if isinstance(e, TLS_Ext_EarlyDataIndicationTicket):
max_size = struct.pack("!I", e.max_early_data_size)
line += binascii.hexlify(max_size)
line += b"\n"
f.write(line)
@ATMT.condition(RECEIVED_CLIENTDATA)
def should_handle_ClientData(self):
if not self.buffer_in:
self.vprint("Client idle time maxed out.")
raise self.CLOSE_NOTIFY()
p = self.buffer_in[0]
self.buffer_in = self.buffer_in[1:]
recv_data = b""
if isinstance(p, TLSApplicationData):
print("> Received: %r" % p.data)
recv_data = p.data
lines = recv_data.split(b"\n")
for line in lines: