Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/PathValidator.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\X509\CertificationPath\PathValidation;
6
7 use function count;
8 use function in_array;
9 use LogicException;
10 use RuntimeException;
11 use SpomkyLabs\Pki\CryptoBridge\Crypto;
12 use SpomkyLabs\Pki\X509\Certificate\Certificate;
13 use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
14 use SpomkyLabs\Pki\X509\Certificate\TBSCertificate;
15 use SpomkyLabs\Pki\X509\CertificationPath\Exception\PathValidationException;
16
17 /**
18 * Implements certification path validation.
19 *
20 * @see https://tools.ietf.org/html/rfc5280#section-6
21 */
22 final class PathValidator
23 {
24 /**
25 * Certification path.
26 *
27 * @var Certificate[]
28 */
29 private readonly array $certificates;
30
31 /**
32 * Certification path trust anchor.
33 */
34 private ?Certificate $trustAnchor = null;
35
36 /**
37 * @param Crypto $crypto Crypto engine
38 * @param PathValidationConfig $config Validation config
39 * @param Certificate ...$certificates Certificates from the trust anchor to
40 * the end-entity certificate
41 */
42 private function __construct(
43 private readonly Crypto $crypto,
44 private readonly PathValidationConfig $config,
45 Certificate ...$certificates
46 ) {
47 if (count($certificates) === 0) {
48 throw new LogicException('No certificates.');
49 }
50 $this->certificates = $certificates;
51 // if trust anchor is explicitly given in configuration
52 if ($config->hasTrustAnchor()) {
53 $this->trustAnchor = $config->trustAnchor();
54 } else {
55 $this->trustAnchor = $certificates[0];
56 }
57 }
58
59 public static function create(
60 Crypto $crypto,
61 PathValidationConfig $config,
62 Certificate ...$certificates
63 ): self {
64 return new self($crypto, $config, ...$certificates);
65 }
66
67 /**
68 * Validate certification path.
69 */
70 public function validate(): PathValidationResult
71 {
72 $n = count($this->certificates);
73 $state = ValidatorState::initialize($this->config, $this->trustAnchor, $n);
74 foreach ($this->certificates as $i => $iValue) {
75 $state = $state->withIndex($i + 1);
76 $cert = $iValue;
77 // process certificate (section 6.1.3.)
78 $state = $this->processCertificate($state, $cert);
79 if (! $state->isFinal()) {
80 // prepare next certificate (section 6.1.4.)
81 $state = $this->prepareNext($state, $cert);
82 }
83 }
84 if (! isset($cert)) {
85 throw new LogicException('No certificates.');
86 }
87 // wrap-up (section 6.1.5.)
88 $state = $this->wrapUp($state, $cert);
89 // return outputs
90 return $state->getResult($this->certificates);
91 }
92
93 /**
94 * Apply basic certificate processing according to RFC 5280 section 6.1.3.
95 *
96 * @see https://tools.ietf.org/html/rfc5280#section-6.1.3
97 */
98 private function processCertificate(ValidatorState $state, Certificate $cert): ValidatorState
99 {
100 // (a.1) verify signature
101 $this->verifySignature($state, $cert);
102 // (a.2) check validity period
103 $this->checkValidity($cert);
104 // (a.3) check that certificate is not revoked
105 $this->checkRevocation();
106 // (a.4) check issuer
107 $this->checkIssuer($state, $cert);
108 // (b)(c) if certificate is self-issued and it is not
109 // the final certificate in the path, skip this step
110 if (! ($cert->isSelfIssued() && ! $state->isFinal())) {
111 // (b) check permitted subtrees
112 $this->checkPermittedSubtrees($state);
113 // (c) check excluded subtrees
114 $this->checkExcludedSubtrees($state);
115 }
116 $extensions = $cert->tbsCertificate()
117 ->extensions();
118 if ($extensions->hasCertificatePolicies()) {
119 // (d) process policy information
120 if ($state->hasValidPolicyTree()) {
121 $state = $state->validPolicyTree()
122 ->processPolicies($state, $cert);
123 }
124 } else {
125 // (e) certificate policies extension not present,
126 // set the valid_policy_tree to NULL
127 $state = $state->withoutValidPolicyTree();
128 }
129 // (f) check that explicit_policy > 0 or valid_policy_tree is set
130 if (! ($state->explicitPolicy() > 0 || $state->hasValidPolicyTree())) {
131 throw new PathValidationException('No valid policies.');
132 }
133 return $state;
134 }
135
136 /**
137 * Apply preparation for the certificate i+1 according to rfc5280 section 6.1.4.
138 *
139 * @see https://tools.ietf.org/html/rfc5280#section-6.1.4
140 */
141 private function prepareNext(ValidatorState $state, Certificate $cert): ValidatorState
142 {
143 // (a)(b) if policy mappings extension is present
144 $state = $this->preparePolicyMappings($state, $cert);
145 // (c) assign working_issuer_name
146 $state = $state->withWorkingIssuerName($cert->tbsCertificate()->subject());
147 // (d)(e)(f)
148 $state = $this->setPublicKeyState($state, $cert);
149 // (g) if name constraints extension is present
150 $state = $this->prepareNameConstraints($state, $cert);
151 // (h) if certificate is not self-issued
152 if (! $cert->isSelfIssued()) {
153 $state = $this->prepareNonSelfIssued($state);
154 }
155 // (i) if policy constraints extension is present
156 $state = $this->preparePolicyConstraints($state, $cert);
157 // (j) if inhibit any policy extension is present
158 $state = $this->prepareInhibitAnyPolicy($state, $cert);
159 // (k) check basic constraints
160 $this->processBasicContraints($cert);
161 // (l) verify max_path_length
162 $state = $this->verifyMaxPathLength($state, $cert);
163 // (m) check pathLenContraint
164 $state = $this->processPathLengthContraint($state, $cert);
165 // (n) check key usage
166 $this->checkKeyUsage($cert);
167 // (o) process relevant extensions
168 return $this->processExtensions($state);
169 }
170
171 /**
172 * Apply wrap-up procedure according to RFC 5280 section 6.1.5.
173 *
174 * @see https://tools.ietf.org/html/rfc5280#section-6.1.5
175 */
176 private function wrapUp(ValidatorState $state, Certificate $cert): ValidatorState
177 {
178 $tbs_cert = $cert->tbsCertificate();
179 $extensions = $tbs_cert->extensions();
180 // (a)
181 if ($state->explicitPolicy() > 0) {
182 $state = $state->withExplicitPolicy($state->explicitPolicy() - 1);
183 }
184 // (b)
185 if ($extensions->hasPolicyConstraints()) {
186 $ext = $extensions->policyConstraints();
187 if ($ext->hasRequireExplicitPolicy() &&
188 $ext->requireExplicitPolicy() === 0) {
189 $state = $state->withExplicitPolicy(0);
190 }
191 }
192 // (c)(d)(e)
193 $state = $this->setPublicKeyState($state, $cert);
194 // (f) process relevant extensions
195 $state = $this->processExtensions($state);
196 // (g) intersection of valid_policy_tree and the initial-policy-set
197 $state = $this->calculatePolicyIntersection($state);
198 // check that explicit_policy > 0 or valid_policy_tree is set
199 if (! ($state->explicitPolicy() > 0 || $state->hasValidPolicyTree())) {
200 throw new PathValidationException('No valid policies.');
201 }
202 // path validation succeeded
203 return $state;
204 }
205
206 /**
207 * Update working_public_key, working_public_key_parameters and working_public_key_algorithm state variables from
208 * certificate.
209 */
210 private function setPublicKeyState(ValidatorState $state, Certificate $cert): ValidatorState
211 {
212 $pk_info = $cert->tbsCertificate()
213 ->subjectPublicKeyInfo();
214 // assign working_public_key
215 $state = $state->withWorkingPublicKey($pk_info);
216 // assign working_public_key_parameters
217 $params = ValidatorState::getAlgorithmParameters($pk_info->algorithmIdentifier());
218 if ($params !== null) {
219 $state = $state->withWorkingPublicKeyParameters($params);
220 } else {
221 // if algorithms differ, set parameters to null
222 if ($pk_info->algorithmIdentifier()->oid() !==
223 $state->workingPublicKeyAlgorithm()
224 ->oid()) {
225 $state = $state->withWorkingPublicKeyParameters();
226 }
227 }
228 // assign working_public_key_algorithm
229 return $state->withWorkingPublicKeyAlgorithm($pk_info->algorithmIdentifier());
230 }
231
232 /**
233 * Verify certificate signature.
234 */
235 private function verifySignature(ValidatorState $state, Certificate $cert): void
236 {
237 try {
238 $valid = $cert->verify($state->workingPublicKey(), $this->crypto);
239 } catch (RuntimeException $e) {
240 throw new PathValidationException('Failed to verify signature: ' . $e->getMessage(), 0, $e);
241 }
242 if (! $valid) {
243 throw new PathValidationException("Certificate signature doesn't match.");
244 }
245 }
246
247 /**
248 * Check certificate validity.
249 */
250 private function checkValidity(Certificate $cert): void
251 {
252 $refdt = $this->config->dateTime();
253 $validity = $cert->tbsCertificate()
254 ->validity();
255 if ($validity->notBefore()->dateTime()->diff($refdt)->invert !== 0) {
256 throw new PathValidationException('Certificate validity period has not started.');
257 }
258 if ($refdt->diff($validity->notAfter()->dateTime())->invert !== 0) {
259 throw new PathValidationException('Certificate has expired.');
260 }
261 }
262
263 /**
264 * Check certificate revocation.
265 */
266 private function checkRevocation(): void
267 {
268 // @todo Implement CRL handling
269 }
270
271 /**
272 * Check certificate issuer.
273 */
274 private function checkIssuer(ValidatorState $state, Certificate $cert): void
275 {
276 if (! $cert->tbsCertificate()->issuer()->equals($state->workingIssuerName())) {
277 throw new PathValidationException('Certification issuer mismatch.');
278 }
279 }
280
281 private function checkPermittedSubtrees(ValidatorState $state): void
282 {
283 // @todo Implement
284 $state->permittedSubtrees();
285 }
286
287 private function checkExcludedSubtrees(ValidatorState $state): void
288 {
289 // @todo Implement
290 $state->excludedSubtrees();
291 }
292
293 /**
294 * Apply policy mappings handling for the preparation step.
295 */
296 private function preparePolicyMappings(ValidatorState $state, Certificate $cert): ValidatorState
297 {
298 $extensions = $cert->tbsCertificate()
299 ->extensions();
300 if ($extensions->hasPolicyMappings()) {
301 // (a) verify that anyPolicy mapping is not used
302 if ($extensions->policyMappings()->hasAnyPolicyMapping()) {
303 throw new PathValidationException('anyPolicy mapping found.');
304 }
305 // (b) process policy mappings
306 if ($state->hasValidPolicyTree()) {
307 $state = $state->validPolicyTree()
308 ->processMappings($state, $cert);
309 }
310 }
311 return $state;
312 }
313
314 /**
315 * Apply name constraints handling for the preparation step.
316 */
317 private function prepareNameConstraints(ValidatorState $state, Certificate $cert): ValidatorState
318 {
319 $extensions = $cert->tbsCertificate()
320 ->extensions();
321 if ($extensions->hasNameConstraints()) {
322 $state = $this->processNameConstraints($state);
323 }
324 return $state;
325 }
326
327 /**
328 * Apply preparation for a non-self-signed certificate.
329 */
330 private function prepareNonSelfIssued(ValidatorState $state): ValidatorState
331 {
332 // (h.1)
333 if ($state->explicitPolicy() > 0) {
334 $state = $state->withExplicitPolicy($state->explicitPolicy() - 1);
335 }
336 // (h.2)
337 if ($state->policyMapping() > 0) {
338 $state = $state->withPolicyMapping($state->policyMapping() - 1);
339 }
340 // (h.3)
341 if ($state->inhibitAnyPolicy() > 0) {
342 $state = $state->withInhibitAnyPolicy($state->inhibitAnyPolicy() - 1);
343 }
344 return $state;
345 }
346
347 /**
348 * Apply policy constraints handling for the preparation step.
349 */
350 private function preparePolicyConstraints(ValidatorState $state, Certificate $cert): ValidatorState
351 {
352 $extensions = $cert->tbsCertificate()
353 ->extensions();
354 if (! $extensions->hasPolicyConstraints()) {
355 return $state;
356 }
357 $ext = $extensions->policyConstraints();
358 // (i.1)
359 if ($ext->hasRequireExplicitPolicy() &&
360 $ext->requireExplicitPolicy() < $state->explicitPolicy()) {
361 $state = $state->withExplicitPolicy($ext->requireExplicitPolicy());
362 }
363 // (i.2)
364 if ($ext->hasInhibitPolicyMapping() &&
365 $ext->inhibitPolicyMapping() < $state->policyMapping()) {
366 $state = $state->withPolicyMapping($ext->inhibitPolicyMapping());
367 }
368 return $state;
369 }
370
371 /**
372 * Apply inhibit any-policy handling for the preparation step.
373 */
374 private function prepareInhibitAnyPolicy(ValidatorState $state, Certificate $cert): ValidatorState
375 {
376 $extensions = $cert->tbsCertificate()
377 ->extensions();
378 if ($extensions->hasInhibitAnyPolicy()) {
379 $ext = $extensions->inhibitAnyPolicy();
380 if ($ext->skipCerts() < $state->inhibitAnyPolicy()) {
381 $state = $state->withInhibitAnyPolicy($ext->skipCerts());
382 }
383 }
384 return $state;
385 }
386
387 /**
388 * Verify maximum certification path length for the preparation step.
389 */
390 private function verifyMaxPathLength(ValidatorState $state, Certificate $cert): ValidatorState
391 {
392 if (! $cert->isSelfIssued()) {
393 if ($state->maxPathLength() <= 0) {
394 throw new PathValidationException('Certification path length exceeded.');
395 }
396 $state = $state->withMaxPathLength($state->maxPathLength() - 1);
397 }
398 return $state;
399 }
400
401 /**
402 * Check key usage extension for the preparation step.
403 */
404 private function checkKeyUsage(Certificate $cert): void
405 {
406 $extensions = $cert->tbsCertificate()
407 ->extensions();
408 if ($extensions->hasKeyUsage()) {
409 $ext = $extensions->keyUsage();
410 if (! $ext->isKeyCertSign()) {
411 throw new PathValidationException('keyCertSign usage not set.');
412 }
413 }
414 }
415
416 private function processNameConstraints(ValidatorState $state): ValidatorState
417 {
418 // @todo Implement
419 return $state;
420 }
421
422 /**
423 * Process basic constraints extension.
424 */
425 private function processBasicContraints(Certificate $cert): void
426 {
427 if ($cert->tbsCertificate()->version() === TBSCertificate::VERSION_3) {
428 $extensions = $cert->tbsCertificate()
429 ->extensions();
430 if (! $extensions->hasBasicConstraints()) {
431 throw new PathValidationException('v3 certificate must have basicConstraints extension.');
432 }
433 // verify that cA is set to TRUE
434 if (! $extensions->basicConstraints()->isCA()) {
435 throw new PathValidationException('Certificate is not a CA certificate.');
436 }
437 }
438 }
439
440 /**
441 * Process pathLenConstraint.
442 */
443 private function processPathLengthContraint(ValidatorState $state, Certificate $cert): ValidatorState
444 {
445 $extensions = $cert->tbsCertificate()
446 ->extensions();
447 if ($extensions->hasBasicConstraints()) {
448 $ext = $extensions->basicConstraints();
449 if ($ext->hasPathLen()) {
450 if ($ext->pathLen() < $state->maxPathLength()) {
451 $state = $state->withMaxPathLength($ext->pathLen());
452 }
453 }
454 }
455 return $state;
456 }
457
458 private function processExtensions(ValidatorState $state): ValidatorState
459 {
460 // @todo Implement
461 return $state;
462 }
463
464 private function calculatePolicyIntersection(ValidatorState $state): ValidatorState
465 {
466 // (i) If the valid_policy_tree is NULL, the intersection is NULL
467 if (! $state->hasValidPolicyTree()) {
468 return $state;
469 }
470 // (ii) If the valid_policy_tree is not NULL and
471 // the user-initial-policy-set is any-policy, the intersection
472 // is the entire valid_policy_tree
473 $initial_policies = $this->config->policySet();
474 if (in_array(PolicyInformation::OID_ANY_POLICY, $initial_policies, true)) {
475 return $state;
476 }
477 // (iii) If the valid_policy_tree is not NULL and the
478 // user-initial-policy-set is not any-policy, calculate
479 // the intersection of the valid_policy_tree and the
480 // user-initial-policy-set as follows
481 return $state->validPolicyTree()
482 ->calculateIntersection($state, $initial_policies);
483 }
484 }