Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,254 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath;
use ArrayIterator;
use function count;
use Countable;
use const E_USER_DEPRECATED;
use IteratorAggregate;
use LogicException;
use SpomkyLabs\Pki\CryptoBridge\Crypto;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\CertificateBundle;
use SpomkyLabs\Pki\X509\Certificate\CertificateChain;
use SpomkyLabs\Pki\X509\CertificationPath\Exception\PathValidationException;
use SpomkyLabs\Pki\X509\CertificationPath\PathBuilding\CertificationPathBuilder;
use SpomkyLabs\Pki\X509\CertificationPath\PathValidation\PathValidationConfig;
use SpomkyLabs\Pki\X509\CertificationPath\PathValidation\PathValidationResult;
use SpomkyLabs\Pki\X509\CertificationPath\PathValidation\PathValidator;
/**
* Implements certification path structure.
*
* Certification path is a list of certificates from the trust anchor to the end entity certificate, possibly spanning
* over multiple intermediate certificates.
*
* @see https://tools.ietf.org/html/rfc5280#section-3.2
*/
final class CertificationPath implements Countable, IteratorAggregate
{
/**
* Certification path.
*
* @var Certificate[]
*/
private readonly array $certificates;
/**
* Whether the path was assembled from a chain that a peer supplied.
*
* The first certificate of such a path is whatever the peer put there, so it must never serve as the trust
* anchor.
*/
private bool $fromPeerSuppliedChain = false;
/**
* Whether the path's first certificate came out of a trust list the application supplied.
*
* Such a head is a trust anchor the application chose, so validating against it is sound and needs no warning.
*/
private bool $anchoredInTrustList = false;
/**
* @param Certificate ...$certificates Certificates from the trust anchor
* to the target end-entity certificate
*/
private function __construct(Certificate ...$certificates)
{
$this->certificates = $certificates;
}
/**
* Initialize from certificates ordered from the trust anchor to the target end-entity certificate.
*
* When no trust anchor is set on the configuration, validate() falls back to the first certificate given here.
* Only pass certificates in an order you control: a path built out of what a peer sent, with its own root at the
* head, would then be validated against that root. Use fromCertificateChain() for peer-supplied material, or
* toTarget() to build the path from a bundle of trust anchors.
*/
public static function create(Certificate ...$certificates): self
{
return new self(...$certificates);
}
/**
* Initialize from certificates whose first one came out of a trust list the application supplied.
*
* @internal Used by CertificationPathBuilder, which only ever heads a path with a certificate taken from the
* trust list it was given.
*/
public static function fromTrustList(Certificate ...$certificates): self
{
$path = self::create(...$certificates);
$path->anchoredInTrustList = true;
return $path;
}
/**
* Initialize from a certificate chain.
*
* A chain comes from a peer, so its topmost certificate is attacker-controlled and cannot be trusted. The
* resulting path therefore refuses to validate unless the configuration carries an explicit trust anchor.
*/
public static function fromCertificateChain(CertificateChain $chain): self
{
$path = self::create(...array_reverse($chain->certificates(), false));
$path->fromPeerSuppliedChain = true;
return $path;
}
/**
* Build certification path to given target.
*
* @param Certificate $target Target end-entity certificate
* @param CertificateBundle $trust_anchors List of trust anchors
* @param null|CertificateBundle $intermediate Optional intermediate certificates
*/
public static function toTarget(
Certificate $target,
CertificateBundle $trust_anchors,
?CertificateBundle $intermediate = null
): self {
return CertificationPathBuilder::create($trust_anchors)->shortestPathToTarget($target, $intermediate);
}
/**
* Build certification path from given trust anchor to target certificate, using intermediate certificates from
* given bundle.
*
* @param Certificate $trust_anchor Trust anchor certificate
* @param Certificate $target Target end-entity certificate
* @param null|CertificateBundle $intermediate Optional intermediate certificates
*/
public static function fromTrustAnchorToTarget(
Certificate $trust_anchor,
Certificate $target,
?CertificateBundle $intermediate = null
): self {
return self::toTarget($target, CertificateBundle::create($trust_anchor), $intermediate);
}
/**
* Get certificates.
*
* @return Certificate[]
*/
public function certificates(): array
{
return $this->certificates;
}
/**
* Get the first certificate of the path.
*
* This is the certificate validate() falls back to when the configuration names no trust anchor. It is the path's
* head, not a certificate the library has established any trust in.
*/
public function trustAnchorCertificate(): Certificate
{
if (count($this->certificates) === 0) {
throw new LogicException('No certificates.');
}
return $this->certificates[0];
}
/**
* Get the end-entity certificate from the path.
*/
public function endEntityCertificate(): Certificate
{
if (count($this->certificates) === 0) {
throw new LogicException('No certificates.');
}
return $this->certificates[count($this->certificates) - 1];
}
/**
* Get certification path as a certificate chain.
*/
public function certificateChain(): CertificateChain
{
return CertificateChain::create(...array_reverse($this->certificates, false));
}
/**
* Check whether certification path starts with one ore more given certificates in parameter order.
*
* @param Certificate ...$certs Certificates
*/
public function startsWith(Certificate ...$certs): bool
{
$n = count($certs);
if ($n > count($this->certificates)) {
return false;
}
for ($i = 0; $i < $n; ++$i) {
if (! $certs[$i]->equals($this->certificates[$i])) {
return false;
}
}
return true;
}
/**
* Validate certification path.
*
* The trust anchor is an input to the validation process, not a part of the path: set it on the configuration
* with PathValidationConfig::withTrustAnchor(). When it is left unset, the first certificate of the path is used
* instead, which is only sound for a path whose head the application chose itself.
*
* A path built by fromCertificateChain() never qualifies, since a peer decided what its first certificate is, and
* validating it against its own root would verify nothing. Such a path requires an explicit trust anchor and
* throws without one.
*
* @param null|Crypto $crypto Crypto engine, use default if not set
*/
public function validate(PathValidationConfig $config, ?Crypto $crypto = null): PathValidationResult
{
if (! $config->hasTrustAnchor()) {
if ($this->fromPeerSuppliedChain) {
throw new PathValidationException(
'The path was built from a peer-supplied certificate chain, so its first certificate cannot '
. 'serve as the trust anchor. Set one with PathValidationConfig::withTrustAnchor(), or build '
. 'the path with CertificationPath::toTarget() from a bundle of trusted certificates.'
);
}
if (! $this->anchoredInTrustList) {
// The guard above is attached to the constructor that was used rather than to the invariant it
// protects, and create() is the constructor an integrator reaches for first. Nothing in the
// result tells a chain anchored in the caller's trust store from one anchored in the attacker's,
// so the fallback is announced here and will be removed in the next major release.
@trigger_error(
'Validating a certification path without an explicit trust anchor is deprecated and will '
. 'throw in the next major release. The first certificate of the path is being used as the '
. 'trust anchor. Name the anchor with PathValidationConfig::withTrustAnchor(), or build the '
. 'path with CertificationPath::toTarget() from a bundle of trusted certificates.',
E_USER_DEPRECATED
);
}
}
$crypto ??= Crypto::getDefault();
return PathValidator::create($crypto, $config, ...$this->certificates)->validate();
}
/**
* @see \Countable::count()
*/
public function count(): int
{
return count($this->certificates);
}
/**
* Get iterator for certificates.
*
* @see \IteratorAggregate::getIterator()
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->certificates);
}
}

View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\Exception;
use RuntimeException;
/**
* Exception thrown on certification path building errors.
*/
final class PathBuildingException extends RuntimeException
{
}

View file

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\Exception;
use SpomkyLabs\Pki\X509\Exception\X509ValidationException;
/**
* Exception thrown on certification path validation errors.
*/
final class PathValidationException extends X509ValidationException
{
}

View file

@ -0,0 +1,253 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\PathBuilding;
use function count;
use function hash;
use function spl_object_id;
use SpomkyLabs\Pki\X501\StringPrep\Exception\StringPreparationException;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\CertificateBundle;
use SpomkyLabs\Pki\X509\CertificationPath\CertificationPath;
use SpomkyLabs\Pki\X509\CertificationPath\Exception\PathBuildingException;
/**
* Class for resolving certification paths.
*
* @see https://tools.ietf.org/html/rfc4158
*/
final class CertificationPathBuilder
{
/**
* Maximum number of certificates a path may hold while being resolved.
*
* The limit bounds the depth of the exploration, on top of the loop detection.
*/
private const MAX_PATH_LENGTH = 10;
/**
* Maximum number of certification paths a single resolution step may produce.
*
* A bundle of mutually compatible certificates yields an exponential number of paths even when it holds no loop,
* so the number of paths must be bounded on its own.
*/
private const MAX_PATHS = 100;
/**
* Maximum number of certificates the resolution may examine before giving up.
*
* Counting the paths that come out bounds nothing when none do: a sub-call that returns no path leaves the count
* untouched, having already explored its whole subtree, and a bundle whose certificates chain to no trust anchor
* is exactly that shape. The work has to be counted where it is done.
*/
private const MAX_VISITED_NODES = 1000;
/**
* Number of certificates examined by the resolution in progress.
*/
private int $visitedNodes = 0;
/**
* Identity of each certificate seen by the resolution in progress, keyed by object id.
*
* @var array<int, string>
*/
private array $identities = [];
/**
* @param CertificateBundle $trustList List of trust anchors
*/
private function __construct(
private readonly CertificateBundle $trustList
) {
}
public static function create(CertificateBundle $trustList): self
{
return new self($trustList);
}
/**
* Get all certification paths to given target certificate from any trust anchor.
*
* @param Certificate $target Target certificate
* @param null|CertificateBundle $intermediate Optional intermediate certificates
*
* @return CertificationPath[]
*/
public function allPathsToTarget(Certificate $target, ?CertificateBundle $intermediate = null): array
{
$this->visitedNodes = 0;
$this->identities = [];
try {
$paths = $this->resolvePathsToTarget($target, $intermediate);
} catch (StringPreparationException $e) {
// matching an issuer name is a name comparison, and a name that cannot be prepared for comparison
// stops the resolution rather than being reported as not equal. Report it as a building failure like
// every other, instead of letting the comparison's own exception escape.
throw new PathBuildingException(
'A certificate name cannot be prepared for comparison: ' . $e->getMessage(),
0,
$e
);
}
// every path is headed by a certificate taken from the trust list this builder was given, so its head is
// a trust anchor the application chose
return array_map(static fn ($certs) => CertificationPath::fromTrustList(...$certs), $paths);
}
/**
* Get the shortest path to given target certificate from any trust anchor.
*
* @param Certificate $target Target certificate
* @param null|CertificateBundle $intermediate Optional intermediate certificates
*/
public function shortestPathToTarget(
Certificate $target,
?CertificateBundle $intermediate = null
): CertificationPath {
$paths = $this->allPathsToTarget($target, $intermediate);
if (count($paths) === 0) {
throw new PathBuildingException('No certification paths.');
}
// a comparison that never returns 0 leaves the order among equal length paths to PHP's sort; the
// spaceship operator makes the choice deterministic instead. When more than one path is possible, use
// allPathsToTarget() and validate them in turn rather than committing to this one.
usort($paths, static fn ($a, $b) => count($a) <=> count($b));
return reset($paths);
}
/**
* Find all issuers of the target certificate from a given bundle.
*
* @param Certificate $target Target certificate
* @param CertificateBundle $bundle Certificates to search
*
* @return Certificate[]
*/
private function findIssuers(Certificate $target, CertificateBundle $bundle): array
{
$issuer_name = $target->tbsCertificate()
->issuer();
$extensions = $target->tbsCertificate()
->extensions();
// find by authority key identifier
$candidates = [];
if ($extensions->hasAuthorityKeyIdentifier()) {
$ext = $extensions->authorityKeyIdentifier();
if ($ext->hasKeyIdentifier()) {
$candidates = $bundle->allBySubjectKeyIdentifier($ext->keyIdentifier());
}
}
if (count($candidates) === 0) {
// RFC 5280 requires the authority key identifier on a CA-issued certificate, but plenty of real
// certificates omit it and the issuer name identifies the issuer on its own. Without the fallback
// such a certificate can never be chained, which pushes integrators towards CertificationPath's
// unsafe constructor. RFC 4158 sect. 3.5.12 expects a builder to match on the name.
$candidates = $bundle->all();
}
$issuers = [];
foreach ($candidates as $issuer) {
// check that issuer name matches
if ($issuer->tbsCertificate()->subject()->equals($issuer_name)) {
$issuers[] = $issuer;
}
}
return $issuers;
}
/**
* Resolve all possible certification paths from any trust anchor to the target certificate, using optional
* intermediate certificates.
*
* Helper method for allPathsToTarget to be called recursively.
*
* @param array<string, true> $visited DER encoding of the certificates already on the path being resolved
*
* @return array<int, array<Certificate>> Array of arrays containing path certificates
*/
private function resolvePathsToTarget(
Certificate $target,
?CertificateBundle $intermediate = null,
array $visited = []
): array {
// count the work where it is done, so that a subtree producing no path is still bounded
if (++$this->visitedNodes > self::MAX_VISITED_NODES) {
throw new PathBuildingException('Too many certificates examined while resolving a certification path.');
}
// array of possible paths
$paths = [];
// signed by certificate in the trust list
foreach ($this->findIssuers($target, $this->trustList) as $issuer) {
// if target is self-signed, path consists of only
// the target certificate
if ($target->equals($issuer)) {
$paths[] = [$target];
} else {
$paths[] = [$issuer, $target];
}
}
if (isset($intermediate)) {
// the target now belongs to the path being resolved
$visited[$this->identity($target)] = true;
// stop exploring once the path has grown past the maximum length
if (count($visited) < self::MAX_PATH_LENGTH) {
// signed by intermediate certificate
foreach ($this->findIssuers($target, $intermediate) as $issuer) {
// intermediate certificate must not be self-signed
if ($issuer->isSelfIssued()) {
continue;
}
// an issuer already on the path being resolved would close a loop
if (isset($visited[$this->identity($issuer)])) {
continue;
}
// resolve paths to issuer
$subpaths = $this->resolvePathsToTarget($issuer, $intermediate, $visited);
foreach ($subpaths as $path) {
$paths[] = array_merge($path, [$target]);
$this->assertPathCount($paths);
}
}
}
}
return $paths;
}
/**
* Ensure that the resolution has not produced more paths than allowed.
*
* The check happens as the paths are collected, so that a bundle crafted to blow up combinatorially is caught
* before the exploration has done the work.
*
* @param array<int, array<Certificate>> $paths
*/
private function assertPathCount(array $paths): void
{
if (count($paths) > self::MAX_PATHS) {
throw new PathBuildingException('Too many certification paths.');
}
}
/**
* Identity of a certificate for the loop detection, computed once per certificate.
*
* The loop check ran on a fresh DER encoding of the same certificate at every node and for every candidate
* issuer, which is far more expensive than the comparison it guards. The encodings are kept in a map keyed by
* object, so each certificate is encoded once for the lifetime of the builder.
*/
private function identity(Certificate $certificate): string
{
// every certificate the resolution sees comes from the target or from a bundle the caller holds, so none
// of them is collected while the resolution runs and an object id cannot be reused underneath the cache
$id = spl_object_id($certificate);
if (! isset($this->identities[$id])) {
$this->identities[$id] = hash('sha256', $certificate->toDER(), true);
}
return $this->identities[$id];
}
}

View file

@ -0,0 +1,303 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\PathValidation;
use function count;
use function in_array;
use function mb_strlen;
use function mb_strtolower;
use function preg_match;
use SpomkyLabs\Pki\X509\Certificate\Extension\NameConstraints\GeneralSubtree;
use SpomkyLabs\Pki\X509\CertificationPath\Exception\PathValidationException;
use SpomkyLabs\Pki\X509\GeneralName\DirectoryName;
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
use SpomkyLabs\Pki\X509\GeneralName\IPAddress;
use function strcspn;
use function strpos;
/**
* Matches general names against the subtrees of a 'Name Constraints' certificate extension.
*
* Only the name forms for which RFC 5280 defines matching rules are supported. Constraints of any other form, as well
* as constraints using the `minimum` and `maximum` fields, cannot be evaluated and are therefore rejected rather than
* silently ignored.
*
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.10
*/
final class NameConstraintsMatcher
{
/**
* General name types for which a matching rule is implemented.
*
* @var list<int>
*/
private const SUPPORTED_TAGS = [
GeneralName::TAG_RFC822_NAME,
GeneralName::TAG_DNS_NAME,
GeneralName::TAG_DIRECTORY_NAME,
GeneralName::TAG_URI,
GeneralName::TAG_IP_ADDRESS,
];
/**
* Assert that every subtree of the set can be evaluated.
*
* @throws PathValidationException If a subtree uses an unsupported name form or a non-default range.
*/
public static function assertSupported(GeneralSubtree $subtree): void
{
$base = $subtree->base();
if (! in_array($base->tag(), self::SUPPORTED_TAGS, true)) {
throw new PathValidationException(
'Name constraint of type ' . $base->tag() . ' is not supported.'
);
}
// RFC 5280 4.2.1.10: within this profile, the minimum field is always zero and the maximum field is absent.
if ($subtree->getMin() !== 0 || $subtree->getMax() !== null) {
throw new PathValidationException('Name constraint with minimum or maximum is not supported.');
}
}
/**
* Whether the given name falls within the subtree.
*
* The name and the subtree base are expected to be of the same type.
*
* @throws PathValidationException If the name cannot be evaluated against the constraint.
*/
public static function matches(GeneralSubtree $subtree, GeneralName $name): bool
{
self::assertSupported($subtree);
$base = $subtree->base();
if ($base->tag() !== $name->tag()) {
return false;
}
return match ($base->tag()) {
GeneralName::TAG_RFC822_NAME => self::matchesEmail($base->string(), $name->string()),
GeneralName::TAG_DNS_NAME => self::matchesDNS($base->string(), $name->string()),
GeneralName::TAG_DIRECTORY_NAME => self::matchesDirectoryName($base, $name),
GeneralName::TAG_URI => self::matchesURI($base->string(), $name->string()),
GeneralName::TAG_IP_ADDRESS => self::matchesIPAddress($base, $name),
default => throw new PathValidationException(
'Name constraint of type ' . $base->tag() . ' is not supported.'
),
};
}
/**
* A host name that this matcher is able to compare byte for byte.
*
* Letters, digits, hyphen, underscore and the wildcard label, in non-empty labels, with no trailing dot. Anything
* else has a spelling this comparison would miss, so it is refused rather than let through.
*
* @var string
*/
private const HOST_SYNTAX = '/^[A-Za-z0-9_*](?:[A-Za-z0-9_*-]*[A-Za-z0-9_*])?'
. '(?:\.[A-Za-z0-9_*](?:[A-Za-z0-9_*-]*[A-Za-z0-9_*])?)*$/';
/**
* Match a domain name against a dNSName constraint.
*
* A constraint matches the host itself and any host below it. A constraint starting with a dot matches subdomains
* only.
*/
private static function matchesDNS(string $base, string $name): bool
{
// an empty constraint matches every name of the type
if ($base === '') {
return true;
}
$base = self::assertBaseHost($base, 'dNSName constraint');
$name = self::assertHost($name, 'dNSName');
if (str_starts_with($base, '.')) {
return str_ends_with($name, $base);
}
return $name === $base || str_ends_with($name, '.' . $base);
}
/**
* Match a mailbox against an rfc822Name constraint.
*
* The constraint is either a complete mailbox, a host name matching every mailbox on that host, or a name starting
* with a dot matching every mailbox below that domain.
*/
private static function matchesEmail(string $base, string $name): bool
{
if ($base === '') {
return true;
}
$namePos = strrpos($name, '@');
if ($namePos === false) {
return false;
}
$nameLocal = substr($name, 0, $namePos);
$nameHost = self::assertHost(substr($name, $namePos + 1), 'rfc822Name host');
$basePos = strrpos($base, '@');
// complete mailbox: the local part is case sensitive, the host part is not
if ($basePos !== false) {
return substr($base, 0, $basePos) === $nameLocal
&& self::assertHost(substr($base, $basePos + 1), 'rfc822Name constraint host') === $nameHost;
}
$base = self::assertBaseHost($base, 'rfc822Name constraint');
if (str_starts_with($base, '.')) {
return str_ends_with($nameHost, $base);
}
return $nameHost === $base;
}
/**
* Match a URI against a uniformResourceIdentifier constraint.
*
* The constraint applies to the host part of the authority component.
*
* @throws PathValidationException If the URI has no host that can be compared, in which case RFC 5280 mandates a
* rejection.
*/
private static function matchesURI(string $base, string $name): bool
{
$host = self::assertHost(self::uriHost($name), 'URI host');
if ($base === '') {
return true;
}
$base = self::assertBaseHost($base, 'uniformResourceIdentifier constraint');
if (str_starts_with($base, '.')) {
return str_ends_with($host, $base);
}
return $host === $base;
}
/**
* Extract the host of a URI's authority component.
*
* parse_url() is not used. It follows neither RFC 3986 nor the WHATWG URL standard that consumers of these names
* implement, and the two disagree on inputs an attacker chooses: for the special schemes the standard ends the
* authority at a backslash, while parse_url() runs past it and takes the host after the last "@". A name matched
* on one host and resolved on another defeats the constraint entirely.
*
* The authority therefore ends at the first of "/", "\", "?" or "#", userinfo is removed at the first "@", and a
* port is removed after it.
*
* @throws PathValidationException If the URI carries no authority.
*/
private static function uriHost(string $uri): string
{
$schemeEnd = strpos($uri, '://');
if ($schemeEnd === false) {
throw new PathValidationException(
"URI '{$uri}' has no authority and cannot be matched against a name constraint."
);
}
$authority = substr($uri, $schemeEnd + 3);
$end = strcspn($authority, '/\\?#');
$authority = substr($authority, 0, $end);
// userinfo ends at the first "@"; anything after it is the host, so a later "@" belongs to neither
$at = strpos($authority, '@');
if ($at !== false) {
$authority = substr($authority, $at + 1);
}
// a port follows the host, and a bracketed IPv6 literal is not a name this matcher compares
$colon = strpos($authority, ':');
if ($colon !== false) {
$authority = substr($authority, 0, $colon);
}
return $authority;
}
/**
* Assert that a host name has a spelling this matcher can compare, and return it folded to lower case.
*
* @throws PathValidationException If the name has any other spelling.
*/
private static function assertHost(string $host, string $what): string
{
if ($host === '' || preg_match(self::HOST_SYNTAX, $host) !== 1) {
throw new PathValidationException(
"{$what} '{$host}' is not a host name that can be matched against a name constraint."
);
}
return mb_strtolower($host, '8bit');
}
/**
* Assert the same of a constraint base, which may additionally start with a dot to mean "below this domain".
*
* @throws PathValidationException If the base has any other spelling.
*/
private static function assertBaseHost(string $base, string $what): string
{
if (str_starts_with($base, '.')) {
return '.' . self::assertHost(substr($base, 1), $what);
}
return self::assertHost($base, $what);
}
/**
* Match a distinguished name against a directoryName constraint.
*
* The constraint matches whenever it is a prefix of the name, an empty constraint therefore matching every name.
*/
private static function matchesDirectoryName(GeneralName $base, GeneralName $name): bool
{
if (! $base instanceof DirectoryName || ! $name instanceof DirectoryName) {
return false;
}
$baseRDNs = $base->dn()
->all();
$nameRDNs = $name->dn()
->all();
if (count($baseRDNs) > count($nameRDNs)) {
return false;
}
foreach ($baseRDNs as $i => $rdn) {
if (! $rdn->equals($nameRDNs[$i])) {
return false;
}
}
return true;
}
/**
* Match an IP address against an iPAddress constraint.
*
* The constraint carries a subnet mask of the same length as the address itself.
*
* @throws PathValidationException If an address cannot be decoded.
*/
private static function matchesIPAddress(GeneralName $base, GeneralName $name): bool
{
if (! $base instanceof IPAddress || ! $name instanceof IPAddress) {
return false;
}
$baseAddress = self::toOctets($base->address());
$nameAddress = self::toOctets($name->address());
// an IPv4 constraint never matches an IPv6 address and vice versa
if (mb_strlen($baseAddress, '8bit') !== mb_strlen($nameAddress, '8bit')) {
return false;
}
if (! $base->hasMask()) {
return $baseAddress === $nameAddress;
}
$mask = self::toOctets($base->mask());
if (mb_strlen($mask, '8bit') !== mb_strlen($baseAddress, '8bit')) {
throw new PathValidationException('Invalid subnet mask in iPAddress name constraint.');
}
return ($baseAddress & $mask) === ($nameAddress & $mask);
}
/**
* @throws PathValidationException If the address is not a valid IPv4 or IPv6 address.
*/
private static function toOctets(string $address): string
{
$octets = inet_pton($address);
if ($octets === false) {
throw new PathValidationException("Invalid IP address '{$address}' in certification path.");
}
return $octets;
}
}

View file

@ -0,0 +1,421 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\PathValidation;
use function array_values;
use DateTimeImmutable;
use InvalidArgumentException;
use LogicException;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
/**
* Configuration for the certification path validation process.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.1
*/
final class PathValidationConfig
{
/**
* Signature algorithm OIDs accepted by default.
*
* MD2, MD4 and MD5 are left out. Chosen prefix collisions against MD5 have been practical since 2009, which
* is enough to forge a certificate that verifies, and no certificate authority in service still signs with
* them: refusing them costs nothing and an opt-in API would protect only those who already knew to ask.
*
* SHA-1 is still in, despite chosen prefix collisions against it being practical since 2020. Legacy
* enterprise and device PKIs continue to rely on it, and cutting them off silently is not this library's
* call to make. Use HARDENED_ALLOWED_SIGNATURE_ALGORITHMS to refuse it.
*
* RSASSA-PSS is left out because it is not implemented: a PSS signed certificate is refused when it is
* parsed, so allowing the OID here advertised a capability that does not exist. When PSS is implemented the
* parameters have to be bound as well as the OID, since Certificate::fromASN1() only compares the OID of the
* outer and the signed algorithm identifiers, which would leave a hash, MGF and salt length downgrade open.
*
* Whether Ed25519 and Ed448 can actually be checked depends on the runtime: the OpenSSL extension only grew
* EdDSA recently, and ext-sodium covers Ed25519 alone. Validation fails closed where it cannot, and
* OpenSSLCrypto::supportsSignatureAlgorithm() answers the question up front for an application that would
* rather narrow this set than have a chain refused later.
*
* @var string[]
*/
public const DEFAULT_ALLOWED_SIGNATURE_ALGORITHMS = [
AlgorithmIdentifier::OID_SHA1_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_SHA224_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_SHA256_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_SHA384_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_SHA512_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA1,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA224,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA256,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA384,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA512,
AlgorithmIdentifier::OID_ED25519,
AlgorithmIdentifier::OID_ED448,
];
/**
* Signature algorithm OIDs for deployments that can refuse SHA-1.
*
* Pass it to withAllowedSignatureAlgorithms(). This is the set the default will narrow to in a future major
* release.
*
* @var string[]
*/
public const HARDENED_ALLOWED_SIGNATURE_ALGORITHMS = [
AlgorithmIdentifier::OID_SHA224_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_SHA256_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_SHA384_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_SHA512_WITH_RSA_ENCRYPTION,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA224,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA256,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA384,
AlgorithmIdentifier::OID_ECDSA_WITH_SHA512,
AlgorithmIdentifier::OID_ED25519,
AlgorithmIdentifier::OID_ED448,
];
/**
* Minimum RSA modulus size, in bits, accepted by default.
*
* RSA-512 has been factorable for decades and RSA-768 was factored in 2009, so a signature made with such a
* key proves nothing; the default refuses them. It stops at 1024 rather than at the 2048 bits the CA/Browser
* Forum has required since 2014, because raising the floor that far in a patch release would cut off legacy
* enterprise and device PKIs, the same reasoning that keeps SHA-1 in the default algorithm set.
*/
public const DEFAULT_MINIMUM_RSA_KEY_SIZE = 1024;
/**
* Minimum RSA modulus size, in bits, for deployments that can require 2048 bits.
*
* Pass it to withMinimumRSAKeySize(). This is the floor the default will rise to in a future major release.
*/
public const HARDENED_MINIMUM_RSA_KEY_SIZE = 2048;
/**
* List of acceptable policy identifiers.
*
* @var string[]
*/
private array $policySet;
/**
* Trust anchor certificate.
*
* If not set, path validation uses the first certificate of the path.
*/
private ?Certificate $trustAnchor = null;
/**
* Signature algorithm OIDs accepted when verifying certificate signatures.
*
* @var string[]
*/
private array $allowedSignatureAlgorithms;
/**
* Minimum RSA modulus size, in bits, accepted when verifying certificate signatures.
*/
private int $minimumRSAKeySize;
/**
* Whether policy mapping in inhibited.
*
* Setting this to true disallows policy mapping.
*/
private bool $policyMappingInhibit;
/**
* Whether the path must be valid for at least one policy in the initial policy set.
*/
private bool $explicitPolicy;
/**
* Whether anyPolicy OID processing should be inhibited.
*
* Setting this to true disallows the usage of anyPolicy.
*/
private bool $anyPolicyInhibit;
/**
* OID's of the critical certificate extensions the application processes by its own means.
*
* They are accepted by the validator in addition to the ones it processes itself.
*
* @var list<string>
*/
private array $additionalCriticalExtensions;
/**
* Whether version 1 and version 2 certificates may act as CA certificates in the path.
*
* RFC 5280 section 6.1.4 (k) allows such a certificate only once the application has confirmed it is a CA
* certificate through out-of-band means. This flag is how the application states that it did.
*/
private bool $legacyV1IntermediatesTrusted;
/**
* @param DateTimeImmutable $dateTime Reference date and time
* @param int $maxLength Maximum certification path length
*/
private function __construct(
private DateTimeImmutable $dateTime,
private int $maxLength
) {
$this->policySet = [PolicyInformation::OID_ANY_POLICY];
$this->allowedSignatureAlgorithms = self::DEFAULT_ALLOWED_SIGNATURE_ALGORITHMS;
$this->minimumRSAKeySize = self::DEFAULT_MINIMUM_RSA_KEY_SIZE;
$this->policyMappingInhibit = false;
$this->explicitPolicy = false;
$this->anyPolicyInhibit = false;
$this->additionalCriticalExtensions = [];
$this->legacyV1IntermediatesTrusted = false;
}
public static function create(DateTimeImmutable $dateTime, int $maxLength): self
{
return new self($dateTime, $maxLength);
}
/**
* Get default configuration.
*/
public static function defaultConfig(): self
{
return self::create(new DateTimeImmutable(), 3);
}
/**
* Get self with maximum path length.
*/
public function withMaxLength(int $length): self
{
$obj = clone $this;
$obj->maxLength = $length;
return $obj;
}
/**
* Get self with reference date and time.
*/
public function withDateTime(DateTimeImmutable $dt): self
{
$obj = clone $this;
$obj->dateTime = $dt;
return $obj;
}
/**
* Get self with trust anchor certificate.
*/
public function withTrustAnchor(Certificate $ca): self
{
$obj = clone $this;
$obj->trustAnchor = $ca;
return $obj;
}
/**
* Get self with initial-policy-mapping-inhibit set.
*/
public function withPolicyMappingInhibit(bool $flag): self
{
$obj = clone $this;
$obj->policyMappingInhibit = $flag;
return $obj;
}
/**
* Get self with initial-explicit-policy set.
*/
public function withExplicitPolicy(bool $flag): self
{
$obj = clone $this;
$obj->explicitPolicy = $flag;
return $obj;
}
/**
* Get self with initial-any-policy-inhibit set.
*/
public function withAnyPolicyInhibit(bool $flag): self
{
$obj = clone $this;
$obj->anyPolicyInhibit = $flag;
return $obj;
}
/**
* Get self with the OID's of the critical extensions the application processes by its own means.
*
* The path validation rejects any certificate carrying a critical extension it cannot process. Use this method to
* declare the extensions handled outside of the validator, so that they no longer cause a rejection.
*
* @param string ...$oids List of extension OID's
*/
public function withAdditionalCriticalExtensions(string ...$oids): self
{
$obj = clone $this;
$obj->additionalCriticalExtensions = array_values($oids);
return $obj;
}
/**
* Get self with version 1 and version 2 certificates allowed to act as CA certificates.
*
* Such a certificate carries no extensions, hence neither basicConstraints nor keyUsage, so nothing in it states
* that it may sign certificates. RFC 5280 section 6.1.4 (k) requires the application to either confirm this
* out-of-band or reject the certificate; the default is to reject.
*
* Only enable this if the certificates in question have been vouched for by other means. Any end-entity
* certificate a trusted CA ever issued in version 1 becomes usable as an intermediate CA for any identity.
*/
public function withLegacyV1IntermediatesTrusted(bool $flag): self
{
$obj = clone $this;
$obj->legacyV1IntermediatesTrusted = $flag;
return $obj;
}
/**
* Get self with user-initial-policy-set set to policy OIDs.
*
* @param string ...$policies List of policy OIDs
*/
public function withPolicySet(string ...$policies): self
{
$obj = clone $this;
$obj->policySet = $policies;
return $obj;
}
/**
* Get self with the set of accepted signature algorithms.
*
* Replaces the default set entirely. Pass HARDENED_ALLOWED_SIGNATURE_ALGORITHMS to also refuse SHA-1.
*
* @param string ...$oids Signature algorithm OIDs
*/
public function withAllowedSignatureAlgorithms(string ...$oids): self
{
$obj = clone $this;
$obj->allowedSignatureAlgorithms = $oids;
return $obj;
}
/**
* Get the signature algorithm OIDs accepted when verifying certificate signatures.
*
* @return string[]
*/
public function allowedSignatureAlgorithms(): array
{
return $this->allowedSignatureAlgorithms;
}
/**
* Get self with the minimum RSA modulus size, in bits, accepted when verifying certificate signatures.
*
* Pass HARDENED_MINIMUM_RSA_KEY_SIZE to require 2048 bits. A size of zero disables the check.
*
* @param int $bits Minimum modulus size in bits
*/
public function withMinimumRSAKeySize(int $bits): self
{
if ($bits < 0) {
throw new InvalidArgumentException('Minimum RSA key size must not be negative.');
}
$obj = clone $this;
$obj->minimumRSAKeySize = $bits;
return $obj;
}
/**
* Get the minimum RSA modulus size, in bits, accepted when verifying certificate signatures.
*/
public function minimumRSAKeySize(): int
{
return $this->minimumRSAKeySize;
}
/**
* Get maximum certification path length.
*/
public function maxLength(): int
{
return $this->maxLength;
}
/**
* Get reference date and time.
*/
public function dateTime(): DateTimeImmutable
{
return $this->dateTime;
}
/**
* Get user-initial-policy-set.
*
* @return string[] Array of OID's
*/
public function policySet(): array
{
return $this->policySet;
}
/**
* Check whether trust anchor certificate is set.
*/
public function hasTrustAnchor(): bool
{
return isset($this->trustAnchor);
}
/**
* Get trust anchor certificate.
*/
public function trustAnchor(): Certificate
{
if (! $this->hasTrustAnchor()) {
throw new LogicException('No trust anchor.');
}
return $this->trustAnchor;
}
public function policyMappingInhibit(): bool
{
return $this->policyMappingInhibit;
}
public function explicitPolicy(): bool
{
return $this->explicitPolicy;
}
public function anyPolicyInhibit(): bool
{
return $this->anyPolicyInhibit;
}
/**
* Get the OID's of the critical extensions the application processes by its own means.
*
* @return list<string> Array of OID's
*/
public function additionalCriticalExtensions(): array
{
return $this->additionalCriticalExtensions;
}
/**
* Whether version 1 and version 2 certificates may act as CA certificates in the path.
*/
public function legacyV1IntermediatesTrusted(): bool
{
return $this->legacyV1IntermediatesTrusted;
}
}

View file

@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\PathValidation;
use function count;
use SpomkyLabs\Pki\ASN1\Element;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType;
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
use SpomkyLabs\Pki\X509\CertificationPath\Policy\PolicyTree;
/**
* Result of the path validation process.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.6
*/
final class PathValidationResult
{
/**
* Certificates in a certification path.
*
* @var Certificate[]
*/
private readonly array $certificates;
/**
* @param Certificate[] $certificates
*/
private function __construct(
array $certificates,
private readonly ?PolicyTree $policyTree,
private readonly PublicKeyInfo $publicKeyInfo,
private readonly AlgorithmIdentifierType $publicKeyAlgo,
private readonly ?Element $publicKeyParameters
) {
$this->certificates = array_values($certificates);
}
/**
* @param Certificate[] $certificates Certificates in a certification path
* @param null|PolicyTree $policyTree Valid policy tree
* @param PublicKeyInfo $publicKeyInfo Public key of the end-entity certificate
* @param AlgorithmIdentifierType $publicKeyAlgo Public key algorithm of the end-entity certificate
* @param null|Element $publicKeyParameters Algorithm parameters
*/
public static function create(
array $certificates,
?PolicyTree $policyTree,
PublicKeyInfo $publicKeyInfo,
AlgorithmIdentifierType $publicKeyAlgo,
?Element $publicKeyParameters = null
): self {
return new self($certificates, $policyTree, $publicKeyInfo, $publicKeyAlgo, $publicKeyParameters);
}
public function getPolicyTree(): ?PolicyTree
{
return $this->policyTree;
}
public function getPublicKeyInfo(): PublicKeyInfo
{
return $this->publicKeyInfo;
}
public function getPublicKeyAlgo(): AlgorithmIdentifierType
{
return $this->publicKeyAlgo;
}
public function getPublicKeyParameters(): ?Element
{
return $this->publicKeyParameters;
}
/**
* Get end-entity certificate.
*/
public function certificate(): Certificate
{
return $this->certificates[count($this->certificates) - 1];
}
/**
* Get certificate policies of the end-entity certificate.
*
* @return PolicyInformation[]
*/
public function policies(): array
{
if ($this->policyTree === null) {
return [];
}
return $this->policyTree->policiesAtDepth(count($this->certificates));
}
}

View file

@ -0,0 +1,719 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\PathValidation;
use function array_values;
use function count;
use function in_array;
use LogicException;
use RuntimeException;
use SpomkyLabs\Pki\CryptoBridge\Crypto;
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
use SpomkyLabs\Pki\X501\StringPrep\Exception\StringPreparationException;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
use SpomkyLabs\Pki\X509\Certificate\Extension\Extension;
use SpomkyLabs\Pki\X509\Certificate\Extension\NameConstraints\GeneralSubtrees;
use SpomkyLabs\Pki\X509\Certificate\TBSCertificate;
use SpomkyLabs\Pki\X509\CertificationPath\Exception\PathValidationException;
use SpomkyLabs\Pki\X509\GeneralName\DirectoryName;
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
use SpomkyLabs\Pki\X509\GeneralName\RFC822Name;
use function sprintf;
/**
* Implements certification path validation.
*
* @see https://tools.ietf.org/html/rfc5280#section-6
*/
final class PathValidator
{
/**
* OID's of the certificate extensions this validator is able to process.
*
* A critical extension whose OID is not listed here cannot be honoured, and therefore makes the path validation
* fail as required by RFC 5280 section 6.1.4 (o) and section 6.1.5 (f).
*
* `subjectAltName` belongs to that set: RFC 5280 section 6.1.3 (b) and (c) define its processing during path
* validation as the matching of its names against the name constraints, which this validator performs. Marking it
* critical is moreover what RFC 5280 section 4.2.1.6 requires of a certificate carrying an empty subject, so
* rejecting it would turn away the very certificates the specification mandates.
*
* An extension outside of this set may still be declared by an application enforcing it by its own means, through
* `PathValidationConfig::withAdditionalCriticalExtensions()`.
*
* @var list<string>
*/
private const PROCESSED_EXTENSIONS = [
Extension::OID_BASIC_CONSTRAINTS,
Extension::OID_KEY_USAGE,
Extension::OID_CERTIFICATE_POLICIES,
Extension::OID_POLICY_MAPPINGS,
Extension::OID_POLICY_CONSTRAINTS,
Extension::OID_INHIBIT_ANY_POLICY,
Extension::OID_NAME_CONSTRAINTS,
Extension::OID_SUBJECT_ALT_NAME,
];
/**
* Attribute holding an electronic mail address embedded in a subject distinguished name.
*
* @see https://tools.ietf.org/html/rfc5280#section-4.1.2.6
*/
private const ATTR_EMAIL_ADDRESS = 'emailAddress';
/**
* Certification path.
*
* @var list<Certificate>
*/
private readonly array $certificates;
/**
* Certification path trust anchor.
*/
private readonly Certificate $trustAnchor;
/**
* @param Crypto $crypto Crypto engine
* @param PathValidationConfig $config Validation config
* @param Certificate ...$certificates Certificates from the trust anchor to
* the end-entity certificate
*/
private function __construct(
private readonly Crypto $crypto,
private readonly PathValidationConfig $config,
Certificate ...$certificates
) {
if (count($certificates) === 0) {
throw new LogicException('No certificates.');
}
$this->certificates = array_values($certificates);
// if trust anchor is explicitly given in configuration
if ($config->hasTrustAnchor()) {
$this->trustAnchor = $config->trustAnchor();
} else {
$this->trustAnchor = $certificates[0];
}
}
public static function create(
Crypto $crypto,
PathValidationConfig $config,
Certificate ...$certificates
): self {
return new self($crypto, $config, ...$certificates);
}
/**
* Validate certification path.
*
* A name comparison is a security decision here, so a name that cannot be prepared for comparison fails the
* validation rather than being reported as not equal, which would let a name escape an excluded subtree. The
* failure is reported as a PathValidationException like every other, instead of escaping as the
* StringPreparationException raised deep inside the comparison.
*
* @throws PathValidationException If the path does not validate.
*/
public function validate(): PathValidationResult
{
try {
return $this->process();
} catch (StringPreparationException $e) {
throw new PathValidationException(
'A name of the certification path cannot be prepared for comparison: ' . $e->getMessage(),
0,
$e
);
}
}
/**
* Run the validation algorithm of RFC 5280 section 6.1.
*/
private function process(): PathValidationResult
{
$n = count($this->certificates);
$state = ValidatorState::initialize($this->config, $this->trustAnchor, $n);
foreach ($this->certificates as $i => $iValue) {
$state = $state->withIndex($i + 1);
$cert = $iValue;
// process certificate (section 6.1.3.)
$state = $this->processCertificate($state, $cert);
if (! $state->isFinal()) {
// prepare next certificate (section 6.1.4.)
$state = $this->prepareNext($state, $cert);
}
}
if (! isset($cert)) {
throw new LogicException('No certificates.');
}
// wrap-up (section 6.1.5.)
$state = $this->wrapUp($state, $cert);
// return outputs
return $state->getResult($this->certificates);
}
/**
* Apply basic certificate processing according to RFC 5280 section 6.1.3.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.3
*/
private function processCertificate(ValidatorState $state, Certificate $cert): ValidatorState
{
// (a.1) verify signature
$this->verifySignature($state, $cert);
// (a.2) check validity period
$this->checkValidity($cert);
// (a.3) check that certificate is not revoked
$this->checkRevocation();
// (a.4) check issuer
$this->checkIssuer($state, $cert);
// (b)(c) if certificate is self-issued and it is not
// the final certificate in the path, skip this step
if (! ($cert->isSelfIssued() && ! $state->isFinal())) {
// (b) check permitted subtrees
$this->checkPermittedSubtrees($state, $cert);
// (c) check excluded subtrees
$this->checkExcludedSubtrees($state, $cert);
}
$extensions = $cert->tbsCertificate()
->extensions();
if ($extensions->hasCertificatePolicies()) {
// (d) process policy information
if ($state->hasValidPolicyTree()) {
$state = $state->validPolicyTree()
->processPolicies($state, $cert);
}
} else {
// (e) certificate policies extension not present,
// set the valid_policy_tree to NULL
$state = $state->withoutValidPolicyTree();
}
// (f) check that explicit_policy > 0 or valid_policy_tree is set
if (! ($state->explicitPolicy() > 0 || $state->hasValidPolicyTree())) {
throw new PathValidationException('No valid policies.');
}
return $state;
}
/**
* Apply preparation for the certificate i+1 according to rfc5280 section 6.1.4.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.4
*/
private function prepareNext(ValidatorState $state, Certificate $cert): ValidatorState
{
// (a)(b) if policy mappings extension is present
$state = $this->preparePolicyMappings($state, $cert);
// (c) assign working_issuer_name
$state = $state->withWorkingIssuerName($cert->tbsCertificate()->subject());
// (d)(e)(f)
$state = $this->setPublicKeyState($state, $cert);
// (g) if name constraints extension is present
$state = $this->prepareNameConstraints($state, $cert);
// (h) if certificate is not self-issued
if (! $cert->isSelfIssued()) {
$state = $this->prepareNonSelfIssued($state);
}
// (i) if policy constraints extension is present
$state = $this->preparePolicyConstraints($state, $cert);
// (j) if inhibit any policy extension is present
$state = $this->prepareInhibitAnyPolicy($state, $cert);
// (k) check basic constraints
$this->processBasicContraints($cert);
// (l) verify max_path_length
$state = $this->verifyMaxPathLength($state, $cert);
// (m) check pathLenContraint
$state = $this->processPathLengthContraint($state, $cert);
// (n) check key usage
$this->checkKeyUsage($cert);
// (o) process relevant extensions
return $this->processExtensions($state, $cert);
}
/**
* Apply wrap-up procedure according to RFC 5280 section 6.1.5.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.5
*/
private function wrapUp(ValidatorState $state, Certificate $cert): ValidatorState
{
$tbs_cert = $cert->tbsCertificate();
$extensions = $tbs_cert->extensions();
// (a)
if ($state->explicitPolicy() > 0) {
$state = $state->withExplicitPolicy($state->explicitPolicy() - 1);
}
// (b)
if ($extensions->hasPolicyConstraints()) {
$ext = $extensions->policyConstraints();
if ($ext->hasRequireExplicitPolicy() &&
$ext->requireExplicitPolicy() === 0) {
$state = $state->withExplicitPolicy(0);
}
}
// (c)(d)(e)
$state = $this->setPublicKeyState($state, $cert);
// (f) process relevant extensions
$state = $this->processExtensions($state, $cert);
// (g) intersection of valid_policy_tree and the initial-policy-set
$state = $this->calculatePolicyIntersection($state);
// check that explicit_policy > 0 or valid_policy_tree is set
if (! ($state->explicitPolicy() > 0 || $state->hasValidPolicyTree())) {
throw new PathValidationException('No valid policies.');
}
// path validation succeeded
return $state;
}
/**
* Update working_public_key, working_public_key_parameters and working_public_key_algorithm state variables from
* certificate.
*/
private function setPublicKeyState(ValidatorState $state, Certificate $cert): ValidatorState
{
$pk_info = $cert->tbsCertificate()
->subjectPublicKeyInfo();
// assign working_public_key
$state = $state->withWorkingPublicKey($pk_info);
// assign working_public_key_parameters
$params = ValidatorState::getAlgorithmParameters($pk_info->algorithmIdentifier());
if ($params !== null) {
$state = $state->withWorkingPublicKeyParameters($params);
} else {
// if algorithms differ, set parameters to null
if ($pk_info->algorithmIdentifier()->oid() !==
$state->workingPublicKeyAlgorithm()
->oid()) {
$state = $state->withWorkingPublicKeyParameters();
}
}
// assign working_public_key_algorithm
return $state->withWorkingPublicKeyAlgorithm($pk_info->algorithmIdentifier());
}
/**
* Verify certificate signature.
*/
private function verifySignature(ValidatorState $state, Certificate $cert): void
{
// A signature is only as good as its digest. Without this check the validator accepts MD5, against which
// chosen prefix collisions are practical, and the application has no way to say no.
$algo = $cert->signatureAlgorithm();
if (! SignaturePolicy::isAlgorithmAllowed($algo, $this->config->allowedSignatureAlgorithms())) {
throw new PathValidationException(sprintf('Signature algorithm %s is not allowed.', $algo->name()));
}
$this->checkIssuerKeySize($state->workingPublicKey());
try {
$valid = $cert->verify($state->workingPublicKey(), $this->crypto);
} catch (RuntimeException $e) {
throw new PathValidationException('Failed to verify signature: ' . $e->getMessage(), 0, $e);
}
if (! $valid) {
throw new PathValidationException("Certificate signature doesn't match.");
}
}
/**
* Check that the key which signed the certificate is large enough to be worth verifying.
*
* Only RSA is covered: an EC key's strength is fixed by its named curve, and the curves this library knows
* are all above the line. A modulus below the floor makes the signature meaningless however well OpenSSL
* verifies it.
*/
private function checkIssuerKeySize(PublicKeyInfo $pubkey_info): void
{
$minimum = $this->config->minimumRSAKeySize();
$bits = SignaturePolicy::rsaKeySizeBelowMinimum($pubkey_info, $minimum);
if ($bits !== null) {
throw new PathValidationException(
sprintf('RSA key size %d is below the minimum of %d bits.', $bits, $minimum)
);
}
}
/**
* Check certificate validity.
*/
private function checkValidity(Certificate $cert): void
{
$refdt = $this->config->dateTime();
$validity = $cert->tbsCertificate()
->validity();
if ($validity->notBefore()->dateTime()->diff($refdt)->invert !== 0) {
throw new PathValidationException('Certificate validity period has not started.');
}
if ($refdt->diff($validity->notAfter()->dateTime())->invert !== 0) {
throw new PathValidationException('Certificate has expired.');
}
}
/**
* Check certificate revocation.
*/
private function checkRevocation(): void
{
// @todo Implement CRL handling
}
/**
* Check certificate issuer.
*/
private function checkIssuer(ValidatorState $state, Certificate $cert): void
{
if (! $cert->tbsCertificate()->issuer()->equals($state->workingIssuerName())) {
throw new PathValidationException('Certification issuer mismatch.');
}
}
/**
* Check that every name of the certificate falls within the permitted subtrees.
*/
private function checkPermittedSubtrees(ValidatorState $state, Certificate $cert): void
{
$permitted = $state->permittedSubtrees();
if (count($permitted) === 0) {
return;
}
foreach ($this->certificateNames($cert) as $name) {
// the state holds the intersection of the constraints of each certificate processed so far,
// so the name must fall within every one of them
foreach ($permitted as $subtrees) {
$this->checkPermittedName($name, $subtrees);
}
}
}
/**
* Check that a name falls within one of the subtrees constraining its own type.
*
* RFC 5280 4.2.1.10: restrictions apply only when the constrained name form is present, hence a name of a type
* that no subtree constrains is unrestricted.
*/
private function checkPermittedName(GeneralName $name, GeneralSubtrees $subtrees): void
{
$constrained = false;
foreach ($subtrees->all() as $subtree) {
if ($subtree->base()->tag() !== $name->tag()) {
continue;
}
$constrained = true;
if (NameConstraintsMatcher::matches($subtree, $name)) {
return;
}
}
if ($constrained) {
throw new PathValidationException(
"Name '{$name->string()}' is not within the permitted subtrees."
);
}
}
/**
* Check that no name of the certificate falls within the excluded subtrees.
*/
private function checkExcludedSubtrees(ValidatorState $state, Certificate $cert): void
{
$excluded = $state->excludedSubtrees();
if ($excluded === null) {
return;
}
foreach ($this->certificateNames($cert) as $name) {
foreach ($excluded->all() as $subtree) {
if ($subtree->base()->tag() !== $name->tag()) {
continue;
}
if (NameConstraintsMatcher::matches($subtree, $name)) {
throw new PathValidationException(
"Name '{$name->string()}' is within an excluded subtree."
);
}
}
}
}
/**
* Get the names of a certificate that are subject to name constraints.
*
* These are the subject distinguished name, as a directoryName, and every name of the subjectAltName extension.
* For a certificate carrying no subjectAltName extension, RFC 5280 4.2.1.10 additionally submits the legacy
* emailAddress attributes of the subject to the rfc822Name constraints.
*
* @return list<GeneralName>
*/
private function certificateNames(Certificate $cert): array
{
$tbsCert = $cert->tbsCertificate();
$names = [];
$subject = $tbsCert->subject();
// an empty subject carries no identity and is constrained by the subjectAltName extension alone
if (count($subject) !== 0) {
$names[] = DirectoryName::create($subject);
}
$extensions = $tbsCert->extensions();
if ($extensions->hasSubjectAlternativeName()) {
foreach ($extensions->subjectAlternativeName()->names()->all() as $name) {
$names[] = $name;
}
return $names;
}
foreach ($subject->all() as $rdn) {
foreach ($rdn->allOf(self::ATTR_EMAIL_ADDRESS) as $attribute) {
$names[] = RFC822Name::create($attribute->value()->stringValue());
}
}
return $names;
}
/**
* Apply policy mappings handling for the preparation step.
*/
private function preparePolicyMappings(ValidatorState $state, Certificate $cert): ValidatorState
{
$extensions = $cert->tbsCertificate()
->extensions();
if ($extensions->hasPolicyMappings()) {
// (a) verify that anyPolicy mapping is not used
if ($extensions->policyMappings()->hasAnyPolicyMapping()) {
throw new PathValidationException('anyPolicy mapping found.');
}
// (b) process policy mappings
if ($state->hasValidPolicyTree()) {
$state = $state->validPolicyTree()
->processMappings($state, $cert);
}
}
return $state;
}
/**
* Apply name constraints handling for the preparation step.
*/
private function prepareNameConstraints(ValidatorState $state, Certificate $cert): ValidatorState
{
$extensions = $cert->tbsCertificate()
->extensions();
if ($extensions->hasNameConstraints()) {
$state = $this->processNameConstraints($state, $cert);
}
return $state;
}
/**
* Apply preparation for a non-self-signed certificate.
*/
private function prepareNonSelfIssued(ValidatorState $state): ValidatorState
{
// (h.1)
if ($state->explicitPolicy() > 0) {
$state = $state->withExplicitPolicy($state->explicitPolicy() - 1);
}
// (h.2)
if ($state->policyMapping() > 0) {
$state = $state->withPolicyMapping($state->policyMapping() - 1);
}
// (h.3)
if ($state->inhibitAnyPolicy() > 0) {
$state = $state->withInhibitAnyPolicy($state->inhibitAnyPolicy() - 1);
}
return $state;
}
/**
* Apply policy constraints handling for the preparation step.
*/
private function preparePolicyConstraints(ValidatorState $state, Certificate $cert): ValidatorState
{
$extensions = $cert->tbsCertificate()
->extensions();
if (! $extensions->hasPolicyConstraints()) {
return $state;
}
$ext = $extensions->policyConstraints();
// (i.1)
if ($ext->hasRequireExplicitPolicy() &&
$ext->requireExplicitPolicy() < $state->explicitPolicy()) {
$state = $state->withExplicitPolicy($ext->requireExplicitPolicy());
}
// (i.2)
if ($ext->hasInhibitPolicyMapping() &&
$ext->inhibitPolicyMapping() < $state->policyMapping()) {
$state = $state->withPolicyMapping($ext->inhibitPolicyMapping());
}
return $state;
}
/**
* Apply inhibit any-policy handling for the preparation step.
*/
private function prepareInhibitAnyPolicy(ValidatorState $state, Certificate $cert): ValidatorState
{
$extensions = $cert->tbsCertificate()
->extensions();
if ($extensions->hasInhibitAnyPolicy()) {
$ext = $extensions->inhibitAnyPolicy();
if ($ext->skipCerts() < $state->inhibitAnyPolicy()) {
$state = $state->withInhibitAnyPolicy($ext->skipCerts());
}
}
return $state;
}
/**
* Verify maximum certification path length for the preparation step.
*/
private function verifyMaxPathLength(ValidatorState $state, Certificate $cert): ValidatorState
{
if (! $cert->isSelfIssued()) {
if ($state->maxPathLength() <= 0) {
throw new PathValidationException('Certification path length exceeded.');
}
$state = $state->withMaxPathLength($state->maxPathLength() - 1);
}
return $state;
}
/**
* Check key usage extension for the preparation step.
*/
private function checkKeyUsage(Certificate $cert): void
{
$extensions = $cert->tbsCertificate()
->extensions();
if ($extensions->hasKeyUsage()) {
$ext = $extensions->keyUsage();
if (! $ext->isKeyCertSign()) {
throw new PathValidationException('keyCertSign usage not set.');
}
}
}
/**
* Intersect the permitted subtrees and unite the excluded subtrees of the certificate into the state.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.4
*/
private function processNameConstraints(ValidatorState $state, Certificate $cert): ValidatorState
{
$ext = $cert->tbsCertificate()
->extensions()
->nameConstraints();
if (! $ext->hasPermittedSubtrees() && ! $ext->hasExcludedSubtrees()) {
throw new PathValidationException('Name constraints extension must contain at least one subtree.');
}
if ($ext->hasPermittedSubtrees()) {
$subtrees = $ext->permittedSubtrees();
$this->assertSubtreesSupported($subtrees);
$state = $state->withAdditionalPermittedSubtrees($subtrees);
}
if ($ext->hasExcludedSubtrees()) {
$subtrees = $ext->excludedSubtrees();
$this->assertSubtreesSupported($subtrees);
$state = $state->withAdditionalExcludedSubtrees($subtrees);
}
return $state;
}
/**
* Reject constraints that cannot be enforced instead of letting the names they cover through unchecked.
*/
private function assertSubtreesSupported(GeneralSubtrees $subtrees): void
{
foreach ($subtrees->all() as $subtree) {
NameConstraintsMatcher::assertSupported($subtree);
}
}
/**
* Process basic constraints extension.
*/
private function processBasicContraints(Certificate $cert): void
{
// a v1 or v2 certificate carries no extensions, so it asserts nothing about being a CA. RFC 5280 section
// 6.1.4 (k) requires it to be either confirmed as a CA certificate out-of-band or rejected; the application
// states that confirmation through the configuration.
if ($cert->tbsCertificate()->version() !== TBSCertificate::VERSION_3) {
if (! $this->config->legacyV1IntermediatesTrusted()) {
throw new PathValidationException(
'Certificate is not a v3 certificate and cannot be verified as a CA certificate.'
);
}
return;
}
$extensions = $cert->tbsCertificate()
->extensions();
if (! $extensions->hasBasicConstraints()) {
throw new PathValidationException('v3 certificate must have basicConstraints extension.');
}
// verify that cA is set to TRUE
if (! $extensions->basicConstraints()->isCA()) {
throw new PathValidationException('Certificate is not a CA certificate.');
}
}
/**
* Process pathLenConstraint.
*/
private function processPathLengthContraint(ValidatorState $state, Certificate $cert): ValidatorState
{
$extensions = $cert->tbsCertificate()
->extensions();
if ($extensions->hasBasicConstraints()) {
$ext = $extensions->basicConstraints();
if ($ext->hasPathLen()) {
if ($ext->pathLen() < $state->maxPathLength()) {
$state = $state->withMaxPathLength($ext->pathLen());
}
}
}
return $state;
}
/**
* Process the extensions of the current certificate.
*
* Every critical extension must be recognized and processed, otherwise the certificate must be rejected.
*
* @see https://tools.ietf.org/html/rfc5280#section-4.2
*/
private function processExtensions(ValidatorState $state, Certificate $cert): ValidatorState
{
$recognized = [...self::PROCESSED_EXTENSIONS, ...$this->config->additionalCriticalExtensions()];
foreach ($cert->tbsCertificate()->extensions() as $extension) {
if (! $extension->isCritical()) {
continue;
}
if (! in_array($extension->oid(), $recognized, true)) {
throw new PathValidationException(sprintf(
'Certificate contains an unhandled critical extension: %s.',
$extension->extensionName()
));
}
}
return $state;
}
private function calculatePolicyIntersection(ValidatorState $state): ValidatorState
{
// (i) If the valid_policy_tree is NULL, the intersection is NULL
if (! $state->hasValidPolicyTree()) {
return $state;
}
// (ii) If the valid_policy_tree is not NULL and
// the user-initial-policy-set is any-policy, the intersection
// is the entire valid_policy_tree
$initial_policies = $this->config->policySet();
if (in_array(PolicyInformation::OID_ANY_POLICY, $initial_policies, true)) {
return $state;
}
// (iii) If the valid_policy_tree is not NULL and the
// user-initial-policy-set is not any-policy, calculate
// the intersection of the valid_policy_tree and the
// user-initial-policy-set as follows
return $state->validPolicyTree()
->calculateIntersection($state, $initial_policies);
}
}

View file

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\PathValidation;
use Brick\Math\BigInteger;
use function in_array;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RSA\RSAPublicKey;
/**
* The parts of a validation policy that apply to any signature, wherever it is verified.
*
* Both the certification path validation and the attribute certificate validation answer the same two questions
* before trusting a signature: is the algorithm one the caller accepts, and is the key that made it large enough to
* be worth verifying. They are asked here so that a single implementation answers them.
*
* @internal
*/
final class SignaturePolicy
{
/**
* Whether the algorithm is one the caller accepts.
*
* A signature is only as good as its digest. Without this check MD5 is accepted, against which chosen prefix
* collisions are practical, and the application has no way to say no.
*
* @param list<string>|string[] $allowed Accepted algorithm OID's
*/
public static function isAlgorithmAllowed(SignatureAlgorithmIdentifier $algo, array $allowed): bool
{
return in_array($algo->oid(), $allowed, true);
}
/**
* Size of the RSA modulus when it falls below the minimum, null when the key is acceptable.
*
* Only RSA is covered: an EC key's strength is fixed by its named curve, and the curves this library knows are
* all above the line. A modulus below the floor makes the signature meaningless however well OpenSSL verifies
* it.
*
* @param int $minimum Minimum modulus size in bits, zero to disable the check
*/
public static function rsaKeySizeBelowMinimum(PublicKeyInfo $pubkey_info, int $minimum): ?int
{
if ($minimum === 0) {
return null;
}
if ($pubkey_info->algorithmIdentifier()->oid() !== AlgorithmIdentifier::OID_RSA_ENCRYPTION) {
return null;
}
$pubkey = $pubkey_info->publicKey();
if (! $pubkey instanceof RSAPublicKey) {
return null;
}
$bits = BigInteger::of($pubkey->modulus())->getBitLength();
return $bits < $minimum ? $bits : null;
}
}

View file

@ -0,0 +1,418 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\PathValidation;
use LogicException;
use SpomkyLabs\Pki\ASN1\Element;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
use SpomkyLabs\Pki\X501\ASN1\Name;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\NameConstraints\GeneralSubtrees;
use SpomkyLabs\Pki\X509\CertificationPath\Policy\PolicyNode;
use SpomkyLabs\Pki\X509\CertificationPath\Policy\PolicyTree;
/**
* State class for the certification path validation process.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.1
* @see https://tools.ietf.org/html/rfc5280#section-6.1.2
*/
final class ValidatorState
{
/**
* Length of the certification path (n).
*/
private ?int $_pathLength = null;
/**
* Current index in the certification path in the range of 1..n (i).
*/
private ?int $_index = null;
/**
* Valid policy tree (valid_policy_tree).
*
* A tree of certificate policies with their optional qualifiers. Each of the leaves of the tree represents a valid
* policy at this stage in the certification path validation. Once the tree is set to NULL, policy processing
* ceases.
*/
private ?PolicyTree $_validPolicyTree = null;
/**
* Permitted subtrees (permitted_subtrees).
*
* A set of root names for each name type defining a set of subtrees within which all subject names in subsequent
* certificates in the certification path must fall.
*
* RFC 5280 defines this variable as the intersection of the permitted subtrees of every certificate processed so
* far. The intersection is kept in its unevaluated form: one entry per constraining certificate, a name being
* within the intersection when it is within each of the entries.
*
* @var list<GeneralSubtrees>
*/
private array $_permittedSubtrees = [];
/**
* Excluded subtrees (excluded_subtrees).
*
* A set of root names for each name type defining a set of subtrees within which no subject name in subsequent
* certificates in the certification path may fall.
*
* This is the union of the excluded subtrees of every certificate processed so far.
*/
private ?GeneralSubtrees $_excludedSubtrees = null;
/**
* Explicit policy (explicit_policy).
*
* An integer that indicates if a non-NULL valid_policy_tree is required.
*/
private ?int $_explicitPolicy = null;
/**
* Inhibit anyPolicy (inhibit_anyPolicy).
*
* An integer that indicates whether the anyPolicy policy identifier is considered a match.
*/
private ?int $_inhibitAnyPolicy = null;
/**
* Policy mapping (policy_mapping).
*
* An integer that indicates if policy mapping is permitted.
*/
private ?int $_policyMapping = null;
/**
* Working public key algorithm (working_public_key_algorithm).
*
* The digital signature algorithm used to verify the signature of a certificate.
*/
private SignatureAlgorithmIdentifier|AlgorithmIdentifierType|null $_workingPublicKeyAlgorithm = null;
/**
* Working public key (working_public_key).
*
* The public key used to verify the signature of a certificate.
*/
private ?PublicKeyInfo $_workingPublicKey = null;
/**
* Working public key parameters (working_public_key_parameters).
*
* Parameters associated with the current public key that may be required to verify a signature.
*/
private ?Element $_workingPublicKeyParameters = null;
/**
* Working issuer name (working_issuer_name).
*
* The issuer distinguished name expected in the next certificate in the chain.
*/
private ?Name $_workingIssuerName = null;
/**
* Maximum certification path length (max_path_length).
*/
private ?int $_maxPathLength = null;
private function __construct()
{
}
/**
* Initialize variables according to RFC 5280 6.1.2.
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.2
*
* @param Certificate $trust_anchor Trust anchor certificate
* @param int $n Number of certificates
* in the certification path
*/
public static function initialize(PathValidationConfig $config, Certificate $trust_anchor, int $n): self
{
$state = new self();
$state->_pathLength = $n;
$state->_index = 1;
$state->_validPolicyTree = PolicyTree::create(PolicyNode::anyPolicyNode());
$state->_permittedSubtrees = [];
$state->_excludedSubtrees = null;
$state->_explicitPolicy = $config->explicitPolicy() ? 0 : $n + 1;
$state->_inhibitAnyPolicy = $config->anyPolicyInhibit() ? 0 : $n + 1;
$state->_policyMapping = $config->policyMappingInhibit() ? 0 : $n + 1;
$state->_workingPublicKeyAlgorithm = $trust_anchor->signatureAlgorithm();
$tbsCert = $trust_anchor->tbsCertificate();
$state->_workingPublicKey = $tbsCert->subjectPublicKeyInfo();
$state->_workingPublicKeyParameters = self::getAlgorithmParameters(
$state->_workingPublicKey->algorithmIdentifier()
);
$state->_workingIssuerName = $tbsCert->subject();
$state->_maxPathLength = $config->maxLength();
return $state;
}
/**
* Get self with current certification path index set.
*/
public function withIndex(int $index): self
{
$state = clone $this;
$state->_index = $index;
return $state;
}
/**
* Get self with valid_policy_tree.
*/
public function withValidPolicyTree(PolicyTree $policy_tree): self
{
$state = clone $this;
$state->_validPolicyTree = $policy_tree;
return $state;
}
/**
* Get self with valid_policy_tree set to null.
*/
public function withoutValidPolicyTree(): self
{
$state = clone $this;
$state->_validPolicyTree = null;
return $state;
}
/**
* Get self with the given permitted subtrees intersected into permitted_subtrees.
*/
public function withAdditionalPermittedSubtrees(GeneralSubtrees $subtrees): self
{
$state = clone $this;
$state->_permittedSubtrees = [...$this->_permittedSubtrees, $subtrees];
return $state;
}
/**
* Get self with the given excluded subtrees added to the union of excluded_subtrees.
*/
public function withAdditionalExcludedSubtrees(GeneralSubtrees $subtrees): self
{
$state = clone $this;
$state->_excludedSubtrees = $this->_excludedSubtrees === null
? $subtrees
: GeneralSubtrees::create(...$this->_excludedSubtrees->all(), ...$subtrees->all());
return $state;
}
/**
* Get self with explicit_policy.
*/
public function withExplicitPolicy(int $num): self
{
$state = clone $this;
$state->_explicitPolicy = $num;
return $state;
}
/**
* Get self with inhibit_anyPolicy.
*/
public function withInhibitAnyPolicy(int $num): self
{
$state = clone $this;
$state->_inhibitAnyPolicy = $num;
return $state;
}
/**
* Get self with policy_mapping.
*/
public function withPolicyMapping(int $num): self
{
$state = clone $this;
$state->_policyMapping = $num;
return $state;
}
/**
* Get self with working_public_key_algorithm.
*/
public function withWorkingPublicKeyAlgorithm(AlgorithmIdentifierType $algo): self
{
$state = clone $this;
$state->_workingPublicKeyAlgorithm = $algo;
return $state;
}
/**
* Get self with working_public_key.
*/
public function withWorkingPublicKey(PublicKeyInfo $pubkey_info): self
{
$state = clone $this;
$state->_workingPublicKey = $pubkey_info;
return $state;
}
/**
* Get self with working_public_key_parameters.
*/
public function withWorkingPublicKeyParameters(?Element $params = null): self
{
$state = clone $this;
$state->_workingPublicKeyParameters = $params;
return $state;
}
/**
* Get self with working_issuer_name.
*/
public function withWorkingIssuerName(Name $issuer): self
{
$state = clone $this;
$state->_workingIssuerName = $issuer;
return $state;
}
/**
* Get self with max_path_length.
*/
public function withMaxPathLength(int $length): self
{
$state = clone $this;
$state->_maxPathLength = $length;
return $state;
}
/**
* Get the certification path length (n).
*/
public function pathLength(): int
{
return $this->_pathLength;
}
/**
* Get the current index in certification path in the range of 1..n.
*/
public function index(): int
{
return $this->_index;
}
/**
* Check whether valid_policy_tree is present.
*/
public function hasValidPolicyTree(): bool
{
return isset($this->_validPolicyTree);
}
public function validPolicyTree(): PolicyTree
{
if (! $this->hasValidPolicyTree()) {
throw new LogicException('valid_policy_tree not set.');
}
return $this->_validPolicyTree;
}
/**
* Get the unevaluated intersection of the permitted subtrees, empty when no constraint applies.
*
* @return list<GeneralSubtrees>
*/
public function permittedSubtrees(): array
{
return $this->_permittedSubtrees;
}
/**
* Get the union of the excluded subtrees, null when no constraint applies.
*/
public function excludedSubtrees(): ?GeneralSubtrees
{
return $this->_excludedSubtrees;
}
public function explicitPolicy(): int
{
return $this->_explicitPolicy;
}
public function inhibitAnyPolicy(): int
{
return $this->_inhibitAnyPolicy;
}
public function policyMapping(): int
{
return $this->_policyMapping;
}
public function workingPublicKeyAlgorithm(): AlgorithmIdentifierType
{
return $this->_workingPublicKeyAlgorithm;
}
public function workingPublicKey(): PublicKeyInfo
{
return $this->_workingPublicKey;
}
public function workingPublicKeyParameters(): ?Element
{
return $this->_workingPublicKeyParameters;
}
public function workingIssuerName(): Name
{
return $this->_workingIssuerName;
}
/**
* Get maximum certification path length.
*/
public function maxPathLength(): int
{
return $this->_maxPathLength;
}
/**
* Check whether processing the final certificate of the certification path.
*/
public function isFinal(): bool
{
return $this->_index === $this->_pathLength;
}
/**
* Get the path validation result.
*
* @param Certificate[] $certificates Certificates in a certification path
*/
public function getResult(array $certificates): PathValidationResult
{
return PathValidationResult::create(
$certificates,
$this->_validPolicyTree,
$this->_workingPublicKey,
$this->_workingPublicKeyAlgorithm,
$this->_workingPublicKeyParameters
);
}
/**
* Get ASN.1 parameters from algorithm identifier.
*
* @return null|Element ASN.1 element or null if parameters are omitted
*/
public static function getAlgorithmParameters(AlgorithmIdentifierType $algo): ?Element
{
$seq = $algo->toASN1();
return $seq->has(1) ? $seq->at(1)
->asElement() : null;
}
}

View file

@ -0,0 +1,240 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\Policy;
use ArrayIterator;
use function count;
use Countable;
use function in_array;
use IteratorAggregate;
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyQualifierInfo;
/**
* Policy node class for certification path validation.
*
* @internal Mutable class used by PolicyTree
*
* @see https://tools.ietf.org/html/rfc5280#section-6.1.2
*/
final class PolicyNode implements IteratorAggregate, Countable
{
/**
* List of child nodes.
*
* @var PolicyNode[]
*/
private array $children;
/**
* Reference to the parent node.
*/
private PolicyNode|null $parent = null;
/**
* @param PolicyQualifierInfo[] $qualifiers
* @param string[] $expectedPolicies
*/
private function __construct(
private readonly string $validPolicy,
private readonly array $qualifiers,
private array $expectedPolicies
) {
$this->children = [];
}
/**
* @param PolicyQualifierInfo[] $qualifiers
* @param string[] $expectedPolicies
*/
public static function create(string $validPolicy, array $qualifiers, array $expectedPolicies): self
{
return new self($validPolicy, $qualifiers, $expectedPolicies);
}
/**
* Create initial node for the policy tree.
*/
public static function anyPolicyNode(): self
{
return self::create(PolicyInformation::OID_ANY_POLICY, [], [PolicyInformation::OID_ANY_POLICY]);
}
/**
* Get the valid policy OID.
*/
public function validPolicy(): string
{
return $this->validPolicy;
}
/**
* Check whether node has anyPolicy as a valid policy.
*/
public function isAnyPolicy(): bool
{
return $this->validPolicy === PolicyInformation::OID_ANY_POLICY;
}
/**
* Get the qualifier set.
*
* @return PolicyQualifierInfo[]
*/
public function qualifiers(): array
{
return $this->qualifiers;
}
/**
* Check whether node has OID as an expected policy.
*/
public function hasExpectedPolicy(string $oid): bool
{
return in_array($oid, $this->expectedPolicies, true);
}
/**
* Get the expected policy set.
*
* @return string[]
*/
public function expectedPolicies(): array
{
return $this->expectedPolicies;
}
/**
* @param string ...$oids Policy OIDs
*/
public function setExpectedPolicies(string ...$oids): void
{
$this->expectedPolicies = $oids;
}
/**
* Check whether node has a child node with given valid policy OID.
*/
public function hasChildWithValidPolicy(string $oid): bool
{
foreach ($this->children as $node) {
if ($node->validPolicy() === $oid) {
return true;
}
}
return false;
}
/**
* Add child node.
*/
public function addChild(self $node): self
{
$id = spl_object_hash($node);
$node->parent = $this;
$this->children[$id] = $node;
return $this;
}
/**
* Get the child nodes.
*
* @return PolicyNode[]
*/
public function children(): array
{
return array_values($this->children);
}
/**
* Remove this node from the tree.
*
* @return self The removed node
*/
public function remove(): self
{
if ($this->parent !== null) {
$id = spl_object_hash($this);
unset($this->parent->children[$id], $this->parent);
}
return $this;
}
/**
* Check whether node has a parent.
*/
public function hasParent(): bool
{
return isset($this->parent);
}
/**
* Get the parent node.
*/
public function parent(): ?self
{
return $this->parent;
}
/**
* Get chain of parent nodes from this node's parent to the root node.
*
* @return PolicyNode[]
*/
public function parents(): array
{
if ($this->parent === null) {
return [];
}
$nodes = $this->parent->parents();
$nodes[] = $this->parent;
return array_reverse($nodes);
}
/**
* Walk tree from this node, applying a callback for each node.
*
* Nodes are traversed depth-first and callback shall be applied post-order.
*/
public function walkNodes(callable $fn): void
{
foreach ($this->children as $node) {
$node->walkNodes($fn);
}
$fn($this);
}
/**
* Get the total number of nodes in a tree.
*/
public function nodeCount(): int
{
$c = 1;
foreach ($this->children as $child) {
$c += $child->nodeCount();
}
return $c;
}
/**
* Get the number of child nodes.
*
* @see \Countable::count()
*/
public function count(): int
{
return count($this->children);
}
/**
* Get iterator for the child nodes.
*
* @see \IteratorAggregate::getIterator()
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->children);
}
}

View file

@ -0,0 +1,422 @@
<?php
declare(strict_types=1);
namespace SpomkyLabs\Pki\X509\CertificationPath\Policy;
use function count;
use function in_array;
use LogicException;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
use SpomkyLabs\Pki\X509\CertificationPath\Exception\PathValidationException;
use SpomkyLabs\Pki\X509\CertificationPath\PathValidation\ValidatorState;
final class PolicyTree
{
/**
* Maximum number of nodes the valid policy tree may hold.
*
* RFC 5280 places no bound on the tree, and it grows multiplicatively: a policy mapping gives a node an expected
* policy set of the size the issuing certificate chose, and the next certificate's anyPolicy then creates one
* child per expected policy per node. The width is multiplied at every level, so the tree is exponential in the
* path length with a base the attacker picks. Under half a megabyte of certificate policies reached a gigabyte
* of nodes, in a path whose every signature verifies.
*
* No legitimate path comes anywhere near this many nodes.
*/
private const MAX_NODES = 5000;
/**
* Number of nodes currently in the tree.
*/
private int $nodeCount;
/**
* @param PolicyNode $root Initial root node
*/
private function __construct(
private ?PolicyNode $root
) {
$this->nodeCount = $root === null ? 0 : $root->nodeCount();
}
public static function create(?PolicyNode $root): self
{
return new self($root);
}
/**
* Process policy information from the certificate.
*
* Certificate policies extension must be present.
*/
public function processPolicies(ValidatorState $state, Certificate $cert): ValidatorState
{
$policies = $cert->tbsCertificate()
->extensions()
->certificatePolicies();
$tree = clone $this;
// (d.1) for each policy P not equal to anyPolicy
foreach ($policies as $policy) {
/** @var PolicyInformation $policy */
if ($policy->isAnyPolicy()) {
$tree->processAnyPolicy($policy, $cert, $state);
} else {
$tree->processPolicy($policy, $state);
}
}
// if whole tree is pruned
if ($tree->pruneTree($state->index() - 1) === 0) {
return $state->withoutValidPolicyTree();
}
return $state->withValidPolicyTree($tree);
}
/**
* Process policy mappings from the certificate.
*/
public function processMappings(ValidatorState $state, Certificate $cert): ValidatorState
{
$tree = clone $this;
if ($state->policyMapping() > 0) {
$tree->_applyMappings($cert, $state);
} elseif ($state->policyMapping() === 0) {
$tree->_deleteMappings($cert, $state);
}
// if whole tree is pruned
if ($tree->root === null) {
return $state->withoutValidPolicyTree();
}
return $state->withValidPolicyTree($tree);
}
/**
* Calculate policy intersection as specified in Wrap-Up Procedure 6.1.5.g.
*
* @param array<string> $policies
*/
public function calculateIntersection(ValidatorState $state, array $policies): ValidatorState
{
$tree = clone $this;
$valid_policy_node_set = $tree->validPolicyNodeSet();
// 2. If the valid_policy of any node in the valid_policy_node_set
// is not in the user-initial-policy-set and is not anyPolicy,
// delete this node and all its children.
$valid_policy_node_set = array_filter(
$valid_policy_node_set,
function (PolicyNode $node) use ($policies) {
if ($node->isAnyPolicy()) {
return true;
}
if (in_array($node->validPolicy(), $policies, true)) {
return true;
}
$node->remove();
return false;
}
);
// array of valid policy OIDs
$valid_policy_set = array_map(static fn (PolicyNode $node) => $node->validPolicy(), $valid_policy_node_set);
// 3. If the valid_policy_tree includes a node of depth n with
// the valid_policy anyPolicy and the user-initial-policy-set
// is not any-policy
foreach ($tree->nodesAtDepth($state->index()) as $node) {
if ($node->hasParent() && $node->isAnyPolicy()) {
// a. Set P-Q to the qualifier_set in the node of depth n
// with valid_policy anyPolicy.
$pq = $node->qualifiers();
// b. For each P-OID in the user-initial-policy-set that is not
// the valid_policy of a node in the valid_policy_node_set,
// create a child node whose parent is the node of depth n-1
// with the valid_policy anyPolicy.
$poids = array_diff($policies, $valid_policy_set);
foreach ($tree->nodesAtDepth($state->index() - 1) as $parent) {
if ($parent->isAnyPolicy()) {
// Set the values in the child node as follows:
// set the valid_policy to P-OID, set the qualifier_set
// to P-Q, and set the expected_policy_set to {P-OID}.
foreach ($poids as $poid) {
$this->addNode($parent, PolicyNode::create($poid, $pq, [$poid]));
}
break;
}
}
// c. Delete the node of depth n with the
// valid_policy anyPolicy.
$node->remove();
}
}
// 4. If there is a node in the valid_policy_tree of depth n-1 or less
// without any child nodes, delete that node. Repeat this step until
// there are no nodes of depth n-1 or less without children.
if ($tree->pruneTree($state->index() - 1) === 0) {
return $state->withoutValidPolicyTree();
}
return $state->withValidPolicyTree($tree);
}
/**
* Get policies at given policy tree depth.
*
* @param int $i Depth in range 1..n
*
* @return PolicyInformation[]
*/
public function policiesAtDepth(int $i): array
{
$policies = [];
foreach ($this->nodesAtDepth($i) as $node) {
$policies[] = PolicyInformation::create($node->validPolicy(), ...$node->qualifiers());
}
return $policies;
}
/**
* Process single policy information.
*/
private function processPolicy(PolicyInformation $policy, ValidatorState $state): void
{
$p_oid = $policy->oid();
$i = $state->index();
$match_count = 0;
// (d.1.i) for each node of depth i-1 in the valid_policy_tree...
foreach ($this->nodesAtDepth($i - 1) as $node) {
// ...where P-OID is in the expected_policy_set
if ($node->hasExpectedPolicy($p_oid)) {
$this->addNode($node, PolicyNode::create($p_oid, $policy->qualifiers(), [$p_oid]));
++$match_count;
}
}
// (d.1.ii) if there was no match in step (i)...
if ($match_count === 0) {
// ...and the valid_policy_tree includes a node of depth i-1 with
// the valid_policy anyPolicy
foreach ($this->nodesAtDepth($i - 1) as $node) {
if ($node->isAnyPolicy()) {
$this->addNode($node, PolicyNode::create($p_oid, $policy->qualifiers(), [$p_oid]));
}
}
}
}
/**
* Process anyPolicy policy information.
*/
private function processAnyPolicy(PolicyInformation $policy, Certificate $cert, ValidatorState $state): void
{
$i = $state->index();
// if (a) inhibit_anyPolicy is greater than 0 or
// (b) i<n and the certificate is self-issued
if (! ($state->inhibitAnyPolicy() > 0 ||
($i < $state->pathLength() && $cert->isSelfIssued()))) {
return;
}
// for each node in the valid_policy_tree of depth i-1
foreach ($this->nodesAtDepth($i - 1) as $node) {
// for each value in the expected_policy_set
foreach ($node->expectedPolicies() as $p_oid) {
// that does not appear in a child node
if (! $node->hasChildWithValidPolicy($p_oid)) {
$this->addNode($node, PolicyNode::create($p_oid, $policy->qualifiers(), [$p_oid]));
}
}
}
}
/**
* Apply policy mappings to the policy tree.
*/
private function _applyMappings(Certificate $cert, ValidatorState $state): void
{
$policy_mappings = $cert->tbsCertificate()
->extensions()
->policyMappings();
// (6.1.4. b.1.) for each node in the valid_policy_tree of depth i...
foreach ($policy_mappings->flattenedMappings() as $idp => $sdps) {
$match_count = 0;
foreach ($this->nodesAtDepth($state->index()) as $node) {
// ...where ID-P is the valid_policy
if ($node->validPolicy() === $idp) {
// set expected_policy_set to the set of subjectDomainPolicy
// values that are specified as equivalent to ID-P by
// the policy mappings extension
$node->setExpectedPolicies(...$sdps);
++$match_count;
}
}
// if no node of depth i in the valid_policy_tree has
// a valid_policy of ID-P...
if ($match_count === 0) {
$this->_applyAnyPolicyMapping($cert, $state, $idp, $sdps);
}
}
}
/**
* Apply anyPolicy mapping to the policy tree as specified in 6.1.4 (b)(1).
*
* @param string $idp OID of the issuer domain policy
* @param array<string> $sdps Array of subject domain policy OIDs
*/
private function _applyAnyPolicyMapping(
Certificate $cert,
ValidatorState $state,
string $idp,
array $sdps
): void {
// (6.1.4. b.1.) ...but there is a node of depth i with
// a valid_policy of anyPolicy
foreach ($this->nodesAtDepth($state->index()) as $node) {
if ($node->isAnyPolicy()) {
// then generate a child node of the node of depth i-1
// that has a valid_policy of anyPolicy as follows...
foreach ($this->nodesAtDepth($state->index() - 1) as $subnode) {
if ($subnode->isAnyPolicy()) {
// try to fetch qualifiers of anyPolicy certificate policy
try {
$qualifiers = $cert->tbsCertificate()
->extensions()
->certificatePolicies()
->anyPolicy()
->qualifiers();
} catch (LogicException) {
// if there's no policies or no qualifiers
$qualifiers = [];
}
$this->addNode($subnode, PolicyNode::create($idp, $qualifiers, $sdps));
// bail after first anyPolicy has been processed
break;
}
}
// bail after first anyPolicy has been processed
break;
}
}
}
/**
* Delete nodes as specified in 6.1.4 (b)(2).
*/
private function _deleteMappings(Certificate $cert, ValidatorState $state): void
{
$idps = $cert->tbsCertificate()
->extensions()
->policyMappings()
->issuerDomainPolicies();
// delete each node of depth i in the valid_policy_tree
// where ID-P is the valid_policy
foreach ($this->nodesAtDepth($state->index()) as $node) {
if (in_array($node->validPolicy(), $idps, true)) {
$node->remove();
}
}
$this->pruneTree($state->index() - 1);
}
/**
* Prune tree starting from given depth.
*
* @return int The number of nodes left in a tree
*/
private function pruneTree(int $depth): int
{
if ($this->root === null) {
return 0;
}
for ($i = $depth; $i > 0; --$i) {
foreach ($this->nodesAtDepth($i) as $node) {
if (count($node) === 0) {
$node->remove();
}
}
}
// if root has no children left
if (count($this->root) === 0) {
$this->root = null;
return 0;
}
return $this->root->nodeCount();
}
/**
* Attach a node to the tree, refusing to let it grow past the bound.
*
* @throws PathValidationException If the tree has grown past MAX_NODES.
*/
private function addNode(PolicyNode $parent, PolicyNode $child): void
{
if (++$this->nodeCount > self::MAX_NODES) {
throw new PathValidationException('Certificate policy tree is too large.');
}
$parent->addChild($child);
}
/**
* Get all nodes at given depth.
*
* @return PolicyNode[]
*/
private function nodesAtDepth(int $i): array
{
if ($this->root === null) {
return [];
}
$depth = 0;
$nodes = [$this->root];
while ($depth < $i) {
$nodes = self::gatherChildren(...$nodes);
if (count($nodes) === 0) {
break;
}
++$depth;
}
return $nodes;
}
/**
* Get the valid policy node set as specified in spec 6.1.5.(g)(iii)1.
*
* @return PolicyNode[]
*/
private function validPolicyNodeSet(): array
{
// 1. Determine the set of policy nodes whose parent nodes have
// a valid_policy of anyPolicy. This is the valid_policy_node_set.
$set = [];
if ($this->root === null) {
return $set;
}
// for each node in a tree
$this->root->walkNodes(
function (PolicyNode $node) use (&$set) {
$parents = $node->parents();
// node has parents
if (count($parents) !== 0) {
// check that each ancestor is an anyPolicy node
foreach ($parents as $ancestor) {
if (! $ancestor->isAnyPolicy()) {
return;
}
}
$set[] = $node;
}
}
);
return $set;
}
/**
* Gather all children of given nodes to a flattened array.
*
* @return PolicyNode[]
*/
private static function gatherChildren(PolicyNode ...$nodes): array
{
$children = [];
foreach ($nodes as $node) {
$children = array_merge($children, $node->children());
}
return $children;
}
}