forked from wbond/asn1crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathx509.py
3031 lines (2429 loc) · 91.2 KB
/
x509.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
# coding: utf-8
"""
ASN.1 type classes for X.509 certificates. Exports the following items:
- Attributes()
- Certificate()
- Extensions()
- GeneralName()
- GeneralNames()
- Name()
Other type classes are defined that help compose the types listed above.
"""
from __future__ import unicode_literals, division, absolute_import, print_function
from contextlib import contextmanager
from encodings import idna # noqa
import hashlib
import re
import socket
import stringprep
import sys
import unicodedata
from ._errors import unwrap
from ._iri import iri_to_uri, uri_to_iri
from ._ordereddict import OrderedDict
from ._types import type_name, str_cls, bytes_to_list
from .algos import AlgorithmIdentifier, AnyAlgorithmIdentifier, DigestAlgorithm, SignedDigestAlgorithm
from .core import (
Any,
BitString,
BMPString,
Boolean,
Choice,
Concat,
Enumerated,
GeneralizedTime,
GeneralString,
IA5String,
Integer,
Null,
NumericString,
ObjectIdentifier,
OctetBitString,
OctetString,
ParsableOctetString,
PrintableString,
Sequence,
SequenceOf,
Set,
SetOf,
TeletexString,
UniversalString,
UTCTime,
UTF8String,
VisibleString,
VOID,
)
from .keys import PublicKeyInfo
from .util import int_to_bytes, int_from_bytes, inet_ntop, inet_pton
# The structures in this file are taken from https://tools.ietf.org/html/rfc5280
# and a few other supplementary sources, mostly due to extra supported
# extension and name OIDs
class DNSName(IA5String):
_encoding = 'idna'
_bad_tag = (12, 19)
def __ne__(self, other):
return not self == other
def __eq__(self, other):
"""
Equality as defined by https://tools.ietf.org/html/rfc5280#section-7.2
:param other:
Another DNSName object
:return:
A boolean
"""
if not isinstance(other, DNSName):
return False
return self.__unicode__().lower() == other.__unicode__().lower()
def set(self, value):
"""
Sets the value of the DNS name
:param value:
A unicode string
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
''',
type_name(self),
type_name(value)
))
if value.startswith('.'):
encoded_value = b'.' + value[1:].encode(self._encoding)
else:
encoded_value = value.encode(self._encoding)
self._unicode = value
self.contents = encoded_value
self._header = None
if self._trailer != b'':
self._trailer = b''
class URI(IA5String):
def set(self, value):
"""
Sets the value of the string
:param value:
A unicode string
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
''',
type_name(self),
type_name(value)
))
self._unicode = value
self.contents = iri_to_uri(value)
self._header = None
if self._trailer != b'':
self._trailer = b''
def __ne__(self, other):
return not self == other
def __eq__(self, other):
"""
Equality as defined by https://tools.ietf.org/html/rfc5280#section-7.4
:param other:
Another URI object
:return:
A boolean
"""
if not isinstance(other, URI):
return False
return iri_to_uri(self.native, True) == iri_to_uri(other.native, True)
def __unicode__(self):
"""
:return:
A unicode string
"""
if self.contents is None:
return ''
if self._unicode is None:
self._unicode = uri_to_iri(self._merge_chunks())
return self._unicode
class EmailAddress(IA5String):
_contents = None
# If the value has gone through the .set() method, thus normalizing it
_normalized = False
# In the wild we've seen this encoded as a UTF8String and PrintableString
_bad_tag = (12, 19)
@property
def contents(self):
"""
:return:
A byte string of the DER-encoded contents of the sequence
"""
return self._contents
@contents.setter
def contents(self, value):
"""
:param value:
A byte string of the DER-encoded contents of the sequence
"""
self._normalized = False
self._contents = value
def set(self, value):
"""
Sets the value of the string
:param value:
A unicode string
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
''',
type_name(self),
type_name(value)
))
if value.find('@') != -1:
mailbox, hostname = value.rsplit('@', 1)
encoded_value = mailbox.encode('ascii') + b'@' + hostname.encode('idna')
else:
encoded_value = value.encode('ascii')
self._normalized = True
self._unicode = value
self.contents = encoded_value
self._header = None
if self._trailer != b'':
self._trailer = b''
def __unicode__(self):
"""
:return:
A unicode string
"""
# We've seen this in the wild as a PrintableString, and since ascii is a
# subset of cp1252, we use the later for decoding to be more user friendly
if self._unicode is None:
contents = self._merge_chunks()
if contents.find(b'@') == -1:
self._unicode = contents.decode('cp1252')
else:
mailbox, hostname = contents.rsplit(b'@', 1)
self._unicode = mailbox.decode('cp1252') + '@' + hostname.decode('idna')
return self._unicode
def __ne__(self, other):
return not self == other
def __eq__(self, other):
"""
Equality as defined by https://tools.ietf.org/html/rfc5280#section-7.5
:param other:
Another EmailAddress object
:return:
A boolean
"""
if not isinstance(other, EmailAddress):
return False
if not self._normalized:
self.set(self.native)
if not other._normalized:
other.set(other.native)
if self._contents.find(b'@') == -1 or other._contents.find(b'@') == -1:
return self._contents == other._contents
other_mailbox, other_hostname = other._contents.rsplit(b'@', 1)
mailbox, hostname = self._contents.rsplit(b'@', 1)
if mailbox != other_mailbox:
return False
if hostname.lower() != other_hostname.lower():
return False
return True
class IPAddress(OctetString):
def parse(self, spec=None, spec_params=None):
"""
This method is not applicable to IP addresses
"""
raise ValueError(unwrap(
'''
IP address values can not be parsed
'''
))
def set(self, value):
"""
Sets the value of the object
:param value:
A unicode string containing an IPv4 address, IPv4 address with CIDR,
an IPv6 address or IPv6 address with CIDR
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
''',
type_name(self),
type_name(value)
))
original_value = value
has_cidr = value.find('/') != -1
cidr = 0
if has_cidr:
parts = value.split('/', 1)
value = parts[0]
cidr = int(parts[1])
if cidr < 0:
raise ValueError(unwrap(
'''
%s value contains a CIDR range less than 0
''',
type_name(self)
))
if value.find(':') != -1:
family = socket.AF_INET6
if cidr > 128:
raise ValueError(unwrap(
'''
%s value contains a CIDR range bigger than 128, the maximum
value for an IPv6 address
''',
type_name(self)
))
cidr_size = 128
else:
family = socket.AF_INET
if cidr > 32:
raise ValueError(unwrap(
'''
%s value contains a CIDR range bigger than 32, the maximum
value for an IPv4 address
''',
type_name(self)
))
cidr_size = 32
cidr_bytes = b''
if has_cidr:
cidr_mask = '1' * cidr
cidr_mask += '0' * (cidr_size - len(cidr_mask))
cidr_bytes = int_to_bytes(int(cidr_mask, 2))
cidr_bytes = (b'\x00' * ((cidr_size // 8) - len(cidr_bytes))) + cidr_bytes
self._native = original_value
self.contents = inet_pton(family, value) + cidr_bytes
self._bytes = self.contents
self._header = None
if self._trailer != b'':
self._trailer = b''
@property
def native(self):
"""
The native Python datatype representation of this value
:return:
A unicode string or None
"""
if self.contents is None:
return None
if self._native is None:
byte_string = self.__bytes__()
byte_len = len(byte_string)
value = None
cidr_int = None
if byte_len in set([32, 16]):
value = inet_ntop(socket.AF_INET6, byte_string[0:16])
if byte_len > 16:
cidr_int = int_from_bytes(byte_string[16:])
elif byte_len in set([8, 4]):
value = inet_ntop(socket.AF_INET, byte_string[0:4])
if byte_len > 4:
cidr_int = int_from_bytes(byte_string[4:])
if cidr_int is not None:
cidr_bits = '{0:b}'.format(cidr_int)
cidr = len(cidr_bits.rstrip('0'))
value = value + '/' + str_cls(cidr)
self._native = value
return self._native
def __ne__(self, other):
return not self == other
def __eq__(self, other):
"""
:param other:
Another IPAddress object
:return:
A boolean
"""
if not isinstance(other, IPAddress):
return False
return self.__bytes__() == other.__bytes__()
class Attribute(Sequence):
_fields = [
('type', ObjectIdentifier),
('values', SetOf, {'spec': Any}),
]
class Attributes(SequenceOf):
_child_spec = Attribute
class KeyUsage(BitString):
_map = {
0: 'digital_signature',
1: 'non_repudiation',
2: 'key_encipherment',
3: 'data_encipherment',
4: 'key_agreement',
5: 'key_cert_sign',
6: 'crl_sign',
7: 'encipher_only',
8: 'decipher_only',
}
class PrivateKeyUsagePeriod(Sequence):
_fields = [
('not_before', GeneralizedTime, {'implicit': 0, 'optional': True}),
('not_after', GeneralizedTime, {'implicit': 1, 'optional': True}),
]
class NotReallyTeletexString(TeletexString):
"""
OpenSSL (and probably some other libraries) puts ISO-8859-1
into TeletexString instead of ITU T.61. We use Windows-1252 when
decoding since it is a superset of ISO-8859-1, and less likely to
cause encoding issues, but we stay strict with encoding to prevent
us from creating bad data.
"""
_decoding_encoding = 'cp1252'
def __unicode__(self):
"""
:return:
A unicode string
"""
if self.contents is None:
return ''
if self._unicode is None:
self._unicode = self._merge_chunks().decode(self._decoding_encoding)
return self._unicode
@contextmanager
def strict_teletex():
try:
NotReallyTeletexString._decoding_encoding = 'teletex'
yield
finally:
NotReallyTeletexString._decoding_encoding = 'cp1252'
class DirectoryString(Choice):
_alternatives = [
('teletex_string', NotReallyTeletexString),
('printable_string', PrintableString),
('universal_string', UniversalString),
('utf8_string', UTF8String),
('bmp_string', BMPString),
# This is an invalid/bad alternative, but some broken certs use it
('ia5_string', IA5String),
]
class NameType(ObjectIdentifier):
_map = {
'2.5.4.3': 'common_name',
'2.5.4.4': 'surname',
'2.5.4.5': 'serial_number',
'2.5.4.6': 'country_name',
'2.5.4.7': 'locality_name',
'2.5.4.8': 'state_or_province_name',
'2.5.4.9': 'street_address',
'2.5.4.10': 'organization_name',
'2.5.4.11': 'organizational_unit_name',
'2.5.4.12': 'title',
'2.5.4.15': 'business_category',
'2.5.4.17': 'postal_code',
'2.5.4.20': 'telephone_number',
'2.5.4.41': 'name',
'2.5.4.42': 'given_name',
'2.5.4.43': 'initials',
'2.5.4.44': 'generation_qualifier',
'2.5.4.45': 'unique_identifier',
'2.5.4.46': 'dn_qualifier',
'2.5.4.65': 'pseudonym',
'2.5.4.97': 'organization_identifier',
# https://www.trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
'2.23.133.2.1': 'tpm_manufacturer',
'2.23.133.2.2': 'tpm_model',
'2.23.133.2.3': 'tpm_version',
'2.23.133.2.4': 'platform_manufacturer',
'2.23.133.2.5': 'platform_model',
'2.23.133.2.6': 'platform_version',
# https://tools.ietf.org/html/rfc2985#page-26
'1.2.840.113549.1.9.1': 'email_address',
# Page 10 of https://cabforum.org/wp-content/uploads/EV-V1_5_5.pdf
'1.3.6.1.4.1.311.60.2.1.1': 'incorporation_locality',
'1.3.6.1.4.1.311.60.2.1.2': 'incorporation_state_or_province',
'1.3.6.1.4.1.311.60.2.1.3': 'incorporation_country',
# https://tools.ietf.org/html/rfc4519#section-2.39
'0.9.2342.19200300.100.1.1': 'user_id',
# https://tools.ietf.org/html/rfc2247#section-4
'0.9.2342.19200300.100.1.25': 'domain_component',
# http://www.alvestrand.no/objectid/0.2.262.1.10.7.20.html
'0.2.262.1.10.7.20': 'name_distinguisher',
}
# This order is largely based on observed order seen in EV certs from
# Symantec and DigiCert. Some of the uncommon name-related fields are
# just placed in what seems like a reasonable order.
preferred_order = [
'incorporation_country',
'incorporation_state_or_province',
'incorporation_locality',
'business_category',
'serial_number',
'country_name',
'postal_code',
'state_or_province_name',
'locality_name',
'street_address',
'organization_name',
'organizational_unit_name',
'title',
'common_name',
'user_id',
'initials',
'generation_qualifier',
'surname',
'given_name',
'name',
'pseudonym',
'dn_qualifier',
'telephone_number',
'email_address',
'domain_component',
'name_distinguisher',
'organization_identifier',
'tpm_manufacturer',
'tpm_model',
'tpm_version',
'platform_manufacturer',
'platform_model',
'platform_version',
]
@classmethod
def preferred_ordinal(cls, attr_name):
"""
Returns an ordering value for a particular attribute key.
Unrecognized attributes and OIDs will be sorted lexically at the end.
:return:
An orderable value.
"""
attr_name = cls.map(attr_name)
if attr_name in cls.preferred_order:
ordinal = cls.preferred_order.index(attr_name)
else:
ordinal = len(cls.preferred_order)
return (ordinal, attr_name)
@property
def human_friendly(self):
"""
:return:
A human-friendly unicode string to display to users
"""
return {
'common_name': 'Common Name',
'surname': 'Surname',
'serial_number': 'Serial Number',
'country_name': 'Country',
'locality_name': 'Locality',
'state_or_province_name': 'State/Province',
'street_address': 'Street Address',
'organization_name': 'Organization',
'organizational_unit_name': 'Organizational Unit',
'title': 'Title',
'business_category': 'Business Category',
'postal_code': 'Postal Code',
'telephone_number': 'Telephone Number',
'name': 'Name',
'given_name': 'Given Name',
'initials': 'Initials',
'generation_qualifier': 'Generation Qualifier',
'unique_identifier': 'Unique Identifier',
'dn_qualifier': 'DN Qualifier',
'pseudonym': 'Pseudonym',
'email_address': 'Email Address',
'incorporation_locality': 'Incorporation Locality',
'incorporation_state_or_province': 'Incorporation State/Province',
'incorporation_country': 'Incorporation Country',
'domain_component': 'Domain Component',
'name_distinguisher': 'Name Distinguisher',
'organization_identifier': 'Organization Identifier',
'tpm_manufacturer': 'TPM Manufacturer',
'tpm_model': 'TPM Model',
'tpm_version': 'TPM Version',
'platform_manufacturer': 'Platform Manufacturer',
'platform_model': 'Platform Model',
'platform_version': 'Platform Version',
'user_id': 'User ID',
}.get(self.native, self.native)
class NameTypeAndValue(Sequence):
_fields = [
('type', NameType),
('value', Any),
]
_oid_pair = ('type', 'value')
_oid_specs = {
'common_name': DirectoryString,
'surname': DirectoryString,
'serial_number': DirectoryString,
'country_name': DirectoryString,
'locality_name': DirectoryString,
'state_or_province_name': DirectoryString,
'street_address': DirectoryString,
'organization_name': DirectoryString,
'organizational_unit_name': DirectoryString,
'title': DirectoryString,
'business_category': DirectoryString,
'postal_code': DirectoryString,
'telephone_number': PrintableString,
'name': DirectoryString,
'given_name': DirectoryString,
'initials': DirectoryString,
'generation_qualifier': DirectoryString,
'unique_identifier': OctetBitString,
'dn_qualifier': DirectoryString,
'pseudonym': DirectoryString,
# https://tools.ietf.org/html/rfc2985#page-26
'email_address': EmailAddress,
# Page 10 of https://cabforum.org/wp-content/uploads/EV-V1_5_5.pdf
'incorporation_locality': DirectoryString,
'incorporation_state_or_province': DirectoryString,
'incorporation_country': DirectoryString,
'domain_component': DNSName,
'name_distinguisher': DirectoryString,
'organization_identifier': DirectoryString,
'tpm_manufacturer': UTF8String,
'tpm_model': UTF8String,
'tpm_version': UTF8String,
'platform_manufacturer': UTF8String,
'platform_model': UTF8String,
'platform_version': UTF8String,
'user_id': DirectoryString,
}
_prepped = None
@property
def prepped_value(self):
"""
Returns the value after being processed by the internationalized string
preparation as specified by RFC 5280
:return:
A unicode string
"""
if self._prepped is None:
self._prepped = self._ldap_string_prep(self['value'].native)
return self._prepped
def __ne__(self, other):
return not self == other
def __eq__(self, other):
"""
Equality as defined by https://tools.ietf.org/html/rfc5280#section-7.1
:param other:
Another NameTypeAndValue object
:return:
A boolean
"""
if not isinstance(other, NameTypeAndValue):
return False
if other['type'].native != self['type'].native:
return False
return other.prepped_value == self.prepped_value
def _ldap_string_prep(self, string):
"""
Implements the internationalized string preparation algorithm from
RFC 4518. https://tools.ietf.org/html/rfc4518#section-2
:param string:
A unicode string to prepare
:return:
A prepared unicode string, ready for comparison
"""
# Map step
string = re.sub('[\u00ad\u1806\u034f\u180b-\u180d\ufe0f-\uff00\ufffc]+', '', string)
string = re.sub('[\u0009\u000a\u000b\u000c\u000d\u0085]', ' ', string)
if sys.maxunicode == 0xffff:
# Some installs of Python 2.7 don't support 8-digit unicode escape
# ranges, so we have to break them into pieces
# Original was: \U0001D173-\U0001D17A and \U000E0020-\U000E007F
string = re.sub('\ud834[\udd73-\udd7a]|\udb40[\udc20-\udc7f]|\U000e0001', '', string)
else:
string = re.sub('[\U0001D173-\U0001D17A\U000E0020-\U000E007F\U000e0001]', '', string)
string = re.sub(
'[\u0000-\u0008\u000e-\u001f\u007f-\u0084\u0086-\u009f\u06dd\u070f\u180e\u200c-\u200f'
'\u202a-\u202e\u2060-\u2063\u206a-\u206f\ufeff\ufff9-\ufffb]+',
'',
string
)
string = string.replace('\u200b', '')
string = re.sub('[\u00a0\u1680\u2000-\u200a\u2028-\u2029\u202f\u205f\u3000]', ' ', string)
string = ''.join(map(stringprep.map_table_b2, string))
# Normalize step
string = unicodedata.normalize('NFKC', string)
# Prohibit step
for char in string:
if stringprep.in_table_a1(char):
raise ValueError(unwrap(
'''
X.509 Name objects may not contain unassigned code points
'''
))
if stringprep.in_table_c8(char):
raise ValueError(unwrap(
'''
X.509 Name objects may not contain change display or
zzzzdeprecated characters
'''
))
if stringprep.in_table_c3(char):
raise ValueError(unwrap(
'''
X.509 Name objects may not contain private use characters
'''
))
if stringprep.in_table_c4(char):
raise ValueError(unwrap(
'''
X.509 Name objects may not contain non-character code points
'''
))
if stringprep.in_table_c5(char):
raise ValueError(unwrap(
'''
X.509 Name objects may not contain surrogate code points
'''
))
if char == '\ufffd':
raise ValueError(unwrap(
'''
X.509 Name objects may not contain the replacement character
'''
))
# Check bidirectional step - here we ensure that we are not mixing
# left-to-right and right-to-left text in the string
has_r_and_al_cat = False
has_l_cat = False
for char in string:
if stringprep.in_table_d1(char):
has_r_and_al_cat = True
elif stringprep.in_table_d2(char):
has_l_cat = True
if has_r_and_al_cat:
first_is_r_and_al = stringprep.in_table_d1(string[0])
last_is_r_and_al = stringprep.in_table_d1(string[-1])
if has_l_cat or not first_is_r_and_al or not last_is_r_and_al:
raise ValueError(unwrap(
'''
X.509 Name object contains a malformed bidirectional
sequence
'''
))
# Insignificant space handling step
string = ' ' + re.sub(' +', ' ', string).strip() + ' '
return string
class RelativeDistinguishedName(SetOf):
_child_spec = NameTypeAndValue
@property
def hashable(self):
"""
:return:
A unicode string that can be used as a dict key or in a set
"""
output = []
values = self._get_values(self)
for key in sorted(values.keys()):
output.append('%s: %s' % (key, values[key]))
# Unit separator is used here since the normalization process for
# values moves any such character, and the keys are all dotted integers
# or under_score_words
return '\x1F'.join(output)
def __ne__(self, other):
return not self == other
def __eq__(self, other):
"""
Equality as defined by https://tools.ietf.org/html/rfc5280#section-7.1
:param other:
Another RelativeDistinguishedName object
:return:
A boolean
"""
if not isinstance(other, RelativeDistinguishedName):
return False
if len(self) != len(other):
return False
self_types = self._get_types(self)
other_types = self._get_types(other)
if self_types != other_types:
return False
self_values = self._get_values(self)
other_values = self._get_values(other)
for type_name_ in self_types:
if self_values[type_name_] != other_values[type_name_]:
return False
return True
def _get_types(self, rdn):
"""
Returns a set of types contained in an RDN
:param rdn:
A RelativeDistinguishedName object
:return:
A set object with unicode strings of NameTypeAndValue type field
values
"""
return set([ntv['type'].native for ntv in rdn])
def _get_values(self, rdn):
"""
Returns a dict of prepped values contained in an RDN
:param rdn:
A RelativeDistinguishedName object
:return:
A dict object with unicode strings of NameTypeAndValue value field
values that have been prepped for comparison
"""
output = {}
[output.update([(ntv['type'].native, ntv.prepped_value)]) for ntv in rdn]
return output
class RDNSequence(SequenceOf):
_child_spec = RelativeDistinguishedName
@property
def hashable(self):
"""
:return:
A unicode string that can be used as a dict key or in a set
"""
# Record separator is used here since the normalization process for
# values moves any such character, and the keys are all dotted integers
# or under_score_words
return '\x1E'.join(rdn.hashable for rdn in self)
def __ne__(self, other):
return not self == other
def __eq__(self, other):
"""
Equality as defined by https://tools.ietf.org/html/rfc5280#section-7.1
:param other:
Another RDNSequence object
:return:
A boolean
"""
if not isinstance(other, RDNSequence):
return False
if len(self) != len(other):
return False
for index, self_rdn in enumerate(self):
if other[index] != self_rdn:
return False
return True
class Name(Choice):
_alternatives = [
('', RDNSequence),
]
_human_friendly = None
_sha1 = None
_sha256 = None
@classmethod
def build(cls, name_dict, use_printable=False):
"""
Creates a Name object from a dict of unicode string keys and values.
The keys should be from NameType._map, or a dotted-integer OID unicode
string.
:param name_dict:
A dict of name information, e.g. {"common_name": "Will Bond",
"country_name": "US", "organization": "Codex Non Sufficit LC"}
:param use_printable:
A bool - if PrintableString should be used for encoding instead of
UTF8String. This is for backwards compatibility with old software.
:return:
An x509.Name object
"""
rdns = []