-
Notifications
You must be signed in to change notification settings - Fork 420
/
Copy pathcrypto.py
2450 lines (1946 loc) · 77.8 KB
/
crypto.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 calendar
import datetime
import functools
import sys
import typing
import warnings
from base64 import b16encode
from collections.abc import Iterable, Sequence
from functools import partial
from typing import (
Any,
Callable,
Union,
)
if sys.version_info >= (3, 13):
from warnings import deprecated
elif sys.version_info < (3, 8):
_T = typing.TypeVar("T")
def deprecated(msg: str, **kwargs: object) -> Callable[[_T], _T]:
return lambda f: f
else:
from typing_extensions import deprecated
from cryptography import utils, x509
from cryptography.hazmat.primitives.asymmetric import (
dsa,
ec,
ed448,
ed25519,
rsa,
)
from OpenSSL._util import StrOrBytesPath
from OpenSSL._util import (
byte_string as _byte_string,
)
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 (
path_bytes as _path_bytes,
)
__all__ = [
"FILETYPE_ASN1",
"FILETYPE_PEM",
"FILETYPE_TEXT",
"TYPE_DSA",
"TYPE_RSA",
"X509",
"Error",
"PKey",
"X509Extension",
"X509Name",
"X509Req",
"X509Store",
"X509StoreContext",
"X509StoreContextError",
"X509StoreFlags",
"dump_certificate",
"dump_certificate_request",
"dump_privatekey",
"dump_publickey",
"get_elliptic_curve",
"get_elliptic_curves",
"load_certificate",
"load_certificate_request",
"load_privatekey",
"load_publickey",
]
_PrivateKey = Union[
dsa.DSAPrivateKey,
ec.EllipticCurvePrivateKey,
ed25519.Ed25519PrivateKey,
ed448.Ed448PrivateKey,
rsa.RSAPrivateKey,
]
_PublicKey = Union[
dsa.DSAPublicKey,
ec.EllipticCurvePublicKey,
ed25519.Ed25519PublicKey,
ed448.Ed448PublicKey,
rsa.RSAPublicKey,
]
_Key = Union[_PrivateKey, _PublicKey]
PassphraseCallableT = Union[bytes, Callable[..., bytes]]
FILETYPE_PEM: int = _lib.SSL_FILETYPE_PEM
FILETYPE_ASN1: int = _lib.SSL_FILETYPE_ASN1
# TODO This was an API mistake. OpenSSL has no such constant.
FILETYPE_TEXT = 2**16 - 1
TYPE_RSA: int = _lib.EVP_PKEY_RSA
TYPE_DSA: int = _lib.EVP_PKEY_DSA
TYPE_DH: int = _lib.EVP_PKEY_DH
TYPE_EC: int = _lib.EVP_PKEY_EC
class Error(Exception):
"""
An error occurred in an `OpenSSL.crypto` API.
"""
_raise_current_error = partial(_exception_from_error_queue, Error)
_openssl_assert = _make_assert(Error)
def _new_mem_buf(buffer: bytes | None = None) -> Any:
"""
Allocate a new OpenSSL memory BIO.
Arrange for the garbage collector to clean it up automatically.
:param buffer: None or some bytes to use to put into the BIO so that they
can be read out.
"""
if buffer is None:
bio = _lib.BIO_new(_lib.BIO_s_mem())
free = _lib.BIO_free
else:
data = _ffi.new("char[]", buffer)
bio = _lib.BIO_new_mem_buf(data, len(buffer))
# Keep the memory alive as long as the bio is alive!
def free(bio: Any, ref: Any = data) -> Any:
return _lib.BIO_free(bio)
_openssl_assert(bio != _ffi.NULL)
bio = _ffi.gc(bio, free)
return bio
def _bio_to_string(bio: Any) -> bytes:
"""
Copy the contents of an OpenSSL BIO object into a Python byte string.
"""
result_buffer = _ffi.new("char**")
buffer_length = _lib.BIO_get_mem_data(bio, result_buffer)
return _ffi.buffer(result_buffer[0], buffer_length)[:]
def _set_asn1_time(boundary: Any, when: bytes) -> None:
"""
The the time value of an ASN1 time object.
@param boundary: An ASN1_TIME pointer (or an object safely
castable to that type) which will have its value set.
@param when: A string representation of the desired time value.
@raise TypeError: If C{when} is not a L{bytes} string.
@raise ValueError: If C{when} does not represent a time in the required
format.
@raise RuntimeError: If the time value cannot be set for some other
(unspecified) reason.
"""
if not isinstance(when, bytes):
raise TypeError("when must be a byte string")
# ASN1_TIME_set_string validates the string without writing anything
# when the destination is NULL.
_openssl_assert(boundary != _ffi.NULL)
set_result = _lib.ASN1_TIME_set_string(boundary, when)
if set_result == 0:
raise ValueError("Invalid string")
def _new_asn1_time(when: bytes) -> Any:
"""
Behaves like _set_asn1_time but returns a new ASN1_TIME object.
@param when: A string representation of the desired time value.
@raise TypeError: If C{when} is not a L{bytes} string.
@raise ValueError: If C{when} does not represent a time in the required
format.
@raise RuntimeError: If the time value cannot be set for some other
(unspecified) reason.
"""
ret = _lib.ASN1_TIME_new()
_openssl_assert(ret != _ffi.NULL)
ret = _ffi.gc(ret, _lib.ASN1_TIME_free)
_set_asn1_time(ret, when)
return ret
def _get_asn1_time(timestamp: Any) -> bytes | None:
"""
Retrieve the time value of an ASN1 time object.
@param timestamp: An ASN1_GENERALIZEDTIME* (or an object safely castable to
that type) from which the time value will be retrieved.
@return: The time value from C{timestamp} as a L{bytes} string in a certain
format. Or C{None} if the object contains no time value.
"""
string_timestamp = _ffi.cast("ASN1_STRING*", timestamp)
if _lib.ASN1_STRING_length(string_timestamp) == 0:
return None
elif (
_lib.ASN1_STRING_type(string_timestamp) == _lib.V_ASN1_GENERALIZEDTIME
):
return _ffi.string(_lib.ASN1_STRING_get0_data(string_timestamp))
else:
generalized_timestamp = _ffi.new("ASN1_GENERALIZEDTIME**")
_lib.ASN1_TIME_to_generalizedtime(timestamp, generalized_timestamp)
_openssl_assert(generalized_timestamp[0] != _ffi.NULL)
string_timestamp = _ffi.cast("ASN1_STRING*", generalized_timestamp[0])
string_data = _lib.ASN1_STRING_get0_data(string_timestamp)
string_result = _ffi.string(string_data)
_lib.ASN1_GENERALIZEDTIME_free(generalized_timestamp[0])
return string_result
class _X509NameInvalidator:
def __init__(self) -> None:
self._names: list[X509Name] = []
def add(self, name: X509Name) -> None:
self._names.append(name)
def clear(self) -> None:
for name in self._names:
# Breaks the object, but also prevents UAF!
del name._name
class PKey:
"""
A class representing an DSA or RSA public key or key pair.
"""
_only_public = False
_initialized = True
def __init__(self) -> None:
pkey = _lib.EVP_PKEY_new()
self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free)
self._initialized = False
def to_cryptography_key(self) -> _Key:
"""
Export as a ``cryptography`` key.
:rtype: One of ``cryptography``'s `key interfaces`_.
.. _key interfaces: https://cryptography.io/en/latest/hazmat/\
primitives/asymmetric/rsa/#key-interfaces
.. versionadded:: 16.1.0
"""
from cryptography.hazmat.primitives.serialization import (
load_der_private_key,
load_der_public_key,
)
if self._only_public:
der = dump_publickey(FILETYPE_ASN1, self)
return typing.cast(_Key, load_der_public_key(der))
else:
der = dump_privatekey(FILETYPE_ASN1, self)
return typing.cast(_Key, load_der_private_key(der, password=None))
@classmethod
def from_cryptography_key(cls, crypto_key: _Key) -> PKey:
"""
Construct based on a ``cryptography`` *crypto_key*.
:param crypto_key: A ``cryptography`` key.
:type crypto_key: One of ``cryptography``'s `key interfaces`_.
:rtype: PKey
.. versionadded:: 16.1.0
"""
if not isinstance(
crypto_key,
(
dsa.DSAPrivateKey,
dsa.DSAPublicKey,
ec.EllipticCurvePrivateKey,
ec.EllipticCurvePublicKey,
ed25519.Ed25519PrivateKey,
ed25519.Ed25519PublicKey,
ed448.Ed448PrivateKey,
ed448.Ed448PublicKey,
rsa.RSAPrivateKey,
rsa.RSAPublicKey,
),
):
raise TypeError("Unsupported key type")
from cryptography.hazmat.primitives.serialization import (
Encoding,
NoEncryption,
PrivateFormat,
PublicFormat,
)
if isinstance(
crypto_key,
(
dsa.DSAPublicKey,
ec.EllipticCurvePublicKey,
ed25519.Ed25519PublicKey,
ed448.Ed448PublicKey,
rsa.RSAPublicKey,
),
):
return load_publickey(
FILETYPE_ASN1,
crypto_key.public_bytes(
Encoding.DER, PublicFormat.SubjectPublicKeyInfo
),
)
else:
der = crypto_key.private_bytes(
Encoding.DER, PrivateFormat.PKCS8, NoEncryption()
)
return load_privatekey(FILETYPE_ASN1, der)
def generate_key(self, type: int, bits: int) -> None:
"""
Generate a key pair of the given type, with the given number of bits.
This generates a key "into" the this object.
:param type: The key type.
:type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA`
:param bits: The number of bits.
:type bits: :py:data:`int` ``>= 0``
:raises TypeError: If :py:data:`type` or :py:data:`bits` isn't
of the appropriate type.
:raises ValueError: If the number of bits isn't an integer of
the appropriate size.
:return: ``None``
"""
if not isinstance(type, int):
raise TypeError("type must be an integer")
if not isinstance(bits, int):
raise TypeError("bits must be an integer")
if type == TYPE_RSA:
if bits <= 0:
raise ValueError("Invalid number of bits")
# TODO Check error return
exponent = _lib.BN_new()
exponent = _ffi.gc(exponent, _lib.BN_free)
_lib.BN_set_word(exponent, _lib.RSA_F4)
rsa = _lib.RSA_new()
result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL)
_openssl_assert(result == 1)
result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa)
_openssl_assert(result == 1)
elif type == TYPE_DSA:
dsa = _lib.DSA_new()
_openssl_assert(dsa != _ffi.NULL)
dsa = _ffi.gc(dsa, _lib.DSA_free)
res = _lib.DSA_generate_parameters_ex(
dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL
)
_openssl_assert(res == 1)
_openssl_assert(_lib.DSA_generate_key(dsa) == 1)
_openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1)
else:
raise Error("No such key type")
self._initialized = True
def check(self) -> bool:
"""
Check the consistency of an RSA private key.
This is the Python equivalent of OpenSSL's ``RSA_check_key``.
:return: ``True`` if key is consistent.
:raise OpenSSL.crypto.Error: if the key is inconsistent.
:raise TypeError: if the key is of a type which cannot be checked.
Only RSA keys can currently be checked.
"""
if self._only_public:
raise TypeError("public key only")
if _lib.EVP_PKEY_type(self.type()) != _lib.EVP_PKEY_RSA:
raise TypeError("Only RSA keys can currently be checked.")
rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
rsa = _ffi.gc(rsa, _lib.RSA_free)
result = _lib.RSA_check_key(rsa)
if result == 1:
return True
_raise_current_error()
def type(self) -> int:
"""
Returns the type of the key
:return: The type of the key.
"""
return _lib.EVP_PKEY_id(self._pkey)
def bits(self) -> int:
"""
Returns the number of bits of the key
:return: The number of bits of the key.
"""
return _lib.EVP_PKEY_bits(self._pkey)
class _EllipticCurve:
"""
A representation of a supported elliptic curve.
@cvar _curves: :py:obj:`None` until an attempt is made to load the curves.
Thereafter, a :py:type:`set` containing :py:type:`_EllipticCurve`
instances each of which represents one curve supported by the system.
@type _curves: :py:type:`NoneType` or :py:type:`set`
"""
_curves = None
def __ne__(self, other: Any) -> bool:
"""
Implement cooperation with the right-hand side argument of ``!=``.
Python 3 seems to have dropped this cooperation in this very narrow
circumstance.
"""
if isinstance(other, _EllipticCurve):
return super().__ne__(other)
return NotImplemented
@classmethod
def _load_elliptic_curves(cls, lib: Any) -> set[_EllipticCurve]:
"""
Get the curves supported by OpenSSL.
:param lib: The OpenSSL library binding object.
:return: A :py:type:`set` of ``cls`` instances giving the names of the
elliptic curves the underlying library supports.
"""
num_curves = lib.EC_get_builtin_curves(_ffi.NULL, 0)
builtin_curves = _ffi.new("EC_builtin_curve[]", num_curves)
# The return value on this call should be num_curves again. We
# could check it to make sure but if it *isn't* then.. what could
# we do? Abort the whole process, I suppose...? -exarkun
lib.EC_get_builtin_curves(builtin_curves, num_curves)
return set(cls.from_nid(lib, c.nid) for c in builtin_curves)
@classmethod
def _get_elliptic_curves(cls, lib: Any) -> set[_EllipticCurve]:
"""
Get, cache, and return the curves supported by OpenSSL.
:param lib: The OpenSSL library binding object.
:return: A :py:type:`set` of ``cls`` instances giving the names of the
elliptic curves the underlying library supports.
"""
if cls._curves is None:
cls._curves = cls._load_elliptic_curves(lib)
return cls._curves
@classmethod
def from_nid(cls, lib: Any, nid: int) -> _EllipticCurve:
"""
Instantiate a new :py:class:`_EllipticCurve` associated with the given
OpenSSL NID.
:param lib: The OpenSSL library binding object.
:param nid: The OpenSSL NID the resulting curve object will represent.
This must be a curve NID (and not, for example, a hash NID) or
subsequent operations will fail in unpredictable ways.
:type nid: :py:class:`int`
:return: The curve object.
"""
return cls(lib, nid, _ffi.string(lib.OBJ_nid2sn(nid)).decode("ascii"))
def __init__(self, lib: Any, nid: int, name: str) -> None:
"""
:param _lib: The :py:mod:`cryptography` binding instance used to
interface with OpenSSL.
:param _nid: The OpenSSL NID identifying the curve this object
represents.
:type _nid: :py:class:`int`
:param name: The OpenSSL short name identifying the curve this object
represents.
:type name: :py:class:`unicode`
"""
self._lib = lib
self._nid = nid
self.name = name
def __repr__(self) -> str:
return f"<Curve {self.name!r}>"
def _to_EC_KEY(self) -> Any:
"""
Create a new OpenSSL EC_KEY structure initialized to use this curve.
The structure is automatically garbage collected when the Python object
is garbage collected.
"""
key = self._lib.EC_KEY_new_by_curve_name(self._nid)
return _ffi.gc(key, _lib.EC_KEY_free)
@deprecated(
"get_elliptic_curves is deprecated. You should use the APIs in "
"cryptography instead."
)
def get_elliptic_curves() -> set[_EllipticCurve]:
"""
Return a set of objects representing the elliptic curves supported in the
OpenSSL build in use.
The curve objects have a :py:class:`unicode` ``name`` attribute by which
they identify themselves.
The curve objects are useful as values for the argument accepted by
:py:meth:`Context.set_tmp_ecdh` to specify which elliptical curve should be
used for ECDHE key exchange.
"""
return _EllipticCurve._get_elliptic_curves(_lib)
@deprecated(
"get_elliptic_curve is deprecated. You should use the APIs in "
"cryptography instead."
)
def get_elliptic_curve(name: str) -> _EllipticCurve:
"""
Return a single curve object selected by name.
See :py:func:`get_elliptic_curves` for information about curve objects.
:param name: The OpenSSL short name identifying the curve object to
retrieve.
:type name: :py:class:`unicode`
If the named curve is not supported then :py:class:`ValueError` is raised.
"""
for curve in get_elliptic_curves():
if curve.name == name:
return curve
raise ValueError("unknown curve name", name)
@functools.total_ordering
class X509Name:
"""
An X.509 Distinguished Name.
:ivar countryName: The country of the entity.
:ivar C: Alias for :py:attr:`countryName`.
:ivar stateOrProvinceName: The state or province of the entity.
:ivar ST: Alias for :py:attr:`stateOrProvinceName`.
:ivar localityName: The locality of the entity.
:ivar L: Alias for :py:attr:`localityName`.
:ivar organizationName: The organization name of the entity.
:ivar O: Alias for :py:attr:`organizationName`.
:ivar organizationalUnitName: The organizational unit of the entity.
:ivar OU: Alias for :py:attr:`organizationalUnitName`
:ivar commonName: The common name of the entity.
:ivar CN: Alias for :py:attr:`commonName`.
:ivar emailAddress: The e-mail address of the entity.
"""
def __init__(self, name: X509Name) -> None:
"""
Create a new X509Name, copying the given X509Name instance.
:param name: The name to copy.
:type name: :py:class:`X509Name`
"""
name = _lib.X509_NAME_dup(name._name)
self._name: Any = _ffi.gc(name, _lib.X509_NAME_free)
def __setattr__(self, name: str, value: Any) -> None:
if name.startswith("_"):
return super().__setattr__(name, value)
# Note: we really do not want str subclasses here, so we do not use
# isinstance.
if type(name) is not str:
raise TypeError(
f"attribute name must be string, not "
f"'{type(value).__name__:.200}'"
)
nid = _lib.OBJ_txt2nid(_byte_string(name))
if nid == _lib.NID_undef:
try:
_raise_current_error()
except Error:
pass
raise AttributeError("No such attribute")
# If there's an old entry for this NID, remove it
for i in range(_lib.X509_NAME_entry_count(self._name)):
ent = _lib.X509_NAME_get_entry(self._name, i)
ent_obj = _lib.X509_NAME_ENTRY_get_object(ent)
ent_nid = _lib.OBJ_obj2nid(ent_obj)
if nid == ent_nid:
ent = _lib.X509_NAME_delete_entry(self._name, i)
_lib.X509_NAME_ENTRY_free(ent)
break
if isinstance(value, str):
value = value.encode("utf-8")
add_result = _lib.X509_NAME_add_entry_by_NID(
self._name, nid, _lib.MBSTRING_UTF8, value, -1, -1, 0
)
if not add_result:
_raise_current_error()
def __getattr__(self, name: str) -> str | None:
"""
Find attribute. An X509Name object has the following attributes:
countryName (alias C), stateOrProvince (alias ST), locality (alias L),
organization (alias O), organizationalUnit (alias OU), commonName
(alias CN) and more...
"""
nid = _lib.OBJ_txt2nid(_byte_string(name))
if nid == _lib.NID_undef:
# This is a bit weird. OBJ_txt2nid indicated failure, but it seems
# a lower level function, a2d_ASN1_OBJECT, also feels the need to
# push something onto the error queue. If we don't clean that up
# now, someone else will bump into it later and be quite confused.
# See lp#314814.
try:
_raise_current_error()
except Error:
pass
raise AttributeError("No such attribute")
entry_index = _lib.X509_NAME_get_index_by_NID(self._name, nid, -1)
if entry_index == -1:
return None
entry = _lib.X509_NAME_get_entry(self._name, entry_index)
data = _lib.X509_NAME_ENTRY_get_data(entry)
result_buffer = _ffi.new("unsigned char**")
data_length = _lib.ASN1_STRING_to_UTF8(result_buffer, data)
_openssl_assert(data_length >= 0)
try:
result = _ffi.buffer(result_buffer[0], data_length)[:].decode(
"utf-8"
)
finally:
# XXX untested
_lib.OPENSSL_free(result_buffer[0])
return result
def __eq__(self, other: Any) -> bool:
if not isinstance(other, X509Name):
return NotImplemented
return _lib.X509_NAME_cmp(self._name, other._name) == 0
def __lt__(self, other: Any) -> bool:
if not isinstance(other, X509Name):
return NotImplemented
return _lib.X509_NAME_cmp(self._name, other._name) < 0
def __repr__(self) -> str:
"""
String representation of an X509Name
"""
result_buffer = _ffi.new("char[]", 512)
format_result = _lib.X509_NAME_oneline(
self._name, result_buffer, len(result_buffer)
)
_openssl_assert(format_result != _ffi.NULL)
return "<X509Name object '{}'>".format(
_ffi.string(result_buffer).decode("utf-8"),
)
def hash(self) -> int:
"""
Return an integer representation of the first four bytes of the
MD5 digest of the DER representation of the name.
This is the Python equivalent of OpenSSL's ``X509_NAME_hash``.
:return: The (integer) hash of this name.
:rtype: :py:class:`int`
"""
return _lib.X509_NAME_hash(self._name)
def der(self) -> bytes:
"""
Return the DER encoding of this name.
:return: The DER encoded form of this name.
:rtype: :py:class:`bytes`
"""
result_buffer = _ffi.new("unsigned char**")
encode_result = _lib.i2d_X509_NAME(self._name, result_buffer)
_openssl_assert(encode_result >= 0)
string_result = _ffi.buffer(result_buffer[0], encode_result)[:]
_lib.OPENSSL_free(result_buffer[0])
return string_result
def get_components(self) -> list[tuple[bytes, bytes]]:
"""
Returns the components of this name, as a sequence of 2-tuples.
:return: The components of this name.
:rtype: :py:class:`list` of ``name, value`` tuples.
"""
result = []
for i in range(_lib.X509_NAME_entry_count(self._name)):
ent = _lib.X509_NAME_get_entry(self._name, i)
fname = _lib.X509_NAME_ENTRY_get_object(ent)
fval = _lib.X509_NAME_ENTRY_get_data(ent)
nid = _lib.OBJ_obj2nid(fname)
name = _lib.OBJ_nid2sn(nid)
# ffi.string does not handle strings containing NULL bytes
# (which may have been generated by old, broken software)
value = _ffi.buffer(
_lib.ASN1_STRING_get0_data(fval), _lib.ASN1_STRING_length(fval)
)[:]
result.append((_ffi.string(name), value))
return result
@deprecated(
"X509Extension support in pyOpenSSL is deprecated. You should use the "
"APIs in cryptography."
)
class X509Extension:
"""
An X.509 v3 certificate extension.
.. deprecated:: 23.3.0
Use cryptography's X509 APIs instead.
"""
def __init__(
self,
type_name: bytes,
critical: bool,
value: bytes,
subject: X509 | None = None,
issuer: X509 | None = None,
) -> None:
"""
Initializes an X509 extension.
:param type_name: The name of the type of extension_ to create.
:type type_name: :py:data:`bytes`
:param bool critical: A flag indicating whether this is a critical
extension.
:param value: The OpenSSL textual representation of the extension's
value.
:type value: :py:data:`bytes`
:param subject: Optional X509 certificate to use as subject.
:type subject: :py:class:`X509`
:param issuer: Optional X509 certificate to use as issuer.
:type issuer: :py:class:`X509`
.. _extension: https://www.openssl.org/docs/manmaster/man5/
x509v3_config.html#STANDARD-EXTENSIONS
"""
ctx = _ffi.new("X509V3_CTX*")
# A context is necessary for any extension which uses the r2i
# conversion method. That is, X509V3_EXT_nconf may segfault if passed
# a NULL ctx. Start off by initializing most of the fields to NULL.
_lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)
# We have no configuration database - but perhaps we should (some
# extensions may require it).
_lib.X509V3_set_ctx_nodb(ctx)
# Initialize the subject and issuer, if appropriate. ctx is a local,
# and as far as I can tell none of the X509V3_* APIs invoked here steal
# any references, so no need to mess with reference counts or
# duplicates.
if issuer is not None:
if not isinstance(issuer, X509):
raise TypeError("issuer must be an X509 instance")
ctx.issuer_cert = issuer._x509
if subject is not None:
if not isinstance(subject, X509):
raise TypeError("subject must be an X509 instance")
ctx.subject_cert = subject._x509
if critical:
# There are other OpenSSL APIs which would let us pass in critical
# separately, but they're harder to use, and since value is already
# a pile of crappy junk smuggling a ton of utterly important
# structured data, what's the point of trying to avoid nasty stuff
# with strings? (However, X509V3_EXT_i2d in particular seems like
# it would be a better API to invoke. I do not know where to get
# the ext_struc it desires for its last parameter, though.)
value = b"critical," + value
extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
if extension == _ffi.NULL:
_raise_current_error()
self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)
@property
def _nid(self) -> Any:
return _lib.OBJ_obj2nid(
_lib.X509_EXTENSION_get_object(self._extension)
)
_prefixes: typing.ClassVar[dict[int, str]] = {
_lib.GEN_EMAIL: "email",
_lib.GEN_DNS: "DNS",
_lib.GEN_URI: "URI",
}
def _subjectAltNameString(self) -> str:
names = _ffi.cast(
"GENERAL_NAMES*", _lib.X509V3_EXT_d2i(self._extension)
)
names = _ffi.gc(names, _lib.GENERAL_NAMES_free)
parts = []
for i in range(_lib.sk_GENERAL_NAME_num(names)):
name = _lib.sk_GENERAL_NAME_value(names, i)
try:
label = self._prefixes[name.type]
except KeyError:
bio = _new_mem_buf()
_lib.GENERAL_NAME_print(bio, name)
parts.append(_bio_to_string(bio).decode("utf-8"))
else:
value = _ffi.buffer(name.d.ia5.data, name.d.ia5.length)[
:
].decode("utf-8")
parts.append(label + ":" + value)
return ", ".join(parts)
def __str__(self) -> str:
"""
:return: a nice text representation of the extension
"""
if _lib.NID_subject_alt_name == self._nid:
return self._subjectAltNameString()
bio = _new_mem_buf()
print_result = _lib.X509V3_EXT_print(bio, self._extension, 0, 0)
_openssl_assert(print_result != 0)
return _bio_to_string(bio).decode("utf-8")
def get_critical(self) -> bool:
"""
Returns the critical field of this X.509 extension.
:return: The critical field.
"""
return _lib.X509_EXTENSION_get_critical(self._extension)
def get_short_name(self) -> bytes:
"""
Returns the short type name of this X.509 extension.
The result is a byte string such as :py:const:`b"basicConstraints"`.
:return: The short type name.
:rtype: :py:data:`bytes`
.. versionadded:: 0.12
"""
obj = _lib.X509_EXTENSION_get_object(self._extension)
nid = _lib.OBJ_obj2nid(obj)
# OpenSSL 3.1.0 has a bug where nid2sn returns NULL for NIDs that
# previously returned UNDEF. This is a workaround for that issue.
# https://github.com/openssl/openssl/commit/908ba3ed9adbb3df90f76
buf = _lib.OBJ_nid2sn(nid)
if buf != _ffi.NULL:
return _ffi.string(buf)
else:
return b"UNDEF"
def get_data(self) -> bytes:
"""
Returns the data of the X509 extension, encoded as ASN.1.
:return: The ASN.1 encoded data of this X509 extension.
:rtype: :py:data:`bytes`
.. versionadded:: 0.12
"""
octet_result = _lib.X509_EXTENSION_get_data(self._extension)
string_result = _ffi.cast("ASN1_STRING*", octet_result)
char_result = _lib.ASN1_STRING_get0_data(string_result)
result_length = _lib.ASN1_STRING_length(string_result)
return _ffi.buffer(char_result, result_length)[:]
@deprecated(
"CSR support in pyOpenSSL is deprecated. You should use the APIs "
"in cryptography."
)
class X509Req:
"""
An X.509 certificate signing requests.
.. deprecated:: 24.2.0
Use `cryptography.x509.CertificateSigningRequest` instead.
"""
def __init__(self) -> None:
req = _lib.X509_REQ_new()
self._req = _ffi.gc(req, _lib.X509_REQ_free)
# Default to version 0.
self.set_version(0)
def to_cryptography(self) -> x509.CertificateSigningRequest:
"""
Export as a ``cryptography`` certificate signing request.
:rtype: ``cryptography.x509.CertificateSigningRequest``
.. versionadded:: 17.1.0
"""
from cryptography.x509 import load_der_x509_csr
der = _dump_certificate_request_internal(FILETYPE_ASN1, self)
return load_der_x509_csr(der)
@classmethod
def from_cryptography(
cls, crypto_req: x509.CertificateSigningRequest
) -> X509Req:
"""
Construct based on a ``cryptography`` *crypto_req*.
:param crypto_req: A ``cryptography`` X.509 certificate signing request
:type crypto_req: ``cryptography.x509.CertificateSigningRequest``
:rtype: X509Req
.. versionadded:: 17.1.0
"""
if not isinstance(crypto_req, x509.CertificateSigningRequest):
raise TypeError("Must be a certificate signing request")