forked from pyca/cryptography
-
Notifications
You must be signed in to change notification settings - Fork 2
/
backend.py
2652 lines (2304 loc) · 98.8 KB
/
backend.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
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
import collections
import contextlib
import itertools
import typing
import warnings
from contextlib import contextmanager
from cryptography import utils, x509
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.backends.openssl import aead
from cryptography.hazmat.backends.openssl.ciphers import _CipherContext
from cryptography.hazmat.backends.openssl.cmac import _CMACContext
from cryptography.hazmat.backends.openssl.dh import (
_DHParameters,
_DHPrivateKey,
_DHPublicKey,
_dh_params_dup,
)
from cryptography.hazmat.backends.openssl.dsa import (
_DSAParameters,
_DSAPrivateKey,
_DSAPublicKey,
)
from cryptography.hazmat.backends.openssl.ec import (
_EllipticCurvePrivateKey,
_EllipticCurvePublicKey,
)
from cryptography.hazmat.backends.openssl.ed25519 import (
_Ed25519PrivateKey,
_Ed25519PublicKey,
)
from cryptography.hazmat.backends.openssl.ed448 import (
_ED448_KEY_SIZE,
_Ed448PrivateKey,
_Ed448PublicKey,
)
from cryptography.hazmat.backends.openssl.hashes import _HashContext
from cryptography.hazmat.backends.openssl.hmac import _HMACContext
from cryptography.hazmat.backends.openssl.poly1305 import (
_POLY1305_KEY_SIZE,
_Poly1305Context,
)
from cryptography.hazmat.backends.openssl.rsa import (
_RSAPrivateKey,
_RSAPublicKey,
)
from cryptography.hazmat.backends.openssl.x25519 import (
_X25519PrivateKey,
_X25519PublicKey,
)
from cryptography.hazmat.backends.openssl.x448 import (
_X448PrivateKey,
_X448PublicKey,
)
from cryptography.hazmat.bindings._rust import (
x509 as rust_x509,
)
from cryptography.hazmat.bindings.openssl import binding
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding
from cryptography.hazmat.primitives.asymmetric import (
dh,
dsa,
ec,
ed25519,
ed448,
rsa,
x25519,
x448,
)
from cryptography.hazmat.primitives.asymmetric.padding import (
MGF1,
OAEP,
PKCS1v15,
PSS,
)
from cryptography.hazmat.primitives.asymmetric.types import (
CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES,
PRIVATE_KEY_TYPES,
PUBLIC_KEY_TYPES,
)
from cryptography.hazmat.primitives.ciphers import (
BlockCipherAlgorithm,
CipherAlgorithm,
)
from cryptography.hazmat.primitives.ciphers.algorithms import (
AES,
AES128,
AES256,
ARC4,
Camellia,
ChaCha20,
SM4,
TripleDES,
_BlowfishInternal,
_CAST5Internal,
_IDEAInternal,
_SEEDInternal,
)
from cryptography.hazmat.primitives.ciphers.modes import (
CBC,
CFB,
CFB8,
CTR,
ECB,
GCM,
Mode,
OFB,
XTS,
)
from cryptography.hazmat.primitives.kdf import scrypt
from cryptography.hazmat.primitives.serialization import pkcs7, ssh
from cryptography.hazmat.primitives.serialization.pkcs12 import (
PBES,
PKCS12Certificate,
PKCS12KeyAndCertificates,
_ALLOWED_PKCS12_TYPES,
_PKCS12_CAS_TYPES,
)
_MemoryBIO = collections.namedtuple("_MemoryBIO", ["bio", "char_ptr"])
# Not actually supported, just used as a marker for some serialization tests.
class _RC2:
pass
class Backend:
"""
OpenSSL API binding interfaces.
"""
name = "openssl"
# FIPS has opinions about acceptable algorithms and key sizes, but the
# disallowed algorithms are still present in OpenSSL. They just error if
# you try to use them. To avoid that we allowlist the algorithms in
# FIPS 140-3. This isn't ideal, but FIPS 140-3 is trash so here we are.
_fips_aead = {
b"aes-128-ccm",
b"aes-192-ccm",
b"aes-256-ccm",
b"aes-128-gcm",
b"aes-192-gcm",
b"aes-256-gcm",
}
# TripleDES encryption is disallowed/deprecated throughout 2023 in
# FIPS 140-3. To keep it simple we denylist any use of TripleDES (TDEA).
_fips_ciphers = (AES,)
# Sometimes SHA1 is still permissible. That logic is contained
# within the various *_supported methods.
_fips_hashes = (
hashes.SHA224,
hashes.SHA256,
hashes.SHA384,
hashes.SHA512,
hashes.SHA512_224,
hashes.SHA512_256,
hashes.SHA3_224,
hashes.SHA3_256,
hashes.SHA3_384,
hashes.SHA3_512,
hashes.SHAKE128,
hashes.SHAKE256,
)
_fips_ecdh_curves = (
ec.SECP224R1,
ec.SECP256R1,
ec.SECP384R1,
ec.SECP521R1,
)
_fips_rsa_min_key_size = 2048
_fips_rsa_min_public_exponent = 65537
_fips_dsa_min_modulus = 1 << 2048
_fips_dh_min_key_size = 2048
_fips_dh_min_modulus = 1 << _fips_dh_min_key_size
def __init__(self):
self._binding = binding.Binding()
self._ffi = self._binding.ffi
self._lib = self._binding.lib
self._rsa_skip_check_key = False
self._fips_enabled = self._is_fips_enabled()
self._cipher_registry = {}
self._register_default_ciphers()
if self._fips_enabled and self._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE:
warnings.warn(
"OpenSSL FIPS mode is enabled. Can't enable DRBG fork safety.",
UserWarning,
)
else:
self.activate_osrandom_engine()
self._dh_types = [self._lib.EVP_PKEY_DH]
if self._lib.Cryptography_HAS_EVP_PKEY_DHX:
self._dh_types.append(self._lib.EVP_PKEY_DHX)
def __repr__(self) -> str:
return "<OpenSSLBackend(version: {}, FIPS: {})>".format(
self.openssl_version_text(), self._fips_enabled
)
def openssl_assert(
self,
ok: bool,
errors: typing.Optional[typing.List[binding._OpenSSLError]] = None,
) -> None:
return binding._openssl_assert(self._lib, ok, errors=errors)
def _is_fips_enabled(self) -> bool:
if self._lib.Cryptography_HAS_300_FIPS:
mode = self._lib.EVP_default_properties_is_fips_enabled(
self._ffi.NULL
)
else:
mode = getattr(self._lib, "FIPS_mode", lambda: 0)()
if mode == 0:
# OpenSSL without FIPS pushes an error on the error stack
self._lib.ERR_clear_error()
return bool(mode)
def _enable_fips(self) -> None:
# This function enables FIPS mode for OpenSSL 3.0.0 on installs that
# have the FIPS provider installed properly.
self._binding._enable_fips()
assert self._is_fips_enabled()
self._fips_enabled = self._is_fips_enabled()
def activate_builtin_random(self) -> None:
if self._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE:
# Obtain a new structural reference.
e = self._lib.ENGINE_get_default_RAND()
if e != self._ffi.NULL:
self._lib.ENGINE_unregister_RAND(e)
# Reset the RNG to use the built-in.
res = self._lib.RAND_set_rand_method(self._ffi.NULL)
self.openssl_assert(res == 1)
# decrement the structural reference from get_default_RAND
res = self._lib.ENGINE_finish(e)
self.openssl_assert(res == 1)
@contextlib.contextmanager
def _get_osurandom_engine(self):
# Fetches an engine by id and returns it. This creates a structural
# reference.
e = self._lib.ENGINE_by_id(self._lib.Cryptography_osrandom_engine_id)
self.openssl_assert(e != self._ffi.NULL)
# Initialize the engine for use. This adds a functional reference.
res = self._lib.ENGINE_init(e)
self.openssl_assert(res == 1)
try:
yield e
finally:
# Decrement the structural ref incremented by ENGINE_by_id.
res = self._lib.ENGINE_free(e)
self.openssl_assert(res == 1)
# Decrement the functional ref incremented by ENGINE_init.
res = self._lib.ENGINE_finish(e)
self.openssl_assert(res == 1)
def activate_osrandom_engine(self) -> None:
if self._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE:
# Unregister and free the current engine.
self.activate_builtin_random()
with self._get_osurandom_engine() as e:
# Set the engine as the default RAND provider.
res = self._lib.ENGINE_set_default_RAND(e)
self.openssl_assert(res == 1)
# Reset the RNG to use the engine
res = self._lib.RAND_set_rand_method(self._ffi.NULL)
self.openssl_assert(res == 1)
def osrandom_engine_implementation(self) -> str:
buf = self._ffi.new("char[]", 64)
with self._get_osurandom_engine() as e:
res = self._lib.ENGINE_ctrl_cmd(
e, b"get_implementation", len(buf), buf, self._ffi.NULL, 0
)
self.openssl_assert(res > 0)
return self._ffi.string(buf).decode("ascii")
def openssl_version_text(self) -> str:
"""
Friendly string name of the loaded OpenSSL library. This is not
necessarily the same version as it was compiled against.
Example: OpenSSL 1.1.1d 10 Sep 2019
"""
return self._ffi.string(
self._lib.OpenSSL_version(self._lib.OPENSSL_VERSION)
).decode("ascii")
def openssl_version_number(self) -> int:
return self._lib.OpenSSL_version_num()
def create_hmac_ctx(
self, key: bytes, algorithm: hashes.HashAlgorithm
) -> _HMACContext:
return _HMACContext(self, key, algorithm)
def _evp_md_from_algorithm(self, algorithm: hashes.HashAlgorithm):
if algorithm.name == "blake2b" or algorithm.name == "blake2s":
alg = "{}{}".format(
algorithm.name, algorithm.digest_size * 8
).encode("ascii")
else:
alg = algorithm.name.encode("ascii")
evp_md = self._lib.EVP_get_digestbyname(alg)
return evp_md
def _evp_md_non_null_from_algorithm(self, algorithm: hashes.HashAlgorithm):
evp_md = self._evp_md_from_algorithm(algorithm)
self.openssl_assert(evp_md != self._ffi.NULL)
return evp_md
def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
if self._fips_enabled and not isinstance(algorithm, self._fips_hashes):
return False
evp_md = self._evp_md_from_algorithm(algorithm)
return evp_md != self._ffi.NULL
def signature_hash_supported(
self, algorithm: hashes.HashAlgorithm
) -> bool:
# Dedicated check for hashing algorithm use in message digest for
# signatures, e.g. RSA PKCS#1 v1.5 SHA1 (sha1WithRSAEncryption).
if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
return False
return self.hash_supported(algorithm)
def scrypt_supported(self) -> bool:
if self._fips_enabled:
return False
else:
return self._lib.Cryptography_HAS_SCRYPT == 1
def hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
# FIPS mode still allows SHA1 for HMAC
if self._fips_enabled and isinstance(algorithm, hashes.SHA1):
return True
return self.hash_supported(algorithm)
def create_hash_ctx(
self, algorithm: hashes.HashAlgorithm
) -> hashes.HashContext:
return _HashContext(self, algorithm)
def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool:
if self._fips_enabled:
# FIPS mode requires AES. TripleDES is disallowed/deprecated in
# FIPS 140-3.
if not isinstance(cipher, self._fips_ciphers):
return False
try:
adapter = self._cipher_registry[type(cipher), type(mode)]
except KeyError:
return False
evp_cipher = adapter(self, cipher, mode)
return self._ffi.NULL != evp_cipher
def register_cipher_adapter(self, cipher_cls, mode_cls, adapter):
if (cipher_cls, mode_cls) in self._cipher_registry:
raise ValueError(
"Duplicate registration for: {} {}.".format(
cipher_cls, mode_cls
)
)
self._cipher_registry[cipher_cls, mode_cls] = adapter
def _register_default_ciphers(self) -> None:
for cipher_cls in [AES, AES128, AES256]:
for mode_cls in [CBC, CTR, ECB, OFB, CFB, CFB8, GCM]:
self.register_cipher_adapter(
cipher_cls,
mode_cls,
GetCipherByName(
"{cipher.name}-{cipher.key_size}-{mode.name}"
),
)
for mode_cls in [CBC, CTR, ECB, OFB, CFB]:
self.register_cipher_adapter(
Camellia,
mode_cls,
GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}"),
)
for mode_cls in [CBC, CFB, CFB8, OFB]:
self.register_cipher_adapter(
TripleDES, mode_cls, GetCipherByName("des-ede3-{mode.name}")
)
self.register_cipher_adapter(
TripleDES, ECB, GetCipherByName("des-ede3")
)
for mode_cls in [CBC, CFB, OFB, ECB]:
self.register_cipher_adapter(
_BlowfishInternal, mode_cls, GetCipherByName("bf-{mode.name}")
)
for mode_cls in [CBC, CFB, OFB, ECB]:
self.register_cipher_adapter(
_SEEDInternal, mode_cls, GetCipherByName("seed-{mode.name}")
)
for cipher_cls, mode_cls in itertools.product(
[_CAST5Internal, _IDEAInternal],
[CBC, OFB, CFB, ECB],
):
self.register_cipher_adapter(
cipher_cls,
mode_cls,
GetCipherByName("{cipher.name}-{mode.name}"),
)
self.register_cipher_adapter(ARC4, type(None), GetCipherByName("rc4"))
# We don't actually support RC2, this is just used by some tests.
self.register_cipher_adapter(_RC2, type(None), GetCipherByName("rc2"))
self.register_cipher_adapter(
ChaCha20, type(None), GetCipherByName("chacha20")
)
self.register_cipher_adapter(AES, XTS, _get_xts_cipher)
for mode_cls in [ECB, CBC, OFB, CFB, CTR]:
self.register_cipher_adapter(
SM4, mode_cls, GetCipherByName("sm4-{mode.name}")
)
def create_symmetric_encryption_ctx(
self, cipher: CipherAlgorithm, mode: Mode
) -> _CipherContext:
return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)
def create_symmetric_decryption_ctx(
self, cipher: CipherAlgorithm, mode: Mode
) -> _CipherContext:
return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT)
def pbkdf2_hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
return self.hmac_supported(algorithm)
def derive_pbkdf2_hmac(
self,
algorithm: hashes.HashAlgorithm,
length: int,
salt: bytes,
iterations: int,
key_material: bytes,
) -> bytes:
buf = self._ffi.new("unsigned char[]", length)
evp_md = self._evp_md_non_null_from_algorithm(algorithm)
key_material_ptr = self._ffi.from_buffer(key_material)
res = self._lib.PKCS5_PBKDF2_HMAC(
key_material_ptr,
len(key_material),
salt,
len(salt),
iterations,
evp_md,
length,
buf,
)
self.openssl_assert(res == 1)
return self._ffi.buffer(buf)[:]
def _consume_errors(self) -> typing.List[binding._OpenSSLError]:
return binding._consume_errors(self._lib)
def _consume_errors_with_text(
self,
) -> typing.List[binding._OpenSSLErrorWithText]:
return binding._consume_errors_with_text(self._lib)
def _bn_to_int(self, bn) -> int:
assert bn != self._ffi.NULL
self.openssl_assert(not self._lib.BN_is_negative(bn))
bn_num_bytes = self._lib.BN_num_bytes(bn)
bin_ptr = self._ffi.new("unsigned char[]", bn_num_bytes)
bin_len = self._lib.BN_bn2bin(bn, bin_ptr)
# A zero length means the BN has value 0
self.openssl_assert(bin_len >= 0)
val = int.from_bytes(self._ffi.buffer(bin_ptr)[:bin_len], "big")
return val
def _int_to_bn(self, num: int, bn=None):
"""
Converts a python integer to a BIGNUM. The returned BIGNUM will not
be garbage collected (to support adding them to structs that take
ownership of the object). Be sure to register it for GC if it will
be discarded after use.
"""
assert bn is None or bn != self._ffi.NULL
if bn is None:
bn = self._ffi.NULL
binary = num.to_bytes(int(num.bit_length() / 8.0 + 1), "big")
bn_ptr = self._lib.BN_bin2bn(binary, len(binary), bn)
self.openssl_assert(bn_ptr != self._ffi.NULL)
return bn_ptr
def generate_rsa_private_key(
self, public_exponent: int, key_size: int
) -> rsa.RSAPrivateKey:
rsa._verify_rsa_parameters(public_exponent, key_size)
rsa_cdata = self._lib.RSA_new()
self.openssl_assert(rsa_cdata != self._ffi.NULL)
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
bn = self._int_to_bn(public_exponent)
bn = self._ffi.gc(bn, self._lib.BN_free)
res = self._lib.RSA_generate_key_ex(
rsa_cdata, key_size, bn, self._ffi.NULL
)
self.openssl_assert(res == 1)
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPrivateKey(
self, rsa_cdata, evp_pkey, self._rsa_skip_check_key
)
def generate_rsa_parameters_supported(
self, public_exponent: int, key_size: int
) -> bool:
return (
public_exponent >= 3
and public_exponent & 1 != 0
and key_size >= 512
)
def load_rsa_private_numbers(
self, numbers: rsa.RSAPrivateNumbers
) -> rsa.RSAPrivateKey:
rsa._check_private_key_components(
numbers.p,
numbers.q,
numbers.d,
numbers.dmp1,
numbers.dmq1,
numbers.iqmp,
numbers.public_numbers.e,
numbers.public_numbers.n,
)
rsa_cdata = self._lib.RSA_new()
self.openssl_assert(rsa_cdata != self._ffi.NULL)
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
p = self._int_to_bn(numbers.p)
q = self._int_to_bn(numbers.q)
d = self._int_to_bn(numbers.d)
dmp1 = self._int_to_bn(numbers.dmp1)
dmq1 = self._int_to_bn(numbers.dmq1)
iqmp = self._int_to_bn(numbers.iqmp)
e = self._int_to_bn(numbers.public_numbers.e)
n = self._int_to_bn(numbers.public_numbers.n)
res = self._lib.RSA_set0_factors(rsa_cdata, p, q)
self.openssl_assert(res == 1)
res = self._lib.RSA_set0_key(rsa_cdata, n, e, d)
self.openssl_assert(res == 1)
res = self._lib.RSA_set0_crt_params(rsa_cdata, dmp1, dmq1, iqmp)
self.openssl_assert(res == 1)
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPrivateKey(
self, rsa_cdata, evp_pkey, self._rsa_skip_check_key
)
def load_rsa_public_numbers(
self, numbers: rsa.RSAPublicNumbers
) -> rsa.RSAPublicKey:
rsa._check_public_key_components(numbers.e, numbers.n)
rsa_cdata = self._lib.RSA_new()
self.openssl_assert(rsa_cdata != self._ffi.NULL)
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
e = self._int_to_bn(numbers.e)
n = self._int_to_bn(numbers.n)
res = self._lib.RSA_set0_key(rsa_cdata, n, e, self._ffi.NULL)
self.openssl_assert(res == 1)
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPublicKey(self, rsa_cdata, evp_pkey)
def _create_evp_pkey_gc(self):
evp_pkey = self._lib.EVP_PKEY_new()
self.openssl_assert(evp_pkey != self._ffi.NULL)
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
return evp_pkey
def _rsa_cdata_to_evp_pkey(self, rsa_cdata):
evp_pkey = self._create_evp_pkey_gc()
res = self._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata)
self.openssl_assert(res == 1)
return evp_pkey
def _bytes_to_bio(self, data: bytes):
"""
Return a _MemoryBIO namedtuple of (BIO, char*).
The char* is the storage for the BIO and it must stay alive until the
BIO is finished with.
"""
data_ptr = self._ffi.from_buffer(data)
bio = self._lib.BIO_new_mem_buf(data_ptr, len(data))
self.openssl_assert(bio != self._ffi.NULL)
return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_ptr)
def _create_mem_bio_gc(self):
"""
Creates an empty memory BIO.
"""
bio_method = self._lib.BIO_s_mem()
self.openssl_assert(bio_method != self._ffi.NULL)
bio = self._lib.BIO_new(bio_method)
self.openssl_assert(bio != self._ffi.NULL)
bio = self._ffi.gc(bio, self._lib.BIO_free)
return bio
def _read_mem_bio(self, bio) -> bytes:
"""
Reads a memory BIO. This only works on memory BIOs.
"""
buf = self._ffi.new("char **")
buf_len = self._lib.BIO_get_mem_data(bio, buf)
self.openssl_assert(buf_len > 0)
self.openssl_assert(buf[0] != self._ffi.NULL)
bio_data = self._ffi.buffer(buf[0], buf_len)[:]
return bio_data
def _evp_pkey_to_private_key(self, evp_pkey) -> PRIVATE_KEY_TYPES:
"""
Return the appropriate type of PrivateKey given an evp_pkey cdata
pointer.
"""
key_type = self._lib.EVP_PKEY_id(evp_pkey)
if key_type == self._lib.EVP_PKEY_RSA:
rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
self.openssl_assert(rsa_cdata != self._ffi.NULL)
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
return _RSAPrivateKey(
self, rsa_cdata, evp_pkey, self._rsa_skip_check_key
)
elif (
key_type == self._lib.EVP_PKEY_RSA_PSS
and not self._lib.CRYPTOGRAPHY_IS_LIBRESSL
and not self._lib.CRYPTOGRAPHY_IS_BORINGSSL
and not self._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111E
):
# At the moment the way we handle RSA PSS keys is to strip the
# PSS constraints from them and treat them as normal RSA keys
# Unfortunately the RSA * itself tracks this data so we need to
# extract, serialize, and reload it without the constraints.
rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
self.openssl_assert(rsa_cdata != self._ffi.NULL)
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
bio = self._create_mem_bio_gc()
res = self._lib.i2d_RSAPrivateKey_bio(bio, rsa_cdata)
self.openssl_assert(res == 1)
return self.load_der_private_key(
self._read_mem_bio(bio), password=None
)
elif key_type == self._lib.EVP_PKEY_DSA:
dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)
self.openssl_assert(dsa_cdata != self._ffi.NULL)
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
return _DSAPrivateKey(self, dsa_cdata, evp_pkey)
elif key_type == self._lib.EVP_PKEY_EC:
ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey)
self.openssl_assert(ec_cdata != self._ffi.NULL)
ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
return _EllipticCurvePrivateKey(self, ec_cdata, evp_pkey)
elif key_type in self._dh_types:
dh_cdata = self._lib.EVP_PKEY_get1_DH(evp_pkey)
self.openssl_assert(dh_cdata != self._ffi.NULL)
dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
return _DHPrivateKey(self, dh_cdata, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_ED25519", None):
# EVP_PKEY_ED25519 is not present in OpenSSL < 1.1.1
return _Ed25519PrivateKey(self, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_X448", None):
# EVP_PKEY_X448 is not present in OpenSSL < 1.1.1
return _X448PrivateKey(self, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_X25519", None):
# EVP_PKEY_X25519 is not present in OpenSSL < 1.1.0
return _X25519PrivateKey(self, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_ED448", None):
# EVP_PKEY_ED448 is not present in OpenSSL < 1.1.1
return _Ed448PrivateKey(self, evp_pkey)
else:
raise UnsupportedAlgorithm("Unsupported key type.")
def _evp_pkey_to_public_key(self, evp_pkey) -> PUBLIC_KEY_TYPES:
"""
Return the appropriate type of PublicKey given an evp_pkey cdata
pointer.
"""
key_type = self._lib.EVP_PKEY_id(evp_pkey)
if key_type == self._lib.EVP_PKEY_RSA:
rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
self.openssl_assert(rsa_cdata != self._ffi.NULL)
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
return _RSAPublicKey(self, rsa_cdata, evp_pkey)
elif (
key_type == self._lib.EVP_PKEY_RSA_PSS
and not self._lib.CRYPTOGRAPHY_IS_LIBRESSL
and not self._lib.CRYPTOGRAPHY_IS_BORINGSSL
and not self._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111E
):
rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
self.openssl_assert(rsa_cdata != self._ffi.NULL)
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
bio = self._create_mem_bio_gc()
res = self._lib.i2d_RSAPublicKey_bio(bio, rsa_cdata)
self.openssl_assert(res == 1)
return self.load_der_public_key(self._read_mem_bio(bio))
elif key_type == self._lib.EVP_PKEY_DSA:
dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)
self.openssl_assert(dsa_cdata != self._ffi.NULL)
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
return _DSAPublicKey(self, dsa_cdata, evp_pkey)
elif key_type == self._lib.EVP_PKEY_EC:
ec_cdata = self._lib.EVP_PKEY_get1_EC_KEY(evp_pkey)
if ec_cdata == self._ffi.NULL:
errors = self._consume_errors_with_text()
raise ValueError("Unable to load EC key", errors)
ec_cdata = self._ffi.gc(ec_cdata, self._lib.EC_KEY_free)
return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey)
elif key_type in self._dh_types:
dh_cdata = self._lib.EVP_PKEY_get1_DH(evp_pkey)
self.openssl_assert(dh_cdata != self._ffi.NULL)
dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
return _DHPublicKey(self, dh_cdata, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_ED25519", None):
# EVP_PKEY_ED25519 is not present in OpenSSL < 1.1.1
return _Ed25519PublicKey(self, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_X448", None):
# EVP_PKEY_X448 is not present in OpenSSL < 1.1.1
return _X448PublicKey(self, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_X25519", None):
# EVP_PKEY_X25519 is not present in OpenSSL < 1.1.0
return _X25519PublicKey(self, evp_pkey)
elif key_type == getattr(self._lib, "EVP_PKEY_ED448", None):
# EVP_PKEY_X25519 is not present in OpenSSL < 1.1.1
return _Ed448PublicKey(self, evp_pkey)
else:
raise UnsupportedAlgorithm("Unsupported key type.")
def _oaep_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
return isinstance(
algorithm,
(
hashes.SHA1,
hashes.SHA224,
hashes.SHA256,
hashes.SHA384,
hashes.SHA512,
),
)
def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool:
if isinstance(padding, PKCS1v15):
return True
elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):
# SHA1 is permissible in MGF1 in FIPS even when SHA1 is blocked
# as signature algorithm.
if self._fips_enabled and isinstance(
padding._mgf._algorithm, hashes.SHA1
):
return True
else:
return self.hash_supported(padding._mgf._algorithm)
elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):
return self._oaep_hash_supported(
padding._mgf._algorithm
) and self._oaep_hash_supported(padding._algorithm)
else:
return False
def generate_dsa_parameters(self, key_size: int) -> dsa.DSAParameters:
if key_size not in (1024, 2048, 3072, 4096):
raise ValueError(
"Key size must be 1024, 2048, 3072, or 4096 bits."
)
ctx = self._lib.DSA_new()
self.openssl_assert(ctx != self._ffi.NULL)
ctx = self._ffi.gc(ctx, self._lib.DSA_free)
res = self._lib.DSA_generate_parameters_ex(
ctx,
key_size,
self._ffi.NULL,
0,
self._ffi.NULL,
self._ffi.NULL,
self._ffi.NULL,
)
self.openssl_assert(res == 1)
return _DSAParameters(self, ctx)
def generate_dsa_private_key(
self, parameters: dsa.DSAParameters
) -> dsa.DSAPrivateKey:
ctx = self._lib.DSAparams_dup(
parameters._dsa_cdata # type: ignore[attr-defined]
)
self.openssl_assert(ctx != self._ffi.NULL)
ctx = self._ffi.gc(ctx, self._lib.DSA_free)
self._lib.DSA_generate_key(ctx)
evp_pkey = self._dsa_cdata_to_evp_pkey(ctx)
return _DSAPrivateKey(self, ctx, evp_pkey)
def generate_dsa_private_key_and_parameters(
self, key_size: int
) -> dsa.DSAPrivateKey:
parameters = self.generate_dsa_parameters(key_size)
return self.generate_dsa_private_key(parameters)
def _dsa_cdata_set_values(self, dsa_cdata, p, q, g, pub_key, priv_key):
res = self._lib.DSA_set0_pqg(dsa_cdata, p, q, g)
self.openssl_assert(res == 1)
res = self._lib.DSA_set0_key(dsa_cdata, pub_key, priv_key)
self.openssl_assert(res == 1)
def load_dsa_private_numbers(
self, numbers: dsa.DSAPrivateNumbers
) -> dsa.DSAPrivateKey:
dsa._check_dsa_private_numbers(numbers)
parameter_numbers = numbers.public_numbers.parameter_numbers
dsa_cdata = self._lib.DSA_new()
self.openssl_assert(dsa_cdata != self._ffi.NULL)
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
p = self._int_to_bn(parameter_numbers.p)
q = self._int_to_bn(parameter_numbers.q)
g = self._int_to_bn(parameter_numbers.g)
pub_key = self._int_to_bn(numbers.public_numbers.y)
priv_key = self._int_to_bn(numbers.x)
self._dsa_cdata_set_values(dsa_cdata, p, q, g, pub_key, priv_key)
evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata)
return _DSAPrivateKey(self, dsa_cdata, evp_pkey)
def load_dsa_public_numbers(
self, numbers: dsa.DSAPublicNumbers
) -> dsa.DSAPublicKey:
dsa._check_dsa_parameters(numbers.parameter_numbers)
dsa_cdata = self._lib.DSA_new()
self.openssl_assert(dsa_cdata != self._ffi.NULL)
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
p = self._int_to_bn(numbers.parameter_numbers.p)
q = self._int_to_bn(numbers.parameter_numbers.q)
g = self._int_to_bn(numbers.parameter_numbers.g)
pub_key = self._int_to_bn(numbers.y)
priv_key = self._ffi.NULL
self._dsa_cdata_set_values(dsa_cdata, p, q, g, pub_key, priv_key)
evp_pkey = self._dsa_cdata_to_evp_pkey(dsa_cdata)
return _DSAPublicKey(self, dsa_cdata, evp_pkey)
def load_dsa_parameter_numbers(
self, numbers: dsa.DSAParameterNumbers
) -> dsa.DSAParameters:
dsa._check_dsa_parameters(numbers)
dsa_cdata = self._lib.DSA_new()
self.openssl_assert(dsa_cdata != self._ffi.NULL)
dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
p = self._int_to_bn(numbers.p)
q = self._int_to_bn(numbers.q)
g = self._int_to_bn(numbers.g)
res = self._lib.DSA_set0_pqg(dsa_cdata, p, q, g)
self.openssl_assert(res == 1)
return _DSAParameters(self, dsa_cdata)
def _dsa_cdata_to_evp_pkey(self, dsa_cdata):
evp_pkey = self._create_evp_pkey_gc()
res = self._lib.EVP_PKEY_set1_DSA(evp_pkey, dsa_cdata)
self.openssl_assert(res == 1)
return evp_pkey
def dsa_supported(self) -> bool:
return not self._fips_enabled
def dsa_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
if not self.dsa_supported():
return False
return self.signature_hash_supported(algorithm)
def cmac_algorithm_supported(self, algorithm) -> bool:
return self.cipher_supported(
algorithm, CBC(b"\x00" * algorithm.block_size)
)
def create_cmac_ctx(self, algorithm: BlockCipherAlgorithm) -> _CMACContext:
return _CMACContext(self, algorithm)
def load_pem_private_key(
self, data: bytes, password: typing.Optional[bytes]
) -> PRIVATE_KEY_TYPES:
return self._load_key(
self._lib.PEM_read_bio_PrivateKey,
self._evp_pkey_to_private_key,
data,
password,
)
def load_pem_public_key(self, data: bytes) -> PUBLIC_KEY_TYPES:
mem_bio = self._bytes_to_bio(data)
# In OpenSSL 3.0.x the PEM_read_bio_PUBKEY function will invoke
# the default password callback if you pass an encrypted private
# key. This is very, very, very bad as the default callback can
# trigger an interactive console prompt, which will hang the
# Python process. We therefore provide our own callback to
# catch this and error out properly.
userdata = self._ffi.new("CRYPTOGRAPHY_PASSWORD_DATA *")
evp_pkey = self._lib.PEM_read_bio_PUBKEY(
mem_bio.bio,
self._ffi.NULL,
self._ffi.addressof(
self._lib._original_lib, "Cryptography_pem_password_cb"
),
userdata,
)
if evp_pkey != self._ffi.NULL:
evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
return self._evp_pkey_to_public_key(evp_pkey)
else:
# It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still
# need to check to see if it is a pure PKCS1 RSA public key (not
# embedded in a subjectPublicKeyInfo)
self._consume_errors()
res = self._lib.BIO_reset(mem_bio.bio)
self.openssl_assert(res == 1)
rsa_cdata = self._lib.PEM_read_bio_RSAPublicKey(
mem_bio.bio,
self._ffi.NULL,
self._ffi.addressof(
self._lib._original_lib, "Cryptography_pem_password_cb"
),
userdata,
)
if rsa_cdata != self._ffi.NULL:
rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
return _RSAPublicKey(self, rsa_cdata, evp_pkey)
else:
self._handle_key_loading_error()
def load_pem_parameters(self, data: bytes) -> dh.DHParameters:
mem_bio = self._bytes_to_bio(data)
# only DH is supported currently
dh_cdata = self._lib.PEM_read_bio_DHparams(
mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
)
if dh_cdata != self._ffi.NULL:
dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
return _DHParameters(self, dh_cdata)
else:
self._handle_key_loading_error()
def load_der_private_key(
self, data: bytes, password: typing.Optional[bytes]
) -> PRIVATE_KEY_TYPES:
# OpenSSL has a function called d2i_AutoPrivateKey that in theory
# handles this automatically, however it doesn't handle encrypted
# private keys. Instead we try to load the key two different ways.
# First we'll try to load it as a traditional key.
bio_data = self._bytes_to_bio(data)
key = self._evp_pkey_from_der_traditional_key(bio_data, password)
if key:
return self._evp_pkey_to_private_key(key)
else:
# Finally we try to load it with the method that handles encrypted
# PKCS8 properly.
return self._load_key(
self._lib.d2i_PKCS8PrivateKey_bio,
self._evp_pkey_to_private_key,
data,
password,