File size: 57,162 Bytes
ddf04fa | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 | diff --git a/src/constraints/matcher.py b/src/constraints/matcher.py
index 395b86c..a352689 100644
--- a/src/constraints/matcher.py
+++ b/src/constraints/matcher.py
@@ -5,9 +5,9 @@ from __future__ import annotations
import ipaddress
from dataclasses import dataclass, field
from typing import List, Optional, Tuple
+from urllib.parse import urlparse
from src.models import (
- Certificate,
ConstraintType,
NameConstraint,
NameConstraintsExtension,
@@ -18,89 +18,129 @@ from src.models import (
@dataclass
class EffectiveConstraints:
"""Represents the accumulated name constraints along a certificate chain."""
- permitted_subtrees: List[NameConstraint] = field(default_factory=list)
+ permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
excluded_subtrees: List[NameConstraint] = field(default_factory=list)
- _permitted_groups: List[List[NameConstraint]] = field(default_factory=list)
+ permitted_subtrees: List[NameConstraint] = field(default_factory=list)
def __post_init__(self) -> None:
- if self.permitted_subtrees and not self._permitted_groups:
- object.__setattr__(self, "_permitted_groups", [list(self.permitted_subtrees)])
+ if self.permitted_subtrees and not self.permitted_groups:
+ self.permitted_groups = [list(self.permitted_subtrees)]
+ elif self.permitted_groups and not self.permitted_subtrees:
+ self.permitted_subtrees = [c for group in self.permitted_groups for c in group]
def is_empty(self) -> bool:
- return not (self.permitted_subtrees or self.excluded_subtrees or self._permitted_groups)
+ return not (self.permitted_groups or self.permitted_subtrees or self.excluded_subtrees)
def merge_parent(self, parent_nc: Optional[NameConstraintsExtension]) -> EffectiveConstraints:
"""Merges parent constraints into this effective constraint set."""
if not parent_nc:
return self
- new_permitted = list(self.permitted_subtrees) + list(parent_nc.permitted_subtrees)
new_excluded = list(self.excluded_subtrees) + list(parent_nc.excluded_subtrees)
- new_groups = [list(g) for g in self._permitted_groups]
+ new_groups = [list(g) for g in self.permitted_groups]
if parent_nc.permitted_subtrees:
new_groups.append(list(parent_nc.permitted_subtrees))
+ new_permitted = [c for group in new_groups for c in group]
return EffectiveConstraints(
permitted_subtrees=new_permitted,
excluded_subtrees=new_excluded,
- _permitted_groups=new_groups,
+ permitted_groups=new_groups,
)
+ def add_ca_constraints(self, ca_nc: Optional[NameConstraintsExtension]) -> None:
+ if not ca_nc:
+ return
+ if ca_nc.excluded_subtrees:
+ self.excluded_subtrees.extend(ca_nc.excluded_subtrees)
+ if ca_nc.permitted_subtrees:
+ self.permitted_groups.append(list(ca_nc.permitted_subtrees))
+ self.permitted_subtrees.extend(ca_nc.permitted_subtrees)
+
def match_dns_constraint(dns_name: str, constraint: str) -> bool:
- """Matches a DNS SAN name against a DNS name constraint.
-
- RFC 5280 DNS Name Constraint Rules:
- - Constraint 'example.com' or '.example.com' matches 'example.com' and 'host.example.com'.
- - Must respect dot boundaries (should not match 'fakecorp.internal' for 'corp.internal').
- """
- clean_dns = dns_name.lower().strip(".")
- clean_constraint = constraint.lower().strip(".")
-
+ """Matches a DNS SAN name against a DNS name constraint adhering to RFC 5280 Section 4.2.1.10."""
+ clean_dns = dns_name.lower().strip()
+ clean_constraint = constraint.lower().strip()
+
+ clean_constraint = clean_constraint.lstrip(".")
+ clean_dns = clean_dns.strip(".")
+
if not clean_constraint:
return True
-
if clean_dns == clean_constraint:
return True
-
if clean_dns.endswith("." + clean_constraint):
return True
-
+ if clean_dns.startswith("*."):
+ suffix = clean_dns[2:]
+ if suffix == clean_constraint or suffix.endswith("." + clean_constraint):
+ return True
return False
def match_ip_constraint(ip_str: str, constraint_cidr: str) -> bool:
- """Matches an IP SAN against an IP CIDR constraint."""
+ """Matches an IP SAN address or CIDR against an IP CIDR constraint."""
try:
- ip = ipaddress.ip_address(ip_str.strip())
net = ipaddress.ip_network(constraint_cidr.strip(), strict=False)
- return ip in net
+ try:
+ ip = ipaddress.ip_address(ip_str.strip())
+ return ip in net
+ except ValueError:
+ sub_net = ipaddress.ip_network(ip_str.strip(), strict=False)
+ return sub_net.subnet_of(net)
except (ValueError, TypeError):
return False
def match_uri_constraint(uri: str, constraint_prefix: str) -> bool:
- """Matches a URI SAN against a URI constraint prefix."""
- return uri.startswith(constraint_prefix)
+ """Matches a URI SAN against a URI constraint prefix per RFC 5280 Section 4.2.1.10."""
+ try:
+ p_uri = urlparse(uri.strip())
+ p_con = urlparse(constraint_prefix.strip())
+ if p_con.scheme and p_uri.scheme.lower() != p_con.scheme.lower():
+ return False
+ if p_con.netloc and p_uri.netloc.lower() != p_con.netloc.lower():
+ return False
-def validate_san_constraints(
+ con_path = p_con.path
+ uri_path = p_uri.path
+
+ if not con_path or con_path == "/":
+ return True
+ if con_path.endswith("/"):
+ return uri_path.startswith(con_path)
+ return uri_path == con_path or uri_path.startswith(con_path + "/")
+ except Exception:
+ return uri.strip().lower().startswith(constraint_prefix.strip().lower())
+
+
+def validate_name_constraints(
san: SubjectAlternativeName,
+ subject_dn: str,
constraints: EffectiveConstraints,
+ is_ca: bool = False,
) -> Tuple[bool, List[str]]:
- """Validates SAN entries against accumulated effective name constraints.
-
- Returns (is_valid, list_of_violation_errors).
- """
- if constraints.is_empty() or san.is_empty():
+ """Validates SAN entries and Subject DN against accumulated effective name constraints."""
+ if constraints.is_empty():
return True, []
errors: List[str] = []
+ has_san = not san.is_empty()
- # 1. Check excluded subtrees (any match violates constraints)
+ # 1. Check excluded subtrees
for excl in constraints.excluded_subtrees:
if excl.type == ConstraintType.DNS:
- for d in san.dns_names:
- if match_dns_constraint(d, excl.value):
- errors.append(f"DNS name '{d}' is excluded by constraint '{excl.value}'")
+ if has_san and san.dns_names:
+ for d in san.dns_names:
+ if match_dns_constraint(d, excl.value):
+ errors.append(f"DNS name '{d}' is excluded by constraint '{excl.value}'")
+ elif not is_ca:
+ # Extract CN from Subject DN for end-entity certificates
+ for part in subject_dn.split(","):
+ if part.strip().startswith("CN="):
+ cn_val = part.strip()[3:]
+ if match_dns_constraint(cn_val, excl.value):
+ errors.append(f"Subject CN '{cn_val}' is excluded by constraint '{excl.value}'")
elif excl.type == ConstraintType.IP:
for ip in san.ip_addresses:
if match_ip_constraint(ip, excl.value):
@@ -110,27 +150,41 @@ def validate_san_constraints(
if match_uri_constraint(u, excl.value):
errors.append(f"URI '{u}' is excluded by constraint '{excl.value}'")
- # 2. Check permitted subtrees (intersection of all ancestor tiers)
- groups = constraints._permitted_groups if constraints._permitted_groups else (
- [constraints.permitted_subtrees] if constraints.permitted_subtrees else []
- )
+ # 2. Check permitted subtree groups
+ groups = constraints.permitted_groups if constraints.permitted_groups else ([constraints.permitted_subtrees] if constraints.permitted_subtrees else [])
+
for group in groups:
- dns_perm = [c.value for c in group if c.type == ConstraintType.DNS]
- if dns_perm and san.dns_names:
- for d in san.dns_names:
- if not any(match_dns_constraint(d, p) for p in dns_perm):
- errors.append(f"DNS name '{d}' is not permitted by allowed DNS subtrees {dns_perm}")
-
- ip_perm = [c.value for c in group if c.type == ConstraintType.IP]
- if ip_perm and san.ip_addresses:
+ dns_perms = [c.value for c in group if c.type == ConstraintType.DNS]
+ if dns_perms:
+ if has_san and san.dns_names:
+ for d in san.dns_names:
+ if not any(match_dns_constraint(d, p) for p in dns_perms):
+ errors.append(f"DNS name '{d}' is not permitted by allowed DNS subtrees {dns_perms}")
+ elif not is_ca:
+ for part in subject_dn.split(","):
+ if part.strip().startswith("CN="):
+ cn_val = part.strip()[3:]
+ if not any(match_dns_constraint(cn_val, p) for p in dns_perms):
+ errors.append(f"Subject CN '{cn_val}' is not permitted by allowed DNS subtrees {dns_perms}")
+
+ ip_perms = [c.value for c in group if c.type == ConstraintType.IP]
+ if ip_perms and san.ip_addresses:
for ip in san.ip_addresses:
- if not any(match_ip_constraint(ip, p) for p in ip_perm):
- errors.append(f"IP address '{ip}' is not permitted by allowed IP subtrees {ip_perm}")
+ if not any(match_ip_constraint(ip, p) for p in ip_perms):
+ errors.append(f"IP address '{ip}' is not permitted by allowed IP subtrees {ip_perms}")
- uri_perm = [c.value for c in group if c.type == ConstraintType.URI]
- if uri_perm and san.uris:
+ uri_perms = [c.value for c in group if c.type == ConstraintType.URI]
+ if uri_perms and san.uris:
for u in san.uris:
- if not any(match_uri_constraint(u, p) for p in uri_perm):
- errors.append(f"URI '{u}' is not permitted by allowed URI subtrees {uri_perm}")
+ if not any(match_uri_constraint(u, p) for p in uri_perms):
+ errors.append(f"URI '{u}' is not permitted by allowed URI subtrees {uri_perms}")
return len(errors) == 0, errors
+
+
+def validate_san_constraints(
+ san: SubjectAlternativeName,
+ constraints: EffectiveConstraints,
+) -> Tuple[bool, List[str]]:
+ """Legacy helper for SAN-only constraint validation."""
+ return validate_name_constraints(san, "", constraints, is_ca=False)
diff --git a/src/path/builder.py b/src/path/builder.py
index 5960b3e..6f8efe5 100644
--- a/src/path/builder.py
+++ b/src/path/builder.py
@@ -37,34 +37,35 @@ class PathBuilder:
self.max_path_length = max_path_length
def find_all_candidate_paths(self, leaf: Certificate) -> List[CandidatePath]:
- """Finds all candidate certification paths from leaf to an installed Trust Anchor."""
- paths: List[CandidatePath] = []
+ """Finds all candidate certification paths from leaf to an installed Trust Anchor using backtracking."""
+ all_paths: List[CandidatePath] = []
- if self.trust_store.is_trust_anchor(leaf):
- return [CandidatePath(certificates=[leaf])]
+ def dfs(current_path: List[Certificate], visited_serials: Set[str]) -> None:
+ current = current_path[-1]
- def _dfs(current_path: List[Certificate], visited_serials: Set[str]) -> None:
- if len(current_path) >= self.max_path_length:
+ if self.trust_store.is_trust_anchor(current):
+ all_paths.append(CandidatePath(certificates=list(current_path)))
return
- current = current_path[-1]
-
- if len(current_path) > 1 and self.trust_store.is_trust_anchor(current):
- paths.append(CandidatePath(certificates=list(current_path)))
+ if len(current_path) >= self.max_path_length:
return
- candidates = self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id)
+ candidates = list(self.trust_store.find_candidates(current.issuer_dn, current.authority_key_id))
- if current.authority_info_access:
- for aia_key, uri in current.authority_info_access.items():
- if aia_key == "ca_issuers" or "ca_issuers" in aia_key:
- remote_cert = self.trust_store.fetch_aia_certificate(uri)
- if remote_cert and remote_cert not in candidates:
- candidates.append(remote_cert)
+ # Lazy AIA ca_issuers resolution
+ if current.authority_info_access and "ca_issuers" in current.authority_info_access:
+ aia_url = current.authority_info_access["ca_issuers"]
+ remote_cert = self.trust_store.fetch_remote_aia_certificate(aia_url)
+ if remote_cert and remote_cert not in candidates:
+ candidates.append(remote_cert)
for cand in candidates:
if cand.serial_number not in visited_serials:
- _dfs(current_path + [cand], visited_serials | {cand.serial_number})
-
- _dfs([leaf], {leaf.serial_number})
- return paths
+ visited_serials.add(cand.serial_number)
+ current_path.append(cand)
+ dfs(current_path, visited_serials)
+ current_path.pop()
+ visited_serials.remove(cand.serial_number)
+
+ dfs([leaf], {leaf.serial_number})
+ return all_paths
diff --git a/src/policy/tree_processor.py b/src/policy/tree_processor.py
index da808a2..5c0fce6 100644
--- a/src/policy/tree_processor.py
+++ b/src/policy/tree_processor.py
@@ -15,23 +15,11 @@ class PolicyNode:
valid_policy: str
qualifier_set: Set[str] = field(default_factory=set)
expected_policy_set: Set[str] = field(default_factory=set)
+ original_initial_policy: Optional[str] = None
parent: Optional[PolicyNode] = None
children: List[PolicyNode] = field(default_factory=list)
-def _prune_tree(nodes_by_depth: Dict[int, List[PolicyNode]], depth: int) -> None:
- """Prunes childless nodes backwards from depth to 0."""
- for d in range(depth, -1, -1):
- nodes = nodes_by_depth.get(d, [])
- to_remove = [node for node in nodes if len(node.children) == 0]
- for node in to_remove:
- if node.parent and node in node.parent.children:
- node.parent.children.remove(node)
- if node in nodes:
- nodes.remove(node)
- nodes_by_depth[d] = nodes
-
-
class PolicyTreeProcessor:
"""Processes certification path policies and computes authorities_constrained_policies."""
@@ -45,140 +33,134 @@ class PolicyTreeProcessor:
Returns (is_valid, authorities_constrained_policies, errors).
"""
- n = len(path_certificates)
- if n == 0:
- return False, set(), ["Empty certificate path"]
-
- # Chain from Root (depth 0) to Leaf (depth n-1)
- chain = list(reversed(path_certificates))
-
- root_node = PolicyNode(
- valid_policy=ANY_POLICY,
- qualifier_set=set(),
- expected_policy_set={ANY_POLICY},
- parent=None,
- children=[],
- )
- nodes_by_depth: dict[int, List[PolicyNode]] = {0: [root_node]}
-
- explicit_policy = 0 if self.config.initial_explicit_policy else (n + 1)
- inhibit_policy_mapping = 0 if self.config.initial_policy_mapping_inhibit else (n + 1)
- inhibit_any_policy = 0 if self.config.initial_any_policy_inhibit else (n + 1)
-
+ errors: List[str] = []
+ # Path from root to leaf
+ certs = path_certificates[::-1]
+ n = len(certs)
+
+ # Initialize state variables from ValidationConfig
+ explicit_policy = 0 if self.config.initial_explicit_policy else n + 1
+ inhibit_policy_mapping = 0 if self.config.initial_policy_mapping_inhibit else n + 1
+ inhibit_any_policy = 0 if self.config.initial_any_policy_inhibit else n + 1
+
+ # Root certificate at index 0 (depth 0)
+ root_cert = certs[0]
+
+ # Read root constraints if present
+ if root_cert.policy_constraints:
+ if root_cert.policy_constraints.require_explicit_policy is not None:
+ explicit_policy = min(explicit_policy, root_cert.policy_constraints.require_explicit_policy)
+ if root_cert.policy_constraints.inhibit_policy_mapping is not None:
+ inhibit_policy_mapping = min(inhibit_policy_mapping, root_cert.policy_constraints.inhibit_policy_mapping)
+ if root_cert.inhibit_any_policy:
+ inhibit_any_policy = min(inhibit_any_policy, root_cert.inhibit_any_policy.skip_certs)
+
+ root_policies: Set[str] = set()
+ if root_cert.certificate_policies and root_cert.certificate_policies.policies:
+ root_policies = {p.policy_identifier for p in root_cert.certificate_policies.policies}
+
+ if not root_policies or ANY_POLICY in root_policies:
+ root_node = PolicyNode(
+ valid_policy=ANY_POLICY,
+ expected_policy_set={ANY_POLICY},
+ original_initial_policy=ANY_POLICY,
+ )
+ nodes_by_depth: List[List[PolicyNode]] = [[root_node]]
+ else:
+ root_nodes: List[PolicyNode] = [
+ PolicyNode(
+ valid_policy=p,
+ expected_policy_set={p},
+ original_initial_policy=p,
+ )
+ for p in root_policies
+ ]
+ nodes_by_depth = [root_nodes]
+
+ # Process certificates from index 1 to n-1 (depth 1 to n-1)
for i in range(1, n):
- cert = chain[i]
- is_leaf_cert = (i == n - 1)
-
- if cert.certificate_policies is None:
- if is_leaf_cert:
- if explicit_policy == 0:
- return False, set(), ["Explicit policy required but leaf certificate contains no policies"]
- return True, set(), []
-
- current_depth_nodes: List[PolicyNode] = []
- for p_node in nodes_by_depth.get(i - 1, []):
- for exp in p_node.expected_policy_set:
- c_node = PolicyNode(
- valid_policy=exp,
- qualifier_set=set(p_node.qualifier_set),
- expected_policy_set={exp},
- parent=p_node,
- children=[],
- )
- p_node.children.append(c_node)
- current_depth_nodes.append(c_node)
- nodes_by_depth[i] = current_depth_nodes
- else:
- cert_policies = cert.certificate_policies.policies
- cert_policy_ids = {p.policy_identifier for p in cert_policies}
- qualifiers_by_id = {p.policy_identifier: set(p.qualifiers) for p in cert_policies}
-
- current_depth_nodes = []
- parent_nodes = nodes_by_depth.get(i - 1, [])
-
- for p_node in parent_nodes:
- if p_node.valid_policy == ANY_POLICY:
- if ANY_POLICY in cert_policy_ids and (inhibit_any_policy > 0 or is_leaf_cert):
- c_node = PolicyNode(
- valid_policy=ANY_POLICY,
- qualifier_set=qualifiers_by_id.get(ANY_POLICY, set()),
- expected_policy_set={ANY_POLICY},
- parent=p_node,
- children=[],
+ cert = certs[i]
+ is_leaf = (i == n - 1)
+ prev_nodes = nodes_by_depth[i - 1]
+ current_depth_nodes: List[PolicyNode] = []
+
+ # Check if intermediate has mappings but no certificate policies
+ if not is_leaf and cert.policy_mappings and (not cert.certificate_policies or not cert.certificate_policies.policies):
+ errors.append(f"Intermediate certificate {cert.subject_dn} contains policy_mappings without certificate_policies")
+ return False, set(), errors
+
+ # Step 1: Certificate Policies
+ if cert.certificate_policies and cert.certificate_policies.policies:
+ cert_p_oids = {p.policy_identifier for p in cert.certificate_policies.policies}
+
+ # Check for anyPolicy wildcard expansion
+ if ANY_POLICY in cert_p_oids and inhibit_any_policy > 0:
+ for parent in prev_nodes:
+ for exp_p in parent.expected_policy_set:
+ orig_pol = parent.original_initial_policy if parent.original_initial_policy != ANY_POLICY else exp_p
+ child = PolicyNode(
+ valid_policy=exp_p,
+ expected_policy_set={exp_p},
+ original_initial_policy=orig_pol,
+ parent=parent,
)
- p_node.children.append(c_node)
- current_depth_nodes.append(c_node)
- for p_id in cert_policy_ids:
- if p_id != ANY_POLICY:
- if ANY_POLICY in p_node.expected_policy_set or p_id in p_node.expected_policy_set:
- c_node = PolicyNode(
- valid_policy=p_id,
- qualifier_set=qualifiers_by_id.get(p_id, set()),
- expected_policy_set={p_id},
- parent=p_node,
- children=[],
- )
- p_node.children.append(c_node)
- current_depth_nodes.append(c_node)
- else:
- if ANY_POLICY in cert_policy_ids and (inhibit_any_policy > 0 or is_leaf_cert):
- for exp in p_node.expected_policy_set:
- c_node = PolicyNode(
- valid_policy=exp,
- qualifier_set=qualifiers_by_id.get(ANY_POLICY, set()),
- expected_policy_set={exp},
- parent=p_node,
- children=[],
+ parent.children.append(child)
+ current_depth_nodes.append(child)
+ else:
+ # Explicit policy processing
+ for p_oid in cert_p_oids:
+ if p_oid == ANY_POLICY:
+ continue
+ for parent in prev_nodes:
+ if parent.valid_policy == p_oid or (
+ parent.valid_policy == ANY_POLICY
+ and (ANY_POLICY in parent.expected_policy_set or p_oid in parent.expected_policy_set)
+ ) or (p_oid in parent.expected_policy_set):
+ orig_pol = parent.original_initial_policy if parent.original_initial_policy != ANY_POLICY else p_oid
+ child = PolicyNode(
+ valid_policy=p_oid,
+ expected_policy_set={p_oid},
+ original_initial_policy=orig_pol,
+ parent=parent,
)
- p_node.children.append(c_node)
- current_depth_nodes.append(c_node)
- for p_id in cert_policy_ids:
- if p_id != ANY_POLICY:
- if p_id in p_node.expected_policy_set:
- c_node = PolicyNode(
- valid_policy=p_id,
- qualifier_set=qualifiers_by_id.get(p_id, set()),
- expected_policy_set={p_id},
- parent=p_node,
- children=[],
- )
- p_node.children.append(c_node)
- current_depth_nodes.append(c_node)
-
- _prune_tree(nodes_by_depth, i - 1)
- nodes_by_depth[i] = current_depth_nodes
-
- if not current_depth_nodes:
- if explicit_policy == 0 or (is_leaf_cert and self.config.initial_explicit_policy):
- return False, set(), [f"Valid policy tree is empty at depth {i}"]
-
- if not is_leaf_cert:
- if cert.policy_mappings:
- if inhibit_policy_mapping > 0:
- for m in cert.policy_mappings.mappings:
- if m.issuer_domain_policy == ANY_POLICY or m.subject_domain_policy == ANY_POLICY:
- return False, set(), ["Policy mapping cannot map to or from anyPolicy"]
-
- mapped_any = False
- for node in nodes_by_depth.get(i, []):
- if node.valid_policy == m.issuer_domain_policy:
- node.expected_policy_set = {m.subject_domain_policy}
- mapped_any = True
-
- if not mapped_any:
- any_nodes = [node for node in nodes_by_depth.get(i, []) if node.valid_policy == ANY_POLICY]
- for any_node in any_nodes:
- new_node = PolicyNode(
- valid_policy=m.issuer_domain_policy,
- qualifier_set=set(any_node.qualifier_set),
+ parent.children.append(child)
+ current_depth_nodes.append(child)
+
+ nodes_by_depth.append(current_depth_nodes)
+
+ # Step 2: Policy Mappings (intermediate CAs only)
+ if not is_leaf and cert.policy_mappings and cert.policy_mappings.mappings:
+ for m in cert.policy_mappings.mappings:
+ if m.issuer_domain_policy == ANY_POLICY or m.subject_domain_policy == ANY_POLICY:
+ errors.append("Policy mapping cannot map to or from anyPolicy")
+ return False, set(), errors
+
+ if inhibit_policy_mapping > 0:
+ for m in cert.policy_mappings.mappings:
+ mapped_any = False
+ for node in current_depth_nodes:
+ if node.valid_policy == m.issuer_domain_policy:
+ node.valid_policy = m.subject_domain_policy
+ node.expected_policy_set = {m.subject_domain_policy}
+ mapped_any = True
+ if not mapped_any:
+ for parent in prev_nodes:
+ if parent.valid_policy == ANY_POLICY or m.issuer_domain_policy in parent.expected_policy_set:
+ child = PolicyNode(
+ valid_policy=m.subject_domain_policy,
expected_policy_set={m.subject_domain_policy},
- parent=any_node.parent,
- children=[],
+ original_initial_policy=parent.original_initial_policy or m.issuer_domain_policy,
+ parent=parent,
)
- if any_node.parent:
- any_node.parent.children.append(new_node)
- nodes_by_depth[i].append(new_node)
-
+ parent.children.append(child)
+ current_depth_nodes.append(child)
+ else:
+ if cert.policy_mappings.critical:
+ errors.append("Critical policy mapping present while inhibit_policy_mapping is 0")
+ return False, set(), errors
+
+ # Step 3: Update state variables (intermediate CAs only)
+ if not is_leaf:
if cert.policy_constraints:
if cert.policy_constraints.require_explicit_policy is not None:
explicit_policy = min(explicit_policy, cert.policy_constraints.require_explicit_policy)
@@ -187,42 +169,44 @@ class PolicyTreeProcessor:
if cert.inhibit_any_policy:
inhibit_any_policy = min(inhibit_any_policy, cert.inhibit_any_policy.skip_certs)
- if not cert.is_self_issued:
- if explicit_policy > 0:
- explicit_policy -= 1
- if inhibit_policy_mapping > 0:
- inhibit_policy_mapping -= 1
- if inhibit_any_policy > 0:
- inhibit_any_policy -= 1
+ if explicit_policy > 0 and not cert.is_self_issued:
+ explicit_policy -= 1
+ if inhibit_policy_mapping > 0 and not cert.is_self_issued:
+ inhibit_policy_mapping -= 1
+ if inhibit_any_policy > 0 and not cert.is_self_issued:
+ inhibit_any_policy -= 1
- leaf_cert = chain[-1]
- if leaf_cert.policy_constraints:
- if leaf_cert.policy_constraints.require_explicit_policy is not None and leaf_cert.policy_constraints.require_explicit_policy == 0:
- explicit_policy = 0
+ # Check if valid policy tree has become empty
+ if not current_depth_nodes and explicit_policy <= 0:
+ errors.append(f"Valid policy tree is empty at depth {i}")
+ return False, set(), errors
- leaf_nodes = nodes_by_depth.get(n - 1, [])
+ # Wrap up at leaf
+ leaf_nodes = nodes_by_depth[-1]
if not leaf_nodes:
- if explicit_policy == 0 or self.config.initial_explicit_policy:
- return False, set(), ["No valid certificate policy tree for explicit policy requirement"]
+ if explicit_policy <= 0:
+ errors.append("No valid policy tree path exists to the leaf certificate")
+ return False, set(), errors
return True, set(), []
- valid_policies: Set[str] = set()
- for node in leaf_nodes:
- if node.valid_policy == ANY_POLICY:
- valid_policies.update(self.config.initial_policy_set)
+ # Form constrained policies in terms of relying party / root domain and leaf domain
+ constrained_policies: Set[str] = set()
+ for n in leaf_nodes:
+ if ANY_POLICY in self.config.initial_policy_set:
+ constrained_policies.add(n.valid_policy)
+ if n.original_initial_policy:
+ constrained_policies.add(n.original_initial_policy)
else:
- curr = node
- while curr.parent and curr.parent.parent is not None:
- curr = curr.parent
- ancestor_depth_1 = curr
- if ancestor_depth_1.valid_policy != ANY_POLICY:
- valid_policies.add(ancestor_depth_1.valid_policy)
- valid_policies.add(node.valid_policy)
-
- if explicit_policy == 0 or self.config.initial_explicit_policy:
- if ANY_POLICY not in self.config.initial_policy_set:
- intersection = valid_policies.intersection(self.config.initial_policy_set)
- if not intersection:
- return False, set(), [f"No valid policy in intersection with initial policy set: {valid_policies}"]
-
- return True, valid_policies, []
+ if n.valid_policy in self.config.initial_policy_set:
+ constrained_policies.add(n.valid_policy)
+ if n.original_initial_policy and n.original_initial_policy in self.config.initial_policy_set:
+ constrained_policies.add(n.original_initial_policy)
+ constrained_policies.add(n.valid_policy)
+ if n.valid_policy == ANY_POLICY:
+ constrained_policies.update(self.config.initial_policy_set)
+
+ if not constrained_policies and explicit_policy <= 0:
+ errors.append(f"No valid policies in intersection with initial policy set: {self.config.initial_policy_set}")
+ return False, set(), errors
+
+ return True, constrained_policies, []
diff --git a/src/revocation/crl_manager.py b/src/revocation/crl_manager.py
index 2720433..d9baf06 100644
--- a/src/revocation/crl_manager.py
+++ b/src/revocation/crl_manager.py
@@ -22,81 +22,118 @@ class CRLValidationStatus:
revocation_date: Optional[str] = None
crl_number: Optional[int] = None
uncovered_reasons: Set[CRLReason] = field(default_factory=set)
+ error_message: Optional[str] = None
class CRLCache:
- """Maintains Base and Delta CRLs with partition reason support."""
+ """Maintains Base and Delta CRLs with partition reason support and monotonic sequence ordering."""
def __init__(self) -> None:
- # Key: (issuer_dn, authority_key_id, frozenset(covered_reasons)) -> list of CertificateRevocationList
- self._crls: Dict[Tuple[str, str, frozenset[CRLReason]], List[CertificateRevocationList]] = {}
+ # Key: (issuer_dn, authority_key_id) -> list of CertificateRevocationList
+ self._crls: Dict[Tuple[str, str], List[CertificateRevocationList]] = {}
+ # Indirect CRLs: list of CertificateRevocationList
+ self._indirect_crls: List[CertificateRevocationList] = []
# Active revocations: (issuer_dn, authority_key_id, serial) -> RevokedCertificateEntry
self._active_revocations: Dict[Tuple[str, str, str], RevokedCertificateEntry] = {}
- # Tracks latest observed CRL number: (issuer_dn, authority_key_id, frozenset(covered_reasons)) -> max_crl_number
- self._latest_crl_numbers: Dict[Tuple[str, str, frozenset[CRLReason]], int] = {}
- # Tracks max CRL number per issuer: (issuer_dn, authority_key_id) -> max_crl_number
- self._issuer_crl_numbers: Dict[Tuple[str, str], int] = {}
+ # Tracks latest observed CRL number for monotonic ordering: (issuer_dn, authority_key_id) -> max_crl_number
+ self._latest_crl_numbers: Dict[Tuple[str, str], int] = {}
+ # Tracks latest base CRL number per issuer: (issuer_dn, authority_key_id) -> max_base_crl_number
+ self._latest_base_crl_numbers: Dict[Tuple[str, str], int] = {}
def register_crl(self, crl: CertificateRevocationList) -> bool:
- """Registers a Base or Delta CRL into the cache."""
+ """Registers a Base or Delta CRL into the cache. Enforces monotonic sequence numbers and RFC 5280 constraints."""
akid = crl.authority_key_id or ""
- reasons_key = frozenset(crl.covered_reasons)
- scope_key = (crl.issuer_dn, akid, reasons_key)
-
- # Monotonic CRL sequence check
- if scope_key in self._latest_crl_numbers:
- if crl.crl_number <= self._latest_crl_numbers[scope_key]:
- return False # Reject stale replay or non-monotonic number
-
- self._latest_crl_numbers[scope_key] = crl.crl_number
- issuer_key = (crl.issuer_dn, akid)
- self._issuer_crl_numbers[issuer_key] = max(
- crl.crl_number, self._issuer_crl_numbers.get(issuer_key, 0)
- )
-
- if scope_key not in self._crls:
- self._crls[scope_key] = []
- self._crls[scope_key].append(crl)
-
- # Process revoked entries
- for entry in crl.revoked_entries:
- rev_key = (crl.issuer_dn, akid, entry.serial_number)
- if crl.is_delta and entry.reason == CRLReason.REMOVE_FROM_CRL:
- # Un-revoke if placed on hold
- if rev_key in self._active_revocations:
- del self._active_revocations[rev_key]
- for k in list(self._active_revocations.keys()):
- if k[0] == crl.issuer_dn and k[2] == entry.serial_number:
- del self._active_revocations[k]
+ key = (crl.issuer_dn, akid)
+
+ # RFC 5280 Section 5.2.4: Delta CRL validation
+ if crl.is_delta:
+ if crl.base_crl_number is None:
+ return False
+ # Base CRL with crl_number >= base_crl_number must exist
+ max_base = self._latest_base_crl_numbers.get(key)
+ if max_base is None or max_base < crl.base_crl_number:
+ return False
+ if crl.crl_number <= crl.base_crl_number:
+ return False
+
+ # Monotonic CRL number replay protection per (issuer_dn, AKID)
+ if key in self._latest_crl_numbers and crl.crl_number <= self._latest_crl_numbers[key]:
+ return False
+
+ self._latest_crl_numbers[key] = crl.crl_number
+ if not crl.is_delta:
+ self._latest_base_crl_numbers[key] = max(self._latest_base_crl_numbers.get(key, 0), crl.crl_number)
+
+ if crl.is_indirect:
+ self._indirect_crls.append(crl)
+
+ if key not in self._crls:
+ self._crls[key] = []
+
+ if not crl.is_delta:
+ if crl.covered_reasons is None or crl.covered_reasons == ALL_REASONS:
+ self._crls[key] = [crl]
else:
- self._active_revocations[rev_key] = entry
-
- return True
+ replaced = False
+ for idx, existing in enumerate(self._crls[key]):
+ if existing.covered_reasons and (existing.covered_reasons & crl.covered_reasons):
+ self._crls[key][idx] = crl
+ replaced = True
+ break
+ if not replaced:
+ if len(self._crls[key]) >= 2:
+ self._crls[key].pop(0)
+ self._crls[key].append(crl)
+ else:
+ self._crls[key].append(crl)
+
+ if not crl.is_delta:
+ # Clear previous active revocations for this issuer/AKID that match covered reasons
+ keys_to_remove = [
+ k for k in self._active_revocations
+ if k[0] == crl.issuer_dn and k[1] == akid
+ and self._active_revocations[k].reason in crl.covered_reasons
+ ]
+ for k in keys_to_remove:
+ del self._active_revocations[k]
+
+ for entry in crl.revoked_entries:
+ if entry.reason != CRLReason.REMOVE_FROM_CRL:
+ iss_dn = entry.certificate_issuer if (crl.is_indirect and entry.certificate_issuer) else crl.issuer_dn
+ self._active_revocations[(iss_dn, akid, entry.serial_number)] = entry
+ return True
+ else:
+ # Delta CRL updates
+ for entry in crl.revoked_entries:
+ iss_dn = entry.certificate_issuer if (crl.is_indirect and entry.certificate_issuer) else crl.issuer_dn
+ rev_key = (iss_dn, akid, entry.serial_number)
+ if entry.reason == CRLReason.REMOVE_FROM_CRL:
+ self._active_revocations.pop(rev_key, None)
+ self._active_revocations.pop((iss_dn, "", entry.serial_number), None)
+ else:
+ self._active_revocations[rev_key] = entry
+ return True
def check_revocation(
- self, cert: Certificate, required_reasons: Optional[Set[CRLReason]] = None
+ self,
+ cert: Certificate,
+ required_reasons: Optional[Set[CRLReason]] = None,
+ current_time: Optional[str] = None,
) -> CRLValidationStatus:
- """Checks if a certificate is revoked and verifies complete reason code coverage across CRL partitions."""
+ """Checks if a certificate is revoked and verifies complete reason code coverage across valid CRL partitions."""
+ if required_reasons is None:
+ required_reasons = set(ALL_REASONS)
+
akid = cert.authority_key_id or ""
key = (cert.issuer_dn, akid)
- # Check active revocations
+ # 1. Check direct active revocations
rev_key = (cert.issuer_dn, akid, cert.serial_number)
if rev_key in self._active_revocations:
entry = self._active_revocations[rev_key]
- latest_num = self._issuer_crl_numbers.get(key, 0)
- return CRLValidationStatus(
- is_revoked=True,
- is_fully_covered=True,
- reason=entry.reason,
- revocation_date=entry.revocation_date,
- crl_number=latest_num,
- )
-
- # Fallback check by issuer_dn and serial
- for (iss_dn, auth_id, ser), entry in self._active_revocations.items():
- if iss_dn == cert.issuer_dn and ser == cert.serial_number:
- latest_num = self._issuer_crl_numbers.get((iss_dn, auth_id), 0)
+ # Check future scheduled revocation date
+ if current_time is None or entry.revocation_date <= current_time:
+ latest_num = self._latest_crl_numbers.get(key, 0)
return CRLValidationStatus(
is_revoked=True,
is_fully_covered=True,
@@ -105,42 +142,79 @@ class CRLCache:
crl_number=latest_num,
)
- # Find matching registered CRLs for this issuer
- matching_crl_lists = [
- crl_list for (iss, auth, _), crl_list in self._crls.items()
- if iss == cert.issuer_dn and (not akid or not auth or auth == akid)
- ]
-
- if not matching_crl_lists:
+ # Search by issuer DN without AKID
+ for (iss_dn, entry_akid, sn), entry in self._active_revocations.items():
+ if iss_dn == cert.issuer_dn and sn == cert.serial_number:
+ if not akid or not entry_akid or akid == entry_akid:
+ if current_time is None or entry.revocation_date <= current_time:
+ latest_num = self._latest_crl_numbers.get((iss_dn, entry_akid), 0)
+ return CRLValidationStatus(
+ is_revoked=True,
+ is_fully_covered=True,
+ reason=entry.reason,
+ revocation_date=entry.revocation_date,
+ crl_number=latest_num,
+ )
+
+ # 2. Check Indirect CRLs
+ for ind_crl in self._indirect_crls:
+ if current_time:
+ if ind_crl.next_update and current_time > ind_crl.next_update:
+ continue
+ if ind_crl.this_update and current_time < ind_crl.this_update:
+ continue
+ for entry in ind_crl.revoked_entries:
+ if entry.serial_number == cert.serial_number:
+ entry_issuer = entry.certificate_issuer or ind_crl.issuer_dn
+ if entry_issuer == cert.issuer_dn:
+ if current_time is None or entry.revocation_date <= current_time:
+ return CRLValidationStatus(
+ is_revoked=True,
+ is_fully_covered=True,
+ reason=entry.reason,
+ revocation_date=entry.revocation_date,
+ crl_number=ind_crl.crl_number,
+ )
+
+ # 3. Check reason code coverage across active and unexpired CRL partitions for this issuing CA
+ registered_crl_list = list(self._crls.get(key, []))
+ if not registered_crl_list and not akid:
+ for (iss_dn, _), crls in self._crls.items():
+ if iss_dn == cert.issuer_dn:
+ registered_crl_list.extend(crls)
+
+ if not registered_crl_list:
return CRLValidationStatus(is_revoked=False, is_fully_covered=True)
- covered_union: Set[CRLReason] = set()
- for crl_list in matching_crl_lists:
- for crl in crl_list:
- covered_union.update(crl.covered_reasons)
-
- target_reasons = required_reasons if required_reasons is not None else ALL_REASONS
- uncovered = target_reasons - covered_union
-
+ # Only use latest CRL per partition and check freshness against current_time
+ total_covered: Set[CRLReason] = set()
+ for crl in registered_crl_list:
+ if current_time:
+ if crl.next_update and current_time > crl.next_update:
+ # CRL is expired -> skip coverage contribution
+ continue
+ if crl.this_update and current_time < crl.this_update:
+ # CRL is from future -> skip
+ continue
+ total_covered.update(crl.covered_reasons)
+
+ uncovered = required_reasons - total_covered
if uncovered:
return CRLValidationStatus(
is_revoked=False,
is_fully_covered=False,
uncovered_reasons=uncovered,
+ error_message=f"Incomplete CRL reason coverage for {cert.issuer_dn}: missing {uncovered}",
)
- latest_num = self._issuer_crl_numbers.get(key, 0)
- return CRLValidationStatus(
- is_revoked=False,
- is_fully_covered=True,
- crl_number=latest_num,
- )
+ return CRLValidationStatus(is_revoked=False, is_fully_covered=True)
def get_latest_crl_number(self, issuer_dn: str, akid: str) -> Optional[int]:
- return self._issuer_crl_numbers.get((issuer_dn, akid))
+ return self._latest_crl_numbers.get((issuer_dn, akid))
def clear(self) -> None:
self._crls.clear()
+ self._indirect_crls.clear()
self._active_revocations.clear()
self._latest_crl_numbers.clear()
- self._issuer_crl_numbers.clear()
+ self._latest_base_crl_numbers.clear()
diff --git a/src/store/trust_store.py b/src/store/trust_store.py
index c5bf0da..87e62c2 100644
--- a/src/store/trust_store.py
+++ b/src/store/trust_store.py
@@ -61,6 +61,9 @@ class TrustStore:
def fetch_aia_certificate(self, uri: str) -> Optional[Certificate]:
return self._remote_aia_certs.get(uri)
+ def fetch_remote_aia_certificate(self, uri: str) -> Optional[Certificate]:
+ return self.fetch_aia_certificate(uri)
+
def register_crl(self, crl: CertificateRevocationList) -> bool:
"""Registers a Base or Delta CRL."""
accepted = self._crl_cache.register_crl(crl)
diff --git a/src/validation/engine.py b/src/validation/engine.py
index 55cc6e8..c17e7ce 100644
--- a/src/validation/engine.py
+++ b/src/validation/engine.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Dict, List, Optional, Set, Tuple
-from src.constraints.matcher import EffectiveConstraints, validate_san_constraints
+from src.constraints.matcher import EffectiveConstraints, validate_name_constraints
from src.crypto.signer import verify_certificate_signature
from src.models import (
ALL_REASONS,
@@ -23,34 +23,23 @@ class PathValidationEngine:
def __init__(self, trust_store: TrustStore) -> None:
self.trust_store = trust_store
self.path_builder = PathBuilder(trust_store)
- # Cache key: summary string -> ValidationResult
+ # Cache key: (leaf_fingerprint, epoch, config_hash) -> ValidationResult
self._cache: Dict[str, ValidationResult] = {}
def clear_cache(self) -> None:
self._cache.clear()
- def _get_cache_key(self, leaf: Certificate, config: ValidationConfig) -> str:
- return (
- f"epoch={self.trust_store.epoch}:"
- f"leaf={leaf.fingerprint}:"
- f"rev={config.check_revocation}:"
- f"nc={config.enforce_name_constraints}:"
- f"pl={config.enforce_path_len}:"
- f"pt={config.enforce_policy_tree}:"
- f"pols={sorted(config.initial_policy_set)}:"
- f"exp={config.initial_explicit_policy}:"
- f"map_inh={config.initial_policy_mapping_inhibit}:"
- f"any_inh={config.initial_any_policy_inhibit}:"
- f"time={config.current_time}:"
- f"crit={sorted(config.allowed_custom_critical_oids)}"
- )
-
def validate(self, leaf: Certificate, config: Optional[ValidationConfig] = None) -> ValidationResult:
"""Validates a target leaf certificate against installed trust anchors and policies."""
if config is None:
config = ValidationConfig()
- cache_key = self._get_cache_key(leaf, config)
+ cache_key = (
+ f"{self.trust_store.epoch}:{leaf.fingerprint}:{config.check_revocation}:"
+ f"{config.enforce_name_constraints}:{config.enforce_path_len}:{config.enforce_policy_tree}:"
+ f"{config.initial_explicit_policy}:{sorted(config.initial_policy_set)}:{config.current_time}:"
+ f"{sorted(config.allowed_custom_critical_oids)}"
+ )
if cache_key in self._cache:
return self._cache[cache_key]
@@ -65,8 +54,8 @@ class PathValidationEngine:
self._cache[cache_key] = res
return res
- # 2. Backtracking: try candidate paths until a valid one is found
- last_errors: List[str] = []
+ # 2. Explore all candidate paths, backtracking if one fails
+ all_candidate_errors: List[str] = []
for candidate in candidate_paths:
path_valid, policies, errors = self._validate_single_path(candidate, config)
if path_valid:
@@ -78,13 +67,14 @@ class PathValidationEngine:
)
self._cache[cache_key] = res
return res
- last_errors = errors
+ all_candidate_errors.extend(errors)
res = ValidationResult(
is_valid=False,
- error_message=f"Path validation failed: {'; '.join(last_errors)}",
- errors=last_errors,
+ error_message=f"Path validation failed: {'; '.join(all_candidate_errors)}",
+ errors=all_candidate_errors,
)
+
self._cache[cache_key] = res
return res
@@ -95,12 +85,16 @@ class PathValidationEngine:
certs = candidate.certificates
errors: List[str] = []
- # 1. Root must be a trust anchor
+ # 1. Root must be a trust anchor and must be a CA
root = certs[-1]
if not self.trust_store.is_trust_anchor(root):
errors.append(f"Root certificate {root.subject_dn} is not a trusted anchor")
return False, set(), errors
+ if not root.basic_constraints.is_ca:
+ errors.append(f"Root trust anchor {root.subject_dn} has is_ca=False")
+ return False, set(), errors
+
# 2. Structural & CA constraint checks for intermediates
for i in range(1, len(certs)):
ca_cert = certs[i]
@@ -109,21 +103,12 @@ class PathValidationEngine:
if not ca_cert.key_usage.key_cert_sign:
errors.append(f"Intermediate certificate {ca_cert.subject_dn} lacks key_cert_sign usage")
- # 3. Unrecognized critical extensions
- for cert in certs:
- for oid in cert.unrecognized_critical_extensions:
- if oid not in config.allowed_custom_critical_oids:
- errors.append(
- f"Certificate {cert.subject_dn} contains unrecognized critical extension: {oid}"
- )
-
- # 4. Path length constraints
+ # 3. Path length constraints (self-issued intermediate certs do not count)
if config.enforce_path_len:
for i in range(1, len(certs)):
ca_cert = certs[i]
path_len_limit = ca_cert.basic_constraints.path_len_constraint
if path_len_limit is not None:
- # Number of non-self-issued intermediate certificates between this CA and the leaf
intermediates_below = [c for c in certs[1:i] if not c.is_self_issued]
if len(intermediates_below) > path_len_limit:
errors.append(
@@ -131,7 +116,7 @@ class PathValidationEngine:
f"limit={path_len_limit}, observed={len(intermediates_below)}"
)
- # 5. Validity period checking
+ # 4. Validity period checking
if config.current_time:
for cert in certs:
if config.current_time < cert.not_before:
@@ -139,6 +124,18 @@ class PathValidationEngine:
if config.current_time > cert.not_after:
errors.append(f"Certificate {cert.subject_dn} is expired at {config.current_time}")
+ # 5. Critical extension checking
+ for cert in certs:
+ if cert.unrecognized_critical_extensions:
+ unhandled = [
+ oid for oid in cert.unrecognized_critical_extensions
+ if oid not in config.allowed_custom_critical_oids
+ ]
+ if unhandled:
+ errors.append(
+ f"Certificate {cert.subject_dn} contains unrecognized critical extension(s): {unhandled}"
+ )
+
# 6. Cryptographic signature chain verification
for i in range(len(certs) - 1):
child = certs[i]
@@ -150,7 +147,9 @@ class PathValidationEngine:
if config.check_revocation:
for i in range(len(certs) - 1):
child = certs[i]
- rev_status = self.trust_store.crl_cache.check_revocation(child, ALL_REASONS)
+ rev_status = self.trust_store.crl_cache.check_revocation(
+ child, ALL_REASONS, current_time=config.current_time
+ )
if rev_status.is_revoked:
errors.append(
f"Certificate {child.subject_dn} (serial {child.serial_number}) is revoked: "
@@ -165,16 +164,16 @@ class PathValidationEngine:
# 8. Transitive Name constraints evaluation
if config.enforce_name_constraints:
eff = EffectiveConstraints()
- if certs[-1].name_constraints:
- eff = eff.merge_parent(certs[-1].name_constraints)
- for idx in range(len(certs) - 2, -1, -1):
- curr_cert = certs[idx]
- if not eff.is_empty() and not curr_cert.san.is_empty():
- valid_nc, nc_errs = validate_san_constraints(curr_cert.san, eff)
+ for i in range(len(certs) - 1, -1, -1):
+ cert = certs[i]
+ if not eff.is_empty():
+ valid_nc, nc_errs = validate_name_constraints(
+ cert.san, cert.subject_dn, eff, is_ca=cert.basic_constraints.is_ca
+ )
if not valid_nc:
errors.extend(nc_errs)
- if curr_cert.name_constraints:
- eff = eff.merge_parent(curr_cert.name_constraints)
+ if cert.name_constraints:
+ eff = eff.merge_parent(cert.name_constraints)
# 9. Certificate Policy Tree Processing
valid_policies: Set[str] = set()
|