-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathtlsconnection.py
4788 lines (4240 loc) · 216 KB
/
tlsconnection.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
# Authors:
# Trevor Perrin
# Google - added reqCAs parameter
# Google (adapted by Sam Rushing and Marcelo Fernandez) - NPN support
# Google - FALLBACK_SCSV
# Dimitris Moraitis - Anon ciphersuites
# Martin von Loewis - python 3 port
# Yngve Pettersen (ported by Paul Sokolovsky) - TLS 1.2
# Hubert Kario - complete refactoring of key exchange methods, addition
# of ECDH support
#
# See the LICENSE file for legal information regarding use of this file.
"""
MAIN CLASS FOR TLS LITE (START HERE!).
"""
from __future__ import division
import time
import socket
from itertools import chain
from .utils.compat import formatExceptionTrace
from .tlsrecordlayer import TLSRecordLayer
from .session import Session, Ticket
from .constants import *
from .utils.cryptomath import derive_secret, getRandomBytes, HKDF_expand_label
from .utils.dns_utils import is_valid_hostname
from .utils.lists import getFirstMatching
from .errors import *
from .messages import *
from .mathtls import *
from .handshakesettings import HandshakeSettings, KNOWN_VERSIONS, CURVE_ALIASES
from .handshakehashes import HandshakeHashes
from .utils.tackwrapper import *
from .utils.deprecations import deprecated_params
from .keyexchange import KeyExchange, RSAKeyExchange, DHE_RSAKeyExchange, \
ECDHE_RSAKeyExchange, SRPKeyExchange, ADHKeyExchange, \
AECDHKeyExchange, FFDHKeyExchange, ECDHKeyExchange
from .handshakehelpers import HandshakeHelpers
from .utils.cipherfactory import createAESCCM, createAESCCM_8, \
createAESGCM, createCHACHA20
class TLSConnection(TLSRecordLayer):
"""
This class wraps a socket and provides TLS handshaking and data transfer.
To use this class, create a new instance, passing a connected
socket into the constructor. Then call some handshake function.
If the handshake completes without raising an exception, then a TLS
connection has been negotiated. You can transfer data over this
connection as if it were a socket.
This class provides both synchronous and asynchronous versions of
its key functions. The synchronous versions should be used when
writing single-or multi-threaded code using blocking sockets. The
asynchronous versions should be used when performing asynchronous,
event-based I/O with non-blocking sockets.
Asynchronous I/O is a complicated subject; typically, you should
not use the asynchronous functions directly, but should use some
framework like asyncore or Twisted which TLS Lite integrates with
(see
:py:class:`~.integration.tlsasyncdispatchermixin.TLSAsyncDispatcherMixIn`).
"""
def __init__(self, sock):
"""Create a new TLSConnection instance.
:param sock: The socket data will be transmitted on. The
socket should already be connected. It may be in blocking or
non-blocking mode.
:type sock: socket.socket
"""
TLSRecordLayer.__init__(self, sock)
self.serverSigAlg = None
self.ecdhCurve = None
self.dhGroupSize = None
self.extendedMasterSecret = False
self._clientRandom = bytearray(0)
self._serverRandom = bytearray(0)
self.next_proto = None
# whether the CCS was already sent in the connection (for hello retry)
self._ccs_sent = False
# if and how big is the limit on records peer is willing to accept
# used only for TLS 1.2 and earlier
self._peer_record_size_limit = None
self._pha_supported = False
def keyingMaterialExporter(self, label, length=20):
"""Return keying material as described in RFC 5705
:type label: bytearray
:param label: label to be provided for the exporter
:type length: int
:param length: number of bytes of the keying material to export
"""
if label in (b'server finished', b'client finished',
b'master secret', b'key expansion'):
raise ValueError("Forbidden label value")
if self.version < (3, 1):
raise ValueError("Supported only in TLSv1.0 and later")
elif self.version < (3, 3):
return PRF(self.session.masterSecret, label,
self._clientRandom + self._serverRandom,
length)
elif self.version == (3, 3):
if self.session.cipherSuite in CipherSuite.sha384PrfSuites:
return PRF_1_2_SHA384(self.session.masterSecret, label,
self._clientRandom + self._serverRandom,
length)
else:
return PRF_1_2(self.session.masterSecret, label,
self._clientRandom + self._serverRandom,
length)
elif self.version == (3, 4):
prf = 'sha256'
if self.session.cipherSuite in CipherSuite.sha384PrfSuites:
prf = 'sha384'
secret = derive_secret(self.session.exporterMasterSecret, label,
None, prf)
ctxhash = secureHash(bytearray(b''), prf)
return HKDF_expand_label(secret, b"exporter", ctxhash, length, prf)
else:
raise AssertionError("Unknown protocol version")
#*********************************************************
# Client Handshake Functions
#*********************************************************
@deprecated_params({"async_": "async"},
"'{old_name}' is a keyword in Python 3.7, use"
"'{new_name}'")
def handshakeClientAnonymous(self, session=None, settings=None,
checker=None, serverName=None,
async_=False):
"""Perform an anonymous handshake in the role of client.
This function performs an SSL or TLS handshake using an
anonymous Diffie Hellman ciphersuite.
Like any handshake function, this can be called on a closed
TLS connection, or on a TLS connection that is already open.
If called on an open connection it performs a re-handshake.
If the function completes without raising an exception, the
TLS connection will be open and available for data transfer.
If an exception is raised, the connection will have been
automatically closed (if it was ever open).
:type session: ~tlslite.session.Session
:param session: A TLS session to attempt to resume. If the
resumption does not succeed, a full handshake will be
performed.
:type settings: ~tlslite.handshakesettings.HandshakeSettings
:param settings: Various settings which can be used to control
the ciphersuites, certificate types, and SSL/TLS versions
offered by the client.
:type checker: ~tlslite.checker.Checker
:param checker: A Checker instance. This instance will be
invoked to examine the other party's authentication
credentials, if the handshake completes succesfully.
:type serverName: string
:param serverName: The ServerNameIndication TLS Extension.
:type async_: bool
:param async_: If False, this function will block until the
handshake is completed. If True, this function will return a
generator. Successive invocations of the generator will
return 0 if it is waiting to read from the socket, 1 if it is
waiting to write to the socket, or will raise StopIteration if
the handshake operation is completed.
:rtype: None or an iterable
:returns: If 'async_' is True, a generator object will be
returned.
:raises socket.error: If a socket error occurs.
:raises tlslite.errors.TLSAbruptCloseError: If the socket is closed
without a preceding alert.
:raises tlslite.errors.TLSAlert: If a TLS alert is signalled.
:raises tlslite.errors.TLSAuthenticationError: If the checker
doesn't like the other party's authentication credentials.
"""
handshaker = self._handshakeClientAsync(anonParams=(True),
session=session,
settings=settings,
checker=checker,
serverName=serverName)
if async_:
return handshaker
for result in handshaker:
pass
@deprecated_params({"async_": "async"},
"'{old_name}' is a keyword in Python 3.7, use"
"'{new_name}'")
def handshakeClientSRP(self, username, password, session=None,
settings=None, checker=None,
reqTack=True, serverName=None,
async_=False):
"""Perform an SRP handshake in the role of client.
This function performs a TLS/SRP handshake. SRP mutually
authenticates both parties to each other using only a
username and password. This function may also perform a
combined SRP and server-certificate handshake, if the server
chooses to authenticate itself with a certificate chain in
addition to doing SRP.
If the function completes without raising an exception, the
TLS connection will be open and available for data transfer.
If an exception is raised, the connection will have been
automatically closed (if it was ever open).
:type username: bytearray
:param username: The SRP username.
:type password: bytearray
:param password: The SRP password.
:type session: ~tlslite.session.Session
:param session: A TLS session to attempt to resume. This
session must be an SRP session performed with the same username
and password as were passed in. If the resumption does not
succeed, a full SRP handshake will be performed.
:type settings: ~tlslite.handshakesettings.HandshakeSettings
:param settings: Various settings which can be used to control
the ciphersuites, certificate types, and SSL/TLS versions
offered by the client.
:type checker: ~tlslite.checker.Checker
:param checker: A Checker instance. This instance will be
invoked to examine the other party's authentication
credentials, if the handshake completes succesfully.
:type reqTack: bool
:param reqTack: Whether or not to send a "tack" TLS Extension,
requesting the server return a TackExtension if it has one.
:type serverName: string
:param serverName: The ServerNameIndication TLS Extension.
:type async_: bool
:param async_: If False, this function will block until the
handshake is completed. If True, this function will return a
generator. Successive invocations of the generator will
return 0 if it is waiting to read from the socket, 1 if it is
waiting to write to the socket, or will raise StopIteration if
the handshake operation is completed.
:rtype: None or an iterable
:returns: If 'async_' is True, a generator object will be
returned.
:raises socket.error: If a socket error occurs.
:raises tlslite.errors.TLSAbruptCloseError: If the socket is closed
without a preceding alert.
:raises tlslite.errors.TLSAlert: If a TLS alert is signalled.
:raises tlslite.errors.TLSAuthenticationError: If the checker
doesn't like the other party's authentication credentials.
"""
# TODO add deprecation warning
if isinstance(username, str):
username = bytearray(username, 'utf-8')
if isinstance(password, str):
password = bytearray(password, 'utf-8')
handshaker = self._handshakeClientAsync(srpParams=(username, password),
session=session, settings=settings, checker=checker,
reqTack=reqTack, serverName=serverName)
# The handshaker is a Python Generator which executes the handshake.
# It allows the handshake to be run in a "piecewise", asynchronous
# fashion, returning 1 when it is waiting to able to write, 0 when
# it is waiting to read.
#
# If 'async_' is True, the generator is returned to the caller,
# otherwise it is executed to completion here.
if async_:
return handshaker
for result in handshaker:
pass
@deprecated_params({"async_": "async"},
"'{old_name}' is a keyword in Python 3.7, use"
"'{new_name}'")
def handshakeClientCert(self, certChain=None, privateKey=None,
session=None, settings=None, checker=None,
nextProtos=None, reqTack=True, serverName=None,
async_=False, alpn=None):
"""Perform a certificate-based handshake in the role of client.
This function performs an SSL or TLS handshake. The server
will authenticate itself using an X.509 certificate
chain. If the handshake succeeds, the server's certificate
chain will be stored in the session's serverCertChain attribute.
Unless a checker object is passed in, this function does no
validation or checking of the server's certificate chain.
If the server requests client authentication, the
client will send the passed-in certificate chain, and use the
passed-in private key to authenticate itself. If no
certificate chain and private key were passed in, the client
will attempt to proceed without client authentication. The
server may or may not allow this.
If the function completes without raising an exception, the
TLS connection will be open and available for data transfer.
If an exception is raised, the connection will have been
automatically closed (if it was ever open).
:type certChain: ~tlslite.x509certchain.X509CertChain
:param certChain: The certificate chain to be used if the
server requests client authentication.
:type privateKey: ~tlslite.utils.rsakey.RSAKey
:param privateKey: The private key to be used if the server
requests client authentication.
:type session: ~tlslite.session.Session
:param session: A TLS session to attempt to resume. If the
resumption does not succeed, a full handshake will be
performed.
:type settings: ~tlslite.handshakesettings.HandshakeSettings
:param settings: Various settings which can be used to control
the ciphersuites, certificate types, and SSL/TLS versions
offered by the client.
:type checker: ~tlslite.checker.Checker
:param checker: A Checker instance. This instance will be
invoked to examine the other party's authentication
credentials, if the handshake completes succesfully.
:type nextProtos: list of str
:param nextProtos: A list of upper layer protocols ordered by
preference, to use in the Next-Protocol Negotiation Extension.
:type reqTack: bool
:param reqTack: Whether or not to send a "tack" TLS Extension,
requesting the server return a TackExtension if it has one.
:type serverName: string
:param serverName: The ServerNameIndication TLS Extension.
:type async_: bool
:param async_: If False, this function will block until the
handshake is completed. If True, this function will return a
generator. Successive invocations of the generator will
return 0 if it is waiting to read from the socket, 1 if it is
waiting to write to the socket, or will raise StopIteration if
the handshake operation is completed.
:type alpn: list of bytearrays
:param alpn: protocol names to advertise to server as supported by
client in the Application Layer Protocol Negotiation extension.
Example items in the array include b'http/1.1' or b'h2'.
:rtype: None or an iterable
:returns: If 'async_' is True, a generator object will be
returned.
:raises socket.error: If a socket error occurs.
:raises tlslite.errors.TLSAbruptCloseError: If the socket is closed
without a preceding alert.
:raises tlslite.errors.TLSAlert: If a TLS alert is signalled.
:raises tlslite.errors.TLSAuthenticationError: If the checker
doesn't like the other party's authentication credentials.
"""
handshaker = \
self._handshakeClientAsync(certParams=(certChain, privateKey),
session=session, settings=settings,
checker=checker,
serverName=serverName,
nextProtos=nextProtos,
reqTack=reqTack,
alpn=alpn)
# The handshaker is a Python Generator which executes the handshake.
# It allows the handshake to be run in a "piecewise", asynchronous
# fashion, returning 1 when it is waiting to able to write, 0 when
# it is waiting to read.
#
# If 'async_' is True, the generator is returned to the caller,
# otherwise it is executed to completion here.
if async_:
return handshaker
for result in handshaker:
pass
def _handshakeClientAsync(self, srpParams=(), certParams=(), anonParams=(),
session=None, settings=None, checker=None,
nextProtos=None, serverName=None, reqTack=True,
alpn=None):
handshaker = self._handshakeClientAsyncHelper(srpParams=srpParams,
certParams=certParams,
anonParams=anonParams,
session=session,
settings=settings,
serverName=serverName,
nextProtos=nextProtos,
reqTack=reqTack,
alpn=alpn)
for result in self._handshakeWrapperAsync(handshaker, checker):
yield result
def _handshakeClientAsyncHelper(self, srpParams, certParams, anonParams,
session, settings, serverName, nextProtos,
reqTack, alpn):
self._handshakeStart(client=True)
#Unpack parameters
srpUsername = None # srpParams[0]
password = None # srpParams[1]
clientCertChain = None # certParams[0]
privateKey = None # certParams[1]
# Allow only one of (srpParams, certParams, anonParams)
if srpParams:
assert(not certParams)
assert(not anonParams)
srpUsername, password = srpParams
if certParams:
assert(not srpParams)
assert(not anonParams)
clientCertChain, privateKey = certParams
if anonParams:
assert(not srpParams)
assert(not certParams)
#Validate parameters
if srpUsername and not password:
raise ValueError("Caller passed a username but no password")
if password and not srpUsername:
raise ValueError("Caller passed a password but no username")
if clientCertChain and not privateKey:
raise ValueError("Caller passed a cert_chain but no privateKey")
if privateKey and not clientCertChain:
raise ValueError("Caller passed a privateKey but no cert_chain")
if reqTack:
if not tackpyLoaded:
reqTack = False
if not settings or not settings.useExperimentalTackExtension:
reqTack = False
if nextProtos is not None:
if len(nextProtos) == 0:
raise ValueError("Caller passed no nextProtos")
if alpn is not None and not alpn:
raise ValueError("Caller passed empty alpn list")
# reject invalid hostnames but accept empty/None ones
if serverName and not is_valid_hostname(serverName):
raise ValueError("Caller provided invalid server host name: {0}"
.format(serverName))
# Validates the settings and filters out any unsupported ciphers
# or crypto libraries that were requested
if not settings:
settings = HandshakeSettings()
settings = settings.validate()
self.sock.padding_cb = settings.padding_cb
if clientCertChain:
if not isinstance(clientCertChain, X509CertChain):
raise ValueError("Unrecognized certificate type")
if "x509" not in settings.certificateTypes:
raise ValueError("Client certificate doesn't match "\
"Handshake Settings")
if session:
# session.valid() ensures session is resumable and has
# non-empty sessionID
if not session.valid():
session = None #ignore non-resumable sessions...
elif session.resumable:
if session.srpUsername != srpUsername:
raise ValueError("Session username doesn't match")
if session.serverName != serverName:
raise ValueError("Session servername doesn't match")
#Add Faults to parameters
if srpUsername and self.fault == Fault.badUsername:
srpUsername += bytearray(b"GARBAGE")
if password and self.fault == Fault.badPassword:
password += bytearray(b"GARBAGE")
# Tentatively set the client's record version.
# We'll use this for the ClientHello, and if an error occurs
# parsing the Server Hello, we'll use this version for the response
# in TLS 1.3 it always needs to be set to TLS 1.0
self.version = \
(3, 1) if settings.maxVersion > (3, 3) else settings.maxVersion
# OK Start sending messages!
# *****************************
# Send the ClientHello.
for result in self._clientSendClientHello(settings, session,
srpUsername, srpParams, certParams,
anonParams, serverName, nextProtos,
reqTack, alpn):
if result in (0,1): yield result
else: break
clientHello = result
#Get the ServerHello.
for result in self._clientGetServerHello(settings, session,
clientHello):
if result in (0,1): yield result
else: break
serverHello = result
cipherSuite = serverHello.cipher_suite
# Check the serverHello.random if it includes the downgrade protection
# values as described in RFC8446 section 4.1.3
# For TLS1.3
if (settings.maxVersion > (3, 3) and self.version <= (3, 3)) and \
(serverHello.random[-8:] == TLS_1_2_DOWNGRADE_SENTINEL or
serverHello.random[-8:] == TLS_1_1_DOWNGRADE_SENTINEL):
for result in self._sendError(AlertDescription.illegal_parameter,
"Connection terminated because "
"of downgrade protection."):
yield result
# For TLS1.2
if settings.maxVersion == (3, 3) and self.version < (3, 3) and \
serverHello.random[-8:] == TLS_1_1_DOWNGRADE_SENTINEL:
for result in self._sendError(AlertDescription.illegal_parameter,
"Connection terminated because "
"of downgrade protection."):
yield result
# if we're doing tls1.3, use the new code as the negotiation is much
# different
ext = serverHello.getExtension(ExtensionType.supported_versions)
if ext and ext.version > (3, 3):
for result in self._clientTLS13Handshake(settings, session,
clientHello,
clientCertChain,
privateKey,
serverHello):
if result in (0, 1):
yield result
else:
break
if result in ["finished", "resumed_and_finished"]:
self._handshakeDone(resumed=(result == "resumed_and_finished"))
self._serverRandom = serverHello.random
self._clientRandom = clientHello.random
return
else:
raise Exception("unexpected return")
# Choose a matching Next Protocol from server list against ours
# (string or None)
nextProto = self._clientSelectNextProto(nextProtos, serverHello)
# Check if server selected encrypt-then-MAC
if serverHello.getExtension(ExtensionType.encrypt_then_mac):
self._recordLayer.encryptThenMAC = True
if serverHello.getExtension(ExtensionType.extended_master_secret):
self.extendedMasterSecret = True
#If the server elected to resume the session, it is handled here.
for result in self._clientResume(session, serverHello,
clientHello.random,
nextProto, settings):
if result in (0,1): yield result
else: break
if result == "resumed_and_finished":
self._handshakeDone(resumed=True)
self._serverRandom = serverHello.random
self._clientRandom = clientHello.random
# alpn protocol is independent of resumption and renegotiation
# and needs to be negotiated every time
alpnExt = serverHello.getExtension(ExtensionType.alpn)
if alpnExt:
session.appProto = alpnExt.protocol_names[0]
return
#If the server selected an SRP ciphersuite, the client finishes
#reading the post-ServerHello messages, then derives a
#premasterSecret and sends a corresponding ClientKeyExchange.
if cipherSuite in CipherSuite.srpAllSuites:
keyExchange = SRPKeyExchange(cipherSuite, clientHello,
serverHello, None, None,
srpUsername=srpUsername,
password=password,
settings=settings)
#If the server selected an anonymous ciphersuite, the client
#finishes reading the post-ServerHello messages.
elif cipherSuite in CipherSuite.dhAllSuites:
keyExchange = DHE_RSAKeyExchange(cipherSuite, clientHello,
serverHello, None)
elif cipherSuite in CipherSuite.ecdhAllSuites:
acceptedCurves = self._curveNamesToList(settings)
keyExchange = ECDHE_RSAKeyExchange(cipherSuite, clientHello,
serverHello, None,
acceptedCurves)
#If the server selected a certificate-based RSA ciphersuite,
#the client finishes reading the post-ServerHello messages. If
#a CertificateRequest message was sent, the client responds with
#a Certificate message containing its certificate chain (if any),
#and also produces a CertificateVerify message that signs the
#ClientKeyExchange.
else:
keyExchange = RSAKeyExchange(cipherSuite, clientHello,
serverHello, None)
# we'll send few messages here, send them in single TCP packet
self.sock.buffer_writes = True
for result in self._clientKeyExchange(settings, cipherSuite,
clientCertChain,
privateKey,
serverHello.certificate_type,
serverHello.tackExt,
clientHello.random,
serverHello.random,
keyExchange):
if result in (0, 1):
yield result
else: break
(premasterSecret, serverCertChain, clientCertChain,
tackExt) = result
#After having previously sent a ClientKeyExchange, the client now
#initiates an exchange of Finished messages.
# socket buffering is turned off in _clientFinished
for result in self._clientFinished(premasterSecret,
clientHello.random,
serverHello.random,
cipherSuite, settings.cipherImplementations,
nextProto, settings):
if result in (0,1): yield result
else: break
masterSecret = result
# check if an application layer protocol was negotiated
alpnProto = None
alpnExt = serverHello.getExtension(ExtensionType.alpn)
if alpnExt:
alpnProto = alpnExt.protocol_names[0]
ext_c = clientHello.getExtension(ExtensionType.ec_point_formats)
ext_s = serverHello.getExtension(ExtensionType.ec_point_formats)
ext_ec_point = ECPointFormat.uncompressed
if ext_c and ext_s:
ext_ec_point = next((i for i in ext_c.formats \
if i in ext_s.formats), \
ECPointFormat.uncompressed)
# Create the session object which is used for resumptions
self.session = Session()
self.session.create(masterSecret, serverHello.session_id, cipherSuite,
srpUsername, clientCertChain, serverCertChain,
tackExt, (serverHello.tackExt is not None),
serverName,
encryptThenMAC=self._recordLayer.encryptThenMAC,
extendedMasterSecret=self.extendedMasterSecret,
appProto=alpnProto,
# NOTE it must be a reference not a copy
tickets=self.tickets,
tls_1_0_tickets=self.tls_1_0_tickets,
ec_point_format=ext_ec_point)
self._handshakeDone(resumed=False)
self._serverRandom = serverHello.random
self._clientRandom = clientHello.random
def _clientSendClientHello(self, settings, session, srpUsername,
srpParams, certParams, anonParams,
serverName, nextProtos, reqTack, alpn):
#Initialize acceptable ciphersuites
cipherSuites = [CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
if srpParams:
cipherSuites += CipherSuite.getSrpAllSuites(settings)
elif certParams:
cipherSuites += CipherSuite.getTLS13Suites(settings)
cipherSuites += CipherSuite.getEcdsaSuites(settings)
cipherSuites += CipherSuite.getEcdheCertSuites(settings)
cipherSuites += CipherSuite.getDheCertSuites(settings)
cipherSuites += CipherSuite.getCertSuites(settings)
cipherSuites += CipherSuite.getDheDsaSuites(settings)
elif anonParams:
cipherSuites += CipherSuite.getEcdhAnonSuites(settings)
cipherSuites += CipherSuite.getAnonSuites(settings)
else:
assert False
#Add any SCSVs. These are not real cipher suites, but signaling
#values which reuse the cipher suite field in the ClientHello.
wireCipherSuites = list(cipherSuites)
if settings.sendFallbackSCSV:
wireCipherSuites.append(CipherSuite.TLS_FALLBACK_SCSV)
#Initialize acceptable certificate types
certificateTypes = settings.getCertificateTypes()
extensions = []
#Initialize TLS extensions
if settings.useEncryptThenMAC:
extensions.append(TLSExtension().\
create(ExtensionType.encrypt_then_mac,
bytearray(0)))
if settings.useExtendedMasterSecret:
extensions.append(TLSExtension().create(ExtensionType.
extended_master_secret,
bytearray(0)))
# In TLS1.2 advertise support for additional signature types
if settings.maxVersion >= (3, 3):
sigList = self._sigHashesToList(settings)
assert len(sigList) > 0
extensions.append(SignatureAlgorithmsExtension().\
create(sigList))
# if we know any protocols for ALPN, advertise them
if alpn:
extensions.append(ALPNExtension().create(alpn))
session_id = bytearray()
# when TLS 1.3 advertised, add key shares, set fake session_id
shares = None
if next((i for i in settings.versions if i > (3, 3)), None):
# if we have a client cert configured, do indicate we're willing
# to perform Post Handshake Authentication
if certParams and certParams[1]:
extensions.append(TLSExtension(
extType=ExtensionType.post_handshake_auth).
create(bytearray(b'')))
self._client_keypair = certParams
# fake session_id for middlebox compatibility mode
session_id = getRandomBytes(32)
extensions.append(SupportedVersionsExtension().
create(settings.versions))
shares = []
for group_name in settings.keyShares:
group_id = getattr(GroupName, group_name)
key_share = self._genKeyShareEntry(group_id, (3, 4))
shares.append(key_share)
# if TLS 1.3 is enabled, key_share must always be sent
# (unless only static PSK is used)
extensions.append(ClientKeyShareExtension().create(shares))
# add info on types of PSKs supported (also used for
# NewSessionTicket so send basically always)
ext = PskKeyExchangeModesExtension().create(
[getattr(PskKeyExchangeMode, i) for i in settings.psk_modes])
extensions.append(ext)
groups = []
#Send the ECC extensions only if we advertise ECC ciphers
if next((cipher for cipher in cipherSuites \
if cipher in CipherSuite.ecdhAllSuites), None) is not None:
groups.extend(self._curveNamesToList(settings))
if settings.ec_point_formats:
extensions.append(ECPointFormatsExtension().\
create(settings.ec_point_formats))
# Advertise FFDHE groups if we have DHE ciphers
if next((cipher for cipher in cipherSuites
if cipher in CipherSuite.dhAllSuites), None) is not None:
groups.extend(self._groupNamesToList(settings))
# Send the extension only if it will be non empty
if groups:
if shares:
# put the groups used for key shares first, and in order
# (req. from RFC 8446, section 4.2.8)
share_ids = [i.group for i in shares]
diff = set(groups) - set(share_ids)
groups = share_ids + [i for i in groups if i in diff]
extensions.append(SupportedGroupsExtension().create(groups))
if settings.use_heartbeat_extension:
extensions.append(HeartbeatExtension().create(
HeartbeatMode.PEER_ALLOWED_TO_SEND))
self.heartbeat_can_receive = True
if settings.record_size_limit:
extensions.append(RecordSizeLimitExtension().create(
settings.record_size_limit))
# If SessionTicket support is enabled and we have a valid ticket, we
# send it in an attempt to resume the session, if SessionTicket support
# is enabled but we don't have a valid ticket, we send an empty ext
# to indicate support for the feaure
if session and session.tls_1_0_tickets:
# first get rid of expired tickets
session.tls_1_0_tickets[:] = [
i for i in session.tls_1_0_tickets if i.valid()]
# then send first ticket
for cached_ticket in session.tls_1_0_tickets:
extensions.append(SessionTicketExtension().create(
cached_ticket.ticket))
break
else:
# or just advertise that we support session resumption
extensions.append(SessionTicketExtension().create(
bytearray(0)))
else:
extensions.append(SessionTicketExtension().create(
bytearray(0)))
# don't send empty list of extensions or extensions in SSLv3
if not extensions or settings.maxVersion == (3, 0):
extensions = None
sent_version = min(settings.maxVersion, (3, 3))
#Either send ClientHello (with a resumable session)...
if session and session.sessionID:
#If it's resumable, then its
#ciphersuite must be one of the acceptable ciphersuites
if session.cipherSuite not in cipherSuites:
raise ValueError("Session's cipher suite not consistent "\
"with parameters")
else:
clientHello = ClientHello()
clientHello.create(sent_version, getRandomBytes(32),
session.sessionID, wireCipherSuites,
certificateTypes,
session.srpUsername,
reqTack, nextProtos is not None,
session.serverName,
extensions=extensions)
#Or send ClientHello (without)
else:
clientHello = ClientHello()
clientHello.create(sent_version, getRandomBytes(32),
session_id, wireCipherSuites,
certificateTypes,
srpUsername,
reqTack, nextProtos is not None,
serverName,
extensions=extensions)
# Check if padding extension should be added
# we want to add extensions even when using just SSLv3
if settings.usePaddingExtension:
HandshakeHelpers.alignClientHelloPadding(clientHello)
# because TLS 1.3 PSK is sent in ClientHello and signs the ClientHello
# we need to send it as the last extension
if (settings.pskConfigs or (session and session.tickets)) \
and settings.maxVersion >= (3, 4):
ext = PreSharedKeyExtension()
idens = []
binders = []
# if we have a previous session, include it in PSKs too
if session and session.tickets:
now = time.time()
# clean the list from obsolete ones
# RFC says that the tickets MUST NOT be cached longer than
# 7 days
session.tickets[:] = (i for i in session.tickets if
i.time + i.ticket_lifetime > now and
i.time + 7 * 24 * 60 * 60 > now)
if session.tickets:
ticket = session.tickets[0]
# ticket.time is in seconds while the obfuscated time
# is in ms
ticket_time = int(
time.time() * 1000 -
ticket.time * 1000 +
ticket.ticket_age_add) % 2**32
idens.append(PskIdentity().create(ticket.ticket,
ticket_time))
binder_len = 48 if session.cipherSuite in \
CipherSuite.sha384PrfSuites else 32
binders.append(bytearray(binder_len))
for psk in settings.pskConfigs:
# skip PSKs with no identities as they're TLS1.3 incompatible
if not psk[0]:
continue
idens.append(PskIdentity().create(psk[0], 0))
psk_hash = psk[2] if len(psk) > 2 else 'sha256'
assert psk_hash in set(['sha256', 'sha384'])
# create fake binder values to create correct length fields
binders.append(bytearray(32 if psk_hash == 'sha256' else 48))
if idens:
ext.create(idens, binders)
clientHello.extensions.append(ext)
# for HRR case we'll need 1st CH and HRR in handshake hashes,
# so pass them in, truncated CH will be added by the helpers to
# the copy of the hashes
HandshakeHelpers.update_binders(clientHello,
self._handshake_hash,
settings.pskConfigs,
session.tickets if session
else None,
session.resumptionMasterSecret
if session else None)
for result in self._sendMsg(clientHello):
yield result
yield clientHello
def _clientGetServerHello(self, settings, session, clientHello):
client_hello_hash = self._handshake_hash.copy()
for result in self._getMsg(ContentType.handshake,
HandshakeType.server_hello):
if result in (0,1): yield result
else: break
hello_retry = None
ext = result.getExtension(ExtensionType.supported_versions)
if result.random == TLS_1_3_HRR and ext and ext.version > (3, 3):
self.version = ext.version
hello_retry = result
# create synthetic handshake hash
prf_name, prf_size = self._getPRFParams(hello_retry.cipher_suite)
self._handshake_hash = HandshakeHashes()
writer = Writer()
writer.add(HandshakeType.message_hash, 1)
writer.addVarSeq(client_hello_hash.digest(prf_name), 1, 3)
self._handshake_hash.update(writer.bytes)
self._handshake_hash.update(hello_retry.write())
# check if all extensions in the HRR were present in client hello
ch_ext_types = set(i.extType for i in clientHello.extensions)
ch_ext_types.add(ExtensionType.cookie)
bad_ext = next((i for i in hello_retry.extensions
if i.extType not in ch_ext_types), None)
if bad_ext:
bad_ext = ExtensionType.toStr(bad_ext)
for result in self._sendError(AlertDescription
.unsupported_extension,
("Unexpected extension in HRR: "
"{0}").format(bad_ext)):
yield result
# handle cookie extension
cookie = hello_retry.getExtension(ExtensionType.cookie)
if cookie:
clientHello.addExtension(cookie)
# handle key share extension
sr_key_share_ext = hello_retry.getExtension(ExtensionType
.key_share)
if sr_key_share_ext:
group_id = sr_key_share_ext.selected_group
# check if group selected by server is valid
groups_ext = clientHello.getExtension(ExtensionType
.supported_groups)
if group_id not in groups_ext.groups:
for result in self._sendError(AlertDescription
.illegal_parameter,
"Server selected group we "
"did not advertise"):
yield result
cl_key_share_ext = clientHello.getExtension(ExtensionType
.key_share)
# check if the server didn't ask for a group we already sent
if next((entry for entry in cl_key_share_ext.client_shares
if entry.group == group_id), None):
for result in self._sendError(AlertDescription
.illegal_parameter,
"Server selected group we "
"did sent the key share "
"for"):
yield result
key_share = self._genKeyShareEntry(group_id, (3, 4))
# old key shares need to be removed
cl_key_share_ext.client_shares = [key_share]
if not cookie and not sr_key_share_ext:
# HRR did not result in change to Client Hello
for result in self._sendError(AlertDescription.
illegal_parameter,
"Received HRR did not cause "
"update to Client Hello"):
yield result
if clientHello.session_id != hello_retry.session_id:
for result in self._sendError(