-
Notifications
You must be signed in to change notification settings - Fork 420
/
Copy pathSSL.py
3144 lines (2642 loc) · 110 KB
/
SSL.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
from __future__ import annotations
import os
import socket
import typing
import warnings
from collections.abc import Sequence
from errno import errorcode
from functools import partial, wraps
from itertools import chain, count
from sys import platform
from typing import Any, Callable, Optional, TypeVar
from weakref import WeakValueDictionary
from cryptography import x509
from cryptography.hazmat.primitives.asymmetric import ec
from OpenSSL._util import (
StrOrBytesPath as _StrOrBytesPath,
)
from OpenSSL._util import (
exception_from_error_queue as _exception_from_error_queue,
)
from OpenSSL._util import (
ffi as _ffi,
)
from OpenSSL._util import (
lib as _lib,
)
from OpenSSL._util import (
make_assert as _make_assert,
)
from OpenSSL._util import (
no_zero_allocator as _no_zero_allocator,
)
from OpenSSL._util import (
path_bytes as _path_bytes,
)
from OpenSSL._util import (
text_to_bytes_and_warn as _text_to_bytes_and_warn,
)
from OpenSSL.crypto import (
FILETYPE_PEM,
X509,
PKey,
X509Name,
X509Store,
_EllipticCurve,
_PassphraseHelper,
_PrivateKey,
)
__all__ = [
"DTLS_CLIENT_METHOD",
"DTLS_METHOD",
"DTLS_SERVER_METHOD",
"MODE_RELEASE_BUFFERS",
"NO_OVERLAPPING_PROTOCOLS",
"OPENSSL_BUILT_ON",
"OPENSSL_CFLAGS",
"OPENSSL_DIR",
"OPENSSL_PLATFORM",
"OPENSSL_VERSION",
"OPENSSL_VERSION_NUMBER",
"OP_ALL",
"OP_CIPHER_SERVER_PREFERENCE",
"OP_COOKIE_EXCHANGE",
"OP_DONT_INSERT_EMPTY_FRAGMENTS",
"OP_EPHEMERAL_RSA",
"OP_MICROSOFT_BIG_SSLV3_BUFFER",
"OP_MICROSOFT_SESS_ID_BUG",
"OP_MSIE_SSLV2_RSA_PADDING",
"OP_NETSCAPE_CA_DN_BUG",
"OP_NETSCAPE_CHALLENGE_BUG",
"OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG",
"OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG",
"OP_NO_COMPRESSION",
"OP_NO_QUERY_MTU",
"OP_NO_TICKET",
"OP_PKCS1_CHECK_1",
"OP_PKCS1_CHECK_2",
"OP_SINGLE_DH_USE",
"OP_SINGLE_ECDH_USE",
"OP_SSLEAY_080_CLIENT_DH_BUG",
"OP_SSLREF2_REUSE_CERT_TYPE_BUG",
"OP_TLS_BLOCK_PADDING_BUG",
"OP_TLS_D5_BUG",
"OP_TLS_ROLLBACK_BUG",
"RECEIVED_SHUTDOWN",
"SENT_SHUTDOWN",
"SESS_CACHE_BOTH",
"SESS_CACHE_CLIENT",
"SESS_CACHE_NO_AUTO_CLEAR",
"SESS_CACHE_NO_INTERNAL",
"SESS_CACHE_NO_INTERNAL_LOOKUP",
"SESS_CACHE_NO_INTERNAL_STORE",
"SESS_CACHE_OFF",
"SESS_CACHE_SERVER",
"SSL3_VERSION",
"SSLEAY_BUILT_ON",
"SSLEAY_CFLAGS",
"SSLEAY_DIR",
"SSLEAY_PLATFORM",
"SSLEAY_VERSION",
"SSL_CB_ACCEPT_EXIT",
"SSL_CB_ACCEPT_LOOP",
"SSL_CB_ALERT",
"SSL_CB_CONNECT_EXIT",
"SSL_CB_CONNECT_LOOP",
"SSL_CB_EXIT",
"SSL_CB_HANDSHAKE_DONE",
"SSL_CB_HANDSHAKE_START",
"SSL_CB_LOOP",
"SSL_CB_READ",
"SSL_CB_READ_ALERT",
"SSL_CB_WRITE",
"SSL_CB_WRITE_ALERT",
"SSL_ST_ACCEPT",
"SSL_ST_CONNECT",
"SSL_ST_MASK",
"TLS1_1_VERSION",
"TLS1_2_VERSION",
"TLS1_3_VERSION",
"TLS1_VERSION",
"TLS_CLIENT_METHOD",
"TLS_METHOD",
"TLS_SERVER_METHOD",
"VERIFY_CLIENT_ONCE",
"VERIFY_FAIL_IF_NO_PEER_CERT",
"VERIFY_NONE",
"VERIFY_PEER",
"Connection",
"Context",
"Error",
"OP_NO_SSLv2",
"OP_NO_SSLv3",
"OP_NO_TLSv1",
"OP_NO_TLSv1_1",
"OP_NO_TLSv1_2",
"OP_NO_TLSv1_3",
"SSLeay_version",
"SSLv23_METHOD",
"Session",
"SysCallError",
"TLSv1_1_METHOD",
"TLSv1_2_METHOD",
"TLSv1_METHOD",
"WantReadError",
"WantWriteError",
"WantX509LookupError",
"X509VerificationCodes",
"ZeroReturnError",
]
OPENSSL_VERSION_NUMBER: int = _lib.OPENSSL_VERSION_NUMBER
OPENSSL_VERSION: int = _lib.OPENSSL_VERSION
OPENSSL_CFLAGS: int = _lib.OPENSSL_CFLAGS
OPENSSL_PLATFORM: int = _lib.OPENSSL_PLATFORM
OPENSSL_DIR: int = _lib.OPENSSL_DIR
OPENSSL_BUILT_ON: int = _lib.OPENSSL_BUILT_ON
SSLEAY_VERSION = OPENSSL_VERSION
SSLEAY_CFLAGS = OPENSSL_CFLAGS
SSLEAY_PLATFORM = OPENSSL_PLATFORM
SSLEAY_DIR = OPENSSL_DIR
SSLEAY_BUILT_ON = OPENSSL_BUILT_ON
SENT_SHUTDOWN = _lib.SSL_SENT_SHUTDOWN
RECEIVED_SHUTDOWN = _lib.SSL_RECEIVED_SHUTDOWN
SSLv23_METHOD = 3
TLSv1_METHOD = 4
TLSv1_1_METHOD = 5
TLSv1_2_METHOD = 6
TLS_METHOD = 7
TLS_SERVER_METHOD = 8
TLS_CLIENT_METHOD = 9
DTLS_METHOD = 10
DTLS_SERVER_METHOD = 11
DTLS_CLIENT_METHOD = 12
SSL3_VERSION: int = _lib.SSL3_VERSION
TLS1_VERSION: int = _lib.TLS1_VERSION
TLS1_1_VERSION: int = _lib.TLS1_1_VERSION
TLS1_2_VERSION: int = _lib.TLS1_2_VERSION
TLS1_3_VERSION: int = _lib.TLS1_3_VERSION
OP_NO_SSLv2: int = _lib.SSL_OP_NO_SSLv2
OP_NO_SSLv3: int = _lib.SSL_OP_NO_SSLv3
OP_NO_TLSv1: int = _lib.SSL_OP_NO_TLSv1
OP_NO_TLSv1_1: int = _lib.SSL_OP_NO_TLSv1_1
OP_NO_TLSv1_2: int = _lib.SSL_OP_NO_TLSv1_2
OP_NO_TLSv1_3: int = _lib.SSL_OP_NO_TLSv1_3
MODE_RELEASE_BUFFERS: int = _lib.SSL_MODE_RELEASE_BUFFERS
OP_SINGLE_DH_USE: int = _lib.SSL_OP_SINGLE_DH_USE
OP_SINGLE_ECDH_USE: int = _lib.SSL_OP_SINGLE_ECDH_USE
OP_EPHEMERAL_RSA: int = _lib.SSL_OP_EPHEMERAL_RSA
OP_MICROSOFT_SESS_ID_BUG: int = _lib.SSL_OP_MICROSOFT_SESS_ID_BUG
OP_NETSCAPE_CHALLENGE_BUG: int = _lib.SSL_OP_NETSCAPE_CHALLENGE_BUG
OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: int = (
_lib.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
)
OP_SSLREF2_REUSE_CERT_TYPE_BUG: int = _lib.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
OP_MICROSOFT_BIG_SSLV3_BUFFER: int = _lib.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
OP_MSIE_SSLV2_RSA_PADDING: int = _lib.SSL_OP_MSIE_SSLV2_RSA_PADDING
OP_SSLEAY_080_CLIENT_DH_BUG: int = _lib.SSL_OP_SSLEAY_080_CLIENT_DH_BUG
OP_TLS_D5_BUG: int = _lib.SSL_OP_TLS_D5_BUG
OP_TLS_BLOCK_PADDING_BUG: int = _lib.SSL_OP_TLS_BLOCK_PADDING_BUG
OP_DONT_INSERT_EMPTY_FRAGMENTS: int = _lib.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
OP_CIPHER_SERVER_PREFERENCE: int = _lib.SSL_OP_CIPHER_SERVER_PREFERENCE
OP_TLS_ROLLBACK_BUG: int = _lib.SSL_OP_TLS_ROLLBACK_BUG
OP_PKCS1_CHECK_1 = _lib.SSL_OP_PKCS1_CHECK_1
OP_PKCS1_CHECK_2: int = _lib.SSL_OP_PKCS1_CHECK_2
OP_NETSCAPE_CA_DN_BUG: int = _lib.SSL_OP_NETSCAPE_CA_DN_BUG
OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: int = (
_lib.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
)
OP_NO_COMPRESSION: int = _lib.SSL_OP_NO_COMPRESSION
OP_NO_QUERY_MTU: int = _lib.SSL_OP_NO_QUERY_MTU
OP_COOKIE_EXCHANGE: int = _lib.SSL_OP_COOKIE_EXCHANGE
OP_NO_TICKET: int = _lib.SSL_OP_NO_TICKET
try:
OP_NO_RENEGOTIATION: int = _lib.SSL_OP_NO_RENEGOTIATION
__all__.append("OP_NO_RENEGOTIATION")
except AttributeError:
pass
try:
OP_IGNORE_UNEXPECTED_EOF: int = _lib.SSL_OP_IGNORE_UNEXPECTED_EOF
__all__.append("OP_IGNORE_UNEXPECTED_EOF")
except AttributeError:
pass
try:
OP_LEGACY_SERVER_CONNECT: int = _lib.SSL_OP_LEGACY_SERVER_CONNECT
__all__.append("OP_LEGACY_SERVER_CONNECT")
except AttributeError:
pass
OP_ALL: int = _lib.SSL_OP_ALL
VERIFY_PEER: int = _lib.SSL_VERIFY_PEER
VERIFY_FAIL_IF_NO_PEER_CERT: int = _lib.SSL_VERIFY_FAIL_IF_NO_PEER_CERT
VERIFY_CLIENT_ONCE: int = _lib.SSL_VERIFY_CLIENT_ONCE
VERIFY_NONE: int = _lib.SSL_VERIFY_NONE
SESS_CACHE_OFF: int = _lib.SSL_SESS_CACHE_OFF
SESS_CACHE_CLIENT: int = _lib.SSL_SESS_CACHE_CLIENT
SESS_CACHE_SERVER: int = _lib.SSL_SESS_CACHE_SERVER
SESS_CACHE_BOTH: int = _lib.SSL_SESS_CACHE_BOTH
SESS_CACHE_NO_AUTO_CLEAR: int = _lib.SSL_SESS_CACHE_NO_AUTO_CLEAR
SESS_CACHE_NO_INTERNAL_LOOKUP: int = _lib.SSL_SESS_CACHE_NO_INTERNAL_LOOKUP
SESS_CACHE_NO_INTERNAL_STORE: int = _lib.SSL_SESS_CACHE_NO_INTERNAL_STORE
SESS_CACHE_NO_INTERNAL: int = _lib.SSL_SESS_CACHE_NO_INTERNAL
SSL_ST_CONNECT: int = _lib.SSL_ST_CONNECT
SSL_ST_ACCEPT: int = _lib.SSL_ST_ACCEPT
SSL_ST_MASK: int = _lib.SSL_ST_MASK
SSL_CB_LOOP: int = _lib.SSL_CB_LOOP
SSL_CB_EXIT: int = _lib.SSL_CB_EXIT
SSL_CB_READ: int = _lib.SSL_CB_READ
SSL_CB_WRITE: int = _lib.SSL_CB_WRITE
SSL_CB_ALERT: int = _lib.SSL_CB_ALERT
SSL_CB_READ_ALERT: int = _lib.SSL_CB_READ_ALERT
SSL_CB_WRITE_ALERT: int = _lib.SSL_CB_WRITE_ALERT
SSL_CB_ACCEPT_LOOP: int = _lib.SSL_CB_ACCEPT_LOOP
SSL_CB_ACCEPT_EXIT: int = _lib.SSL_CB_ACCEPT_EXIT
SSL_CB_CONNECT_LOOP: int = _lib.SSL_CB_CONNECT_LOOP
SSL_CB_CONNECT_EXIT: int = _lib.SSL_CB_CONNECT_EXIT
SSL_CB_HANDSHAKE_START: int = _lib.SSL_CB_HANDSHAKE_START
SSL_CB_HANDSHAKE_DONE: int = _lib.SSL_CB_HANDSHAKE_DONE
_T = TypeVar("_T")
class _NoOverlappingProtocols:
pass
NO_OVERLAPPING_PROTOCOLS = _NoOverlappingProtocols()
# Callback types.
_ALPNSelectCallback = Callable[
[
"Connection",
typing.List[bytes],
],
typing.Union[bytes, _NoOverlappingProtocols],
]
_CookieGenerateCallback = Callable[["Connection"], bytes]
_CookieVerifyCallback = Callable[["Connection", bytes], bool]
_OCSPClientCallback = Callable[["Connection", bytes, Optional[_T]], bool]
_OCSPServerCallback = Callable[["Connection", Optional[_T]], bytes]
_PassphraseCallback = Callable[[int, bool, Optional[_T]], bytes]
_VerifyCallback = Callable[["Connection", X509, int, int, int], bool]
class X509VerificationCodes:
"""
Success and error codes for X509 verification, as returned by the
underlying ``X509_STORE_CTX_get_error()`` function and passed by pyOpenSSL
to verification callback functions.
See `OpenSSL Verification Errors
<https://www.openssl.org/docs/manmaster/man3/X509_verify_cert_error_string.html#ERROR-CODES>`_
for details.
"""
OK = _lib.X509_V_OK
ERR_UNABLE_TO_GET_ISSUER_CERT = _lib.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
ERR_UNABLE_TO_GET_CRL = _lib.X509_V_ERR_UNABLE_TO_GET_CRL
ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE = (
_lib.X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE
)
ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = (
_lib.X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE
)
ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = (
_lib.X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY
)
ERR_CERT_SIGNATURE_FAILURE = _lib.X509_V_ERR_CERT_SIGNATURE_FAILURE
ERR_CRL_SIGNATURE_FAILURE = _lib.X509_V_ERR_CRL_SIGNATURE_FAILURE
ERR_CERT_NOT_YET_VALID = _lib.X509_V_ERR_CERT_NOT_YET_VALID
ERR_CERT_HAS_EXPIRED = _lib.X509_V_ERR_CERT_HAS_EXPIRED
ERR_CRL_NOT_YET_VALID = _lib.X509_V_ERR_CRL_NOT_YET_VALID
ERR_CRL_HAS_EXPIRED = _lib.X509_V_ERR_CRL_HAS_EXPIRED
ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = (
_lib.X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD
)
ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = (
_lib.X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD
)
ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = (
_lib.X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD
)
ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = (
_lib.X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD
)
ERR_OUT_OF_MEM = _lib.X509_V_ERR_OUT_OF_MEM
ERR_DEPTH_ZERO_SELF_SIGNED_CERT = (
_lib.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
)
ERR_SELF_SIGNED_CERT_IN_CHAIN = _lib.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = (
_lib.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
)
ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = (
_lib.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE
)
ERR_CERT_CHAIN_TOO_LONG = _lib.X509_V_ERR_CERT_CHAIN_TOO_LONG
ERR_CERT_REVOKED = _lib.X509_V_ERR_CERT_REVOKED
ERR_INVALID_CA = _lib.X509_V_ERR_INVALID_CA
ERR_PATH_LENGTH_EXCEEDED = _lib.X509_V_ERR_PATH_LENGTH_EXCEEDED
ERR_INVALID_PURPOSE = _lib.X509_V_ERR_INVALID_PURPOSE
ERR_CERT_UNTRUSTED = _lib.X509_V_ERR_CERT_UNTRUSTED
ERR_CERT_REJECTED = _lib.X509_V_ERR_CERT_REJECTED
ERR_SUBJECT_ISSUER_MISMATCH = _lib.X509_V_ERR_SUBJECT_ISSUER_MISMATCH
ERR_AKID_SKID_MISMATCH = _lib.X509_V_ERR_AKID_SKID_MISMATCH
ERR_AKID_ISSUER_SERIAL_MISMATCH = (
_lib.X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH
)
ERR_KEYUSAGE_NO_CERTSIGN = _lib.X509_V_ERR_KEYUSAGE_NO_CERTSIGN
ERR_UNABLE_TO_GET_CRL_ISSUER = _lib.X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER
ERR_UNHANDLED_CRITICAL_EXTENSION = (
_lib.X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION
)
ERR_KEYUSAGE_NO_CRL_SIGN = _lib.X509_V_ERR_KEYUSAGE_NO_CRL_SIGN
ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = (
_lib.X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION
)
ERR_INVALID_NON_CA = _lib.X509_V_ERR_INVALID_NON_CA
ERR_PROXY_PATH_LENGTH_EXCEEDED = _lib.X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED
ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = (
_lib.X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE
)
ERR_PROXY_CERTIFICATES_NOT_ALLOWED = (
_lib.X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED
)
ERR_INVALID_EXTENSION = _lib.X509_V_ERR_INVALID_EXTENSION
ERR_INVALID_POLICY_EXTENSION = _lib.X509_V_ERR_INVALID_POLICY_EXTENSION
ERR_NO_EXPLICIT_POLICY = _lib.X509_V_ERR_NO_EXPLICIT_POLICY
ERR_DIFFERENT_CRL_SCOPE = _lib.X509_V_ERR_DIFFERENT_CRL_SCOPE
ERR_UNSUPPORTED_EXTENSION_FEATURE = (
_lib.X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE
)
ERR_UNNESTED_RESOURCE = _lib.X509_V_ERR_UNNESTED_RESOURCE
ERR_PERMITTED_VIOLATION = _lib.X509_V_ERR_PERMITTED_VIOLATION
ERR_EXCLUDED_VIOLATION = _lib.X509_V_ERR_EXCLUDED_VIOLATION
ERR_SUBTREE_MINMAX = _lib.X509_V_ERR_SUBTREE_MINMAX
ERR_UNSUPPORTED_CONSTRAINT_TYPE = (
_lib.X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE
)
ERR_UNSUPPORTED_CONSTRAINT_SYNTAX = (
_lib.X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX
)
ERR_UNSUPPORTED_NAME_SYNTAX = _lib.X509_V_ERR_UNSUPPORTED_NAME_SYNTAX
ERR_CRL_PATH_VALIDATION_ERROR = _lib.X509_V_ERR_CRL_PATH_VALIDATION_ERROR
ERR_HOSTNAME_MISMATCH = _lib.X509_V_ERR_HOSTNAME_MISMATCH
ERR_EMAIL_MISMATCH = _lib.X509_V_ERR_EMAIL_MISMATCH
ERR_IP_ADDRESS_MISMATCH = _lib.X509_V_ERR_IP_ADDRESS_MISMATCH
ERR_APPLICATION_VERIFICATION = _lib.X509_V_ERR_APPLICATION_VERIFICATION
# Taken from https://golang.org/src/crypto/x509/root_linux.go
_CERTIFICATE_FILE_LOCATIONS = [
"/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
"/etc/pki/tls/certs/ca-bundle.crt", # Fedora/RHEL 6
"/etc/ssl/ca-bundle.pem", # OpenSUSE
"/etc/pki/tls/cacert.pem", # OpenELEC
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # CentOS/RHEL 7
]
_CERTIFICATE_PATH_LOCATIONS = [
"/etc/ssl/certs", # SLES10/SLES11
]
# These values are compared to output from cffi's ffi.string so they must be
# byte strings.
_CRYPTOGRAPHY_MANYLINUX_CA_DIR = b"/opt/pyca/cryptography/openssl/certs"
_CRYPTOGRAPHY_MANYLINUX_CA_FILE = b"/opt/pyca/cryptography/openssl/cert.pem"
class Error(Exception):
"""
An error occurred in an `OpenSSL.SSL` API.
"""
_raise_current_error = partial(_exception_from_error_queue, Error)
_openssl_assert = _make_assert(Error)
class WantReadError(Error):
pass
class WantWriteError(Error):
pass
class WantX509LookupError(Error):
pass
class ZeroReturnError(Error):
pass
class SysCallError(Error):
pass
class _CallbackExceptionHelper:
"""
A base class for wrapper classes that allow for intelligent exception
handling in OpenSSL callbacks.
:ivar list _problems: Any exceptions that occurred while executing in a
context where they could not be raised in the normal way. Typically
this is because OpenSSL has called into some Python code and requires a
return value. The exceptions are saved to be raised later when it is
possible to do so.
"""
def __init__(self) -> None:
self._problems: list[Exception] = []
def raise_if_problem(self) -> None:
"""
Raise an exception from the OpenSSL error queue or that was previously
captured whe running a callback.
"""
if self._problems:
try:
_raise_current_error()
except Error:
pass
raise self._problems.pop(0)
class _VerifyHelper(_CallbackExceptionHelper):
"""
Wrap a callback such that it can be used as a certificate verification
callback.
"""
def __init__(self, callback: _VerifyCallback) -> None:
_CallbackExceptionHelper.__init__(self)
@wraps(callback)
def wrapper(ok, store_ctx): # type: ignore[no-untyped-def]
x509 = _lib.X509_STORE_CTX_get_current_cert(store_ctx)
_lib.X509_up_ref(x509)
cert = X509._from_raw_x509_ptr(x509)
error_number = _lib.X509_STORE_CTX_get_error(store_ctx)
error_depth = _lib.X509_STORE_CTX_get_error_depth(store_ctx)
index = _lib.SSL_get_ex_data_X509_STORE_CTX_idx()
ssl = _lib.X509_STORE_CTX_get_ex_data(store_ctx, index)
connection = Connection._reverse_mapping[ssl]
try:
result = callback(
connection, cert, error_number, error_depth, ok
)
except Exception as e:
self._problems.append(e)
return 0
else:
if result:
_lib.X509_STORE_CTX_set_error(store_ctx, _lib.X509_V_OK)
return 1
else:
return 0
self.callback = _ffi.callback(
"int (*)(int, X509_STORE_CTX *)", wrapper
)
class _ALPNSelectHelper(_CallbackExceptionHelper):
"""
Wrap a callback such that it can be used as an ALPN selection callback.
"""
def __init__(self, callback: _ALPNSelectCallback) -> None:
_CallbackExceptionHelper.__init__(self)
@wraps(callback)
def wrapper(ssl, out, outlen, in_, inlen, arg): # type: ignore[no-untyped-def]
try:
conn = Connection._reverse_mapping[ssl]
# The string passed to us is made up of multiple
# length-prefixed bytestrings. We need to split that into a
# list.
instr = _ffi.buffer(in_, inlen)[:]
protolist = []
while instr:
encoded_len = instr[0]
proto = instr[1 : encoded_len + 1]
protolist.append(proto)
instr = instr[encoded_len + 1 :]
# Call the callback
outbytes = callback(conn, protolist)
any_accepted = True
if outbytes is NO_OVERLAPPING_PROTOCOLS:
outbytes = b""
any_accepted = False
elif not isinstance(outbytes, bytes):
raise TypeError(
"ALPN callback must return a bytestring or the "
"special NO_OVERLAPPING_PROTOCOLS sentinel value."
)
# Save our callback arguments on the connection object to make
# sure that they don't get freed before OpenSSL can use them.
# Then, return them in the appropriate output parameters.
conn._alpn_select_callback_args = [
_ffi.new("unsigned char *", len(outbytes)),
_ffi.new("unsigned char[]", outbytes),
]
outlen[0] = conn._alpn_select_callback_args[0][0]
out[0] = conn._alpn_select_callback_args[1]
if not any_accepted:
return _lib.SSL_TLSEXT_ERR_NOACK
return _lib.SSL_TLSEXT_ERR_OK
except Exception as e:
self._problems.append(e)
return _lib.SSL_TLSEXT_ERR_ALERT_FATAL
self.callback = _ffi.callback(
(
"int (*)(SSL *, unsigned char **, unsigned char *, "
"const unsigned char *, unsigned int, void *)"
),
wrapper,
)
class _OCSPServerCallbackHelper(_CallbackExceptionHelper):
"""
Wrap a callback such that it can be used as an OCSP callback for the server
side.
Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
ways. For servers, that callback is expected to retrieve some OCSP data and
hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
is expected to check the OCSP data, and returns a negative value on error,
0 if the response is not acceptable, or positive if it is. These are
mutually exclusive return code behaviours, and they mean that we need two
helpers so that we always return an appropriate error code if the user's
code throws an exception.
Given that we have to have two helpers anyway, these helpers are a bit more
helpery than most: specifically, they hide a few more of the OpenSSL
functions so that the user has an easier time writing these callbacks.
This helper implements the server side.
"""
def __init__(self, callback: _OCSPServerCallback[Any]) -> None:
_CallbackExceptionHelper.__init__(self)
@wraps(callback)
def wrapper(ssl, cdata): # type: ignore[no-untyped-def]
try:
conn = Connection._reverse_mapping[ssl]
# Extract the data if any was provided.
if cdata != _ffi.NULL:
data = _ffi.from_handle(cdata)
else:
data = None
# Call the callback.
ocsp_data = callback(conn, data)
if not isinstance(ocsp_data, bytes):
raise TypeError("OCSP callback must return a bytestring.")
# If the OCSP data was provided, we will pass it to OpenSSL.
# However, we have an early exit here: if no OCSP data was
# provided we will just exit out and tell OpenSSL that there
# is nothing to do.
if not ocsp_data:
return 3 # SSL_TLSEXT_ERR_NOACK
# OpenSSL takes ownership of this data and expects it to have
# been allocated by OPENSSL_malloc.
ocsp_data_length = len(ocsp_data)
data_ptr = _lib.OPENSSL_malloc(ocsp_data_length)
_ffi.buffer(data_ptr, ocsp_data_length)[:] = ocsp_data
_lib.SSL_set_tlsext_status_ocsp_resp(
ssl, data_ptr, ocsp_data_length
)
return 0
except Exception as e:
self._problems.append(e)
return 2 # SSL_TLSEXT_ERR_ALERT_FATAL
self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
class _OCSPClientCallbackHelper(_CallbackExceptionHelper):
"""
Wrap a callback such that it can be used as an OCSP callback for the client
side.
Annoyingly, OpenSSL defines one OCSP callback but uses it in two different
ways. For servers, that callback is expected to retrieve some OCSP data and
hand it to OpenSSL, and may return only SSL_TLSEXT_ERR_OK,
SSL_TLSEXT_ERR_FATAL, and SSL_TLSEXT_ERR_NOACK. For clients, that callback
is expected to check the OCSP data, and returns a negative value on error,
0 if the response is not acceptable, or positive if it is. These are
mutually exclusive return code behaviours, and they mean that we need two
helpers so that we always return an appropriate error code if the user's
code throws an exception.
Given that we have to have two helpers anyway, these helpers are a bit more
helpery than most: specifically, they hide a few more of the OpenSSL
functions so that the user has an easier time writing these callbacks.
This helper implements the client side.
"""
def __init__(self, callback: _OCSPClientCallback[Any]) -> None:
_CallbackExceptionHelper.__init__(self)
@wraps(callback)
def wrapper(ssl, cdata): # type: ignore[no-untyped-def]
try:
conn = Connection._reverse_mapping[ssl]
# Extract the data if any was provided.
if cdata != _ffi.NULL:
data = _ffi.from_handle(cdata)
else:
data = None
# Get the OCSP data.
ocsp_ptr = _ffi.new("unsigned char **")
ocsp_len = _lib.SSL_get_tlsext_status_ocsp_resp(ssl, ocsp_ptr)
if ocsp_len < 0:
# No OCSP data.
ocsp_data = b""
else:
# Copy the OCSP data, then pass it to the callback.
ocsp_data = _ffi.buffer(ocsp_ptr[0], ocsp_len)[:]
valid = callback(conn, ocsp_data, data)
# Return 1 on success or 0 on error.
return int(bool(valid))
except Exception as e:
self._problems.append(e)
# Return negative value if an exception is hit.
return -1
self.callback = _ffi.callback("int (*)(SSL *, void *)", wrapper)
class _CookieGenerateCallbackHelper(_CallbackExceptionHelper):
def __init__(self, callback: _CookieGenerateCallback) -> None:
_CallbackExceptionHelper.__init__(self)
@wraps(callback)
def wrapper(ssl, out, outlen): # type: ignore[no-untyped-def]
try:
conn = Connection._reverse_mapping[ssl]
cookie = callback(conn)
out[0 : len(cookie)] = cookie
outlen[0] = len(cookie)
return 1
except Exception as e:
self._problems.append(e)
# "a zero return value can be used to abort the handshake"
return 0
self.callback = _ffi.callback(
"int (*)(SSL *, unsigned char *, unsigned int *)",
wrapper,
)
class _CookieVerifyCallbackHelper(_CallbackExceptionHelper):
def __init__(self, callback: _CookieVerifyCallback) -> None:
_CallbackExceptionHelper.__init__(self)
@wraps(callback)
def wrapper(ssl, c_cookie, cookie_len): # type: ignore[no-untyped-def]
try:
conn = Connection._reverse_mapping[ssl]
return callback(conn, bytes(c_cookie[0:cookie_len]))
except Exception as e:
self._problems.append(e)
return 0
self.callback = _ffi.callback(
"int (*)(SSL *, unsigned char *, unsigned int)",
wrapper,
)
def _asFileDescriptor(obj: Any) -> int:
fd = None
if not isinstance(obj, int):
meth = getattr(obj, "fileno", None)
if meth is not None:
obj = meth()
if isinstance(obj, int):
fd = obj
if not isinstance(fd, int):
raise TypeError("argument must be an int, or have a fileno() method.")
elif fd < 0:
raise ValueError(
f"file descriptor cannot be a negative integer ({fd:i})"
)
return fd
def OpenSSL_version(type: int) -> bytes:
"""
Return a string describing the version of OpenSSL in use.
:param type: One of the :const:`OPENSSL_` constants defined in this module.
"""
return _ffi.string(_lib.OpenSSL_version(type))
SSLeay_version = OpenSSL_version
def _make_requires(flag: int, error: str) -> Callable[[_T], _T]:
"""
Builds a decorator that ensures that functions that rely on OpenSSL
functions that are not present in this build raise NotImplementedError,
rather than AttributeError coming out of cryptography.
:param flag: A cryptography flag that guards the functions, e.g.
``Cryptography_HAS_NEXTPROTONEG``.
:param error: The string to be used in the exception if the flag is false.
"""
def _requires_decorator(func): # type: ignore[no-untyped-def]
if not flag:
@wraps(func)
def explode(*args, **kwargs): # type: ignore[no-untyped-def]
raise NotImplementedError(error)
return explode
else:
return func
return _requires_decorator
_requires_keylog = _make_requires(
getattr(_lib, "Cryptography_HAS_KEYLOG", 0), "Key logging not available"
)
class Session:
"""
A class representing an SSL session. A session defines certain connection
parameters which may be re-used to speed up the setup of subsequent
connections.
.. versionadded:: 0.14
"""
_session: Any
class Context:
"""
:class:`OpenSSL.SSL.Context` instances define the parameters for setting
up new SSL connections.
:param method: One of TLS_METHOD, TLS_CLIENT_METHOD, TLS_SERVER_METHOD,
DTLS_METHOD, DTLS_CLIENT_METHOD, or DTLS_SERVER_METHOD.
SSLv23_METHOD, TLSv1_METHOD, etc. are deprecated and should
not be used.
"""
_methods: typing.ClassVar[
dict[int, tuple[Callable[[], Any], int | None]]
] = {
SSLv23_METHOD: (_lib.TLS_method, None),
TLSv1_METHOD: (_lib.TLS_method, TLS1_VERSION),
TLSv1_1_METHOD: (_lib.TLS_method, TLS1_1_VERSION),
TLSv1_2_METHOD: (_lib.TLS_method, TLS1_2_VERSION),
TLS_METHOD: (_lib.TLS_method, None),
TLS_SERVER_METHOD: (_lib.TLS_server_method, None),
TLS_CLIENT_METHOD: (_lib.TLS_client_method, None),
DTLS_METHOD: (_lib.DTLS_method, None),
DTLS_SERVER_METHOD: (_lib.DTLS_server_method, None),
DTLS_CLIENT_METHOD: (_lib.DTLS_client_method, None),
}
def __init__(self, method: int) -> None:
if not isinstance(method, int):
raise TypeError("method must be an integer")
try:
method_func, version = self._methods[method]
except KeyError:
raise ValueError("No such protocol")
method_obj = method_func()
_openssl_assert(method_obj != _ffi.NULL)
context = _lib.SSL_CTX_new(method_obj)
_openssl_assert(context != _ffi.NULL)
context = _ffi.gc(context, _lib.SSL_CTX_free)
self._context = context
self._passphrase_helper: _PassphraseHelper | None = None
self._passphrase_callback: _PassphraseCallback[Any] | None = None
self._passphrase_userdata: Any | None = None
self._verify_helper: _VerifyHelper | None = None
self._verify_callback: _VerifyCallback | None = None
self._info_callback = None
self._keylog_callback = None
self._tlsext_servername_callback = None
self._app_data = None
self._alpn_select_helper: _ALPNSelectHelper | None = None
self._alpn_select_callback: _ALPNSelectCallback | None = None
self._ocsp_helper: (
_OCSPClientCallbackHelper | _OCSPServerCallbackHelper | None
) = None
self._ocsp_callback: (
_OCSPClientCallback[Any] | _OCSPServerCallback[Any] | None
) = None
self._ocsp_data: Any | None = None
self._cookie_generate_helper: _CookieGenerateCallbackHelper | None = (
None
)
self._cookie_verify_helper: _CookieVerifyCallbackHelper | None = None
self.set_mode(_lib.SSL_MODE_ENABLE_PARTIAL_WRITE)
if version is not None:
self.set_min_proto_version(version)
self.set_max_proto_version(version)
def set_min_proto_version(self, version: int) -> None:
"""
Set the minimum supported protocol version. Setting the minimum
version to 0 will enable protocol versions down to the lowest version
supported by the library.
If the underlying OpenSSL build is missing support for the selected
version, this method will raise an exception.
"""
_openssl_assert(
_lib.SSL_CTX_set_min_proto_version(self._context, version) == 1
)
def set_max_proto_version(self, version: int) -> None:
"""
Set the maximum supported protocol version. Setting the maximum
version to 0 will enable protocol versions up to the highest version
supported by the library.
If the underlying OpenSSL build is missing support for the selected
version, this method will raise an exception.
"""
_openssl_assert(
_lib.SSL_CTX_set_max_proto_version(self._context, version) == 1
)
def load_verify_locations(
self,
cafile: _StrOrBytesPath | None,
capath: _StrOrBytesPath | None = None,
) -> None:
"""
Let SSL know where we can find trusted certificates for the certificate
chain. Note that the certificates have to be in PEM format.
If capath is passed, it must be a directory prepared using the
``c_rehash`` tool included with OpenSSL. Either, but not both, of
*pemfile* or *capath* may be :data:`None`.
:param cafile: In which file we can find the certificates (``bytes`` or
``str``).
:param capath: In which directory we can find the certificates
(``bytes`` or ``str``).
:return: None
"""
if cafile is None:
cafile = _ffi.NULL
else:
cafile = _path_bytes(cafile)
if capath is None:
capath = _ffi.NULL
else:
capath = _path_bytes(capath)
load_result = _lib.SSL_CTX_load_verify_locations(
self._context, cafile, capath
)
if not load_result:
_raise_current_error()
def _wrap_callback(
self, callback: _PassphraseCallback[_T]
) -> _PassphraseHelper:
@wraps(callback)
def wrapper(size: int, verify: bool, userdata: Any) -> bytes:
return callback(size, verify, self._passphrase_userdata)
return _PassphraseHelper(
FILETYPE_PEM, wrapper, more_args=True, truncate=True
)
def set_passwd_cb(
self,
callback: _PassphraseCallback[_T],
userdata: _T | None = None,
) -> None:
"""
Set the passphrase callback. This function will be called
when a private key with a passphrase is loaded.
:param callback: The Python callback to use. This must accept three
positional arguments. First, an integer giving the maximum length
of the passphrase it may return. If the returned passphrase is
longer than this, it will be truncated. Second, a boolean value
which will be true if the user should be prompted for the
passphrase twice and the callback should verify that the two values
supplied are equal. Third, the value given as the *userdata*
parameter to :meth:`set_passwd_cb`. The *callback* must return
a byte string. If an error occurs, *callback* should return a false
value (e.g. an empty string).
:param userdata: (optional) A Python object which will be given as
argument to the callback
:return: None
"""
if not callable(callback):
raise TypeError("callback must be callable")
self._passphrase_helper = self._wrap_callback(callback)