/
validate.py
1963 lines (1626 loc) · 71.5 KB
/
validate.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
from __future__ import unicode_literals, division, absolute_import, print_function
from asn1crypto import x509, crl
from oscrypto import asymmetric
import oscrypto.errors
from ._errors import pretty_message
from ._types import str_cls, type_name
from .context import ValidationContext
from .errors import (
CRLNoMatchesError,
CRLValidationError,
CRLValidationIndeterminateError,
InvalidCertificateError,
OCSPNoMatchesError,
OCSPValidationIndeterminateError,
PathValidationError,
RevokedError,
SoftFailError,
)
from .path import ValidationPath
def validate_path(validation_context, path):
"""
Validates the path using the algorithm from
https://tools.ietf.org/html/rfc5280#section-6.1, with the exception
that name constraints are not checked or enforced.
Critical extensions on the end-entity certificate are not validated
and are left up to the consuming application to process and/or fail on.
:param validation_context:
A certvalidator.context.ValidationContext object to use for
configuring validation behavior
:param path:
A certvalidator.path.ValidationPath object of the path to validate
:raises:
certvalidator.errors.PathValidationError - when an error occurs validating the path
certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked
:return:
The final certificate in the path - an instance of
asn1crypto.x509.Certificate
"""
return _validate_path(validation_context, path)
def validate_tls_hostname(validation_context, cert, hostname):
"""
Validates the end-entity certificate from a
certvalidator.path.ValidationPath object to ensure that the certificate
is valid for the hostname provided and that the certificate is valid for
the purpose of a TLS connection.
THE CERTIFICATE PATH MUST BE VALIDATED SEPARATELY VIA validate_path()!
:param validation_context:
A certvalidator.context.ValidationContext object to use for
configuring validation behavior
:param cert:
An asn1crypto.x509.Certificate object returned from validate_path()
:param hostname:
A unicode string of the TLS server hostname
:raises:
certvalidator.errors.InvalidCertificateError - when the certificate is not valid for TLS or the hostname
"""
if not isinstance(validation_context, ValidationContext):
raise TypeError(pretty_message(
'''
validation_context must be an instance of
certvalidator.context.ValidationContext, not %s
''',
type_name(validation_context)
))
if validation_context.is_whitelisted(cert):
return
if not cert.is_valid_domain_ip(hostname):
raise InvalidCertificateError(pretty_message(
'''
The X.509 certificate provided is not valid for %s. Valid hostnames
include: %s
''',
hostname,
', '.join(cert.valid_domains)
))
bad_key_usage = cert.key_usage_value and 'digital_signature' not in cert.key_usage_value.native
bad_ext_key_usage = cert.extended_key_usage_value and 'server_auth' not in cert.extended_key_usage_value.native
if bad_key_usage or bad_ext_key_usage:
raise InvalidCertificateError(pretty_message(
'''
The X.509 certificate provided is not valid for securing TLS
connections
'''
))
def validate_usage(validation_context, cert, key_usage, extended_key_usage, extended_optional):
"""
Validates the end-entity certificate from a
certvalidator.path.ValidationPath object to ensure that the certificate
is valid for the key usage and extended key usage purposes specified.
THE CERTIFICATE PATH MUST BE VALIDATED SEPARATELY VIA validate_path()!
:param validation_context:
A certvalidator.context.ValidationContext object to use for
configuring validation behavior
:param cert:
An asn1crypto.x509.Certificate object returned from validate_path()
:param key_usage:
A set of unicode strings of the required key usage purposes
:param extended_key_usage:
A set of unicode strings of the required extended key usage purposes
:param extended_optional:
A bool - if the extended_key_usage extension may be omitted and still
considered valid
:raises:
certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified
"""
if not isinstance(validation_context, ValidationContext):
raise TypeError(pretty_message(
'''
validation_context must be an instance of
certvalidator.context.ValidationContext, not %s
''',
type_name(validation_context)
))
if validation_context.is_whitelisted(cert):
return
if key_usage is None:
key_usage = set()
if extended_key_usage is None:
extended_key_usage = set()
if not isinstance(key_usage, set):
raise TypeError(pretty_message(
'''
key_usage must be a set of unicode strings, not %s
''',
type_name(key_usage)
))
if not isinstance(extended_key_usage, set):
raise TypeError(pretty_message(
'''
extended_key_usage must be a set of unicode strings, not %s
''',
type_name(extended_key_usage)
))
if not isinstance(extended_optional, bool):
raise TypeError(pretty_message(
'''
extended_optional must be a boolean, not %s
''',
type_name(extended_optional)
))
missing_key_usage = key_usage
if cert.key_usage_value:
missing_key_usage = key_usage - cert.key_usage_value.native
missing_extended_key_usage = set()
if extended_optional is False and not cert.extended_key_usage_value:
missing_extended_key_usage = extended_key_usage
elif cert.extended_key_usage_value is not None:
missing_extended_key_usage = extended_key_usage - set(cert.extended_key_usage_value.native)
if missing_key_usage or missing_extended_key_usage:
plural = 's' if len(missing_key_usage | missing_extended_key_usage) > 1 else ''
friendly_purposes = []
for purpose in sorted(missing_key_usage | missing_extended_key_usage):
friendly_purposes.append(purpose.replace('_', ' '))
raise InvalidCertificateError(pretty_message(
'''
The X.509 certificate provided is not valid for the purpose%s of %s
''',
plural,
', '.join(friendly_purposes)
))
def _validate_path(validation_context, path, end_entity_name_override=None):
"""
Internal copy of validate_path() that allows overriding the name of the
end-entity certificate as used in exception messages. This functionality is
used during chain validation when dealing with indirect CRLs issuer or
OCSP responder certificates.
:param validation_context:
A certvalidator.context.ValidationContext object to use for
configuring validation behavior
:param path:
A certvalidator.path.ValidationPath object of the path to validate
:param end_entity_name_override:
A unicode string of the name to use for the final certificate in the
path. This is necessary when dealing with indirect CRL issuers or
OCSP responder certificates.
:return:
The final certificate in the path - an instance of
asn1crypto.x509.Certificate
"""
if not isinstance(path, ValidationPath):
raise TypeError(pretty_message(
'''
path must be an instance of certvalidator.path.ValidationPath,
not %s
''',
type_name(path)
))
if not isinstance(validation_context, ValidationContext):
raise TypeError(pretty_message(
'''
validation_context must be an instance of
certvalidator.context.ValidationContext, not %s
''',
type_name(validation_context)
))
moment = validation_context.moment
if end_entity_name_override is not None and not isinstance(end_entity_name_override, str_cls):
raise TypeError(pretty_message(
'''
end_entity_name_override must be a unicode string, not %s
''',
type_name(end_entity_name_override)
))
# Inputs
trust_anchor = path.first
# We skip the trust anchor when measuring the path since technically
# the trust anchor is not part of the path
path_length = len(path) - 1
# We don't accept any certificate policy or name constraint values as input
# and instead just start allowing everything during initialization
# Step 1: initialization
# Step 1 a
valid_policy_tree = PolicyTreeRoot('any_policy', set(), set(['any_policy']))
# Steps 1 b-c skipped since they relate to name constraints
# Steps 1 d-f
# We do not use initial-explicit-policy, initial-any-policy-inhibit or
# initial-policy-mapping-inhibit, so they are all set to the path length + 1
explicit_policy = path_length + 1
inhibit_any_policy = path_length + 1
policy_mapping = path_length + 1
# Steps 1 g-i
working_public_key = trust_anchor.public_key
# Step 1 j
working_issuer_name = trust_anchor.subject
# Step 1 k
max_path_length = path_length
if trust_anchor.max_path_length is not None:
max_path_length = trust_anchor.max_path_length
# Step 2: basic processing
index = 1
last_index = len(path) - 1
completed_path = ValidationPath(trust_anchor)
validation_context.record_validation(trust_anchor, completed_path)
cert = trust_anchor
while index <= last_index:
cert = path[index]
# Step 2 a 1
signature_algo = cert['signature_algorithm'].signature_algo
hash_algo = cert['signature_algorithm'].hash_algo
if hash_algo in validation_context.weak_hash_algos:
raise PathValidationError(pretty_message(
'''
The path could not be validated because the signature of %s
uses the weak hash algorithm %s
''',
_cert_type(index, last_index, end_entity_name_override, definite=True),
hash_algo
))
if signature_algo == 'rsassa_pkcs1v15':
verify_func = asymmetric.rsa_pkcs1v15_verify
elif signature_algo == 'dsa':
verify_func = asymmetric.dsa_verify
elif signature_algo == 'ecdsa':
verify_func = asymmetric.ecdsa_verify
else:
raise PathValidationError(pretty_message(
'''
The path could not be validated because the signature of %s
uses the unsupported algorithm %s
''',
_cert_type(index, last_index, end_entity_name_override, definite=True),
signature_algo
))
try:
key_object = asymmetric.load_public_key(working_public_key)
verify_func(key_object, cert['signature_value'].native, cert['tbs_certificate'].dump(), hash_algo)
except (oscrypto.errors.SignatureError):
raise PathValidationError(pretty_message(
'''
The path could not be validated because the signature of %s
could not be verified
''',
_cert_type(index, last_index, end_entity_name_override, definite=True)
))
# Step 2 a 2
if not validation_context.is_whitelisted(cert):
validity = cert['tbs_certificate']['validity']
if moment < validity['not_before'].native:
raise PathValidationError(pretty_message(
'''
The path could not be validated because %s is not valid
until %s
''',
_cert_type(index, last_index, end_entity_name_override, definite=True),
validity['not_before'].native.strftime('%Y-%m-%d %H:%M:%SZ')
))
if moment > validity['not_after'].native:
raise PathValidationError(pretty_message(
'''
The path could not be validated because %s expired %s
''',
_cert_type(index, last_index, end_entity_name_override, definite=True),
validity['not_after'].native.strftime('%Y-%m-%d %H:%M:%SZ')
))
# Step 2 a 3 - CRL/OCSP
if not validation_context._skip_revocation_checks:
status_good = False
revocation_check_failed = False
matched = False
soft_fail = False
failures = []
if cert.ocsp_urls or validation_context.revocation_mode == 'require':
try:
verify_ocsp_response(
cert,
path,
validation_context,
cert_description=_cert_type(
index,
last_index,
end_entity_name_override,
definite=True
),
end_entity_name_override=end_entity_name_override
)
status_good = True
matched = True
except (OCSPValidationIndeterminateError) as e:
failures.extend([failure[0] for failure in e.failures])
revocation_check_failed = True
matched = True
except (SoftFailError):
soft_fail = True
except (OCSPNoMatchesError):
pass
if not status_good and (cert.crl_distribution_points or validation_context.revocation_mode == 'require'):
try:
cert_description = _cert_type(index, last_index, end_entity_name_override, definite=True)
verify_crl(
cert,
path,
validation_context,
cert_description=cert_description,
end_entity_name_override=end_entity_name_override
)
revocation_check_failed = False
status_good = True
matched = True
except (CRLValidationIndeterminateError) as e:
failures.extend([failure[0] for failure in e.failures])
revocation_check_failed = True
matched = True
except (SoftFailError):
soft_fail = True
except (CRLNoMatchesError):
pass
if not soft_fail:
if not matched and validation_context.revocation_mode == 'require':
raise PathValidationError(pretty_message(
'''
The path could not be validated because no revocation
information could be found for %s
''',
_cert_type(index, last_index, end_entity_name_override, definite=True)
))
if not status_good and revocation_check_failed:
raise PathValidationError(pretty_message(
'''
The path could not be validated because the %s revocation
checks failed: %s
''',
_cert_type(index, last_index, end_entity_name_override),
'; '.join(failures)
))
# Step 2 a 4
if cert.issuer != working_issuer_name:
raise PathValidationError(pretty_message(
'''
The path could not be validated because the %s issuer name
could not be matched
''',
_cert_type(index, last_index, end_entity_name_override),
))
# Steps 2 b-c skipped since they relate to name constraints
# Steps 2 d
if cert.certificate_policies_value and valid_policy_tree is not None:
cert_any_policy = None
cert_policy_identifiers = set()
# Step 2 d 1
for policy in cert.certificate_policies_value:
policy_identifier = policy['policy_identifier'].native
if policy_identifier == 'any_policy':
cert_any_policy = policy
continue
cert_policy_identifiers.add(policy_identifier)
policy_qualifiers = policy['policy_qualifiers']
policy_id_match = False
parent_any_policy = None
# Step 2 d 1 i
for node in valid_policy_tree.at_depth(index - 1):
if node.valid_policy == 'any_policy':
parent_any_policy = node
if policy_identifier not in node.expected_policy_set:
continue
policy_id_match = True
node.add_child(
policy_identifier,
policy_qualifiers,
set([policy_identifier])
)
# Step 2 d 1 ii
if not policy_id_match and parent_any_policy:
parent_any_policy.add_child(
policy_identifier,
policy_qualifiers,
set([policy_identifier])
)
# Step 2 d 2
if cert_any_policy and (inhibit_any_policy > 0 or (index < path_length and cert.self_issued)):
for node in valid_policy_tree.at_depth(index - 1):
for expected_policy_identifier in node.expected_policy_set:
if expected_policy_identifier not in cert_policy_identifiers:
node.add_child(
expected_policy_identifier,
cert_any_policy['policy_qualifiers'],
set([expected_policy_identifier])
)
# Step 2 d 3
for node in valid_policy_tree.walk_up(index - 1):
if not node.children:
node.parent.remove_child(node)
if len(valid_policy_tree.children) == 0:
valid_policy_tree = None
# Step 2 e
if cert.certificate_policies_value is None:
valid_policy_tree = None
# Step 2 f
if valid_policy_tree is None and explicit_policy <= 0:
raise PathValidationError(pretty_message(
'''
The path could not be validated because there is no valid set
of policies for %s
''',
_cert_type(index, last_index, end_entity_name_override, definite=True),
))
if index != last_index:
# Step 3: prepare for certificate index+1
if cert.policy_mappings_value:
policy_map = {}
for mapping in cert.policy_mappings_value:
issuer_domain_policy = mapping['issuer_domain_policy'].native
subject_domain_policy = mapping['subject_domain_policy'].native
if issuer_domain_policy not in policy_map:
policy_map[issuer_domain_policy] = set()
policy_map[issuer_domain_policy].add(subject_domain_policy)
# Step 3 a
if issuer_domain_policy == 'any_policy' or subject_domain_policy == 'any_policy':
raise PathValidationError(pretty_message(
'''
The path could not be validated because %s contains
a policy mapping for the "any policy"
''',
_cert_type(index, last_index, end_entity_name_override, definite=True)
))
# Step 3 b
if valid_policy_tree is not None:
for mapping in cert.policy_mappings_value:
issuer_domain_policy = mapping['issuer_domain_policy'].native
# Step 3 b 1
if policy_mapping > 0:
issuer_domain_policy_match = False
cert_any_policy = None
for node in valid_policy_tree.at_depth(index):
if node.valid_policy == 'any_policy':
cert_any_policy = node
if node.valid_policy == issuer_domain_policy:
issuer_domain_policy_match = True
node.expected_policy_set = policy_map[issuer_domain_policy]
if not issuer_domain_policy_match and cert_any_policy:
cert_any_policy.parent.add_child(
issuer_domain_policy,
cert_any_policy.qualifier_set,
policy_map[issuer_domain_policy]
)
# Step 3 b 2
elif policy_mapping == 0:
for node in valid_policy_tree.at_depth(index):
if node.valid_policy == issuer_domain_policy:
node.parent.remove_child(node)
for node in valid_policy_tree.walk_up(index - 1):
if not node.children:
node.parent.remove_child(node)
if len(valid_policy_tree.children) == 0:
valid_policy_tree = None
# Step 3 c
working_issuer_name = cert.subject
# Steps 3 d-f
# Handle inheritance of DSA parameters from a signing CA to the
# next in the chain
copy_params = None
if cert.public_key.algorithm == 'dsa' and cert.public_key.hash_algo is None:
if working_public_key.algorithm == 'dsa':
copy_params = working_public_key['algorithm']['parameters'].copy()
working_public_key = cert.public_key
if copy_params:
working_public_key['algorithm']['parameters'] = copy_params
# Step 3 g skipped since it relates to name constraints
# Step 3 h
if not cert.self_issued:
# Step 3 h 1
if explicit_policy != 0:
explicit_policy -= 1
# Step 3 h 2
if policy_mapping != 0:
policy_mapping -= 1
# Step 3 h 3
if inhibit_any_policy != 0:
inhibit_any_policy -= 1
# Step 3 i
if cert.policy_constraints_value:
# Step 3 i 1
require_explicit_policy = cert.policy_constraints_value['require_explicit_policy'].native
if require_explicit_policy is not None and require_explicit_policy < explicit_policy:
explicit_policy = require_explicit_policy
# Step 3 i 2
inhibit_policy_mapping = cert.policy_constraints_value['inhibit_policy_mapping'].native
if inhibit_policy_mapping is not None and inhibit_policy_mapping < policy_mapping:
policy_mapping = inhibit_policy_mapping
# Step 3 j
if cert.inhibit_any_policy_value:
inhibit_any_policy = min(cert.inhibit_any_policy_value.native, inhibit_any_policy)
# Step 3 k
if not cert.ca:
raise PathValidationError(pretty_message(
'''
The path could not be validated because %s is not a CA
''',
_cert_type(index, last_index, end_entity_name_override, definite=True)
))
# Step 3 l
if not cert.self_issued:
if max_path_length == 0:
raise PathValidationError(pretty_message(
'''
The path could not be validated because it exceeds the
maximum path length
'''
))
max_path_length -= 1
# Step 3 m
if cert.max_path_length is not None and cert.max_path_length < max_path_length:
max_path_length = cert.max_path_length
# Step 3 n
if cert.key_usage_value and 'key_cert_sign' not in cert.key_usage_value.native:
raise PathValidationError(pretty_message(
'''
The path could not be validated because %s is not allowed
to sign certificates
''',
_cert_type(index, last_index, end_entity_name_override, definite=True)
))
# Step 3 o
# Check for critical unsupported extensions
supported_extensions = set([
'authority_information_access',
'authority_key_identifier',
'basic_constraints',
'crl_distribution_points',
'extended_key_usage',
'freshest_crl',
'key_identifier',
'key_usage',
'ocsp_no_check',
'certificate_policies',
'policy_mappings',
'policy_constraints',
'inhibit_any_policy',
])
unsupported_critical_extensions = cert.critical_extensions - supported_extensions
if unsupported_critical_extensions:
raise PathValidationError(pretty_message(
'''
The path could not be validated because %s contains the
following unsupported critical extension%s: %s
''',
_cert_type(index, last_index, end_entity_name_override, definite=True),
's' if len(unsupported_critical_extensions) != 1 else '',
', '.join(sorted(unsupported_critical_extensions)),
))
if validation_context:
completed_path = completed_path.copy().append(cert)
validation_context.record_validation(cert, completed_path)
index += 1
# Step 4: wrap-up procedure
# Step 4 a
if explicit_policy != 0:
explicit_policy -= 1
# Step 4 b
if cert.policy_constraints_value:
if cert.policy_constraints_value['require_explicit_policy'].native == 0:
explicit_policy = 0
# Steps 4 c-e skipped since this method doesn't output it
# Step 4 f skipped since this method defers that to the calling application
# Step 4 g
# Step 4 g i
if valid_policy_tree is None:
intersection = None
# Step 4 g ii
else:
intersection = valid_policy_tree
# Step 4 g iii is skipped since the initial policy set is always any_policy
if explicit_policy == 0 and intersection is None:
raise PathValidationError(pretty_message(
'''
The path could not be validated because there is no valid set of
policies for %s
''',
_cert_type(last_index, last_index, end_entity_name_override, definite=True)
))
return cert
def _cert_type(index, last_index, end_entity_name_override, definite=False):
"""
:param index:
An integer of the index of the certificate in the path
:param last_index:
An integer of the last index in the path
:param end_entity_name_override:
None or a unicode string of the name to use for the final certificate
in the path. Used for indirect CRL issuer and OCSP responder
certificates.
:param definite:
When returning the string "end-entity certificate", passing this flag
as True will prepend "the " to the result
:return:
A unicode string describing the position of a certificate in the chain
"""
if index != last_index:
return 'intermediate certificate %s' % index
prefix = 'the ' if definite else ''
if end_entity_name_override is not None:
return prefix + end_entity_name_override
return prefix + 'end-entity certificate'
def _self_signed(cert):
"""
Determines if a certificate is self-signed
:param cert:
An asn1crypto.x509.Certificate object to check
:return:
A boolean - True if the certificate is self-signed, False otherwise
"""
self_signed = cert.self_signed
if self_signed == 'yes':
return True
if self_signed == 'no':
return False
# In the case of "maybe", we have to check the signature
signature_algo = cert['signature_algorithm'].signature_algo
hash_algo = cert['signature_algorithm'].hash_algo
if signature_algo == 'rsassa_pkcs1v15':
verify_func = asymmetric.rsa_pkcs1v15_verify
elif signature_algo == 'dsa':
verify_func = asymmetric.dsa_verify
elif signature_algo == 'ecdsa':
verify_func = asymmetric.ecdsa_verify
else:
raise PathValidationError(pretty_message(
'''
Unable to verify the signature of the certificate since it uses
the unsupported algorithm %s
''',
signature_algo
))
try:
key_object = asymmetric.load_certificate(cert)
verify_func(key_object, cert['signature_value'].native, cert['tbs_certificate'].dump(), hash_algo)
return True
except (oscrypto.errors.SignatureError):
return False
def verify_ocsp_response(cert, path, validation_context, cert_description=None, end_entity_name_override=None):
"""
Verifies an OCSP response, checking to make sure the certificate has not
been revoked. Fulfills the requirements of
https://tools.ietf.org/html/rfc6960#section-3.2.
:param cert:
An asn1cyrpto.x509.Certificate object to verify the OCSP reponse for
:param path:
A certvalidator.path.ValidationPath object for the cert
:param validation_context:
A certvalidator.context.ValidationContext object to use for caching
validation information
:param cert_description:
None or a unicode string containing a description of the certificate to
be used in exception messages
:param end_entity_name_override:
None or a unicode string of the name to use for the end-entity
certificate when including in exception messages
:raises:
certvalidator.errors.OCSPNoMatchesError - when none of the OCSP responses match the certificate
certvalidator.errors.OCSPValidationIndeterminateError - when the OCSP response could not be verified
certvalidator.errors.RevokedError - when the OCSP response indicates the certificate has been revoked
"""
if not isinstance(cert, x509.Certificate):
raise TypeError(pretty_message(
'''
cert must be an instance of asn1crypto.x509.Certificate, not %s
''',
type_name(cert)
))
if not isinstance(path, ValidationPath):
raise TypeError(pretty_message(
'''
path must be an instance of certvalidator.path.ValidationPath,
not %s
''',
type_name(path)
))
if not isinstance(validation_context, ValidationContext):
raise TypeError(pretty_message(
'''
validation_context must be an instance of
certvalidator.context.ValidationContext, not %s
''',
type_name(validation_context)
))
if cert_description is None:
cert_description = 'the certificate'
if not isinstance(cert_description, str_cls):
raise TypeError(pretty_message(
'''
cert_description must be a unicode string, not %s
''',
type_name(cert_description)
))
moment = validation_context.moment
issuer = path.find_issuer(cert)
certificate_registry = validation_context.certificate_registry
failures = []
mismatch_failures = 0
ocsp_responses = validation_context.retrieve_ocsps(cert, issuer)
for ocsp_response in ocsp_responses:
# Make sure that we get a valid response back from the OCSP responder
status = ocsp_response['response_status'].native
if status != 'successful':
mismatch_failures += 1
continue
response_bytes = ocsp_response['response_bytes']
if response_bytes['response_type'].native != 'basic_ocsp_response':
mismatch_failures += 1
continue
response = response_bytes['response'].parsed
tbs_response = response['tbs_response_data']
# With a valid response, now a check is performed to see if the response is
# applicable for the cert and moment requested
cert_response = tbs_response['responses'][0]
response_cert_id = cert_response['cert_id']
issuer_hash_algo = response_cert_id['hash_algorithm']['algorithm'].native
cert_issuer_name_hash = getattr(cert.issuer, issuer_hash_algo)
cert_issuer_key_hash = getattr(issuer.public_key, issuer_hash_algo)
key_hash_mismatch = response_cert_id['issuer_key_hash'].native != cert_issuer_key_hash
name_mismatch = response_cert_id['issuer_name_hash'].native != cert_issuer_name_hash
serial_mismatch = response_cert_id['serial_number'].native != cert.serial_number
if (name_mismatch or serial_mismatch) and key_hash_mismatch:
mismatch_failures += 1
continue
if name_mismatch:
failures.append((
'OCSP response issuer name hash does not match',
ocsp_response
))
continue
if serial_mismatch:
failures.append((
'OCSP response certificate serial number does not match',
ocsp_response
))
continue
if key_hash_mismatch:
failures.append((
'OCSP response issuer key hash does not match',
ocsp_response
))
continue
if moment < cert_response['this_update'].native:
failures.append((
'OCSP response is from after the validation time',
ocsp_response
))
continue
if moment > cert_response['next_update'].native:
failures.append((
'OCSP response is from before the validation time',
ocsp_response
))
continue
# To verify the response as legitimate, the responder cert must be located
if tbs_response['responder_id'].name == 'by_key':
key_identifier = tbs_response['responder_id'].native
signing_cert = certificate_registry.retrieve_by_key_identifier(key_identifier)
else:
candidate_signing_certs = certificate_registry.retrieve_by_name(
tbs_response['responder_id'].chosen,
None
)
signing_cert = candidate_signing_certs[0] if candidate_signing_certs else None
if not signing_cert:
failures.append((
pretty_message(
'''
Unable to verify OCSP response since response signing
certificate could not be located
'''
),
ocsp_response
))
continue
# The responder cert has to have a valid path back to one of the trust roots
if not certificate_registry.is_ca(signing_cert):
signing_cert_paths = certificate_registry.build_paths(signing_cert)
for signing_cert_path in signing_cert_paths:
try:
# Store the original revocation check value
changed_revocation_flags = False
skip_ocsp = signing_cert.ocsp_no_check_value is not None
skip_ocsp = skip_ocsp or signing_cert_path == path
if skip_ocsp and validation_context._skip_revocation_checks is False:
changed_revocation_flags = True
original_revocation_mode = validation_context.revocation_mode
new_revocation_mode = "soft-fail" if original_revocation_mode == "soft-fail" else "hard-fail"
validation_context._skip_revocation_checks = True