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
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:
parent
7197eaebf2
commit
9c0f8de791
15771 changed files with 1564103 additions and 5 deletions
69
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttCertIssuer.php
vendored
Normal file
69
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttCertIssuer.php
vendored
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Name;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Certificate;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\DirectoryName;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Base class implementing *AttCertIssuer* ASN.1 CHOICE type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
*/
|
||||
abstract class AttCertIssuer
|
||||
{
|
||||
/**
|
||||
* Generate ASN.1 element.
|
||||
*/
|
||||
abstract public function toASN1(): Element;
|
||||
|
||||
/**
|
||||
* Check whether AttCertIssuer identifies given certificate.
|
||||
*/
|
||||
abstract public function identifiesPKC(Certificate $cert): bool;
|
||||
|
||||
/**
|
||||
* Initialize from distinguished name.
|
||||
*
|
||||
* This conforms to RFC 5755 which states that only v2Form must be used, and issuerName must contain exactly one
|
||||
* GeneralName of DirectoryName type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.2.3
|
||||
*/
|
||||
public static function fromName(Name $name): self
|
||||
{
|
||||
return V2Form::create(GeneralNames::create(DirectoryName::create($name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from an issuer's public key certificate.
|
||||
*/
|
||||
public static function fromPKC(Certificate $cert): self
|
||||
{
|
||||
return self::fromName($cert->tbsCertificate()->subject());
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*
|
||||
* @param UnspecifiedType $el CHOICE
|
||||
*/
|
||||
public static function fromASN1(UnspecifiedType $el): self
|
||||
{
|
||||
if (! $el->isTagged()) {
|
||||
throw new UnexpectedValueException('v1Form issuer not supported.');
|
||||
}
|
||||
$tagged = $el->asTagged();
|
||||
return match ($tagged->tag()) {
|
||||
0 => V2Form::fromV2ASN1($tagged->asImplicit(Element::TYPE_SEQUENCE)->asSequence()),
|
||||
default => throw new UnexpectedValueException('Unsupported issuer type.'),
|
||||
};
|
||||
}
|
||||
}
|
||||
86
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttCertValidityPeriod.php
vendored
Normal file
86
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttCertValidityPeriod.php
vendored
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\GeneralizedTime;
|
||||
use SpomkyLabs\Pki\X509\Feature\DateTimeHelper;
|
||||
|
||||
/**
|
||||
* Implements *AttCertValidityPeriod* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
*/
|
||||
final class AttCertValidityPeriod
|
||||
{
|
||||
use DateTimeHelper;
|
||||
|
||||
private function __construct(
|
||||
private readonly DateTimeImmutable $notBeforeTime,
|
||||
private readonly DateTimeImmutable $notAfterTime
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(DateTimeImmutable $notBeforeTime, DateTimeImmutable $notAfterTime): self
|
||||
{
|
||||
return new self($notBeforeTime, $notAfterTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$nb = $seq->at(0)
|
||||
->asGeneralizedTime()
|
||||
->dateTime();
|
||||
$na = $seq->at(1)
|
||||
->asGeneralizedTime()
|
||||
->dateTime();
|
||||
return self::create($nb, $na);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from date strings.
|
||||
*
|
||||
* @param null|string $nb_date Not before date
|
||||
* @param null|string $na_date Not after date
|
||||
* @param null|string $tz Timezone string
|
||||
*/
|
||||
public static function fromStrings(?string $nb_date, ?string $na_date, ?string $tz = null): self
|
||||
{
|
||||
$nb = self::createDateTime($nb_date, $tz);
|
||||
$na = self::createDateTime($na_date, $tz);
|
||||
return self::create($nb, $na);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get not before time.
|
||||
*/
|
||||
public function notBeforeTime(): DateTimeImmutable
|
||||
{
|
||||
return $this->notBeforeTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get not after time.
|
||||
*/
|
||||
public function notAfterTime(): DateTimeImmutable
|
||||
{
|
||||
return $this->notAfterTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create(
|
||||
GeneralizedTime::create($this->notBeforeTime),
|
||||
GeneralizedTime::create($this->notAfterTime)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* Implements value for 'Access Identity' attribute.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4.2
|
||||
*/
|
||||
final class AccessIdentityAttributeValue extends SvceAuthInfo
|
||||
{
|
||||
public const OID = '1.3.6.1.5.5.7.10.2';
|
||||
|
||||
private function __construct(GeneralName $service, GeneralName $ident, ?string $authInfo)
|
||||
{
|
||||
parent::__construct(self::OID, $service, $ident, $authInfo);
|
||||
}
|
||||
|
||||
public static function create(GeneralName $service, GeneralName $ident, ?string $_authInfo = null): self
|
||||
{
|
||||
return new self($service, $ident, $_authInfo);
|
||||
}
|
||||
|
||||
public static function fromASN1(UnspecifiedType $el): static
|
||||
{
|
||||
$seq = $el->asSequence();
|
||||
$service = GeneralName::fromASN1($seq->at(0)->asTagged());
|
||||
$ident = GeneralName::fromASN1($seq->at(1)->asTagged());
|
||||
$auth_info = null;
|
||||
if ($seq->has(2, Element::TYPE_OCTET_STRING)) {
|
||||
$auth_info = $seq->at(2)
|
||||
->asString()
|
||||
->string();
|
||||
}
|
||||
return static::create($service, $ident, $auth_info);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* Implements value for 'Service Authentication Information' attribute.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4.1
|
||||
*/
|
||||
final class AuthenticationInfoAttributeValue extends SvceAuthInfo
|
||||
{
|
||||
public const OID = '1.3.6.1.5.5.7.10.1';
|
||||
|
||||
private function __construct(GeneralName $service, GeneralName $ident, ?string $auth_info)
|
||||
{
|
||||
parent::__construct(self::OID, $service, $ident, $auth_info);
|
||||
}
|
||||
|
||||
public static function create(GeneralName $service, GeneralName $ident, ?string $auth_info = null): self
|
||||
{
|
||||
return new self($service, $ident, $auth_info);
|
||||
}
|
||||
|
||||
public static function fromASN1(UnspecifiedType $el): static
|
||||
{
|
||||
$seq = $el->asSequence();
|
||||
$service = GeneralName::fromASN1($seq->at(0)->asTagged());
|
||||
$ident = GeneralName::fromASN1($seq->at(1)->asTagged());
|
||||
$auth_info = null;
|
||||
if ($seq->has(2, Element::TYPE_OCTET_STRING)) {
|
||||
$auth_info = $seq->at(2)
|
||||
->asString()
|
||||
->string();
|
||||
}
|
||||
return static::create($service, $ident, $auth_info);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
/**
|
||||
* Implements value for 'Charging Identity' attribute.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4.3
|
||||
*/
|
||||
final class ChargingIdentityAttributeValue extends IetfAttrSyntax
|
||||
{
|
||||
public const OID = '1.3.6.1.5.5.7.10.3';
|
||||
|
||||
public static function create(IetfAttrValue ...$values): self
|
||||
{
|
||||
return new self(self::OID, ...$values);
|
||||
}
|
||||
}
|
||||
20
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/GroupAttributeValue.php
vendored
Normal file
20
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/GroupAttributeValue.php
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
/**
|
||||
* Implements value for 'Group' attribute.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4.4
|
||||
*/
|
||||
final class GroupAttributeValue extends IetfAttrSyntax
|
||||
{
|
||||
public const OID = '1.3.6.1.5.5.7.10.4';
|
||||
|
||||
public static function create(IetfAttrValue ...$values): self
|
||||
{
|
||||
return new self(self::OID, ...$values);
|
||||
}
|
||||
}
|
||||
171
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/IetfAttrSyntax.php
vendored
Normal file
171
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/IetfAttrSyntax.php
vendored
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\BinaryMatch;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\MatchingRule;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
|
||||
/**
|
||||
* Base class implementing *IetfAttrSyntax* ASN.1 type used by attribute certificate attribute values.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4
|
||||
*/
|
||||
abstract class IetfAttrSyntax extends AttributeValue implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Policy authority.
|
||||
*/
|
||||
protected ?GeneralNames $_policyAuthority;
|
||||
|
||||
/**
|
||||
* Values.
|
||||
*
|
||||
* @var IetfAttrValue[]
|
||||
*/
|
||||
protected array $_values;
|
||||
|
||||
protected function __construct(string $oid, IetfAttrValue ...$values)
|
||||
{
|
||||
parent::__construct($oid);
|
||||
$this->_policyAuthority = null;
|
||||
$this->_values = $values;
|
||||
}
|
||||
|
||||
abstract public static function create(IetfAttrValue ...$values): self;
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromASN1(UnspecifiedType $el): AttributeValue
|
||||
{
|
||||
$seq = $el->asSequence();
|
||||
$authority = null;
|
||||
$idx = 0;
|
||||
if ($seq->hasTagged(0)) {
|
||||
$authority = GeneralNames::fromASN1(
|
||||
$seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
++$idx;
|
||||
}
|
||||
$values = array_map(IetfAttrValue::fromASN1(...), $seq->at($idx)->asSequence()->elements());
|
||||
$obj = static::create(...$values);
|
||||
$obj->_policyAuthority = $authority;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with policy authority.
|
||||
*/
|
||||
public function withPolicyAuthority(GeneralNames $names): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->_policyAuthority = $names;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether policy authority is present.
|
||||
*/
|
||||
public function hasPolicyAuthority(): bool
|
||||
{
|
||||
return isset($this->_policyAuthority);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get policy authority.
|
||||
*/
|
||||
public function policyAuthority(): GeneralNames
|
||||
{
|
||||
if (! $this->hasPolicyAuthority()) {
|
||||
throw new LogicException('policyAuthority not set.');
|
||||
}
|
||||
return $this->_policyAuthority;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get values.
|
||||
*
|
||||
* @return IetfAttrValue[]
|
||||
*/
|
||||
public function values(): array
|
||||
{
|
||||
return $this->_values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get first value.
|
||||
*/
|
||||
public function first(): IetfAttrValue
|
||||
{
|
||||
if (count($this->_values) === 0) {
|
||||
throw new LogicException('No values.');
|
||||
}
|
||||
return $this->_values[0];
|
||||
}
|
||||
|
||||
public function toASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->_policyAuthority)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, $this->_policyAuthority->toASN1());
|
||||
}
|
||||
$values = array_map(static fn (IetfAttrValue $val) => $val->toASN1(), $this->_values);
|
||||
$elements[] = Sequence::create(...$values);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
public function stringValue(): string
|
||||
{
|
||||
return '#' . bin2hex($this->toASN1()->toDER());
|
||||
}
|
||||
|
||||
public function equalityMatchingRule(): MatchingRule
|
||||
{
|
||||
return new BinaryMatch();
|
||||
}
|
||||
|
||||
public function rfc2253String(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of values.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->_values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for values.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->_values);
|
||||
}
|
||||
|
||||
protected function _transcodedString(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
}
|
||||
128
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/IetfAttrValue.php
vendored
Normal file
128
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/IetfAttrValue.php
vendored
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\UTF8String;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use Stringable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *IetfAttrSyntax.values* ASN.1 CHOICE type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4
|
||||
*/
|
||||
final class IetfAttrValue implements Stringable
|
||||
{
|
||||
private function __construct(
|
||||
private readonly string $value,
|
||||
private readonly int $type
|
||||
) {
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public static function create(string $value, int $type): self
|
||||
{
|
||||
return new self($value, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(UnspecifiedType $el): self
|
||||
{
|
||||
return match ($el->tag()) {
|
||||
Element::TYPE_OCTET_STRING, Element::TYPE_UTF8_STRING => self::create(
|
||||
$el->asString()
|
||||
->string(),
|
||||
$el->tag()
|
||||
),
|
||||
Element::TYPE_OBJECT_IDENTIFIER => self::create($el->asObjectIdentifier()->oid(), $el->tag()),
|
||||
default => throw new UnexpectedValueException('Type ' . Element::tagToName($el->tag()) . ' not supported.'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from octet string.
|
||||
*/
|
||||
public static function fromOctets(string $octets): self
|
||||
{
|
||||
return self::create($octets, Element::TYPE_OCTET_STRING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from UTF-8 string.
|
||||
*/
|
||||
public static function fromString(string $str): self
|
||||
{
|
||||
return self::create($str, Element::TYPE_UTF8_STRING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from OID.
|
||||
*/
|
||||
public static function fromOID(string $oid): self
|
||||
{
|
||||
return self::create($oid, Element::TYPE_OBJECT_IDENTIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get type tag.
|
||||
*/
|
||||
public function type(): int
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether value type is octets.
|
||||
*/
|
||||
public function isOctets(): bool
|
||||
{
|
||||
return $this->type === Element::TYPE_OCTET_STRING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether value type is OID.
|
||||
*/
|
||||
public function isOID(): bool
|
||||
{
|
||||
return $this->type === Element::TYPE_OBJECT_IDENTIFIER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether value type is string.
|
||||
*/
|
||||
public function isString(): bool
|
||||
{
|
||||
return $this->type === Element::TYPE_UTF8_STRING;
|
||||
}
|
||||
|
||||
public function value(): string
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Element
|
||||
{
|
||||
return match ($this->type) {
|
||||
Element::TYPE_OCTET_STRING => OctetString::create($this->value),
|
||||
Element::TYPE_UTF8_STRING => UTF8String::create($this->value),
|
||||
Element::TYPE_OBJECT_IDENTIFIER => ObjectIdentifier::create($this->value),
|
||||
default => throw new LogicException('Type ' . Element::tagToName($this->type) . ' not supported.'),
|
||||
};
|
||||
}
|
||||
}
|
||||
129
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/RoleAttributeValue.php
vendored
Normal file
129
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/RoleAttributeValue.php
vendored
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\BinaryMatch;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\MatchingRule;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\UniformResourceIdentifier;
|
||||
|
||||
/**
|
||||
* Implements value for 'Role' attribute.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4.5
|
||||
*/
|
||||
final class RoleAttributeValue extends AttributeValue
|
||||
{
|
||||
/**
|
||||
* @param GeneralName $roleName Role name
|
||||
* @param null|GeneralNames $roleAuthority Issuing authority
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly GeneralName $roleName,
|
||||
private readonly ?GeneralNames $roleAuthority
|
||||
) {
|
||||
parent::__construct(AttributeType::OID_ROLE);
|
||||
}
|
||||
|
||||
public static function create(GeneralName $roleName, ?GeneralNames $roleAuthority = null): self
|
||||
{
|
||||
return new self($roleName, $roleAuthority);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from a role string.
|
||||
*
|
||||
* @param string $role_name Role name in URI format
|
||||
* @param null|GeneralNames $authority Issuing authority
|
||||
*/
|
||||
public static function fromString(string $role_name, ?GeneralNames $authority = null): self
|
||||
{
|
||||
return self::create(UniformResourceIdentifier::create($role_name), $authority);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromASN1(UnspecifiedType $el): AttributeValue
|
||||
{
|
||||
$seq = $el->asSequence();
|
||||
$authority = null;
|
||||
if ($seq->hasTagged(0)) {
|
||||
$authority = GeneralNames::fromASN1(
|
||||
$seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
}
|
||||
$name = GeneralName::fromASN1($seq->getTagged(1)->asExplicit()->asTagged());
|
||||
return self::create($name, $authority);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether issuing authority is present.
|
||||
*/
|
||||
public function hasRoleAuthority(): bool
|
||||
{
|
||||
return isset($this->roleAuthority);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get issuing authority.
|
||||
*/
|
||||
public function roleAuthority(): GeneralNames
|
||||
{
|
||||
if (! $this->hasRoleAuthority()) {
|
||||
throw new LogicException('roleAuthority not set.');
|
||||
}
|
||||
return $this->roleAuthority;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get role name.
|
||||
*/
|
||||
public function roleName(): GeneralName
|
||||
{
|
||||
return $this->roleName;
|
||||
}
|
||||
|
||||
public function toASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->roleAuthority)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, $this->roleAuthority->toASN1());
|
||||
}
|
||||
$elements[] = ExplicitlyTaggedType::create(1, $this->roleName->toASN1());
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
public function stringValue(): string
|
||||
{
|
||||
return '#' . bin2hex($this->toASN1()->toDER());
|
||||
}
|
||||
|
||||
public function equalityMatchingRule(): MatchingRule
|
||||
{
|
||||
return new BinaryMatch();
|
||||
}
|
||||
|
||||
public function rfc2253String(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
|
||||
protected function _transcodedString(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
}
|
||||
95
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/SvceAuthInfo.php
vendored
Normal file
95
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attribute/SvceAuthInfo.php
vendored
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Attribute;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\BinaryMatch;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\MatchingRule;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* Base class implementing *SvceAuthInfo* ASN.1 type used by attribute certificate attribute values.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.4.1
|
||||
*/
|
||||
abstract class SvceAuthInfo extends AttributeValue
|
||||
{
|
||||
protected function __construct(
|
||||
string $oid,
|
||||
private readonly GeneralName $service,
|
||||
private readonly GeneralName $ident,
|
||||
private readonly ?string $authInfo = null
|
||||
) {
|
||||
parent::__construct($oid);
|
||||
}
|
||||
|
||||
abstract public static function fromASN1(UnspecifiedType $el): static;
|
||||
|
||||
/**
|
||||
* Get service name.
|
||||
*/
|
||||
public function service(): GeneralName
|
||||
{
|
||||
return $this->service;
|
||||
}
|
||||
|
||||
public function ident(): GeneralName
|
||||
{
|
||||
return $this->ident;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether authentication info is present.
|
||||
*/
|
||||
public function hasAuthInfo(): bool
|
||||
{
|
||||
return isset($this->authInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentication info.
|
||||
*/
|
||||
public function authInfo(): string
|
||||
{
|
||||
if (! $this->hasAuthInfo()) {
|
||||
throw new LogicException('authInfo not set.');
|
||||
}
|
||||
return $this->authInfo;
|
||||
}
|
||||
|
||||
public function toASN1(): Element
|
||||
{
|
||||
$elements = [$this->service->toASN1(), $this->ident->toASN1()];
|
||||
if (isset($this->authInfo)) {
|
||||
$elements[] = OctetString::create($this->authInfo);
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
public function stringValue(): string
|
||||
{
|
||||
return '#' . bin2hex($this->toASN1()->toDER());
|
||||
}
|
||||
|
||||
public function equalityMatchingRule(): MatchingRule
|
||||
{
|
||||
return new BinaryMatch();
|
||||
}
|
||||
|
||||
public function rfc2253String(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
|
||||
protected function _transcodedString(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
}
|
||||
208
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttributeCertificate.php
vendored
Normal file
208
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttributeCertificate.php
vendored
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use RuntimeException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\CryptoBridge\Crypto;
|
||||
use SpomkyLabs\Pki\CryptoEncoding\PEM;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Signature\Signature;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Certificate;
|
||||
use SpomkyLabs\Pki\X509\Feature\SignedDER;
|
||||
use Stringable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *AttributeCertificate* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
*/
|
||||
final class AttributeCertificate implements Stringable
|
||||
{
|
||||
use SignedDER;
|
||||
|
||||
/**
|
||||
* @param AttributeCertificateInfo $acInfo Attribute certificate information.
|
||||
* @param SignatureAlgorithmIdentifier $signatureAlgorithm Signature algorithm.
|
||||
* @param Signature $signatureValue Signature value.
|
||||
* @param null|string $acInfoDER Encoding of the acinfo as it was received, when decoded from DER.
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly AttributeCertificateInfo $acInfo,
|
||||
private readonly SignatureAlgorithmIdentifier $signatureAlgorithm,
|
||||
private readonly Signature $signatureValue,
|
||||
private readonly ?string $acInfoDER = null
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attribute certificate as a PEM formatted string.
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toPEM()
|
||||
->string();
|
||||
}
|
||||
|
||||
public static function create(
|
||||
AttributeCertificateInfo $acInfo,
|
||||
SignatureAlgorithmIdentifier $signatureAlgorithm,
|
||||
Signature $signatureValue
|
||||
): self {
|
||||
return new self($acInfo, $signatureAlgorithm, $signatureValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$acinfo = AttributeCertificateInfo::fromASN1($seq->at(0)->asSequence());
|
||||
$algo = AlgorithmIdentifier::fromASN1($seq->at(1)->asSequence());
|
||||
if (! $algo instanceof SignatureAlgorithmIdentifier) {
|
||||
throw new UnexpectedValueException('Unsupported signature algorithm ' . $algo->oid() . '.');
|
||||
}
|
||||
// RFC 5755 section 4.1: signatureAlgorithm sits outside the signed part, so anyone can change it. It must
|
||||
// repeat the algorithm of the acinfo, which is signed.
|
||||
if ($algo->oid() !== $acinfo->signature()->oid()) {
|
||||
throw new UnexpectedValueException(
|
||||
'Signature algorithm ' . $algo->oid() . ' does not match the algorithm ' .
|
||||
$acinfo->signature()
|
||||
->oid() . ' of the acinfo.'
|
||||
);
|
||||
}
|
||||
$signature = Signature::fromSignatureData($seq->at(2)->asBitString()->string(), $algo);
|
||||
return self::create($acinfo, $algo, $signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from DER data.
|
||||
*/
|
||||
public static function fromDER(string $data): self
|
||||
{
|
||||
[$seq, $acInfoDER] = self::decodeSignedDER($data, 'AttributeCertificate');
|
||||
$ac = self::fromASN1($seq);
|
||||
// Keep the acinfo exactly as it arrived, so that verify() checks the signature over the bytes the issuer
|
||||
// signed rather than over what the parser produced.
|
||||
return new self($ac->acInfo, $ac->signatureAlgorithm, $ac->signatureValue, $acInfoDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from PEM.
|
||||
*/
|
||||
public static function fromPEM(PEM $pem): self
|
||||
{
|
||||
if ($pem->type() !== PEM::TYPE_ATTRIBUTE_CERTIFICATE) {
|
||||
throw new UnexpectedValueException('Invalid PEM type.');
|
||||
}
|
||||
return self::fromDER($pem->data());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attribute certificate info.
|
||||
*/
|
||||
public function acinfo(): AttributeCertificateInfo
|
||||
{
|
||||
return $this->acInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signature algorithm identifier.
|
||||
*/
|
||||
public function signatureAlgorithm(): SignatureAlgorithmIdentifier
|
||||
{
|
||||
return $this->signatureAlgorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signature value.
|
||||
*/
|
||||
public function signatureValue(): Signature
|
||||
{
|
||||
return $this->signatureValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create(
|
||||
$this->acInfo->toASN1(),
|
||||
$this->signatureAlgorithm->toASN1(),
|
||||
$this->signatureValue->bitString()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attribute certificate as a DER.
|
||||
*/
|
||||
public function toDER(): string
|
||||
{
|
||||
return $this->toASN1()
|
||||
->toDER();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attribute certificate as a PEM.
|
||||
*/
|
||||
public function toPEM(): PEM
|
||||
{
|
||||
return PEM::create(PEM::TYPE_ATTRIBUTE_CERTIFICATE, $this->toDER());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether attribute certificate is issued to the subject identified by given public key certificate.
|
||||
*
|
||||
* @param Certificate $cert Certificate
|
||||
*/
|
||||
public function isHeldBy(Certificate $cert): bool
|
||||
{
|
||||
if (! $this->acInfo->holder()->identifiesPKC($cert)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether attribute certificate is issued by given public key certificate.
|
||||
*
|
||||
* @param Certificate $cert Certificate
|
||||
*/
|
||||
public function isIssuedBy(Certificate $cert): bool
|
||||
{
|
||||
if (! $this->acInfo->issuer()->identifiesPKC($cert)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify signature.
|
||||
*
|
||||
* @param PublicKeyInfo $pubkey_info Signer's public key
|
||||
* @param null|Crypto $crypto Crypto engine, use default if not set
|
||||
*/
|
||||
public function verify(PublicKeyInfo $pubkey_info, ?Crypto $crypto = null): bool
|
||||
{
|
||||
$crypto ??= Crypto::getDefault();
|
||||
// An attribute certificate built in memory was never received as bytes; re-encoding it is then the only
|
||||
// option, and the correct one.
|
||||
$data = $this->acInfoDER ?? $this->acInfo->toASN1()
|
||||
->toDER();
|
||||
// a bool returning predicate must not throw on a signature it cannot check: the algorithm is named by
|
||||
// the certificate, so an attacker picks it, and `if (! $cert->verify($key))` in application code would
|
||||
// otherwise become an unhandled fatal. An unsupported algorithm, a key the algorithm does not match and
|
||||
// an engine level failure all mean the same thing to the caller: the signature was not verified.
|
||||
try {
|
||||
return $crypto->verify($data, $this->signatureValue, $pubkey_info, $this->signatureAlgorithm);
|
||||
} catch (RuntimeException|UnexpectedValueException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
411
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttributeCertificateInfo.php
vendored
Normal file
411
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/AttributeCertificateInfo.php
vendored
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use Brick\Math\BigInteger;
|
||||
use function chr;
|
||||
use function count;
|
||||
use const E_USER_DEPRECATED;
|
||||
use InvalidArgumentException;
|
||||
use LogicException;
|
||||
use function ord;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\CryptoBridge\Crypto;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKeyInfo;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Extension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extensions;
|
||||
use SpomkyLabs\Pki\X509\Certificate\UniqueIdentifier;
|
||||
use function sprintf;
|
||||
use function strval;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *AttributeCertificateInfo* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
*/
|
||||
final class AttributeCertificateInfo
|
||||
{
|
||||
public const VERSION_2 = 1;
|
||||
|
||||
/**
|
||||
* AC version.
|
||||
*/
|
||||
private readonly int $version;
|
||||
|
||||
/**
|
||||
* Signature algorithm identifier.
|
||||
*/
|
||||
private ?SignatureAlgorithmIdentifier $signature = null;
|
||||
|
||||
/**
|
||||
* AC serial number as a base 10 integer.
|
||||
*/
|
||||
private ?string $serialNumber = null;
|
||||
|
||||
/**
|
||||
* Issuer unique identifier.
|
||||
*/
|
||||
private ?UniqueIdentifier $issuerUniqueID = null;
|
||||
|
||||
/**
|
||||
* Extensions.
|
||||
*/
|
||||
private Extensions $extensions;
|
||||
|
||||
/**
|
||||
* @param Holder $holder AC holder
|
||||
* @param AttCertIssuer $issuer AC issuer
|
||||
* @param AttCertValidityPeriod $attrCertValidityPeriod Validity
|
||||
* @param Attributes $attributes Attributes
|
||||
*/
|
||||
private function __construct(
|
||||
private Holder $holder,
|
||||
private AttCertIssuer $issuer,
|
||||
private AttCertValidityPeriod $attrCertValidityPeriod,
|
||||
private Attributes $attributes
|
||||
) {
|
||||
$this->version = self::VERSION_2;
|
||||
$this->extensions = Extensions::create();
|
||||
}
|
||||
|
||||
/**
|
||||
* Smallest random serial number that meets the CA/Browser Forum Baseline Requirements, in octets.
|
||||
*
|
||||
* They ask for at least 64 bits of CSPRNG output. The sign bit costs one, so eight octets fall just short
|
||||
* and nine are needed. Smaller sizes are still accepted, with a deprecation notice.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const MIN_RANDOM_SERIAL_SIZE = 9;
|
||||
|
||||
/**
|
||||
* Default random serial number size, in octets. RFC 5280 section 4.1.2.2 caps serial numbers at 20 octets.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const DEFAULT_RANDOM_SERIAL_SIZE = 20;
|
||||
|
||||
public static function create(
|
||||
Holder $holder,
|
||||
AttCertIssuer $issuer,
|
||||
AttCertValidityPeriod $attrCertValidityPeriod,
|
||||
Attributes $attributes
|
||||
): self {
|
||||
return new self($holder, $issuer, $attrCertValidityPeriod, $attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$idx = 0;
|
||||
$version = $seq->at($idx++)
|
||||
->asInteger()
|
||||
->intNumber();
|
||||
if ($version !== self::VERSION_2) {
|
||||
throw new UnexpectedValueException('Version must be 2.');
|
||||
}
|
||||
$holder = Holder::fromASN1($seq->at($idx++)->asSequence());
|
||||
$issuer = AttCertIssuer::fromASN1($seq->at($idx++));
|
||||
$signature = AlgorithmIdentifier::fromASN1($seq->at($idx++)->asSequence());
|
||||
if (! $signature instanceof SignatureAlgorithmIdentifier) {
|
||||
throw new UnexpectedValueException('Unsupported signature algorithm ' . $signature->oid() . '.');
|
||||
}
|
||||
$serial = $seq->at($idx++)
|
||||
->asInteger()
|
||||
->number();
|
||||
$validity = AttCertValidityPeriod::fromASN1($seq->at($idx++)->asSequence());
|
||||
$attribs = Attributes::fromASN1($seq->at($idx++)->asSequence());
|
||||
$obj = self::create($holder, $issuer, $validity, $attribs);
|
||||
$obj->signature = $signature;
|
||||
$obj->serialNumber = $serial;
|
||||
if ($seq->has($idx, Element::TYPE_BIT_STRING)) {
|
||||
$obj->issuerUniqueID = UniqueIdentifier::fromASN1($seq->at($idx++)->asBitString());
|
||||
}
|
||||
if ($seq->has($idx, Element::TYPE_SEQUENCE)) {
|
||||
$obj->extensions = Extensions::fromASN1($seq->at($idx)->asSequence());
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with holder.
|
||||
*/
|
||||
public function withHolder(Holder $holder): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->holder = $holder;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with issuer.
|
||||
*/
|
||||
public function withIssuer(AttCertIssuer $issuer): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->issuer = $issuer;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with signature algorithm identifier.
|
||||
*/
|
||||
public function withSignature(SignatureAlgorithmIdentifier $algo): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->signature = $algo;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with serial number.
|
||||
*
|
||||
* @param int|string $serial Base 10 serial number
|
||||
*/
|
||||
public function withSerialNumber(int|string $serial): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->serialNumber = strval($serial);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with random positive serial number.
|
||||
*
|
||||
* @param int $size Number of random bytes
|
||||
*/
|
||||
public function withRandomSerialNumber(int $size = self::DEFAULT_RANDOM_SERIAL_SIZE): self
|
||||
{
|
||||
return $this->withSerialNumber(self::generateSerialNumber($size));
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw a serial number from a CSPRNG.
|
||||
*
|
||||
* The most significant bit is cleared so the DER INTEGER encodes a positive value, which is why 64 bits of
|
||||
* entropy need nine octets rather than eight.
|
||||
*
|
||||
* @param int $size Number of random octets
|
||||
*/
|
||||
private static function generateSerialNumber(int $size): string
|
||||
{
|
||||
if ($size < 1) {
|
||||
throw new InvalidArgumentException('Serial number size must be at least one octet.');
|
||||
}
|
||||
if ($size < self::MIN_RANDOM_SERIAL_SIZE) {
|
||||
@trigger_error(sprintf(
|
||||
'A %d octet serial number carries %.2f bits of entropy, below the 64 bits the CA/Browser Forum'
|
||||
. ' Baseline Requirements ask for. Use at least %d octets.',
|
||||
$size,
|
||||
8 * $size - 1,
|
||||
self::MIN_RANDOM_SERIAL_SIZE
|
||||
), E_USER_DEPRECATED);
|
||||
}
|
||||
$octets = random_bytes($size);
|
||||
$octets[0] = chr(ord($octets[0]) & 0x7F);
|
||||
$num = BigInteger::fromBytes($octets, false);
|
||||
|
||||
return $num->isZero() ? '1' : $num->toBase(10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with validity period.
|
||||
*/
|
||||
public function withValidity(AttCertValidityPeriod $validity): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->attrCertValidityPeriod = $validity;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with attributes.
|
||||
*/
|
||||
public function withAttributes(Attributes $attribs): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->attributes = $attribs;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with issuer unique identifier.
|
||||
*/
|
||||
public function withIssuerUniqueID(UniqueIdentifier $uid): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->issuerUniqueID = $uid;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with extensions.
|
||||
*/
|
||||
public function withExtensions(Extensions $extensions): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->extensions = $extensions;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with extensions added.
|
||||
*
|
||||
* @param Extension ...$exts One or more Extension objects
|
||||
*/
|
||||
public function withAdditionalExtensions(Extension ...$exts): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->extensions = $obj->extensions->withExtensions(...$exts);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
public function version(): int
|
||||
{
|
||||
return $this->version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get AC holder.
|
||||
*/
|
||||
public function holder(): Holder
|
||||
{
|
||||
return $this->holder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get AC issuer.
|
||||
*/
|
||||
public function issuer(): AttCertIssuer
|
||||
{
|
||||
return $this->issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether signature is set.
|
||||
*/
|
||||
public function hasSignature(): bool
|
||||
{
|
||||
return $this->signature !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signature algorithm identifier.
|
||||
*/
|
||||
public function signature(): SignatureAlgorithmIdentifier
|
||||
{
|
||||
if (! $this->hasSignature()) {
|
||||
throw new LogicException('signature not set.');
|
||||
}
|
||||
return $this->signature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether serial number is present.
|
||||
*/
|
||||
public function hasSerialNumber(): bool
|
||||
{
|
||||
return isset($this->serialNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get AC serial number as a base 10 integer.
|
||||
*/
|
||||
public function serialNumber(): string
|
||||
{
|
||||
if (! $this->hasSerialNumber()) {
|
||||
throw new LogicException('serialNumber not set.');
|
||||
}
|
||||
return $this->serialNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validity period.
|
||||
*/
|
||||
public function validityPeriod(): AttCertValidityPeriod
|
||||
{
|
||||
return $this->attrCertValidityPeriod;
|
||||
}
|
||||
|
||||
public function attributes(): Attributes
|
||||
{
|
||||
return $this->attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether issuer unique identifier is present.
|
||||
*/
|
||||
public function hasIssuerUniqueID(): bool
|
||||
{
|
||||
return isset($this->issuerUniqueID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get issuer unique identifier.
|
||||
*/
|
||||
public function issuerUniqueID(): UniqueIdentifier
|
||||
{
|
||||
if (! $this->hasIssuerUniqueID()) {
|
||||
throw new LogicException('issuerUniqueID not set.');
|
||||
}
|
||||
return $this->issuerUniqueID;
|
||||
}
|
||||
|
||||
public function extensions(): Extensions
|
||||
{
|
||||
return $this->extensions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [Integer::create($this->version), $this->holder->toASN1(),
|
||||
$this->issuer->toASN1(), $this->signature()
|
||||
->toASN1(),
|
||||
Integer::create($this->serialNumber()),
|
||||
$this->attrCertValidityPeriod->toASN1(),
|
||||
$this->attributes->toASN1(), ];
|
||||
if (isset($this->issuerUniqueID)) {
|
||||
$elements[] = $this->issuerUniqueID->toASN1();
|
||||
}
|
||||
if (count($this->extensions) !== 0) {
|
||||
$elements[] = $this->extensions->toASN1();
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create signed attribute certificate.
|
||||
*
|
||||
* @param SignatureAlgorithmIdentifier $algo Signature algorithm
|
||||
* @param PrivateKeyInfo $privkey_info Private key
|
||||
* @param null|Crypto $crypto Crypto engine, use default if not set
|
||||
*/
|
||||
public function sign(
|
||||
SignatureAlgorithmIdentifier $algo,
|
||||
PrivateKeyInfo $privkey_info,
|
||||
?Crypto $crypto = null
|
||||
): AttributeCertificate {
|
||||
$crypto ??= Crypto::getDefault();
|
||||
$aci = clone $this;
|
||||
if (! isset($aci->serialNumber)) {
|
||||
$aci->serialNumber = self::generateSerialNumber(self::DEFAULT_RANDOM_SERIAL_SIZE);
|
||||
}
|
||||
$aci->signature = $algo;
|
||||
$data = $aci->toASN1()
|
||||
->toDER();
|
||||
$signature = $crypto->sign($data, $privkey_info, $algo);
|
||||
return AttributeCertificate::create($aci, $algo, $signature);
|
||||
}
|
||||
}
|
||||
151
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attributes.php
vendored
Normal file
151
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Attributes.php
vendored
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use SpomkyLabs\Pki\X501\ASN1\Attribute;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Collection\SequenceOfAttributes;
|
||||
use SpomkyLabs\Pki\X509\AttributeCertificate\Attribute\AccessIdentityAttributeValue;
|
||||
use SpomkyLabs\Pki\X509\AttributeCertificate\Attribute\AuthenticationInfoAttributeValue;
|
||||
use SpomkyLabs\Pki\X509\AttributeCertificate\Attribute\ChargingIdentityAttributeValue;
|
||||
use SpomkyLabs\Pki\X509\AttributeCertificate\Attribute\GroupAttributeValue;
|
||||
use SpomkyLabs\Pki\X509\AttributeCertificate\Attribute\RoleAttributeValue;
|
||||
|
||||
/**
|
||||
* Implements *Attributes* ASN.1 type of *AttributeCertificateInfo*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.2.7
|
||||
*/
|
||||
final class Attributes extends SequenceOfAttributes
|
||||
{
|
||||
/**
|
||||
* Mapping from OID to attribute value class name.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const MAP_OID_TO_CLASS = [
|
||||
AccessIdentityAttributeValue::OID => AccessIdentityAttributeValue::class,
|
||||
AuthenticationInfoAttributeValue::OID => AuthenticationInfoAttributeValue::class,
|
||||
ChargingIdentityAttributeValue::OID => ChargingIdentityAttributeValue::class,
|
||||
GroupAttributeValue::OID => GroupAttributeValue::class,
|
||||
AttributeType::OID_ROLE => RoleAttributeValue::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Initialize from attribute values.
|
||||
*
|
||||
* @param AttributeValue ...$values List of attribute values
|
||||
*/
|
||||
public static function fromAttributeValues(AttributeValue ...$values): static
|
||||
{
|
||||
return static::create(...array_map(static fn (AttributeValue $value) => $value->toAttribute(), $values));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Access Identity' attribute is present.
|
||||
*/
|
||||
public function hasAccessIdentity(): bool
|
||||
{
|
||||
return $this->has(AccessIdentityAttributeValue::OID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first 'Access Identity' attribute value.
|
||||
*/
|
||||
public function accessIdentity(): AccessIdentityAttributeValue
|
||||
{
|
||||
return $this->firstOf(AccessIdentityAttributeValue::OID)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Service Authentication Information' attribute is present.
|
||||
*/
|
||||
public function hasAuthenticationInformation(): bool
|
||||
{
|
||||
return $this->has(AuthenticationInfoAttributeValue::OID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first 'Service Authentication Information' attribute value.
|
||||
*/
|
||||
public function authenticationInformation(): AuthenticationInfoAttributeValue
|
||||
{
|
||||
return $this->firstOf(AuthenticationInfoAttributeValue::OID)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Charging Identity' attribute is present.
|
||||
*/
|
||||
public function hasChargingIdentity(): bool
|
||||
{
|
||||
return $this->has(ChargingIdentityAttributeValue::OID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first 'Charging Identity' attribute value.
|
||||
*/
|
||||
public function chargingIdentity(): ChargingIdentityAttributeValue
|
||||
{
|
||||
return $this->firstOf(ChargingIdentityAttributeValue::OID)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Group' attribute is present.
|
||||
*/
|
||||
public function hasGroup(): bool
|
||||
{
|
||||
return $this->has(GroupAttributeValue::OID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first 'Group' attribute value.
|
||||
*/
|
||||
public function group(): GroupAttributeValue
|
||||
{
|
||||
return $this->firstOf(GroupAttributeValue::OID)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Role' attribute is present.
|
||||
*/
|
||||
public function hasRole(): bool
|
||||
{
|
||||
return $this->has(AttributeType::OID_ROLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first 'Role' attribute value.
|
||||
*/
|
||||
public function role(): RoleAttributeValue
|
||||
{
|
||||
return $this->firstOf(AttributeType::OID_ROLE)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all 'Role' attribute values.
|
||||
*
|
||||
* @return RoleAttributeValue[]
|
||||
*/
|
||||
public function roles(): array
|
||||
{
|
||||
return array_merge(
|
||||
[],
|
||||
...array_map(static fn (Attribute $attr) => $attr->values(), $this->allOf(AttributeType::OID_ROLE))
|
||||
);
|
||||
}
|
||||
|
||||
protected static function _castAttributeValues(Attribute $attribute): Attribute
|
||||
{
|
||||
$oid = $attribute->oid();
|
||||
if (isset(self::MAP_OID_TO_CLASS[$oid])) {
|
||||
return $attribute->castValues(self::MAP_OID_TO_CLASS[$oid]);
|
||||
}
|
||||
return $attribute;
|
||||
}
|
||||
}
|
||||
242
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Holder.php
vendored
Normal file
242
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Holder.php
vendored
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Certificate;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\DirectoryName;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
|
||||
/**
|
||||
* Implements *Holder* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
*/
|
||||
final class Holder
|
||||
{
|
||||
/**
|
||||
* Linked object.
|
||||
*/
|
||||
private ?ObjectDigestInfo $objectDigestInfo = null;
|
||||
|
||||
private function __construct(
|
||||
private ?IssuerSerial $baseCertificateID,
|
||||
private ?GeneralNames $entityName
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(?IssuerSerial $baseCertificateID = null, ?GeneralNames $entityName = null): self
|
||||
{
|
||||
return new self($baseCertificateID, $entityName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from a holder's public key certificate.
|
||||
*/
|
||||
public static function fromPKC(Certificate $cert): self
|
||||
{
|
||||
return self::create(IssuerSerial::fromPKC($cert));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$cert_id = null;
|
||||
$entity_name = null;
|
||||
$digest_info = null;
|
||||
if ($seq->hasTagged(0)) {
|
||||
$cert_id = IssuerSerial::fromASN1(
|
||||
$seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
}
|
||||
if ($seq->hasTagged(1)) {
|
||||
$entity_name = GeneralNames::fromASN1(
|
||||
$seq->getTagged(1)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
}
|
||||
if ($seq->hasTagged(2)) {
|
||||
$digest_info = ObjectDigestInfo::fromASN1(
|
||||
$seq->getTagged(2)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
}
|
||||
return self::create($cert_id, $entity_name)
|
||||
->withObjectDigestInfo($digest_info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with base certificate ID.
|
||||
*/
|
||||
public function withBaseCertificateID(IssuerSerial $issuer): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->baseCertificateID = $issuer;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with entity name.
|
||||
*/
|
||||
public function withEntityName(GeneralNames $names): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->entityName = $names;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with object digest info.
|
||||
*/
|
||||
public function withObjectDigestInfo(?ObjectDigestInfo $odi): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->objectDigestInfo = $odi;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether base certificate ID is present.
|
||||
*/
|
||||
public function hasBaseCertificateID(): bool
|
||||
{
|
||||
return isset($this->baseCertificateID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get base certificate ID.
|
||||
*/
|
||||
public function baseCertificateID(): IssuerSerial
|
||||
{
|
||||
if (! $this->hasBaseCertificateID()) {
|
||||
throw new LogicException('baseCertificateID not set.');
|
||||
}
|
||||
return $this->baseCertificateID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether entity name is present.
|
||||
*/
|
||||
public function hasEntityName(): bool
|
||||
{
|
||||
return isset($this->entityName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get entity name.
|
||||
*/
|
||||
public function entityName(): GeneralNames
|
||||
{
|
||||
if (! $this->hasEntityName()) {
|
||||
throw new LogicException('entityName not set.');
|
||||
}
|
||||
return $this->entityName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether object digest info is present.
|
||||
*/
|
||||
public function hasObjectDigestInfo(): bool
|
||||
{
|
||||
return isset($this->objectDigestInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get object digest info.
|
||||
*/
|
||||
public function objectDigestInfo(): ObjectDigestInfo
|
||||
{
|
||||
if (! $this->hasObjectDigestInfo()) {
|
||||
throw new LogicException('objectDigestInfo not set.');
|
||||
}
|
||||
return $this->objectDigestInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->baseCertificateID)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, $this->baseCertificateID->toASN1());
|
||||
}
|
||||
if (isset($this->entityName)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(1, $this->entityName->toASN1());
|
||||
}
|
||||
if (isset($this->objectDigestInfo)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(2, $this->objectDigestInfo->toASN1());
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether Holder identifies given certificate.
|
||||
*/
|
||||
public function identifiesPKC(Certificate $cert): bool
|
||||
{
|
||||
// if neither baseCertificateID nor entityName are present
|
||||
if ($this->baseCertificateID === null && $this->entityName === null) {
|
||||
return false;
|
||||
}
|
||||
// if baseCertificateID is present, but doesn't match
|
||||
if ($this->baseCertificateID !== null && ! $this->baseCertificateID->identifiesPKC($cert)) {
|
||||
return false;
|
||||
}
|
||||
// if entityName is present, but doesn't match
|
||||
if ($this->entityName !== null && ! $this->_checkEntityName($cert)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether entityName matches the given certificate.
|
||||
*/
|
||||
private function _checkEntityName(Certificate $cert): bool
|
||||
{
|
||||
$name = $this->entityName?->firstDN();
|
||||
if ($name !== null && $cert->tbsCertificate()->subject()->equals($name)) {
|
||||
return true;
|
||||
}
|
||||
$exts = $cert->tbsCertificate()
|
||||
->extensions();
|
||||
if ($exts->hasSubjectAlternativeName()) {
|
||||
$ext = $exts->subjectAlternativeName();
|
||||
if ($this->_checkEntityAlternativeNames($ext->names())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether any of the subject alternative names match entityName.
|
||||
*/
|
||||
private function _checkEntityAlternativeNames(GeneralNames $san): bool
|
||||
{
|
||||
// only directory names supported for now
|
||||
$name = $this->entityName?->firstDN();
|
||||
if ($name === null) {
|
||||
return false;
|
||||
}
|
||||
foreach ($san->allOf(GeneralName::TAG_DIRECTORY_NAME) as $dn) {
|
||||
if ($dn instanceof DirectoryName && $dn->dn()->equals($name)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
141
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/IssuerSerial.php
vendored
Normal file
141
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/IssuerSerial.php
vendored
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Certificate;
|
||||
use SpomkyLabs\Pki\X509\Certificate\UniqueIdentifier;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\DirectoryName;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
|
||||
/**
|
||||
* Implements *IssuerSerial* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
*/
|
||||
final class IssuerSerial
|
||||
{
|
||||
private function __construct(
|
||||
private readonly GeneralNames $issuer,
|
||||
private readonly string $serial,
|
||||
private readonly ?UniqueIdentifier $issuerUID
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(GeneralNames $issuer, string $serial, ?UniqueIdentifier $issuerUID = null): self
|
||||
{
|
||||
return new self($issuer, $serial, $issuerUID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$issuer = GeneralNames::fromASN1($seq->at(0)->asSequence());
|
||||
$serial = $seq->at(1)
|
||||
->asInteger()
|
||||
->number();
|
||||
$uid = null;
|
||||
if ($seq->has(2, Element::TYPE_BIT_STRING)) {
|
||||
$uid = UniqueIdentifier::fromASN1($seq->at(2)->asBitString());
|
||||
}
|
||||
return self::create($issuer, $serial, $uid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from a public key certificate.
|
||||
*/
|
||||
public static function fromPKC(Certificate $cert): self
|
||||
{
|
||||
$tbsCert = $cert->tbsCertificate();
|
||||
$issuer = GeneralNames::create(DirectoryName::create($tbsCert->issuer()));
|
||||
$serial = $tbsCert->serialNumber();
|
||||
$uid = $tbsCert->hasIssuerUniqueID() ? $tbsCert->issuerUniqueID() : null;
|
||||
return self::create($issuer, $serial, $uid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get issuer name.
|
||||
*/
|
||||
public function issuer(): GeneralNames
|
||||
{
|
||||
return $this->issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get serial number.
|
||||
*/
|
||||
public function serial(): string
|
||||
{
|
||||
return $this->serial;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether issuer unique identifier is present.
|
||||
*/
|
||||
public function hasIssuerUID(): bool
|
||||
{
|
||||
return isset($this->issuerUID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get issuer unique identifier.
|
||||
*/
|
||||
public function issuerUID(): UniqueIdentifier
|
||||
{
|
||||
if (! $this->hasIssuerUID()) {
|
||||
throw new LogicException('issuerUID not set.');
|
||||
}
|
||||
return $this->issuerUID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [$this->issuer->toASN1(), Integer::create($this->serial)];
|
||||
if (isset($this->issuerUID)) {
|
||||
$elements[] = $this->issuerUID->toASN1();
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether this IssuerSerial identifies given certificate.
|
||||
*/
|
||||
public function identifiesPKC(Certificate $cert): bool
|
||||
{
|
||||
$tbs = $cert->tbsCertificate();
|
||||
if (! $tbs->issuer()->equals($this->issuer->firstDN())) {
|
||||
return false;
|
||||
}
|
||||
if ($tbs->serialNumber() !== $this->serial) {
|
||||
return false;
|
||||
}
|
||||
if ($this->issuerUID !== null && ! $this->_checkUniqueID($cert)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether issuerUID matches given certificate.
|
||||
*/
|
||||
private function _checkUniqueID(Certificate $cert): bool
|
||||
{
|
||||
if (! $cert->tbsCertificate()->hasIssuerUniqueID()) {
|
||||
return false;
|
||||
}
|
||||
$uid = $cert->tbsCertificate()
|
||||
->issuerUniqueID()
|
||||
->string();
|
||||
return $this->issuerUID?->string() === $uid;
|
||||
}
|
||||
}
|
||||
80
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/ObjectDigestInfo.php
vendored
Normal file
80
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/ObjectDigestInfo.php
vendored
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Enumerated;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\AlgorithmIdentifierType;
|
||||
|
||||
/**
|
||||
* Implements *ObjectDigestInfo* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-7.3
|
||||
*/
|
||||
final class ObjectDigestInfo
|
||||
{
|
||||
public const TYPE_PUBLIC_KEY = 0;
|
||||
|
||||
public const TYPE_PUBLIC_KEY_CERT = 1;
|
||||
|
||||
public const TYPE_OTHER_OBJECT_TYPES = 2;
|
||||
|
||||
private function __construct(
|
||||
private readonly int $digestedObjectType,
|
||||
private readonly AlgorithmIdentifierType $digestAlgorithm,
|
||||
private readonly BitString $objectDigest,
|
||||
private readonly ?string $otherObjectTypeID
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(
|
||||
int $digestedObjectType,
|
||||
AlgorithmIdentifierType $digestAlgorithm,
|
||||
BitString $objectDigest,
|
||||
?string $otherObjectTypeID = null
|
||||
): self {
|
||||
return new self($digestedObjectType, $digestAlgorithm, $objectDigest, $otherObjectTypeID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$idx = 0;
|
||||
$oid = null;
|
||||
$type = $seq->at($idx++)
|
||||
->asEnumerated()
|
||||
->intNumber();
|
||||
if ($seq->has($idx, Element::TYPE_OBJECT_IDENTIFIER)) {
|
||||
$oid = $seq->at($idx++)
|
||||
->asObjectIdentifier()
|
||||
->oid();
|
||||
}
|
||||
$algo = AlgorithmIdentifier::fromASN1($seq->at($idx++)->asSequence());
|
||||
$digest = $seq->at($idx)
|
||||
->asBitString();
|
||||
return self::create($type, $algo, $digest, $oid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [Enumerated::create($this->digestedObjectType)];
|
||||
if (isset($this->otherObjectTypeID)) {
|
||||
$elements[] = ObjectIdentifier::create($this->otherObjectTypeID);
|
||||
}
|
||||
$elements[] = $this->digestAlgorithm->toASN1();
|
||||
$elements[] = $this->objectDigest;
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
116
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/V2Form.php
vendored
Normal file
116
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/V2Form.php
vendored
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Name;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Certificate;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
|
||||
/**
|
||||
* Implements *V2Form* ASN.1 type used as a attribute certificate issuer.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.1
|
||||
*/
|
||||
final class V2Form extends AttCertIssuer
|
||||
{
|
||||
private function __construct(
|
||||
private readonly ?GeneralNames $issuerName,
|
||||
private readonly ?IssuerSerial $baseCertificateID,
|
||||
private readonly ?ObjectDigestInfo $objectDigestInfo
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(
|
||||
?GeneralNames $issuerName = null,
|
||||
?IssuerSerial $baseCertificateID = null,
|
||||
?ObjectDigestInfo $objectDigestInfo = null
|
||||
): self {
|
||||
return new self($issuerName, $baseCertificateID, $objectDigestInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromV2ASN1(Sequence $seq): self
|
||||
{
|
||||
$issuer = null;
|
||||
$cert_id = null;
|
||||
$digest_info = null;
|
||||
if ($seq->has(0, Element::TYPE_SEQUENCE)) {
|
||||
$issuer = GeneralNames::fromASN1($seq->at(0)->asSequence());
|
||||
}
|
||||
if ($seq->hasTagged(0)) {
|
||||
$cert_id = IssuerSerial::fromASN1(
|
||||
$seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
}
|
||||
if ($seq->hasTagged(1)) {
|
||||
$digest_info = ObjectDigestInfo::fromASN1(
|
||||
$seq->getTagged(1)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
}
|
||||
return self::create($issuer, $cert_id, $digest_info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether issuer name is set.
|
||||
*/
|
||||
public function hasIssuerName(): bool
|
||||
{
|
||||
return isset($this->issuerName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get issuer name.
|
||||
*/
|
||||
public function issuerName(): GeneralNames
|
||||
{
|
||||
if (! $this->hasIssuerName()) {
|
||||
throw new LogicException('issuerName not set.');
|
||||
}
|
||||
return $this->issuerName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get DN of the issuer.
|
||||
*
|
||||
* This is a convenience method conforming to RFC 5755, which states that Issuer must contain only one non-empty
|
||||
* distinguished name.
|
||||
*/
|
||||
public function name(): Name
|
||||
{
|
||||
return $this->issuerName()
|
||||
->firstDN();
|
||||
}
|
||||
|
||||
public function toASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->issuerName)) {
|
||||
$elements[] = $this->issuerName->toASN1();
|
||||
}
|
||||
if (isset($this->baseCertificateID)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, $this->baseCertificateID->toASN1());
|
||||
}
|
||||
if (isset($this->objectDigestInfo)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(1, $this->objectDigestInfo->toASN1());
|
||||
}
|
||||
return ImplicitlyTaggedType::create(0, Sequence::create(...$elements));
|
||||
}
|
||||
|
||||
public function identifiesPKC(Certificate $cert): bool
|
||||
{
|
||||
$name = $this->issuerName?->firstDN();
|
||||
return ! ($name === null || ! $cert->tbsCertificate()->subject()->equals($name));
|
||||
}
|
||||
}
|
||||
220
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Validation/ACValidationConfig.php
vendored
Normal file
220
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Validation/ACValidationConfig.php
vendored
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Validation;
|
||||
|
||||
use function array_values;
|
||||
use DateTimeImmutable;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Certificate;
|
||||
use SpomkyLabs\Pki\X509\Certificate\CertificateBundle;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Target\Target;
|
||||
use SpomkyLabs\Pki\X509\CertificationPath\CertificationPath;
|
||||
use SpomkyLabs\Pki\X509\CertificationPath\PathValidation\PathValidationConfig;
|
||||
|
||||
/**
|
||||
* Provides configuration context for the attribute certificate validation.
|
||||
*/
|
||||
final class ACValidationConfig
|
||||
{
|
||||
/**
|
||||
* Evaluation reference time, or null to resolve it on every evaluation.
|
||||
*/
|
||||
private ?DateTimeImmutable $evalTime;
|
||||
|
||||
/**
|
||||
* Certificates of the attribute authorities the caller directly trusts, or null when the caller takes
|
||||
* responsibility for RFC 5755 sect. 5 check 4 itself.
|
||||
*/
|
||||
private ?CertificateBundle $trustedAttributeAuthorities;
|
||||
|
||||
/**
|
||||
* Whether the caller supplied the path validation configuration.
|
||||
*/
|
||||
private bool $pathValidationConfigProvided;
|
||||
|
||||
/**
|
||||
* Permitted targets.
|
||||
*
|
||||
* @var Target[]
|
||||
*/
|
||||
private array $targets;
|
||||
|
||||
/**
|
||||
* Configuration applied when validating the holder and issuer certification paths.
|
||||
*/
|
||||
private PathValidationConfig $pathValidationConfig;
|
||||
|
||||
/**
|
||||
* OID's of the critical attribute 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 = [];
|
||||
|
||||
/**
|
||||
* @param CertificationPath $holderPath Certification path of the AC holder
|
||||
* @param CertificationPath $issuerPath Certification path of the AC issuer
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly CertificationPath $holderPath,
|
||||
private readonly CertificationPath $issuerPath
|
||||
) {
|
||||
// resolved on every evaluation rather than snapshotted here: a config object shared by a DI container or
|
||||
// held across requests in a worker runtime would otherwise keep validating expired credentials and
|
||||
// expired certificates for the lifetime of the process
|
||||
$this->evalTime = null;
|
||||
$this->targets = [];
|
||||
$this->trustedAttributeAuthorities = null;
|
||||
$this->pathValidationConfig = PathValidationConfig::defaultConfig();
|
||||
$this->pathValidationConfigProvided = false;
|
||||
}
|
||||
|
||||
public static function create(CertificationPath $holderPath, CertificationPath $issuerPath): self
|
||||
{
|
||||
return new self($holderPath, $issuerPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certification path of the AC's holder.
|
||||
*/
|
||||
public function holderPath(): CertificationPath
|
||||
{
|
||||
return $this->holderPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certification path of the AC's issuer.
|
||||
*/
|
||||
public function issuerPath(): CertificationPath
|
||||
{
|
||||
return $this->issuerPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with the configuration used to validate the holder and issuer certification paths.
|
||||
*
|
||||
* Without this, those two paths are validated on the default configuration and the caller cannot express any
|
||||
* policy for them, including which signature algorithms are acceptable. The maximum path length and the
|
||||
* evaluation time are still derived from this object.
|
||||
*/
|
||||
public function withPathValidationConfig(PathValidationConfig $config): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->pathValidationConfig = $config;
|
||||
$obj->pathValidationConfigProvided = true;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with the OID's of the critical extensions the application processes by its own means.
|
||||
*
|
||||
* The validation rejects an attribute 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 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the configuration used to validate the holder and issuer certification paths.
|
||||
*/
|
||||
public function pathValidationConfig(): PathValidationConfig
|
||||
{
|
||||
return $this->pathValidationConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the caller supplied the path validation configuration.
|
||||
*
|
||||
* The validator derives a maximum path length from the length of the path it was handed when the caller did
|
||||
* not, and leaves the caller's own limit alone when they did.
|
||||
*/
|
||||
public function hasPathValidationConfig(): bool
|
||||
{
|
||||
return $this->pathValidationConfigProvided;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given evaluation reference time.
|
||||
*/
|
||||
public function withEvaluationTime(DateTimeImmutable $dt): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->evalTime = $dt;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the evaluation reference time.
|
||||
*
|
||||
* Unless withEvaluationTime() pinned it, this is the instant the call is made rather than the instant this
|
||||
* object was built.
|
||||
*/
|
||||
public function evaluationTime(): DateTimeImmutable
|
||||
{
|
||||
return $this->evalTime ?? new DateTimeImmutable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with the attribute authorities that are directly trusted to issue attribute certificates.
|
||||
*
|
||||
* RFC 5755 sect. 5 check 4 requires the AC issuer to be directly trusted as an attribute authority. Without
|
||||
* this list the validator accepts whatever end-entity certificate the issuer path ends in, so a caller who
|
||||
* locates the attribute authority by matching the issuer name against a bundle turns every end-entity
|
||||
* certificate under the trust anchor into an attribute authority.
|
||||
*
|
||||
* @param Certificate ...$certs Certificates of the trusted attribute authorities
|
||||
*/
|
||||
public function withTrustedAttributeAuthorities(Certificate ...$certs): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->trustedAttributeAuthorities = CertificateBundle::create(...$certs);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attribute authorities that are directly trusted, or null when the caller has not named any.
|
||||
*/
|
||||
public function trustedAttributeAuthorities(): ?CertificateBundle
|
||||
{
|
||||
return $this->trustedAttributeAuthorities;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with permitted targets.
|
||||
*/
|
||||
public function withTargets(Target ...$targets): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->targets = $targets;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get array of permitted targets.
|
||||
*
|
||||
* @return Target[]
|
||||
*/
|
||||
public function targets(): array
|
||||
{
|
||||
return $this->targets;
|
||||
}
|
||||
}
|
||||
274
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Validation/ACValidator.php
vendored
Normal file
274
vendor/spomky-labs/pki-framework/src/X509/AttributeCertificate/Validation/ACValidator.php
vendored
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Validation;
|
||||
|
||||
use function count;
|
||||
use function in_array;
|
||||
use SpomkyLabs\Pki\CryptoBridge\Crypto;
|
||||
use SpomkyLabs\Pki\X509\AttributeCertificate\AttributeCertificate;
|
||||
use SpomkyLabs\Pki\X509\AttributeCertificate\Validation\Exception\ACValidationException;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Certificate;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Extension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Target\Targets;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\TargetInformationExtension;
|
||||
use SpomkyLabs\Pki\X509\CertificationPath\CertificationPath;
|
||||
use SpomkyLabs\Pki\X509\CertificationPath\Exception\PathValidationException;
|
||||
use SpomkyLabs\Pki\X509\CertificationPath\PathValidation\PathValidationConfig;
|
||||
use SpomkyLabs\Pki\X509\CertificationPath\PathValidation\SignaturePolicy;
|
||||
use function sprintf;
|
||||
|
||||
/**
|
||||
* Implements attribute certificate validation conforming to RFC 5755.
|
||||
*
|
||||
* RFC 5755 sect. 5 check 4 requires the AC issuer to be directly trusted as an attribute authority. Name the
|
||||
* trusted authorities with ACValidationConfig::withTrustedAttributeAuthorities() to have that check run here;
|
||||
* without it the check is the caller's responsibility, and this validator only establishes that the issuer
|
||||
* certificate chains to the trust anchor and carries a profile that permits signing.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-5
|
||||
*/
|
||||
final class ACValidator
|
||||
{
|
||||
/**
|
||||
* OID's of the attribute certificate extensions this validator is able to process.
|
||||
*
|
||||
* A critical extension whose OID is not listed here cannot be honoured, and therefore makes the validation fail
|
||||
* as required by RFC 5755 section 5, check 7. An application that processes further extensions by its own means
|
||||
* may declare them through `ACValidationConfig::withAdditionalCriticalExtensions()`.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private const PROCESSED_EXTENSIONS = [
|
||||
Extension::OID_TARGET_INFORMATION,
|
||||
Extension::OID_NO_REV_AVAIL,
|
||||
];
|
||||
|
||||
/**
|
||||
* Crypto engine.
|
||||
*/
|
||||
private readonly Crypto $crypto;
|
||||
|
||||
/**
|
||||
* @param AttributeCertificate $ac Attribute certificate to validate
|
||||
* @param ACValidationConfig $config Validation configuration
|
||||
* @param null|Crypto $crypto Crypto engine, use default if not set
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly AttributeCertificate $ac,
|
||||
private readonly ACValidationConfig $config,
|
||||
?Crypto $crypto
|
||||
) {
|
||||
$this->crypto = $crypto ?? Crypto::getDefault();
|
||||
}
|
||||
|
||||
public static function create(
|
||||
AttributeCertificate $ac,
|
||||
ACValidationConfig $config,
|
||||
?Crypto $crypto = null
|
||||
): self {
|
||||
return new self($ac, $config, $crypto);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate attribute certificate.
|
||||
*
|
||||
* @return AttributeCertificate Validated AC
|
||||
*/
|
||||
public function validate(): AttributeCertificate
|
||||
{
|
||||
$this->validateHolder();
|
||||
$issuer = $this->verifyIssuer();
|
||||
$this->validateIssuerProfile($issuer);
|
||||
$this->validateTime();
|
||||
$this->validateTargeting();
|
||||
$this->validateExtensions();
|
||||
return $this->ac;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that every critical extension of the attribute certificate is one this validator honours.
|
||||
*
|
||||
* An attribute certificate carries authorisation, and a critical extension is how its issuer narrows that
|
||||
* authorisation. Accepting one that cannot be processed grants the attributes unconditionally, which is why
|
||||
* RFC 5755 section 5, check 7 requires the certificate to be rejected instead.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-5
|
||||
*/
|
||||
private function validateExtensions(): void
|
||||
{
|
||||
$recognized = [...self::PROCESSED_EXTENSIONS, ...$this->config->additionalCriticalExtensions()];
|
||||
foreach ($this->ac->acinfo()->extensions() as $extension) {
|
||||
if (! $extension->isCritical()) {
|
||||
continue;
|
||||
}
|
||||
if (! in_array($extension->oid(), $recognized, true)) {
|
||||
throw new ACValidationException(sprintf(
|
||||
'Attribute certificate contains an unhandled critical extension: %s.',
|
||||
$extension->extensionName()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate AC holder's certification.
|
||||
*
|
||||
* @return Certificate Certificate of the AC's holder
|
||||
*/
|
||||
private function validateHolder(): Certificate
|
||||
{
|
||||
$path = $this->config->holderPath();
|
||||
$config = $this->pathConfigFor($path);
|
||||
try {
|
||||
$holder = $path->validate($config, $this->crypto)
|
||||
->certificate();
|
||||
} catch (PathValidationException $e) {
|
||||
throw new ACValidationException("Failed to validate holder PKC's certification path.", 0, $e);
|
||||
}
|
||||
if (! $this->ac->isHeldBy($holder)) {
|
||||
throw new ACValidationException("Name mismatch of AC's holder PKC.");
|
||||
}
|
||||
return $holder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify AC's signature and issuer's certification.
|
||||
*
|
||||
* @return Certificate Certificate of the AC's issuer
|
||||
*/
|
||||
private function verifyIssuer(): Certificate
|
||||
{
|
||||
$path = $this->config->issuerPath();
|
||||
$config = $this->pathConfigFor($path);
|
||||
try {
|
||||
$issuer = $path->validate($config, $this->crypto)
|
||||
->certificate();
|
||||
} catch (PathValidationException $e) {
|
||||
throw new ACValidationException("Failed to validate issuer PKC's certification path.", 0, $e);
|
||||
}
|
||||
if (! $this->ac->isIssuedBy($issuer)) {
|
||||
throw new ACValidationException("Name mismatch of AC's issuer PKC.");
|
||||
}
|
||||
$pubkey_info = $issuer->tbsCertificate()
|
||||
->subjectPublicKeyInfo();
|
||||
// The certification paths above are validated under a policy that names the acceptable signature algorithms
|
||||
// and the smallest acceptable RSA modulus. The attribute certificate's own signature is the one that
|
||||
// carries the authorisation, so the same policy has to reach it: the crypto engine will otherwise verify an
|
||||
// MD5 signature, and the attribute authority's own key is never a working key of either path, so its size
|
||||
// was never measured.
|
||||
$config = $this->config->pathValidationConfig();
|
||||
$algo = $this->ac->signatureAlgorithm();
|
||||
if (! SignaturePolicy::isAlgorithmAllowed($algo, $config->allowedSignatureAlgorithms())) {
|
||||
throw new ACValidationException(sprintf('Signature algorithm %s is not allowed.', $algo->name()));
|
||||
}
|
||||
$minimum = $config->minimumRSAKeySize();
|
||||
$bits = SignaturePolicy::rsaKeySizeBelowMinimum($pubkey_info, $minimum);
|
||||
if ($bits !== null) {
|
||||
throw new ACValidationException(
|
||||
sprintf('RSA key size %d is below the minimum of %d bits.', $bits, $minimum)
|
||||
);
|
||||
}
|
||||
if (! $this->ac->verify($pubkey_info, $this->crypto)) {
|
||||
throw new ACValidationException('Failed to verify signature.');
|
||||
}
|
||||
return $issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path validation configuration to use for one of the two certification paths.
|
||||
*
|
||||
* The maximum path length is derived from the path itself only when the caller did not supply a
|
||||
* configuration of their own: overriding it unconditionally made PathValidationConfig::maxLength() a no-op
|
||||
* for both paths, so a caller who set a limit did not get it.
|
||||
*/
|
||||
private function pathConfigFor(CertificationPath $path): PathValidationConfig
|
||||
{
|
||||
$config = $this->config->pathValidationConfig()
|
||||
->withDateTime($this->config->evaluationTime());
|
||||
if (! $this->config->hasPathValidationConfig()) {
|
||||
$config = $config->withMaxLength(count($path));
|
||||
}
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate AC issuer's profile.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.5
|
||||
*/
|
||||
private function validateIssuerProfile(Certificate $cert): void
|
||||
{
|
||||
$exts = $cert->tbsCertificate()
|
||||
->extensions();
|
||||
// sect. 4.5 permits either bit: an attribute authority that asserts non-repudiation only is conforming
|
||||
if ($exts->hasKeyUsage()
|
||||
&& ! $exts->keyUsage()
|
||||
->isDigitalSignature()
|
||||
&& ! $exts->keyUsage()
|
||||
->isNonRepudiation()) {
|
||||
throw new ACValidationException(
|
||||
"Issuer PKC's Key Usage extension doesn't permit" .
|
||||
' verification of digital signatures.'
|
||||
);
|
||||
}
|
||||
if ($exts->hasBasicConstraints() && $exts->basicConstraints()->isCA()) {
|
||||
throw new ACValidationException('Issuer PKC must not be a CA.');
|
||||
}
|
||||
// RFC 5755 sect. 5, check 4: the AC issuer must be directly trusted as an attribute authority
|
||||
$authorities = $this->config->trustedAttributeAuthorities();
|
||||
if ($authorities !== null && ! $authorities->contains($cert)) {
|
||||
throw new ACValidationException('Issuer PKC is not a trusted attribute authority.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate AC's validity period.
|
||||
*/
|
||||
private function validateTime(): void
|
||||
{
|
||||
$t = $this->config->evaluationTime();
|
||||
$validity = $this->ac->acinfo()
|
||||
->validityPeriod();
|
||||
if ($validity->notBeforeTime()->diff($t)->invert === 1) {
|
||||
throw new ACValidationException('Validity period has not started.');
|
||||
}
|
||||
if ($t->diff($validity->notAfterTime())->invert === 1) {
|
||||
throw new ACValidationException('Attribute certificate has expired.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate AC's target information.
|
||||
*/
|
||||
private function validateTargeting(): void
|
||||
{
|
||||
$exts = $this->ac->acinfo()
|
||||
->extensions();
|
||||
// if target information extension is not present
|
||||
if (! $exts->has(Extension::OID_TARGET_INFORMATION)) {
|
||||
return;
|
||||
}
|
||||
$ext = $exts->get(Extension::OID_TARGET_INFORMATION);
|
||||
if ($ext instanceof TargetInformationExtension &&
|
||||
! $this->_hasMatchingTarget($ext->targets())) {
|
||||
throw new ACValidationException("Attribute certificate doesn't have a matching target.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether validation configuration has matching targets.
|
||||
*
|
||||
* @param Targets $targets Set of eligible targets
|
||||
*/
|
||||
private function _hasMatchingTarget(Targets $targets): bool
|
||||
{
|
||||
foreach ($this->config->targets() as $target) {
|
||||
if ($targets->hasTarget($target)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\AttributeCertificate\Validation\Exception;
|
||||
|
||||
use SpomkyLabs\Pki\X509\Exception\X509ValidationException;
|
||||
|
||||
final class ACValidationException extends X509ValidationException
|
||||
{
|
||||
}
|
||||
256
vendor/spomky-labs/pki-framework/src/X509/Certificate/Certificate.php
vendored
Normal file
256
vendor/spomky-labs/pki-framework/src/X509/Certificate/Certificate.php
vendored
Normal file
|
|
@ -0,0 +1,256 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use RuntimeException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\CryptoBridge\Crypto;
|
||||
use SpomkyLabs\Pki\CryptoEncoding\PEM;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Signature\Signature;
|
||||
use SpomkyLabs\Pki\X509\Feature\SignedDER;
|
||||
use Stringable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *Certificate* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.1
|
||||
*/
|
||||
final class Certificate implements Stringable
|
||||
{
|
||||
use SignedDER;
|
||||
|
||||
/**
|
||||
* @param TBSCertificate $tbsCertificate "To be signed" certificate information.
|
||||
* @param SignatureAlgorithmIdentifier $signatureAlgorithm Signature algorithm.
|
||||
* @param Signature $signatureValue Signature value.
|
||||
* @param null|string $tbsCertificateDER Encoding of the tbsCertificate as it was received, when decoded from
|
||||
* DER.
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly TBSCertificate $tbsCertificate,
|
||||
private readonly SignatureAlgorithmIdentifier $signatureAlgorithm,
|
||||
private readonly Signature $signatureValue,
|
||||
private readonly ?string $tbsCertificateDER = null
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate as a PEM formatted string.
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toPEM()
|
||||
->string();
|
||||
}
|
||||
|
||||
public static function create(
|
||||
TBSCertificate $tbsCertificate,
|
||||
SignatureAlgorithmIdentifier $signatureAlgorithm,
|
||||
Signature $signatureValue
|
||||
): self {
|
||||
return new self($tbsCertificate, $signatureAlgorithm, $signatureValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$tbsCert = TBSCertificate::fromASN1($seq->at(0)->asSequence());
|
||||
$algo = AlgorithmIdentifier::fromASN1($seq->at(1)->asSequence());
|
||||
if (! $algo instanceof SignatureAlgorithmIdentifier) {
|
||||
throw new UnexpectedValueException('Unsupported signature algorithm ' . $algo->oid() . '.');
|
||||
}
|
||||
// RFC 5280 section 4.1.1.2: signatureAlgorithm sits outside the signed part, so anyone can change it. It
|
||||
// must repeat the algorithm of the tbsCertificate, which is signed.
|
||||
if ($algo->oid() !== $tbsCert->signature()->oid()) {
|
||||
throw new UnexpectedValueException(
|
||||
'Signature algorithm ' . $algo->oid() . ' does not match the algorithm ' .
|
||||
$tbsCert->signature()
|
||||
->oid() . ' of the tbsCertificate.'
|
||||
);
|
||||
}
|
||||
$signature = Signature::fromSignatureData($seq->at(2)->asBitString()->string(), $algo);
|
||||
return self::create($tbsCert, $algo, $signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from DER.
|
||||
*/
|
||||
public static function fromDER(string $data): self
|
||||
{
|
||||
[$seq, $tbsCertificateDER] = self::decodeSignedDER($data, 'Certificate');
|
||||
$cert = self::fromASN1($seq);
|
||||
// Keep the tbsCertificate exactly as it arrived, so that verify() checks the signature over the bytes the
|
||||
// issuer signed rather than over what the parser produced.
|
||||
return new self($cert->tbsCertificate, $cert->signatureAlgorithm, $cert->signatureValue, $tbsCertificateDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from PEM.
|
||||
*/
|
||||
public static function fromPEM(PEM $pem): self
|
||||
{
|
||||
if ($pem->type() !== PEM::TYPE_CERTIFICATE) {
|
||||
throw new UnexpectedValueException('Invalid PEM type.');
|
||||
}
|
||||
return self::fromDER($pem->data());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate information.
|
||||
*/
|
||||
public function tbsCertificate(): TBSCertificate
|
||||
{
|
||||
return $this->tbsCertificate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signature algorithm.
|
||||
*/
|
||||
public function signatureAlgorithm(): SignatureAlgorithmIdentifier
|
||||
{
|
||||
return $this->signatureAlgorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signature value.
|
||||
*/
|
||||
public function signatureValue(): Signature
|
||||
{
|
||||
return $this->signatureValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether certificate is self-issued.
|
||||
*/
|
||||
public function isSelfIssued(): bool
|
||||
{
|
||||
return $this->tbsCertificate->subject()
|
||||
->equals($this->tbsCertificate->issuer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether this is the very same certificate as another, comparing the encodings octet by octet.
|
||||
*
|
||||
* The comparison used to be on the serial number, the key identifier of the subject public key and the subject
|
||||
* DN alone, which are three public values an attacker is free to repeat: a certificate agreeing on them but
|
||||
* differing in issuer, validity, every extension and the signature was reported as the same certificate, and
|
||||
* `CertificateBundle::contains()` answered "yes" for a certificate that was not in the bundle.
|
||||
*
|
||||
* @param Certificate $cert Certificate to compare to
|
||||
*/
|
||||
public function equals(self $cert): bool
|
||||
{
|
||||
return hash_equals($this->toDER(), $cert->toDER());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the certificate names the same subject, holding the same key, with the same serial number.
|
||||
*
|
||||
* This is not an identity check: two certificates may agree on all three and still be issued by different
|
||||
* issuers, carry different extensions and be signed by different keys. Use `equals()` to answer "is this the
|
||||
* certificate I have", and this predicate only to group certificates that were issued for the same subject
|
||||
* key, such as a re-issued certificate and the one it replaces.
|
||||
*
|
||||
* @param Certificate $cert Certificate to compare to
|
||||
*/
|
||||
public function hasEqualSubjectIdentity(self $cert): bool
|
||||
{
|
||||
return $this->_hasEqualSerialNumber($cert) &&
|
||||
$this->_hasEqualPublicKey($cert) && $this->_hasEqualSubject($cert);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create(
|
||||
$this->tbsCertificate->toASN1(),
|
||||
$this->signatureAlgorithm->toASN1(),
|
||||
$this->signatureValue->bitString()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate as a DER.
|
||||
*/
|
||||
public function toDER(): string
|
||||
{
|
||||
return $this->toASN1()
|
||||
->toDER();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate as a PEM.
|
||||
*/
|
||||
public function toPEM(): PEM
|
||||
{
|
||||
return PEM::create(PEM::TYPE_CERTIFICATE, $this->toDER());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify certificate signature.
|
||||
*
|
||||
* @param PublicKeyInfo $pubkey_info Issuer's public key
|
||||
* @param null|Crypto $crypto Crypto engine, use default if not set
|
||||
*
|
||||
* @return bool True if certificate signature is valid
|
||||
*/
|
||||
public function verify(PublicKeyInfo $pubkey_info, ?Crypto $crypto = null): bool
|
||||
{
|
||||
$crypto ??= Crypto::getDefault();
|
||||
// A certificate built in memory was never received as bytes; re-encoding it is then the only option, and
|
||||
// the correct one.
|
||||
$data = $this->tbsCertificateDER ?? $this->tbsCertificate->toASN1()
|
||||
->toDER();
|
||||
// a bool returning predicate must not throw on a signature it cannot check: the algorithm is named by
|
||||
// the certificate, so an attacker picks it, and `if (! $cert->verify($key))` in application code would
|
||||
// otherwise become an unhandled fatal. An unsupported algorithm, a key the algorithm does not match and
|
||||
// an engine level failure all mean the same thing to the caller: the signature was not verified.
|
||||
try {
|
||||
return $crypto->verify($data, $this->signatureValue, $pubkey_info, $this->signatureAlgorithm);
|
||||
} catch (RuntimeException|UnexpectedValueException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether certificate has serial number equal to another.
|
||||
*/
|
||||
private function _hasEqualSerialNumber(self $cert): bool
|
||||
{
|
||||
$sn1 = $this->tbsCertificate->serialNumber();
|
||||
$sn2 = $cert->tbsCertificate->serialNumber();
|
||||
return $sn1 === $sn2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether certificate has public key equal to another.
|
||||
*/
|
||||
private function _hasEqualPublicKey(self $cert): bool
|
||||
{
|
||||
$kid1 = $this->tbsCertificate->subjectPublicKeyInfo()
|
||||
->keyIdentifier();
|
||||
$kid2 = $cert->tbsCertificate->subjectPublicKeyInfo()
|
||||
->keyIdentifier();
|
||||
return $kid1 === $kid2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether certificate has subject equal to another.
|
||||
*/
|
||||
private function _hasEqualSubject(self $cert): bool
|
||||
{
|
||||
$dn1 = $this->tbsCertificate->subject();
|
||||
$dn2 = $cert->tbsCertificate->subject();
|
||||
return $dn1->equals($dn2);
|
||||
}
|
||||
}
|
||||
237
vendor/spomky-labs/pki-framework/src/X509/Certificate/CertificateBundle.php
vendored
Normal file
237
vendor/spomky-labs/pki-framework/src/X509/Certificate/CertificateBundle.php
vendored
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use SpomkyLabs\Pki\CryptoEncoding\PEM;
|
||||
use SpomkyLabs\Pki\CryptoEncoding\PEMBundle;
|
||||
|
||||
/**
|
||||
* Implements a list of certificates.
|
||||
*/
|
||||
final class CertificateBundle implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Certificates.
|
||||
*
|
||||
* @var Certificate[]
|
||||
*/
|
||||
private array $certs;
|
||||
|
||||
/**
|
||||
* Mapping from public key id to array of certificates.
|
||||
*
|
||||
* @var null|(Certificate[])[]
|
||||
*/
|
||||
private ?array $keyIdMap = null;
|
||||
|
||||
/**
|
||||
* @param Certificate ...$certs Certificate objects
|
||||
*/
|
||||
private function __construct(Certificate ...$certs)
|
||||
{
|
||||
$this->certs = $certs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset internal cached variables on clone.
|
||||
*/
|
||||
public function __clone()
|
||||
{
|
||||
$this->keyIdMap = null;
|
||||
}
|
||||
|
||||
public static function create(Certificate ...$certs): self
|
||||
{
|
||||
return new self(...$certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from PEMs.
|
||||
*
|
||||
* @param PEM ...$pems PEM objects
|
||||
*/
|
||||
public static function fromPEMs(PEM ...$pems): self
|
||||
{
|
||||
$certs = array_map(Certificate::fromPEM(...), $pems);
|
||||
return self::create(...$certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from PEM bundle.
|
||||
*/
|
||||
public static function fromPEMBundle(PEMBundle $pem_bundle): self
|
||||
{
|
||||
return self::fromPEMs(...$pem_bundle->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with certificates added.
|
||||
*/
|
||||
public function withCertificates(Certificate ...$cert): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->certs = array_merge($obj->certs, $cert);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with certificates from PEMBundle added.
|
||||
*/
|
||||
public function withPEMBundle(PEMBundle $pem_bundle): self
|
||||
{
|
||||
$certs = $this->certs;
|
||||
foreach ($pem_bundle as $pem) {
|
||||
$certs[] = Certificate::fromPEM($pem);
|
||||
}
|
||||
return self::create(...$certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with single certificate from PEM added.
|
||||
*/
|
||||
public function withPEM(PEM $pem): self
|
||||
{
|
||||
$certs = $this->certs;
|
||||
$certs[] = Certificate::fromPEM($pem);
|
||||
return self::create(...$certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether bundle contains a given certificate.
|
||||
*/
|
||||
public function contains(Certificate $cert): bool
|
||||
{
|
||||
// the computed identifier is derived from the key itself, so a certificate is always registered under it
|
||||
$id = $cert->tbsCertificate()
|
||||
->subjectPublicKeyInfo()
|
||||
->keyIdentifier();
|
||||
$map = $this->_getKeyIdMap();
|
||||
if (! isset($map[$id])) {
|
||||
return false;
|
||||
}
|
||||
foreach ($map[$id] as $c) {
|
||||
/** @var Certificate $c */
|
||||
if ($cert->equals($c)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all certificates that have given subject key identifier.
|
||||
*
|
||||
* A certificate is indexed both under the identifier computed from its subjectPublicKeyInfo and under the one
|
||||
* its subjectKeyIdentifier extension declares, when the two differ. The declared value is arbitrary data that
|
||||
* is never checked against the key, so indexing on it alone let a single certificate whose extension repeats
|
||||
* a real intermediate's identifier displace that intermediate and deny validation of a good chain.
|
||||
*
|
||||
* The certificates whose computed identifier matches come first, ahead of those that only claim the value, so
|
||||
* a caller that takes the first match takes the one that actually holds the key.
|
||||
*
|
||||
* @return Certificate[]
|
||||
*/
|
||||
public function allBySubjectKeyIdentifier(string $id): array
|
||||
{
|
||||
$map = $this->_getKeyIdMap();
|
||||
if (! isset($map[$id])) {
|
||||
return [];
|
||||
}
|
||||
$computed = [];
|
||||
$declared = [];
|
||||
foreach ($map[$id] as $cert) {
|
||||
$keyId = $cert->tbsCertificate()
|
||||
->subjectPublicKeyInfo()
|
||||
->keyIdentifier();
|
||||
if ($keyId === $id) {
|
||||
$computed[] = $cert;
|
||||
} else {
|
||||
$declared[] = $cert;
|
||||
}
|
||||
}
|
||||
return array_merge($computed, $declared);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all certificates in a bundle.
|
||||
*
|
||||
* @return Certificate[]
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->certs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for certificates.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate mapping by public key id.
|
||||
*
|
||||
* @return (Certificate[])[]
|
||||
*/
|
||||
private function _getKeyIdMap(): array
|
||||
{
|
||||
// lazily build mapping
|
||||
if (! isset($this->keyIdMap)) {
|
||||
$this->keyIdMap = [];
|
||||
foreach ($this->certs as $cert) {
|
||||
foreach (self::_getCertKeyIds($cert) as $id) {
|
||||
if (! isset($this->keyIdMap[$id])) {
|
||||
$this->keyIdMap[$id] = [];
|
||||
}
|
||||
$this->keyIdMap[$id][] = $cert;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->keyIdMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the public key ids the certificate is to be indexed under.
|
||||
*
|
||||
* The identifier computed from the subjectPublicKeyInfo comes first: it is derived from the key and cannot be
|
||||
* chosen. The subjectKeyIdentifier extension is added alongside it, so a lookup on the value another
|
||||
* certificate's authorityKeyIdentifier declares still finds this one, without letting that claim be the only
|
||||
* way the certificate can be found.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function _getCertKeyIds(Certificate $cert): array
|
||||
{
|
||||
$ids = [$cert->tbsCertificate()
|
||||
->subjectPublicKeyInfo()
|
||||
->keyIdentifier()];
|
||||
$exts = $cert->tbsCertificate()
|
||||
->extensions();
|
||||
if ($exts->hasSubjectKeyIdentifier()) {
|
||||
$declared = $exts->subjectKeyIdentifier()
|
||||
->keyIdentifier();
|
||||
if ($declared !== $ids[0]) {
|
||||
$ids[] = $declared;
|
||||
}
|
||||
}
|
||||
return $ids;
|
||||
}
|
||||
}
|
||||
124
vendor/spomky-labs/pki-framework/src/X509/Certificate/CertificateChain.php
vendored
Normal file
124
vendor/spomky-labs/pki-framework/src/X509/Certificate/CertificateChain.php
vendored
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\CryptoEncoding\PEM;
|
||||
use SpomkyLabs\Pki\CryptoEncoding\PEMBundle;
|
||||
use SpomkyLabs\Pki\X509\CertificationPath\CertificationPath;
|
||||
|
||||
/**
|
||||
* Ordered list of certificates from the end-entity to the trust anchor.
|
||||
*/
|
||||
final class CertificateChain implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* List of certificates in a chain.
|
||||
*
|
||||
* @var Certificate[]
|
||||
*/
|
||||
private readonly array $certs;
|
||||
|
||||
/**
|
||||
* @param Certificate ...$certs List of certificates, end-entity first
|
||||
*/
|
||||
private function __construct(Certificate ...$certs)
|
||||
{
|
||||
$this->certs = $certs;
|
||||
}
|
||||
|
||||
public static function create(Certificate ...$certs): self
|
||||
{
|
||||
return new self(...$certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from a list of PEMs.
|
||||
*/
|
||||
public static function fromPEMs(PEM ...$pems): self
|
||||
{
|
||||
$certs = array_map(Certificate::fromPEM(...), $pems);
|
||||
return self::create(...$certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from a string containing multiple PEM blocks.
|
||||
*/
|
||||
public static function fromPEMString(string $str): self
|
||||
{
|
||||
$pems = PEMBundle::fromString($str)->all();
|
||||
return self::fromPEMs(...$pems);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all certificates in a chain ordered from the end-entity certificate to the trust anchor.
|
||||
*
|
||||
* @return Certificate[]
|
||||
*/
|
||||
public function certificates(): array
|
||||
{
|
||||
return $this->certs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the end-entity certificate.
|
||||
*/
|
||||
public function endEntityCertificate(): Certificate
|
||||
{
|
||||
if (count($this->certs) === 0) {
|
||||
throw new LogicException('No certificates.');
|
||||
}
|
||||
return $this->certs[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the trust anchor certificate.
|
||||
*/
|
||||
public function trustAnchorCertificate(): Certificate
|
||||
{
|
||||
if (count($this->certs) === 0) {
|
||||
throw new LogicException('No certificates.');
|
||||
}
|
||||
return $this->certs[count($this->certs) - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert certificate chain to certification path.
|
||||
*/
|
||||
public function certificationPath(): CertificationPath
|
||||
{
|
||||
return CertificationPath::fromCertificateChain($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert certificate chain to string of PEM blocks.
|
||||
*/
|
||||
public function toPEMString(): string
|
||||
{
|
||||
return implode("\n", array_map(static fn (Certificate $cert) => $cert->toPEM()->string(), $this->certs));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->certs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for certificates.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->certs);
|
||||
}
|
||||
}
|
||||
184
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/AAControlsExtension.php
vendored
Normal file
184
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/AAControlsExtension.php
vendored
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Boolean;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements 'AA Controls' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-7.4
|
||||
*/
|
||||
final class AAControlsExtension extends Extension
|
||||
{
|
||||
/**
|
||||
* @param null|string[] $permittedAttrs
|
||||
* @param null|string[] $excludedAttrs
|
||||
*/
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly ?int $pathLenConstraint,
|
||||
private readonly ?array $permittedAttrs,
|
||||
private readonly ?array $excludedAttrs,
|
||||
private readonly bool $permitUnSpecified
|
||||
) {
|
||||
parent::__construct(self::OID_AA_CONTROLS, $critical);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $critical Path length contraint.
|
||||
* @param null|string[] $permittedAttrs Permitted attributes.
|
||||
* @param null|string[] $excludedAttrs Excluded attributes.
|
||||
* @param bool $permitUnSpecified Whether to permit unspecified attributes.
|
||||
*/
|
||||
public static function create(
|
||||
bool $critical,
|
||||
?int $pathLenConstraint = null,
|
||||
?array $permittedAttrs = null,
|
||||
?array $excludedAttrs = null,
|
||||
bool $permitUnSpecified = true
|
||||
): self {
|
||||
return new self($critical, $pathLenConstraint, $permittedAttrs, $excludedAttrs, $permitUnSpecified);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether path length constraint is present.
|
||||
*/
|
||||
public function hasPathLen(): bool
|
||||
{
|
||||
return isset($this->pathLenConstraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get path length constraint.
|
||||
*/
|
||||
public function pathLen(): int
|
||||
{
|
||||
if (! $this->hasPathLen()) {
|
||||
throw new LogicException('pathLen not set.');
|
||||
}
|
||||
return $this->pathLenConstraint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether permitted attributes are present.
|
||||
*/
|
||||
public function hasPermittedAttrs(): bool
|
||||
{
|
||||
return isset($this->permittedAttrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get OID's of permitted attributes.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function permittedAttrs(): array
|
||||
{
|
||||
if (! $this->hasPermittedAttrs()) {
|
||||
throw new LogicException('permittedAttrs not set.');
|
||||
}
|
||||
return $this->permittedAttrs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether excluded attributes are present.
|
||||
*/
|
||||
public function hasExcludedAttrs(): bool
|
||||
{
|
||||
return isset($this->excludedAttrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get OID's of excluded attributes.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function excludedAttrs(): array
|
||||
{
|
||||
if (! $this->hasExcludedAttrs()) {
|
||||
throw new LogicException('excludedAttrs not set.');
|
||||
}
|
||||
return $this->excludedAttrs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to permit attributes that are not explicitly specified in neither permitted nor excluded list.
|
||||
*/
|
||||
public function permitUnspecified(): bool
|
||||
{
|
||||
return $this->permitUnSpecified;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$seq = UnspecifiedType::fromDER($data)->asSequence();
|
||||
$path_len = null;
|
||||
$permitted = null;
|
||||
$excluded = null;
|
||||
$permit_unspecified = true;
|
||||
$idx = 0;
|
||||
if ($seq->has($idx, Element::TYPE_INTEGER)) {
|
||||
$path_len = $seq->at($idx++)
|
||||
->asInteger()
|
||||
->intNumber();
|
||||
}
|
||||
if ($seq->hasTagged(0)) {
|
||||
$attr_seq = $seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence();
|
||||
$permitted = array_map(
|
||||
static fn (UnspecifiedType $el) => $el->asObjectIdentifier()
|
||||
->oid(),
|
||||
$attr_seq->elements()
|
||||
);
|
||||
++$idx;
|
||||
}
|
||||
if ($seq->hasTagged(1)) {
|
||||
$attr_seq = $seq->getTagged(1)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence();
|
||||
$excluded = array_map(
|
||||
static fn (UnspecifiedType $el) => $el->asObjectIdentifier()
|
||||
->oid(),
|
||||
$attr_seq->elements()
|
||||
);
|
||||
++$idx;
|
||||
}
|
||||
if ($seq->has($idx, Element::TYPE_BOOLEAN)) {
|
||||
$permit_unspecified = $seq->at($idx)
|
||||
->asBoolean()
|
||||
->value();
|
||||
}
|
||||
return self::create($critical, $path_len, $permitted, $excluded, $permit_unspecified);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->pathLenConstraint)) {
|
||||
$elements[] = Integer::create($this->pathLenConstraint);
|
||||
}
|
||||
if (isset($this->permittedAttrs)) {
|
||||
$oids = array_map(ObjectIdentifier::create(...), $this->permittedAttrs);
|
||||
$elements[] = ImplicitlyTaggedType::create(0, Sequence::create(...$oids));
|
||||
}
|
||||
if (isset($this->excludedAttrs)) {
|
||||
$oids = array_map(ObjectIdentifier::create(...), $this->excludedAttrs);
|
||||
$elements[] = ImplicitlyTaggedType::create(1, Sequence::create(...$oids));
|
||||
}
|
||||
if (! $this->permitUnSpecified) {
|
||||
$elements[] = Boolean::create(false);
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\AccessDescription;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* Base class implementing *AccessDescription* ASN.1 type for 'Authority Information Access' and 'Subject Information
|
||||
* Access' certificate extensions.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.2.1
|
||||
*/
|
||||
abstract class AccessDescription
|
||||
{
|
||||
/**
|
||||
* @param string $accessMethod Access method OID
|
||||
* @param GeneralName $accessLocation Access location
|
||||
*/
|
||||
protected function __construct(
|
||||
protected readonly string $accessMethod,
|
||||
protected readonly GeneralName $accessLocation
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
abstract public static function fromASN1(Sequence $seq): static;
|
||||
|
||||
/**
|
||||
* Get the access method OID.
|
||||
*/
|
||||
public function accessMethod(): string
|
||||
{
|
||||
return $this->accessMethod;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the access location.
|
||||
*/
|
||||
public function accessLocation(): GeneralName
|
||||
{
|
||||
return $this->accessLocation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create(ObjectIdentifier::create($this->accessMethod), $this->accessLocation->toASN1());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\AccessDescription;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.2.1
|
||||
*/
|
||||
final class AuthorityAccessDescription extends AccessDescription
|
||||
{
|
||||
/**
|
||||
* Access method OID's.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const OID_METHOD_OSCP = '1.3.6.1.5.5.7.48.1';
|
||||
|
||||
public const OID_METHOD_CA_ISSUERS = '1.3.6.1.5.5.7.48.2';
|
||||
|
||||
public static function create(string $accessMethod, GeneralName $accessLocation): self
|
||||
{
|
||||
return new self($accessMethod, $accessLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): static
|
||||
{
|
||||
return new static($seq->at(0)->asObjectIdentifier()->oid(), GeneralName::fromASN1($seq->at(1)->asTagged()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether access method is OSCP.
|
||||
*/
|
||||
public function isOSCPMethod(): bool
|
||||
{
|
||||
return $this->accessMethod === self::OID_METHOD_OSCP;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether access method is CA issuers.
|
||||
*/
|
||||
public function isCAIssuersMethod(): bool
|
||||
{
|
||||
return $this->accessMethod === self::OID_METHOD_CA_ISSUERS;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\AccessDescription;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.2.2
|
||||
*/
|
||||
final class SubjectAccessDescription extends AccessDescription
|
||||
{
|
||||
/**
|
||||
* Access method OID's.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const OID_METHOD_TIME_STAMPING = '1.3.6.1.5.5.7.48.3';
|
||||
|
||||
public const OID_METHOD_CA_REPOSITORY = '1.3.6.1.5.5.7.48.5';
|
||||
|
||||
public static function create(string $accessMethod, GeneralName $accessLocation): self
|
||||
{
|
||||
return new self($accessMethod, $accessLocation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): static
|
||||
{
|
||||
return new static($seq->at(0)->asObjectIdentifier()->oid(), GeneralName::fromASN1($seq->at(1)->asTagged()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether access method is time stamping.
|
||||
*/
|
||||
public function isTimeStampingMethod(): bool
|
||||
{
|
||||
return $this->accessMethod === self::OID_METHOD_TIME_STAMPING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether access method is CA repository.
|
||||
*/
|
||||
public function isCARepositoryMethod(): bool
|
||||
{
|
||||
return $this->accessMethod === self::OID_METHOD_CA_REPOSITORY;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\AccessDescription\AccessDescription;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\AccessDescription\AuthorityAccessDescription;
|
||||
|
||||
/**
|
||||
* Implements 'Authority Information Access' extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.2.1
|
||||
*/
|
||||
final class AuthorityInformationAccessExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Access descriptions.
|
||||
*
|
||||
* @var AuthorityAccessDescription[]
|
||||
*/
|
||||
private readonly array $accessDescriptions;
|
||||
|
||||
private function __construct(bool $critical, AuthorityAccessDescription ...$access)
|
||||
{
|
||||
parent::__construct(self::OID_AUTHORITY_INFORMATION_ACCESS, $critical);
|
||||
$this->accessDescriptions = $access;
|
||||
}
|
||||
|
||||
public static function create(bool $critical, AuthorityAccessDescription ...$access): self
|
||||
{
|
||||
return new self($critical, ...$access);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the access descriptions.
|
||||
*
|
||||
* @return AuthorityAccessDescription[]
|
||||
*/
|
||||
public function accessDescriptions(): array
|
||||
{
|
||||
return $this->accessDescriptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of access descriptions.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->accessDescriptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for access descriptions.
|
||||
*
|
||||
* @return ArrayIterator List of AuthorityAccessDescription objects
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->accessDescriptions);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$access = array_map(
|
||||
static fn (UnspecifiedType $el) => AuthorityAccessDescription::fromASN1($el->asSequence()),
|
||||
UnspecifiedType::fromDER($data)->asSequence()->elements()
|
||||
);
|
||||
return self::create($critical, ...$access);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = array_map(static fn (AccessDescription $access) => $access->toASN1(), $this->accessDescriptions);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
163
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/AuthorityKeyIdentifierExtension.php
vendored
Normal file
163
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/AuthorityKeyIdentifierExtension.php
vendored
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements 'Authority Key Identifier' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.1
|
||||
*/
|
||||
final class AuthorityKeyIdentifierExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly ?string $keyIdentifier,
|
||||
private readonly ?GeneralNames $authorityCertIssuer,
|
||||
private readonly null|string $authorityCertSerialNumber
|
||||
) {
|
||||
parent::__construct(self::OID_AUTHORITY_KEY_IDENTIFIER, $critical);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $critical Conforming CA's must mark as non-critical (false)
|
||||
* @param null|string $keyIdentifier Key identifier
|
||||
* @param null|GeneralNames $authorityCertIssuer Issuer name
|
||||
*/
|
||||
public static function create(
|
||||
bool $critical,
|
||||
?string $keyIdentifier,
|
||||
?GeneralNames $authorityCertIssuer = null,
|
||||
null|string $authorityCertSerialNumber = null
|
||||
): self {
|
||||
return new self($critical, $keyIdentifier, $authorityCertIssuer, $authorityCertSerialNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create from public key info.
|
||||
*/
|
||||
public static function fromPublicKeyInfo(PublicKeyInfo $pki): self
|
||||
{
|
||||
return self::create(false, $pki->keyIdentifier());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether key identifier is present.
|
||||
*/
|
||||
public function hasKeyIdentifier(): bool
|
||||
{
|
||||
return isset($this->keyIdentifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get key identifier.
|
||||
*/
|
||||
public function keyIdentifier(): string
|
||||
{
|
||||
if (! $this->hasKeyIdentifier()) {
|
||||
throw new LogicException('keyIdentifier not set.');
|
||||
}
|
||||
return $this->keyIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether issuer is present.
|
||||
*/
|
||||
public function hasIssuer(): bool
|
||||
{
|
||||
return isset($this->authorityCertIssuer);
|
||||
}
|
||||
|
||||
public function issuer(): GeneralNames
|
||||
{
|
||||
if (! $this->hasIssuer()) {
|
||||
throw new LogicException('authorityCertIssuer not set.');
|
||||
}
|
||||
return $this->authorityCertIssuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether serial is present.
|
||||
*/
|
||||
public function hasSerial(): bool
|
||||
{
|
||||
return isset($this->authorityCertSerialNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get serial number.
|
||||
*
|
||||
* @return string Base 10 integer string
|
||||
*/
|
||||
public function serial(): string
|
||||
{
|
||||
if (! $this->hasSerial()) {
|
||||
throw new LogicException('authorityCertSerialNumber not set.');
|
||||
}
|
||||
return $this->authorityCertSerialNumber;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$seq = UnspecifiedType::fromDER($data)->asSequence();
|
||||
$keyIdentifier = null;
|
||||
$issuer = null;
|
||||
$serial = null;
|
||||
if ($seq->hasTagged(0)) {
|
||||
$keyIdentifier = $seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_OCTET_STRING)
|
||||
->asOctetString()
|
||||
->string();
|
||||
}
|
||||
if ($seq->hasTagged(1) || $seq->hasTagged(2)) {
|
||||
if (! $seq->hasTagged(1) || ! $seq->hasTagged(2)) {
|
||||
throw new UnexpectedValueException(
|
||||
'AuthorityKeyIdentifier must have both' .
|
||||
' authorityCertIssuer and authorityCertSerialNumber' .
|
||||
' present or both absent.'
|
||||
);
|
||||
}
|
||||
$issuer = GeneralNames::fromASN1($seq->getTagged(1)->asImplicit(Element::TYPE_SEQUENCE)->asSequence());
|
||||
$serial = $seq->getTagged(2)
|
||||
->asImplicit(Element::TYPE_INTEGER)
|
||||
->asInteger()
|
||||
->number();
|
||||
}
|
||||
return self::create($critical, $keyIdentifier, $issuer, $serial);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->keyIdentifier)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, OctetString::create($this->keyIdentifier));
|
||||
}
|
||||
// if either issuer or serial is set, both must be set
|
||||
if (isset($this->authorityCertIssuer) ||
|
||||
isset($this->authorityCertSerialNumber)) {
|
||||
if (! isset($this->authorityCertIssuer,
|
||||
$this->authorityCertSerialNumber)) {
|
||||
throw new LogicException(
|
||||
'AuthorityKeyIdentifier must have both' .
|
||||
' authorityCertIssuer and authorityCertSerialNumber' .
|
||||
' present or both absent.'
|
||||
);
|
||||
}
|
||||
$elements[] = ImplicitlyTaggedType::create(1, $this->authorityCertIssuer->toASN1());
|
||||
$elements[] = ImplicitlyTaggedType::create(2, Integer::create($this->authorityCertSerialNumber));
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
95
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/BasicConstraintsExtension.php
vendored
Normal file
95
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/BasicConstraintsExtension.php
vendored
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Boolean;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements 'Basic Constraints' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.9
|
||||
*/
|
||||
final class BasicConstraintsExtension extends Extension
|
||||
{
|
||||
/**
|
||||
* @param bool $ca Whether certificate is a CA.
|
||||
* @param int|null $pathLen Maximum certification path length.
|
||||
*/
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly bool $ca,
|
||||
private readonly ?int $pathLen
|
||||
) {
|
||||
parent::__construct(self::OID_BASIC_CONSTRAINTS, $critical);
|
||||
}
|
||||
|
||||
public static function create(bool $critical, bool $ca, ?int $pathLen = null): self
|
||||
{
|
||||
return new self($critical, $ca, $pathLen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether certificate is a CA.
|
||||
*/
|
||||
public function isCA(): bool
|
||||
{
|
||||
return $this->ca;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether path length is present.
|
||||
*/
|
||||
public function hasPathLen(): bool
|
||||
{
|
||||
return isset($this->pathLen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get path length.
|
||||
*/
|
||||
public function pathLen(): int
|
||||
{
|
||||
if (! $this->hasPathLen()) {
|
||||
throw new LogicException('pathLenConstraint not set.');
|
||||
}
|
||||
return $this->pathLen;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$seq = UnspecifiedType::fromDER($data)->asSequence();
|
||||
$ca = false;
|
||||
$path_len = null;
|
||||
$idx = 0;
|
||||
if ($seq->has($idx, Element::TYPE_BOOLEAN)) {
|
||||
$ca = $seq->at($idx++)
|
||||
->asBoolean()
|
||||
->value();
|
||||
}
|
||||
if ($seq->has($idx, Element::TYPE_INTEGER)) {
|
||||
$path_len = $seq->at($idx)
|
||||
->asInteger()
|
||||
->intNumber();
|
||||
}
|
||||
return self::create($critical, $ca, $path_len);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if ($this->ca) {
|
||||
$elements[] = Boolean::create(true);
|
||||
}
|
||||
if (isset($this->pathLen)) {
|
||||
$elements[] = Integer::create($this->pathLen);
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\DistributionPoint\DistributionPoint;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements 'CRL Distribution Points' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.13
|
||||
*/
|
||||
class CRLDistributionPointsExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Distribution points.
|
||||
*
|
||||
* @var DistributionPoint[]
|
||||
*/
|
||||
protected array $distributionPoints;
|
||||
|
||||
protected function __construct(string $oid, bool $critical, DistributionPoint ...$distributionPoints)
|
||||
{
|
||||
parent::__construct($oid, $critical);
|
||||
$this->distributionPoints = $distributionPoints;
|
||||
}
|
||||
|
||||
public static function create(bool $critical, DistributionPoint ...$distribution_points): self
|
||||
{
|
||||
return new self(self::OID_CRL_DISTRIBUTION_POINTS, $critical, ...$distribution_points);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get distribution points.
|
||||
*
|
||||
* @return DistributionPoint[]
|
||||
*/
|
||||
public function distributionPoints(): array
|
||||
{
|
||||
return $this->distributionPoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of distribution points.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->distributionPoints);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for distribution points.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->distributionPoints);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$dps = array_map(
|
||||
static fn (UnspecifiedType $el) => DistributionPoint::fromASN1($el->asSequence()),
|
||||
UnspecifiedType::fromDER($data)->asSequence()->elements()
|
||||
);
|
||||
if (count($dps) === 0) {
|
||||
throw new UnexpectedValueException('CRLDistributionPoints must have at least one DistributionPoint.');
|
||||
}
|
||||
// late static bound, extended by Freshest CRL extension
|
||||
return static::create($critical, ...$dps);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
if (count($this->distributionPoints) === 0) {
|
||||
throw new LogicException('No distribution points.');
|
||||
}
|
||||
$elements = array_map(static fn (DistributionPoint $dp) => $dp->toASN1(), $this->distributionPoints);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
124
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/CertificatePoliciesExtension.php
vendored
Normal file
124
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/CertificatePoliciesExtension.php
vendored
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements 'Certificate Policies' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.4
|
||||
*/
|
||||
final class CertificatePoliciesExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Policy information terms.
|
||||
*
|
||||
* @var PolicyInformation[]
|
||||
*/
|
||||
protected array $_policies;
|
||||
|
||||
private function __construct(bool $critical, PolicyInformation ...$policies)
|
||||
{
|
||||
parent::__construct(Extension::OID_CERTIFICATE_POLICIES, $critical);
|
||||
$this->_policies = [];
|
||||
foreach ($policies as $policy) {
|
||||
$this->_policies[$policy->oid()] = $policy;
|
||||
}
|
||||
}
|
||||
|
||||
public static function create(bool $critical, PolicyInformation ...$policies): self
|
||||
{
|
||||
return new self($critical, ...$policies);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether policy information by OID is present.
|
||||
*/
|
||||
public function has(string $oid): bool
|
||||
{
|
||||
return isset($this->_policies[$oid]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get policy information by OID.
|
||||
*/
|
||||
public function get(string $oid): PolicyInformation
|
||||
{
|
||||
if (! $this->has($oid)) {
|
||||
throw new LogicException("Not certificate policy by OID {$oid}.");
|
||||
}
|
||||
return $this->_policies[$oid];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether anyPolicy is present.
|
||||
*/
|
||||
public function hasAnyPolicy(): bool
|
||||
{
|
||||
return $this->has(PolicyInformation::OID_ANY_POLICY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get anyPolicy information.
|
||||
*/
|
||||
public function anyPolicy(): PolicyInformation
|
||||
{
|
||||
if (! $this->hasAnyPolicy()) {
|
||||
throw new LogicException('No anyPolicy.');
|
||||
}
|
||||
return $this->get(PolicyInformation::OID_ANY_POLICY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of policies.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->_policies);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for policy information terms.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->_policies);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$policies = array_map(
|
||||
static fn (UnspecifiedType $el) => PolicyInformation::fromASN1($el->asSequence()),
|
||||
UnspecifiedType::fromDER($data)->asSequence()->elements()
|
||||
);
|
||||
if (count($policies) === 0) {
|
||||
throw new UnexpectedValueException('certificatePolicies must contain at least one PolicyInformation.');
|
||||
}
|
||||
return self::create($critical, ...$policies);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
if (count($this->_policies) === 0) {
|
||||
throw new LogicException('No policies.');
|
||||
}
|
||||
$elements = array_map(static fn (PolicyInformation $pi) => $pi->toASN1(), array_values($this->_policies));
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\IA5String;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *CPSuri* ASN.1 type used by 'Certificate Policies' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.4
|
||||
*/
|
||||
final class CPSQualifier extends PolicyQualifierInfo
|
||||
{
|
||||
private function __construct(
|
||||
private readonly string $uri
|
||||
) {
|
||||
parent::__construct(self::OID_CPS);
|
||||
}
|
||||
|
||||
public static function create(string $uri): self
|
||||
{
|
||||
return new self($uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromQualifierASN1(UnspecifiedType $el): PolicyQualifierInfo
|
||||
{
|
||||
return self::create($el->asString()->string());
|
||||
}
|
||||
|
||||
public function uri(): string
|
||||
{
|
||||
return $this->uri;
|
||||
}
|
||||
|
||||
protected function qualifierASN1(): Element
|
||||
{
|
||||
return IA5String::create($this->uri);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\BMPString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\IA5String;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\UTF8String;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\VisibleString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\StringType;
|
||||
use Stringable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *DisplayText* ASN.1 CHOICE type used by 'Certificate Policies' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.4
|
||||
*/
|
||||
final class DisplayText implements Stringable
|
||||
{
|
||||
private function __construct(
|
||||
private readonly string $text,
|
||||
private readonly int $tag
|
||||
) {
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->string();
|
||||
}
|
||||
|
||||
public static function create(string $text, int $tag): self
|
||||
{
|
||||
return new self($text, $tag);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(StringType $el): self
|
||||
{
|
||||
return self::create($el->string(), $el->tag());
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from a UTF-8 string.
|
||||
*/
|
||||
public static function fromString(string $str): self
|
||||
{
|
||||
return self::create($str, Element::TYPE_UTF8_STRING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the text.
|
||||
*/
|
||||
public function string(): string
|
||||
{
|
||||
return $this->text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 element.
|
||||
*/
|
||||
public function toASN1(): StringType
|
||||
{
|
||||
return match ($this->tag) {
|
||||
Element::TYPE_IA5_STRING => IA5String::create($this->text),
|
||||
Element::TYPE_VISIBLE_STRING => VisibleString::create($this->text),
|
||||
Element::TYPE_BMP_STRING => BMPString::create($this->text),
|
||||
Element::TYPE_UTF8_STRING => UTF8String::create($this->text),
|
||||
default => throw new UnexpectedValueException('Type ' . Element::tagToName(
|
||||
$this->tag
|
||||
) . ' not supported.'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *NoticeReference* ASN.1 type used by 'Certificate Policies' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.4
|
||||
*/
|
||||
final class NoticeReference
|
||||
{
|
||||
/**
|
||||
* Notification reference numbers.
|
||||
*
|
||||
* @var int[]
|
||||
*/
|
||||
private readonly array $numbers;
|
||||
|
||||
private function __construct(
|
||||
private readonly DisplayText $organization,
|
||||
int ...$numbers
|
||||
) {
|
||||
$this->numbers = $numbers;
|
||||
}
|
||||
|
||||
public static function create(DisplayText $organization, int ...$numbers): self
|
||||
{
|
||||
return new self($organization, ...$numbers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$org = DisplayText::fromASN1($seq->at(0)->asString());
|
||||
$numbers = array_map(
|
||||
static fn (UnspecifiedType $el) => $el->asInteger()
|
||||
->intNumber(),
|
||||
$seq->at(1)
|
||||
->asSequence()
|
||||
->elements()
|
||||
);
|
||||
return self::create($org, ...$numbers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get reference organization.
|
||||
*/
|
||||
public function organization(): DisplayText
|
||||
{
|
||||
return $this->organization;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get reference numbers.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public function numbers(): array
|
||||
{
|
||||
return $this->numbers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$org = $this->organization->toASN1();
|
||||
$nums = array_map(Integer::create(...), $this->numbers);
|
||||
return Sequence::create($org, Sequence::create(...$nums));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,190 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *PolicyInformation* ASN.1 type used by 'Certificate Policies' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.4
|
||||
*/
|
||||
final class PolicyInformation implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Wildcard policy.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const OID_ANY_POLICY = '2.5.29.32.0';
|
||||
|
||||
/**
|
||||
* Policy qualifiers.
|
||||
*
|
||||
* @var PolicyQualifierInfo[]
|
||||
*/
|
||||
private array $qualifiers;
|
||||
|
||||
private function __construct(
|
||||
private readonly string $oid,
|
||||
PolicyQualifierInfo ...$qualifiers
|
||||
) {
|
||||
$this->qualifiers = [];
|
||||
foreach ($qualifiers as $qualifier) {
|
||||
$this->qualifiers[$qualifier->oid()] = $qualifier;
|
||||
}
|
||||
}
|
||||
|
||||
public static function create(string $oid, PolicyQualifierInfo ...$qualifiers): self
|
||||
{
|
||||
return new self($oid, ...$qualifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$oid = $seq->at(0)
|
||||
->asObjectIdentifier()
|
||||
->oid();
|
||||
$qualifiers = [];
|
||||
if (count($seq) > 1) {
|
||||
$qualifiers = array_map(
|
||||
static fn (UnspecifiedType $el) => PolicyQualifierInfo::fromASN1($el->asSequence()),
|
||||
$seq->at(1)
|
||||
->asSequence()
|
||||
->elements()
|
||||
);
|
||||
}
|
||||
return self::create($oid, ...$qualifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get policy identifier.
|
||||
*/
|
||||
public function oid(): string
|
||||
{
|
||||
return $this->oid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether this policy is anyPolicy.
|
||||
*/
|
||||
public function isAnyPolicy(): bool
|
||||
{
|
||||
return $this->oid === self::OID_ANY_POLICY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get policy qualifiers.
|
||||
*
|
||||
* @return PolicyQualifierInfo[]
|
||||
*/
|
||||
public function qualifiers(): array
|
||||
{
|
||||
return array_values($this->qualifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether qualifier is present.
|
||||
*/
|
||||
public function has(string $oid): bool
|
||||
{
|
||||
return isset($this->qualifiers[$oid]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get qualifier by OID.
|
||||
*/
|
||||
public function get(string $oid): PolicyQualifierInfo
|
||||
{
|
||||
if (! $this->has($oid)) {
|
||||
throw new LogicException("No {$oid} qualifier.");
|
||||
}
|
||||
return $this->qualifiers[$oid];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether CPS qualifier is present.
|
||||
*/
|
||||
public function hasCPSQualifier(): bool
|
||||
{
|
||||
return $this->has(PolicyQualifierInfo::OID_CPS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get CPS qualifier.
|
||||
*/
|
||||
public function CPSQualifier(): CPSQualifier
|
||||
{
|
||||
if (! $this->hasCPSQualifier()) {
|
||||
throw new LogicException('CPS qualifier not set.');
|
||||
}
|
||||
return $this->get(PolicyQualifierInfo::OID_CPS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether user notice qualifier is present.
|
||||
*/
|
||||
public function hasUserNoticeQualifier(): bool
|
||||
{
|
||||
return $this->has(PolicyQualifierInfo::OID_UNOTICE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user notice qualifier.
|
||||
*/
|
||||
public function userNoticeQualifier(): UserNoticeQualifier
|
||||
{
|
||||
if (! $this->hasUserNoticeQualifier()) {
|
||||
throw new LogicException('User notice qualifier not set.');
|
||||
}
|
||||
return $this->get(PolicyQualifierInfo::OID_UNOTICE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [ObjectIdentifier::create($this->oid)];
|
||||
if (count($this->qualifiers) !== 0) {
|
||||
$qualifiers = array_map(
|
||||
static fn (PolicyQualifierInfo $pqi) => $pqi->toASN1(),
|
||||
array_values($this->qualifiers)
|
||||
);
|
||||
$elements[] = Sequence::create(...$qualifiers);
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of qualifiers.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->qualifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for qualifiers.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->qualifiers);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Base class for *PolicyQualifierInfo* ASN.1 types used by 'Certificate Policies' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.4
|
||||
*/
|
||||
abstract class PolicyQualifierInfo
|
||||
{
|
||||
/**
|
||||
* OID for the CPS Pointer qualifier.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const OID_CPS = '1.3.6.1.5.5.7.2.1';
|
||||
|
||||
/**
|
||||
* OID for the user notice qualifier.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const OID_UNOTICE = '1.3.6.1.5.5.7.2.2';
|
||||
|
||||
protected function __construct(
|
||||
protected string $oid
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from qualifier ASN.1 element.
|
||||
*/
|
||||
abstract public static function fromQualifierASN1(UnspecifiedType $el): self;
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$oid = $seq->at(0)
|
||||
->asObjectIdentifier()
|
||||
->oid();
|
||||
return match ($oid) {
|
||||
self::OID_CPS => CPSQualifier::fromQualifierASN1($seq->at(1)),
|
||||
self::OID_UNOTICE => UserNoticeQualifier::fromQualifierASN1($seq->at(1)),
|
||||
default => throw new UnexpectedValueException("Qualifier {$oid} not supported."),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get qualifier identifier.
|
||||
*/
|
||||
public function oid(): string
|
||||
{
|
||||
return $this->oid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create(ObjectIdentifier::create($this->oid), $this->qualifierASN1());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 for the 'qualifier' field.
|
||||
*/
|
||||
abstract protected function qualifierASN1(): Element;
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *UserNotice* ASN.1 type used by 'Certificate Policies' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.4
|
||||
*/
|
||||
final class UserNoticeQualifier extends PolicyQualifierInfo
|
||||
{
|
||||
private function __construct(
|
||||
private readonly ?DisplayText $text,
|
||||
private readonly ?NoticeReference $ref
|
||||
) {
|
||||
parent::__construct(self::OID_UNOTICE);
|
||||
}
|
||||
|
||||
public static function create(?DisplayText $text = null, ?NoticeReference $ref = null): self
|
||||
{
|
||||
return new self($text, $ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromQualifierASN1(UnspecifiedType $el): PolicyQualifierInfo
|
||||
{
|
||||
$seq = $el->asSequence();
|
||||
$ref = null;
|
||||
$text = null;
|
||||
$idx = 0;
|
||||
if ($seq->has($idx, Element::TYPE_SEQUENCE)) {
|
||||
$ref = NoticeReference::fromASN1($seq->at($idx++)->asSequence());
|
||||
}
|
||||
if ($seq->has($idx, Element::TYPE_STRING)) {
|
||||
$text = DisplayText::fromASN1($seq->at($idx)->asString());
|
||||
}
|
||||
return self::create($text, $ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether explicit text is present.
|
||||
*/
|
||||
public function hasExplicitText(): bool
|
||||
{
|
||||
return isset($this->text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get explicit text.
|
||||
*/
|
||||
public function explicitText(): DisplayText
|
||||
{
|
||||
if (! $this->hasExplicitText()) {
|
||||
throw new LogicException('explicitText not set.');
|
||||
}
|
||||
return $this->text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether notice reference is present.
|
||||
*/
|
||||
public function hasNoticeRef(): bool
|
||||
{
|
||||
return isset($this->ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get notice reference.
|
||||
*/
|
||||
public function noticeRef(): NoticeReference
|
||||
{
|
||||
if (! $this->hasNoticeRef()) {
|
||||
throw new LogicException('noticeRef not set.');
|
||||
}
|
||||
return $this->ref;
|
||||
}
|
||||
|
||||
protected function qualifierASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->ref)) {
|
||||
$elements[] = $this->ref->toASN1();
|
||||
}
|
||||
if (isset($this->text)) {
|
||||
$elements[] = $this->text->toASN1();
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\DistributionPoint;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
|
||||
/**
|
||||
* Implements *DistributionPoint* ASN.1 type used by 'CRL Distribution Points' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.13
|
||||
*/
|
||||
final class DistributionPoint
|
||||
{
|
||||
private function __construct(
|
||||
private readonly ?DistributionPointName $distributionPoint,
|
||||
private readonly ?ReasonFlags $reasons,
|
||||
private readonly ?GeneralNames $issuer
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(
|
||||
?DistributionPointName $distributionPoint = null,
|
||||
?ReasonFlags $reasons = null,
|
||||
?GeneralNames $issuer = null
|
||||
): self {
|
||||
return new self($distributionPoint, $reasons, $issuer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$name = null;
|
||||
$reasons = null;
|
||||
$issuer = null;
|
||||
if ($seq->hasTagged(0)) {
|
||||
// promoted to explicit tagging because underlying type is CHOICE
|
||||
$name = DistributionPointName::fromTaggedType($seq->getTagged(0)->asExplicit()->asTagged());
|
||||
}
|
||||
if ($seq->hasTagged(1)) {
|
||||
$reasons = ReasonFlags::fromASN1(
|
||||
$seq->getTagged(1)
|
||||
->asImplicit(Element::TYPE_BIT_STRING)
|
||||
->asBitString()
|
||||
);
|
||||
}
|
||||
if ($seq->hasTagged(2)) {
|
||||
$issuer = GeneralNames::fromASN1(
|
||||
$seq->getTagged(2)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)
|
||||
->asSequence()
|
||||
);
|
||||
}
|
||||
return self::create($name, $reasons, $issuer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether distribution point name is set.
|
||||
*/
|
||||
public function hasDistributionPointName(): bool
|
||||
{
|
||||
return isset($this->distributionPoint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get distribution point name.
|
||||
*/
|
||||
public function distributionPointName(): DistributionPointName
|
||||
{
|
||||
if (! $this->hasDistributionPointName()) {
|
||||
throw new LogicException('distributionPoint not set.');
|
||||
}
|
||||
return $this->distributionPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether distribution point name is set, and it's a full name.
|
||||
*/
|
||||
public function hasFullName(): bool
|
||||
{
|
||||
return $this->distributionPointName()
|
||||
->tag() ===
|
||||
DistributionPointName::TAG_FULL_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get full distribution point name.
|
||||
*/
|
||||
public function fullName(): FullName
|
||||
{
|
||||
if (! $this->distributionPoint instanceof FullName || ! $this->hasFullName()) {
|
||||
throw new LogicException('fullName not set.');
|
||||
}
|
||||
return $this->distributionPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether distribution point name is set and it's a relative name.
|
||||
*/
|
||||
public function hasRelativeName(): bool
|
||||
{
|
||||
return $this->distributionPointName()
|
||||
->tag() ===
|
||||
DistributionPointName::TAG_RDN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get relative distribution point name.
|
||||
*/
|
||||
public function relativeName(): RelativeName
|
||||
{
|
||||
if (! $this->distributionPoint instanceof RelativeName || ! $this->hasRelativeName()) {
|
||||
throw new LogicException('nameRelativeToCRLIssuer not set.');
|
||||
}
|
||||
return $this->distributionPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether reasons flags is set.
|
||||
*/
|
||||
public function hasReasons(): bool
|
||||
{
|
||||
return isset($this->reasons);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get revocation reason flags.
|
||||
*/
|
||||
public function reasons(): ReasonFlags
|
||||
{
|
||||
if (! $this->hasReasons()) {
|
||||
throw new LogicException('reasons not set.');
|
||||
}
|
||||
return $this->reasons;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether cRLIssuer is set.
|
||||
*/
|
||||
public function hasCRLIssuer(): bool
|
||||
{
|
||||
return isset($this->issuer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get CRL issuer.
|
||||
*/
|
||||
public function crlIssuer(): GeneralNames
|
||||
{
|
||||
if (! $this->hasCRLIssuer()) {
|
||||
throw new LogicException('crlIssuer not set.');
|
||||
}
|
||||
return $this->issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->distributionPoint)) {
|
||||
$elements[] = ExplicitlyTaggedType::create(0, $this->distributionPoint->toASN1());
|
||||
}
|
||||
if (isset($this->reasons)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(1, $this->reasons->toASN1());
|
||||
}
|
||||
if (isset($this->issuer)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(2, $this->issuer->toASN1());
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\DistributionPoint;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\RDN;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Base class for *DistributionPointName* ASN.1 CHOICE type used by 'CRL Distribution Points' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.13
|
||||
*/
|
||||
abstract class DistributionPointName
|
||||
{
|
||||
public const TAG_FULL_NAME = 0;
|
||||
|
||||
public const TAG_RDN = 1;
|
||||
|
||||
protected function __construct(
|
||||
protected int $tag
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from TaggedType.
|
||||
*/
|
||||
public static function fromTaggedType(TaggedType $el): self
|
||||
{
|
||||
return match ($el->tag()) {
|
||||
self::TAG_FULL_NAME => FullName::create(GeneralNames::fromASN1(
|
||||
$el->asImplicit(Element::TYPE_SEQUENCE)->asSequence()
|
||||
)),
|
||||
self::TAG_RDN => RelativeName::create(RDN::fromASN1($el->asImplicit(Element::TYPE_SET)->asSet())),
|
||||
default => throw new UnexpectedValueException(
|
||||
'DistributionPointName tag ' . $el->tag() . ' not supported.'
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get type tag.
|
||||
*/
|
||||
public function tag(): int
|
||||
{
|
||||
return $this->tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): ImplicitlyTaggedType
|
||||
{
|
||||
return ImplicitlyTaggedType::create($this->tag, $this->_valueASN1());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 element.
|
||||
*/
|
||||
abstract protected function _valueASN1(): Element;
|
||||
}
|
||||
47
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/DistributionPoint/FullName.php
vendored
Normal file
47
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/DistributionPoint/FullName.php
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\DistributionPoint;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\UniformResourceIdentifier;
|
||||
|
||||
/**
|
||||
* Implements 'fullName' ASN.1 CHOICE type of *DistributionPointName* used by 'CRL Distribution Points' certificate
|
||||
* extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.13
|
||||
*/
|
||||
final class FullName extends DistributionPointName
|
||||
{
|
||||
private function __construct(
|
||||
private readonly GeneralNames $names
|
||||
) {
|
||||
parent::__construct(self::TAG_FULL_NAME);
|
||||
}
|
||||
|
||||
public static function create(GeneralNames $names): self
|
||||
{
|
||||
return new self($names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize with a single URI.
|
||||
*/
|
||||
public static function fromURI(string $uri): self
|
||||
{
|
||||
return self::create(GeneralNames::create(UniformResourceIdentifier::create($uri)));
|
||||
}
|
||||
|
||||
public function names(): GeneralNames
|
||||
{
|
||||
return $this->names;
|
||||
}
|
||||
|
||||
protected function _valueASN1(): Element
|
||||
{
|
||||
return $this->names->toASN1();
|
||||
}
|
||||
}
|
||||
133
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/DistributionPoint/ReasonFlags.php
vendored
Normal file
133
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/DistributionPoint/ReasonFlags.php
vendored
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\DistributionPoint;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
|
||||
use SpomkyLabs\Pki\ASN1\Util\Flags;
|
||||
|
||||
/**
|
||||
* Implements *ReasonFlags* ASN.1 type used by 'CRL Distribution Points' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.13
|
||||
*/
|
||||
final class ReasonFlags
|
||||
{
|
||||
// const UNUSED = 0x100;
|
||||
public const KEY_COMPROMISE = 0x080;
|
||||
|
||||
public const CA_COMPROMISE = 0x040;
|
||||
|
||||
public const AFFILIATION_CHANGED = 0x020;
|
||||
|
||||
public const SUPERSEDED = 0x010;
|
||||
|
||||
public const CESSATION_OF_OPERATION = 0x008;
|
||||
|
||||
public const CERTIFICATE_HOLD = 0x004;
|
||||
|
||||
public const PRIVILEGE_WITHDRAWN = 0x002;
|
||||
|
||||
public const AA_COMPROMISE = 0x001;
|
||||
|
||||
private function __construct(
|
||||
private readonly int $flags
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(int $flags): self
|
||||
{
|
||||
return new self($flags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(BitString $bs): self
|
||||
{
|
||||
return self::create(Flags::fromBitString($bs, 9)->intNumber());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether keyCompromise flag is set.
|
||||
*/
|
||||
public function isKeyCompromise(): bool
|
||||
{
|
||||
return $this->flagSet(self::KEY_COMPROMISE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether cACompromise flag is set.
|
||||
*/
|
||||
public function isCACompromise(): bool
|
||||
{
|
||||
return $this->flagSet(self::CA_COMPROMISE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether affiliationChanged flag is set.
|
||||
*/
|
||||
public function isAffiliationChanged(): bool
|
||||
{
|
||||
return $this->flagSet(self::AFFILIATION_CHANGED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether superseded flag is set.
|
||||
*/
|
||||
public function isSuperseded(): bool
|
||||
{
|
||||
return $this->flagSet(self::SUPERSEDED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether cessationOfOperation flag is set.
|
||||
*/
|
||||
public function isCessationOfOperation(): bool
|
||||
{
|
||||
return $this->flagSet(self::CESSATION_OF_OPERATION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether certificateHold flag is set.
|
||||
*/
|
||||
public function isCertificateHold(): bool
|
||||
{
|
||||
return $this->flagSet(self::CERTIFICATE_HOLD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether privilegeWithdrawn flag is set.
|
||||
*/
|
||||
public function isPrivilegeWithdrawn(): bool
|
||||
{
|
||||
return $this->flagSet(self::PRIVILEGE_WITHDRAWN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether aACompromise flag is set.
|
||||
*/
|
||||
public function isAACompromise(): bool
|
||||
{
|
||||
return $this->flagSet(self::AA_COMPROMISE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 element.
|
||||
*/
|
||||
public function toASN1(): BitString
|
||||
{
|
||||
$flags = Flags::create($this->flags, 9);
|
||||
return $flags->bitString()
|
||||
->withoutTrailingZeroes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether given flag is set.
|
||||
*/
|
||||
private function flagSet(int $flag): bool
|
||||
{
|
||||
return (bool) ($this->flags & $flag);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\DistributionPoint;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\X501\ASN1\RDN;
|
||||
|
||||
/**
|
||||
* Implements 'nameRelativeToCRLIssuer' ASN.1 CHOICE type of *DistributionPointName* used by 'CRL Distribution Points'
|
||||
* certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.13
|
||||
*/
|
||||
final class RelativeName extends DistributionPointName
|
||||
{
|
||||
private function __construct(
|
||||
private readonly RDN $rdn
|
||||
) {
|
||||
parent::__construct(self::TAG_RDN);
|
||||
}
|
||||
|
||||
public static function create(RDN $rdn): self
|
||||
{
|
||||
return new self($rdn);
|
||||
}
|
||||
|
||||
public function rdn(): RDN
|
||||
{
|
||||
return $this->rdn;
|
||||
}
|
||||
|
||||
protected function _valueASN1(): Element
|
||||
{
|
||||
return $this->rdn->toASN1();
|
||||
}
|
||||
}
|
||||
160
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/ExtendedKeyUsageExtension.php
vendored
Normal file
160
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/ExtendedKeyUsageExtension.php
vendored
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use function in_array;
|
||||
use IteratorAggregate;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements 'Extended Key Usage' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.12
|
||||
*/
|
||||
final class ExtendedKeyUsageExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
public const OID_SERVER_AUTH = '1.3.6.1.5.5.7.3.1';
|
||||
|
||||
public const OID_CLIENT_AUTH = '1.3.6.1.5.5.7.3.2';
|
||||
|
||||
public const OID_CODE_SIGNING = '1.3.6.1.5.5.7.3.3';
|
||||
|
||||
public const OID_EMAIL_PROTECTION = '1.3.6.1.5.5.7.3.4';
|
||||
|
||||
public const OID_IPSEC_END_SYSTEM = '1.3.6.1.5.5.7.3.5';
|
||||
|
||||
public const OID_IPSEC_TUNNEL = '1.3.6.1.5.5.7.3.6';
|
||||
|
||||
public const OID_IPSEC_USER = '1.3.6.1.5.5.7.3.7';
|
||||
|
||||
public const OID_TIME_STAMPING = '1.3.6.1.5.5.7.3.8';
|
||||
|
||||
public const OID_OCSP_SIGNING = '1.3.6.1.5.5.7.3.9';
|
||||
|
||||
public const OID_DVCS = '1.3.6.1.5.5.7.3.10';
|
||||
|
||||
public const OID_SBGP_CERT_AA_SERVER_AUTH = '1.3.6.1.5.5.7.3.11';
|
||||
|
||||
public const OID_SCVP_RESPONDER = '1.3.6.1.5.5.7.3.12';
|
||||
|
||||
public const OID_EAP_OVER_PPP = '1.3.6.1.5.5.7.3.13';
|
||||
|
||||
public const OID_EAP_OVER_LAN = '1.3.6.1.5.5.7.3.14';
|
||||
|
||||
public const OID_SCVP_SERVER = '1.3.6.1.5.5.7.3.15';
|
||||
|
||||
public const OID_SCVP_CLIENT = '1.3.6.1.5.5.7.3.16';
|
||||
|
||||
public const OID_IPSEC_IKE = '1.3.6.1.5.5.7.3.17';
|
||||
|
||||
public const OID_CAPWAP_AC = '1.3.6.1.5.5.7.3.18';
|
||||
|
||||
public const OID_CAPWAP_WTP = '1.3.6.1.5.5.7.3.19';
|
||||
|
||||
public const OID_SIP_DOMAIN = '1.3.6.1.5.5.7.3.20';
|
||||
|
||||
public const OID_SECURE_SHELL_CLIENT = '1.3.6.1.5.5.7.3.21';
|
||||
|
||||
public const OID_SECURE_SHELL_SERVER = '1.3.6.1.5.5.7.3.22';
|
||||
|
||||
public const OID_SEND_ROUTER = '1.3.6.1.5.5.7.3.23';
|
||||
|
||||
public const OID_SEND_PROXY = '1.3.6.1.5.5.7.3.24';
|
||||
|
||||
public const OID_SEND_OWNER = '1.3.6.1.5.5.7.3.25';
|
||||
|
||||
public const OID_SEND_PROXIED_OWNER = '1.3.6.1.5.5.7.3.26';
|
||||
|
||||
public const OID_CMC_CA = '1.3.6.1.5.5.7.3.27';
|
||||
|
||||
public const OID_CMC_RA = '1.3.6.1.5.5.7.3.28';
|
||||
|
||||
public const OID_CMC_ARCHIVE = '1.3.6.1.5.5.7.3.29';
|
||||
|
||||
/**
|
||||
* Purpose OID's.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private readonly array $purposes;
|
||||
|
||||
private function __construct(bool $critical, string ...$purposes)
|
||||
{
|
||||
parent::__construct(self::OID_EXT_KEY_USAGE, $critical);
|
||||
$this->purposes = $purposes;
|
||||
}
|
||||
|
||||
public static function create(bool $critical, string ...$purposes): self
|
||||
{
|
||||
return new self($critical, ...$purposes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether purposes are present.
|
||||
*
|
||||
* If multiple purposes are checked, all must be present.
|
||||
*/
|
||||
public function has(string ...$oids): bool
|
||||
{
|
||||
foreach ($oids as $oid) {
|
||||
if (! in_array($oid, $this->purposes, true)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get key usage purpose OID's.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function purposes(): array
|
||||
{
|
||||
return $this->purposes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of purposes.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->purposes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for usage purposes.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->purposes);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$purposes = array_map(
|
||||
static fn (UnspecifiedType $el) => $el->asObjectIdentifier()
|
||||
->oid(),
|
||||
UnspecifiedType::fromDER($data)->asSequence()->elements()
|
||||
);
|
||||
return self::create($critical, ...$purposes);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = array_map(ObjectIdentifier::create(...), $this->purposes);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
336
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Extension.php
vendored
Normal file
336
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Extension.php
vendored
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use function array_key_exists;
|
||||
use function count;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Exception\DecodeException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Boolean;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
|
||||
use function sprintf;
|
||||
use Stringable;
|
||||
|
||||
/**
|
||||
* Base class for certificate extensions.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.1
|
||||
*/
|
||||
abstract class Extension implements Stringable
|
||||
{
|
||||
// OID's from standard certificate extensions
|
||||
public const OID_OBSOLETE_AUTHORITY_KEY_IDENTIFIER = '2.5.29.1';
|
||||
|
||||
public const OID_OBSOLETE_KEY_ATTRIBUTES = '2.5.29.2';
|
||||
|
||||
public const OID_OBSOLETE_CERTIFICATE_POLICIES = '2.5.29.3';
|
||||
|
||||
public const OID_OBSOLETE_KEY_USAGE_RESTRICTION = '2.5.29.4';
|
||||
|
||||
public const OID_OBSOLETE_POLICY_MAPPING = '2.5.29.5';
|
||||
|
||||
public const OID_OBSOLETE_SUBTREES_CONSTRAINT = '2.5.29.6';
|
||||
|
||||
public const OID_OBSOLETE_SUBJECT_ALT_NAME = '2.5.29.7';
|
||||
|
||||
public const OID_OBSOLETE_ISSUER_ALT_NAME = '2.5.29.8';
|
||||
|
||||
public const OID_SUBJECT_DIRECTORY_ATTRIBUTES = '2.5.29.9';
|
||||
|
||||
public const OID_OBSOLETE_BASIC_CONSTRAINTS = '2.5.29.10';
|
||||
|
||||
public const OID_SUBJECT_KEY_IDENTIFIER = '2.5.29.14';
|
||||
|
||||
public const OID_KEY_USAGE = '2.5.29.15';
|
||||
|
||||
public const OID_PRIVATE_KEY_USAGE_PERIOD = '2.5.29.16';
|
||||
|
||||
public const OID_SUBJECT_ALT_NAME = '2.5.29.17';
|
||||
|
||||
public const OID_ISSUER_ALT_NAME = '2.5.29.18';
|
||||
|
||||
public const OID_BASIC_CONSTRAINTS = '2.5.29.19';
|
||||
|
||||
public const OID_CRL_NUMBER = '2.5.29.20';
|
||||
|
||||
public const OID_REASON_CODE = '2.5.29.21';
|
||||
|
||||
public const OID_OBSOLETE_EXPIRATION_DATE = '2.5.29.22';
|
||||
|
||||
public const OID_INSTRUCTION_CODE = '2.5.29.23';
|
||||
|
||||
public const OID_INVALIDITY_DATE = '2.5.29.24';
|
||||
|
||||
public const OID_OBSOLETE_CRL_DISTRIBUTION_POINTS = '2.5.29.25';
|
||||
|
||||
public const OID_OBSOLETE_ISSUING_DISTRIBUTION_POINT = '2.5.29.26';
|
||||
|
||||
public const OID_DELTA_CRL_INDICATOR = '2.5.29.27';
|
||||
|
||||
public const OID_ISSUING_DISTRIBUTION_POINT = '2.5.29.28';
|
||||
|
||||
public const OID_CERTIFICATE_ISSUER = '2.5.29.29';
|
||||
|
||||
public const OID_NAME_CONSTRAINTS = '2.5.29.30';
|
||||
|
||||
public const OID_CRL_DISTRIBUTION_POINTS = '2.5.29.31';
|
||||
|
||||
public const OID_CERTIFICATE_POLICIES = '2.5.29.32';
|
||||
|
||||
public const OID_POLICY_MAPPINGS = '2.5.29.33';
|
||||
|
||||
public const OID_OBSOLETE_POLICY_CONSTRAINTS = '2.5.29.34';
|
||||
|
||||
public const OID_AUTHORITY_KEY_IDENTIFIER = '2.5.29.35';
|
||||
|
||||
public const OID_POLICY_CONSTRAINTS = '2.5.29.36';
|
||||
|
||||
public const OID_EXT_KEY_USAGE = '2.5.29.37';
|
||||
|
||||
public const OID_AUTHORITY_ATTRIBUTE_IDENTIFIER = '2.5.29.38';
|
||||
|
||||
public const OID_ROLE_SPEC_CERT_IDENTIFIER = '2.5.29.39';
|
||||
|
||||
public const OID_CRL_STREAM_IDENTIFIER = '2.5.29.40';
|
||||
|
||||
public const OID_BASIC_ATT_CONSTRAINTS = '2.5.29.41';
|
||||
|
||||
public const OID_DELEGATED_NAME_CONSTRAINTS = '2.5.29.42';
|
||||
|
||||
public const OID_TIME_SPECIFICATION = '2.5.29.43';
|
||||
|
||||
public const OID_CRL_SCOPE = '2.5.29.44';
|
||||
|
||||
public const OID_STATUS_REFERRALS = '2.5.29.45';
|
||||
|
||||
public const OID_FRESHEST_CRL = '2.5.29.46';
|
||||
|
||||
public const OID_ORDERED_LIST = '2.5.29.47';
|
||||
|
||||
public const OID_ATTRIBUTE_DESCRIPTOR = '2.5.29.48';
|
||||
|
||||
public const OID_USER_NOTICE = '2.5.29.49';
|
||||
|
||||
public const OID_SOA_IDENTIFIER = '2.5.29.50';
|
||||
|
||||
public const OID_BASE_UPDATE_TIME = '2.5.29.51';
|
||||
|
||||
public const OID_ACCEPTABLE_CERT_POLICIES = '2.5.29.52';
|
||||
|
||||
public const OID_DELTA_INFO = '2.5.29.53';
|
||||
|
||||
public const OID_INHIBIT_ANY_POLICY = '2.5.29.54';
|
||||
|
||||
public const OID_TARGET_INFORMATION = '2.5.29.55';
|
||||
|
||||
public const OID_NO_REV_AVAIL = '2.5.29.56';
|
||||
|
||||
public const OID_ACCEPTABLE_PRIVILEGE_POLICIES = '2.5.29.57';
|
||||
|
||||
public const OID_TO_BE_REVOKED = '2.5.29.58';
|
||||
|
||||
public const OID_REVOKED_GROUPS = '2.5.29.59';
|
||||
|
||||
public const OID_EXPIRED_CERTS_ON_CRL = '2.5.29.60';
|
||||
|
||||
public const OID_INDIRECT_ISSUER = '2.5.29.61';
|
||||
|
||||
public const OID_NO_ASSERTION = '2.5.29.62';
|
||||
|
||||
public const OID_AA_ISSUING_DISTRIBUTION_POINT = '2.5.29.63';
|
||||
|
||||
public const OID_ISSUED_ON_BEHALF_OF = '2.5.29.64';
|
||||
|
||||
public const OID_SINGLE_USE = '2.5.29.65';
|
||||
|
||||
public const OID_GROUP_AC = '2.5.29.66';
|
||||
|
||||
public const OID_ALLOWED_ATT_ASS = '2.5.29.67';
|
||||
|
||||
public const OID_ATTRIBUTE_MAPPINGS = '2.5.29.68';
|
||||
|
||||
public const OID_HOLDER_NAME_CONSTRAINTS = '2.5.29.69';
|
||||
|
||||
// OID's from private certificate extensions arc
|
||||
public const OID_AUTHORITY_INFORMATION_ACCESS = '1.3.6.1.5.5.7.1.1';
|
||||
|
||||
public const OID_AA_CONTROLS = '1.3.6.1.5.5.7.1.6';
|
||||
|
||||
public const OID_SUBJECT_INFORMATION_ACCESS = '1.3.6.1.5.5.7.1.11';
|
||||
|
||||
public const OID_LOGOTYPE = '1.3.6.1.5.5.7.1.12';
|
||||
|
||||
/**
|
||||
* Mapping from extension ID to implementation class name.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const MAP_OID_TO_CLASS = [
|
||||
self::OID_AUTHORITY_KEY_IDENTIFIER => AuthorityKeyIdentifierExtension::class,
|
||||
self::OID_SUBJECT_KEY_IDENTIFIER => SubjectKeyIdentifierExtension::class,
|
||||
self::OID_KEY_USAGE => KeyUsageExtension::class,
|
||||
self::OID_CERTIFICATE_POLICIES => CertificatePoliciesExtension::class,
|
||||
self::OID_POLICY_MAPPINGS => PolicyMappingsExtension::class,
|
||||
self::OID_SUBJECT_ALT_NAME => SubjectAlternativeNameExtension::class,
|
||||
self::OID_ISSUER_ALT_NAME => IssuerAlternativeNameExtension::class,
|
||||
self::OID_SUBJECT_DIRECTORY_ATTRIBUTES => SubjectDirectoryAttributesExtension::class,
|
||||
self::OID_BASIC_CONSTRAINTS => BasicConstraintsExtension::class,
|
||||
self::OID_NAME_CONSTRAINTS => NameConstraintsExtension::class,
|
||||
self::OID_POLICY_CONSTRAINTS => PolicyConstraintsExtension::class,
|
||||
self::OID_EXT_KEY_USAGE => ExtendedKeyUsageExtension::class,
|
||||
self::OID_CRL_DISTRIBUTION_POINTS => CRLDistributionPointsExtension::class,
|
||||
self::OID_INHIBIT_ANY_POLICY => InhibitAnyPolicyExtension::class,
|
||||
self::OID_FRESHEST_CRL => FreshestCRLExtension::class,
|
||||
self::OID_NO_REV_AVAIL => NoRevocationAvailableExtension::class,
|
||||
self::OID_TARGET_INFORMATION => TargetInformationExtension::class,
|
||||
self::OID_AUTHORITY_INFORMATION_ACCESS => AuthorityInformationAccessExtension::class,
|
||||
self::OID_AA_CONTROLS => AAControlsExtension::class,
|
||||
self::OID_SUBJECT_INFORMATION_ACCESS => SubjectInformationAccessExtension::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Mapping from extensions ID to short name.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const MAP_OID_TO_NAME = [
|
||||
self::OID_AUTHORITY_KEY_IDENTIFIER => 'authorityKeyIdentifier',
|
||||
self::OID_SUBJECT_KEY_IDENTIFIER => 'subjectKeyIdentifier',
|
||||
self::OID_KEY_USAGE => 'keyUsage',
|
||||
self::OID_PRIVATE_KEY_USAGE_PERIOD => 'privateKeyUsagePeriod',
|
||||
self::OID_CERTIFICATE_POLICIES => 'certificatePolicies',
|
||||
self::OID_POLICY_MAPPINGS => 'policyMappings',
|
||||
self::OID_SUBJECT_ALT_NAME => 'subjectAltName',
|
||||
self::OID_ISSUER_ALT_NAME => 'issuerAltName',
|
||||
self::OID_SUBJECT_DIRECTORY_ATTRIBUTES => 'subjectDirectoryAttributes',
|
||||
self::OID_BASIC_CONSTRAINTS => 'basicConstraints',
|
||||
self::OID_NAME_CONSTRAINTS => 'nameConstraints',
|
||||
self::OID_POLICY_CONSTRAINTS => 'policyConstraints',
|
||||
self::OID_EXT_KEY_USAGE => 'extKeyUsage',
|
||||
self::OID_CRL_DISTRIBUTION_POINTS => 'cRLDistributionPoints',
|
||||
self::OID_INHIBIT_ANY_POLICY => 'inhibitAnyPolicy',
|
||||
self::OID_FRESHEST_CRL => 'freshestCRL',
|
||||
self::OID_NO_REV_AVAIL => 'noRevAvail',
|
||||
self::OID_TARGET_INFORMATION => 'targetInformation',
|
||||
self::OID_AUTHORITY_INFORMATION_ACCESS => 'authorityInfoAccess',
|
||||
self::OID_AA_CONTROLS => 'aaControls',
|
||||
self::OID_SUBJECT_INFORMATION_ACCESS => 'subjectInfoAccess',
|
||||
self::OID_LOGOTYPE => 'logotype',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param string $oid Extension OID
|
||||
* @param bool $critical Whether extension is critical
|
||||
*/
|
||||
protected function __construct(
|
||||
private readonly string $oid,
|
||||
private readonly bool $critical
|
||||
) {
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->extensionName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$idx = 0;
|
||||
// an Extension is two or three elements; without the check a truncated SEQUENCE reaches Structure::at()
|
||||
// and raises an OutOfBoundsException instead of a decoding failure
|
||||
$count = count($seq);
|
||||
if ($count < 2 || $count > 3) {
|
||||
throw new DecodeException(sprintf('Extension must have 2 or 3 elements, got %d.', $count));
|
||||
}
|
||||
$extnID = $seq->at($idx++)
|
||||
->asObjectIdentifier()
|
||||
->oid();
|
||||
$critical = false;
|
||||
if ($seq->has($idx, Element::TYPE_BOOLEAN)) {
|
||||
$critical = $seq->at($idx++)
|
||||
->asBoolean()
|
||||
->value();
|
||||
}
|
||||
$data = $seq->at($idx)
|
||||
->asOctetString()
|
||||
->string();
|
||||
if (array_key_exists($extnID, self::MAP_OID_TO_CLASS)) {
|
||||
$cls = self::MAP_OID_TO_CLASS[$extnID];
|
||||
return $cls::fromDER($data, $critical);
|
||||
}
|
||||
return UnknownExtension::fromRawString($extnID, $critical, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get extension OID.
|
||||
*/
|
||||
public function oid(): string
|
||||
{
|
||||
return $this->oid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether extension is critical.
|
||||
*/
|
||||
public function isCritical(): bool
|
||||
{
|
||||
return $this->critical;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [ObjectIdentifier::create($this->oid)];
|
||||
if ($this->critical) {
|
||||
$elements[] = Boolean::create(true);
|
||||
}
|
||||
$elements[] = $this->extnValue();
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get short name of the extension.
|
||||
*/
|
||||
public function extensionName(): string
|
||||
{
|
||||
if (array_key_exists($this->oid, self::MAP_OID_TO_NAME)) {
|
||||
return self::MAP_OID_TO_NAME[$this->oid];
|
||||
}
|
||||
return $this->oid();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ASN.1 structure of the extension value.
|
||||
*/
|
||||
abstract protected function valueASN1(): Element;
|
||||
|
||||
/**
|
||||
* Parse extension value from DER.
|
||||
*
|
||||
* @param string $data DER data
|
||||
* @param bool $critical Whether extension is critical
|
||||
*/
|
||||
abstract protected static function fromDER(string $data, bool $critical): static;
|
||||
|
||||
/**
|
||||
* Get the extnValue element.
|
||||
*/
|
||||
protected function extnValue(): OctetString
|
||||
{
|
||||
return OctetString::create($this->valueASN1()->toDER());
|
||||
}
|
||||
}
|
||||
20
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/FreshestCRLExtension.php
vendored
Normal file
20
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/FreshestCRLExtension.php
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\DistributionPoint\DistributionPoint;
|
||||
|
||||
/**
|
||||
* Implements 'Freshest CRL' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.15
|
||||
*/
|
||||
final class FreshestCRLExtension extends CRLDistributionPointsExtension
|
||||
{
|
||||
public static function create(bool $critical, DistributionPoint ...$distribution_points): self
|
||||
{
|
||||
return new self(self::OID_FRESHEST_CRL, $critical, ...$distribution_points);
|
||||
}
|
||||
}
|
||||
44
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/InhibitAnyPolicyExtension.php
vendored
Normal file
44
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/InhibitAnyPolicyExtension.php
vendored
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements 'Inhibit anyPolicy' extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.14
|
||||
*/
|
||||
final class InhibitAnyPolicyExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly int $skipCerts
|
||||
) {
|
||||
parent::__construct(self::OID_INHIBIT_ANY_POLICY, $critical);
|
||||
}
|
||||
|
||||
public static function create(bool $critical, int $skipCerts): self
|
||||
{
|
||||
return new self($critical, $skipCerts);
|
||||
}
|
||||
|
||||
public function skipCerts(): int
|
||||
{
|
||||
return $this->skipCerts;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
return self::create($critical, UnspecifiedType::fromDER($data)->asInteger()->intNumber());
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
return Integer::create($this->skipCerts);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
|
||||
/**
|
||||
* Implements 'Issuer Alternative Name' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.7
|
||||
*/
|
||||
final class IssuerAlternativeNameExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly GeneralNames $names
|
||||
) {
|
||||
parent::__construct(self::OID_ISSUER_ALT_NAME, $critical);
|
||||
}
|
||||
|
||||
public static function create(bool $critical, GeneralNames $names): self
|
||||
{
|
||||
return new self($critical, $names);
|
||||
}
|
||||
|
||||
public function names(): GeneralNames
|
||||
{
|
||||
return $this->names;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
return self::create($critical, GeneralNames::fromASN1(UnspecifiedType::fromDER($data)->asSequence()));
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
return $this->names->toASN1();
|
||||
}
|
||||
}
|
||||
142
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/KeyUsageExtension.php
vendored
Normal file
142
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/KeyUsageExtension.php
vendored
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\ASN1\Util\Flags;
|
||||
|
||||
/**
|
||||
* Implements 'Key Usage' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.3
|
||||
*/
|
||||
final class KeyUsageExtension extends Extension
|
||||
{
|
||||
public const DIGITAL_SIGNATURE = 0x100;
|
||||
|
||||
public const NON_REPUDIATION = 0x080;
|
||||
|
||||
public const KEY_ENCIPHERMENT = 0x040;
|
||||
|
||||
public const DATA_ENCIPHERMENT = 0x020;
|
||||
|
||||
public const KEY_AGREEMENT = 0x010;
|
||||
|
||||
public const KEY_CERT_SIGN = 0x008;
|
||||
|
||||
public const CRL_SIGN = 0x004;
|
||||
|
||||
public const ENCIPHER_ONLY = 0x002;
|
||||
|
||||
public const DECIPHER_ONLY = 0x001;
|
||||
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly int $keyUsage
|
||||
) {
|
||||
parent::__construct(self::OID_KEY_USAGE, $critical);
|
||||
}
|
||||
|
||||
public static function create(bool $critical, int $keyUsage): self
|
||||
{
|
||||
return new self($critical, $keyUsage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether digitalSignature flag is set.
|
||||
*/
|
||||
public function isDigitalSignature(): bool
|
||||
{
|
||||
return $this->_flagSet(self::DIGITAL_SIGNATURE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether nonRepudiation/contentCommitment flag is set.
|
||||
*/
|
||||
public function isNonRepudiation(): bool
|
||||
{
|
||||
return $this->_flagSet(self::NON_REPUDIATION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether keyEncipherment flag is set.
|
||||
*/
|
||||
public function isKeyEncipherment(): bool
|
||||
{
|
||||
return $this->_flagSet(self::KEY_ENCIPHERMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether dataEncipherment flag is set.
|
||||
*/
|
||||
public function isDataEncipherment(): bool
|
||||
{
|
||||
return $this->_flagSet(self::DATA_ENCIPHERMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether keyAgreement flag is set.
|
||||
*/
|
||||
public function isKeyAgreement(): bool
|
||||
{
|
||||
return $this->_flagSet(self::KEY_AGREEMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether keyCertSign flag is set.
|
||||
*/
|
||||
public function isKeyCertSign(): bool
|
||||
{
|
||||
return $this->_flagSet(self::KEY_CERT_SIGN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether cRLSign flag is set.
|
||||
*/
|
||||
public function isCRLSign(): bool
|
||||
{
|
||||
return $this->_flagSet(self::CRL_SIGN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether encipherOnly flag is set.
|
||||
*/
|
||||
public function isEncipherOnly(): bool
|
||||
{
|
||||
return $this->_flagSet(self::ENCIPHER_ONLY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether decipherOnly flag is set.
|
||||
*/
|
||||
public function isDecipherOnly(): bool
|
||||
{
|
||||
return $this->_flagSet(self::DECIPHER_ONLY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether given flag is set.
|
||||
*/
|
||||
protected function _flagSet(int $flag): bool
|
||||
{
|
||||
return (bool) ($this->keyUsage & $flag);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
return self::create(
|
||||
$critical,
|
||||
Flags::fromBitString(UnspecifiedType::fromDER($data)->asBitString(), 9)->intNumber()
|
||||
);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$flags = Flags::create($this->keyUsage, 9);
|
||||
return $flags->bitString()
|
||||
->withoutTrailingZeroes();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\NameConstraints;
|
||||
|
||||
use function count;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* Implements *GeneralSubtree* ASN.1 type used by 'Name Constraints' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.10
|
||||
*/
|
||||
final class GeneralSubtree
|
||||
{
|
||||
private function __construct(
|
||||
private readonly GeneralName $base,
|
||||
private readonly int $min,
|
||||
private readonly ?int $max
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(GeneralName $base, int $min = 0, ?int $max = null): self
|
||||
{
|
||||
return new self($base, $min, $max);
|
||||
}
|
||||
|
||||
public function getBase(): GeneralName
|
||||
{
|
||||
return $this->base;
|
||||
}
|
||||
|
||||
public function getMin(): int
|
||||
{
|
||||
return $this->min;
|
||||
}
|
||||
|
||||
public function getMax(): ?int
|
||||
{
|
||||
return $this->max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$base = GeneralName::fromASN1($seq->at(0)->asTagged());
|
||||
$min = 0;
|
||||
$max = null;
|
||||
// GeneralName is a CHOICE, which may be tagged as otherName [0]
|
||||
// or rfc822Name [1]. As minimum and maximum are also implicitly tagged,
|
||||
// we have to iterate the remaining elements instead of just checking
|
||||
// for tagged types.
|
||||
$count = count($seq);
|
||||
for ($i = 1; $i < $count; ++$i) {
|
||||
$el = $seq->at($i)
|
||||
->expectTagged();
|
||||
switch ($el->tag()) {
|
||||
case 0:
|
||||
$min = $el->asImplicit(Element::TYPE_INTEGER)
|
||||
->asInteger()
|
||||
->intNumber();
|
||||
break;
|
||||
case 1:
|
||||
$max = $el->asImplicit(Element::TYPE_INTEGER)
|
||||
->asInteger()
|
||||
->intNumber();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return self::create($base, $min, $max);
|
||||
}
|
||||
|
||||
public function base(): GeneralName
|
||||
{
|
||||
return $this->base;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [$this->base->toASN1()];
|
||||
if ($this->min !== 0) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, Integer::create($this->min));
|
||||
}
|
||||
if (isset($this->max)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(1, Integer::create($this->max));
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\NameConstraints;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *GeneralSubtrees* ASN.1 type used by 'Name Constraints' certificate extension.
|
||||
*
|
||||
* @see @see https://tools.ietf.org/html/rfc5280#section-4.2.1.10
|
||||
*/
|
||||
final class GeneralSubtrees implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Subtrees.
|
||||
*
|
||||
* @var GeneralSubtree[]
|
||||
*/
|
||||
private readonly array $subtrees;
|
||||
|
||||
private function __construct(GeneralSubtree ...$subtrees)
|
||||
{
|
||||
$this->subtrees = $subtrees;
|
||||
}
|
||||
|
||||
public static function create(GeneralSubtree ...$subtrees): self
|
||||
{
|
||||
return new self(...$subtrees);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$subtrees = array_map(
|
||||
static fn (UnspecifiedType $el) => GeneralSubtree::fromASN1($el->asSequence()),
|
||||
$seq->elements()
|
||||
);
|
||||
if (count($subtrees) === 0) {
|
||||
throw new UnexpectedValueException('GeneralSubtrees must contain at least one GeneralSubtree.');
|
||||
}
|
||||
return self::create(...$subtrees);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all subtrees.
|
||||
*
|
||||
* @return GeneralSubtree[]
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->subtrees;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
if (count($this->subtrees) === 0) {
|
||||
throw new LogicException('No subtrees.');
|
||||
}
|
||||
$elements = array_map(static fn (GeneralSubtree $gs) => $gs->toASN1(), $this->subtrees);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->subtrees);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for subtrees.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->subtrees);
|
||||
}
|
||||
}
|
||||
106
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/NameConstraintsExtension.php
vendored
Normal file
106
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/NameConstraintsExtension.php
vendored
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\NameConstraints\GeneralSubtrees;
|
||||
|
||||
/**
|
||||
* Implements 'Name Constraints' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.10
|
||||
*/
|
||||
final class NameConstraintsExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly ?GeneralSubtrees $permitted,
|
||||
private readonly ?GeneralSubtrees $excluded
|
||||
) {
|
||||
parent::__construct(self::OID_NAME_CONSTRAINTS, $critical);
|
||||
}
|
||||
|
||||
public static function create(
|
||||
bool $critical,
|
||||
?GeneralSubtrees $permitted = null,
|
||||
?GeneralSubtrees $excluded = null
|
||||
): self {
|
||||
return new self($critical, $permitted, $excluded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether permitted subtrees are present.
|
||||
*/
|
||||
public function hasPermittedSubtrees(): bool
|
||||
{
|
||||
return isset($this->permitted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get permitted subtrees.
|
||||
*/
|
||||
public function permittedSubtrees(): GeneralSubtrees
|
||||
{
|
||||
if (! $this->hasPermittedSubtrees()) {
|
||||
throw new LogicException('No permitted subtrees.');
|
||||
}
|
||||
return $this->permitted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether excluded subtrees are present.
|
||||
*/
|
||||
public function hasExcludedSubtrees(): bool
|
||||
{
|
||||
return isset($this->excluded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get excluded subtrees.
|
||||
*/
|
||||
public function excludedSubtrees(): GeneralSubtrees
|
||||
{
|
||||
if (! $this->hasExcludedSubtrees()) {
|
||||
throw new LogicException('No excluded subtrees.');
|
||||
}
|
||||
return $this->excluded;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$seq = UnspecifiedType::fromDER($data)->asSequence();
|
||||
$permitted = null;
|
||||
$excluded = null;
|
||||
if ($seq->hasTagged(0)) {
|
||||
$permitted = GeneralSubtrees::fromASN1(
|
||||
$seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)->asSequence()
|
||||
);
|
||||
}
|
||||
if ($seq->hasTagged(1)) {
|
||||
$excluded = GeneralSubtrees::fromASN1(
|
||||
$seq->getTagged(1)
|
||||
->asImplicit(Element::TYPE_SEQUENCE)->asSequence()
|
||||
);
|
||||
}
|
||||
return self::create($critical, $permitted, $excluded);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->permitted)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, $this->permitted->toASN1());
|
||||
}
|
||||
if (isset($this->excluded)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(1, $this->excluded->toASN1());
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\NullType;
|
||||
|
||||
/**
|
||||
* Implements 'No Revocation Available' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.3.6
|
||||
*/
|
||||
final class NoRevocationAvailableExtension extends Extension
|
||||
{
|
||||
private function __construct(bool $critical)
|
||||
{
|
||||
parent::__construct(self::OID_NO_REV_AVAIL, $critical);
|
||||
}
|
||||
|
||||
public static function create(bool $critical): self
|
||||
{
|
||||
return new self($critical);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
NullType::fromDER($data);
|
||||
return self::create($critical);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
return NullType::create();
|
||||
}
|
||||
}
|
||||
96
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/PolicyConstraintsExtension.php
vendored
Normal file
96
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/PolicyConstraintsExtension.php
vendored
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements 'Policy Constraints' certificate extensions.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.11
|
||||
*/
|
||||
final class PolicyConstraintsExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly ?int $requireExplicitPolicy,
|
||||
private readonly ?int $inhibitPolicyMapping
|
||||
) {
|
||||
parent::__construct(self::OID_POLICY_CONSTRAINTS, $critical);
|
||||
}
|
||||
|
||||
public static function create(
|
||||
bool $critical,
|
||||
?int $requireExplicitPolicy = null,
|
||||
?int $inhibitPolicyMapping = null
|
||||
): self {
|
||||
return new self($critical, $requireExplicitPolicy, $inhibitPolicyMapping);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether requireExplicitPolicy is present.
|
||||
*/
|
||||
public function hasRequireExplicitPolicy(): bool
|
||||
{
|
||||
return isset($this->requireExplicitPolicy);
|
||||
}
|
||||
|
||||
public function requireExplicitPolicy(): int
|
||||
{
|
||||
if (! $this->hasRequireExplicitPolicy()) {
|
||||
throw new LogicException('requireExplicitPolicy not set.');
|
||||
}
|
||||
return $this->requireExplicitPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether inhibitPolicyMapping is present.
|
||||
*/
|
||||
public function hasInhibitPolicyMapping(): bool
|
||||
{
|
||||
return isset($this->inhibitPolicyMapping);
|
||||
}
|
||||
|
||||
public function inhibitPolicyMapping(): int
|
||||
{
|
||||
if (! $this->hasInhibitPolicyMapping()) {
|
||||
throw new LogicException('inhibitPolicyMapping not set.');
|
||||
}
|
||||
return $this->inhibitPolicyMapping;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$seq = UnspecifiedType::fromDER($data)->asSequence();
|
||||
$require_explicit_policy = null;
|
||||
$inhibit_policy_mapping = null;
|
||||
if ($seq->hasTagged(0)) {
|
||||
$require_explicit_policy = $seq->getTagged(0)
|
||||
->asImplicit(Element::TYPE_INTEGER)->asInteger()->intNumber();
|
||||
}
|
||||
if ($seq->hasTagged(1)) {
|
||||
$inhibit_policy_mapping = $seq->getTagged(1)
|
||||
->asImplicit(Element::TYPE_INTEGER)->asInteger()->intNumber();
|
||||
}
|
||||
return self::create($critical, $require_explicit_policy, $inhibit_policy_mapping);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = [];
|
||||
if (isset($this->requireExplicitPolicy)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, Integer::create($this->requireExplicitPolicy));
|
||||
}
|
||||
if (isset($this->inhibitPolicyMapping)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(1, Integer::create($this->inhibitPolicyMapping));
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
76
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/PolicyMappings/PolicyMapping.php
vendored
Normal file
76
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/PolicyMappings/PolicyMapping.php
vendored
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\PolicyMappings;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
|
||||
/**
|
||||
* Implements ASN.1 type containing policy mapping values to be used in 'Policy Mappings' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.5
|
||||
*/
|
||||
final class PolicyMapping
|
||||
{
|
||||
/**
|
||||
* @param string $issuerDomainPolicy OID of the issuer policy
|
||||
* @param string $subjectDomainPolicy OID of the subject policy
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly string $issuerDomainPolicy,
|
||||
private readonly string $subjectDomainPolicy
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(string $issuerDomainPolicy, string $subjectDomainPolicy): self
|
||||
{
|
||||
return new self($issuerDomainPolicy, $subjectDomainPolicy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$issuer_policy = $seq->at(0)
|
||||
->asObjectIdentifier()
|
||||
->oid();
|
||||
$subject_policy = $seq->at(1)
|
||||
->asObjectIdentifier()
|
||||
->oid();
|
||||
return self::create($issuer_policy, $subject_policy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get issuer domain policy.
|
||||
*
|
||||
* @return string OID in dotted format
|
||||
*/
|
||||
public function issuerDomainPolicy(): string
|
||||
{
|
||||
return $this->issuerDomainPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get subject domain policy.
|
||||
*
|
||||
* @return string OID in dotted format
|
||||
*/
|
||||
public function subjectDomainPolicy(): string
|
||||
{
|
||||
return $this->subjectDomainPolicy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create(
|
||||
ObjectIdentifier::create($this->issuerDomainPolicy),
|
||||
ObjectIdentifier::create($this->subjectDomainPolicy)
|
||||
);
|
||||
}
|
||||
}
|
||||
165
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/PolicyMappingsExtension.php
vendored
Normal file
165
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/PolicyMappingsExtension.php
vendored
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePolicy\PolicyInformation;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\PolicyMappings\PolicyMapping;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements 'Policy Mappings' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.5
|
||||
*/
|
||||
final class PolicyMappingsExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Policy mappings.
|
||||
*
|
||||
* @var PolicyMapping[]
|
||||
*/
|
||||
private readonly array $mappings;
|
||||
|
||||
/**
|
||||
* @param PolicyMapping ...$mappings One or more PolicyMapping objects
|
||||
*/
|
||||
private function __construct(bool $critical, PolicyMapping ...$mappings)
|
||||
{
|
||||
parent::__construct(self::OID_POLICY_MAPPINGS, $critical);
|
||||
$this->mappings = $mappings;
|
||||
}
|
||||
|
||||
public static function create(bool $critical, PolicyMapping ...$mappings): self
|
||||
{
|
||||
return new self($critical, ...$mappings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all mappings.
|
||||
*
|
||||
* @return PolicyMapping[]
|
||||
*/
|
||||
public function mappings(): array
|
||||
{
|
||||
return $this->mappings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get mappings flattened into a single array of arrays of subject domains keyed by issuer domain.
|
||||
*
|
||||
* Eg. if policy mappings contains multiple mappings with the same issuer domain policy, their corresponding subject
|
||||
* domain policies are placed under the same key.
|
||||
*
|
||||
* @return (string[])[]
|
||||
*/
|
||||
public function flattenedMappings(): array
|
||||
{
|
||||
$mappings = [];
|
||||
foreach ($this->mappings as $mapping) {
|
||||
$idp = $mapping->issuerDomainPolicy();
|
||||
if (! isset($mappings[$idp])) {
|
||||
$mappings[$idp] = [];
|
||||
}
|
||||
array_push($mappings[$idp], $mapping->subjectDomainPolicy());
|
||||
}
|
||||
return $mappings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all subject domain policy OIDs that are mapped to given issuer domain policy OID.
|
||||
*
|
||||
* @param string $oid Issuer domain policy
|
||||
*
|
||||
* @return string[] List of OIDs in dotted format
|
||||
*/
|
||||
public function issuerMappings(string $oid): array
|
||||
{
|
||||
$oids = [];
|
||||
foreach ($this->mappings as $mapping) {
|
||||
if ($mapping->issuerDomainPolicy() === $oid) {
|
||||
$oids[] = $mapping->subjectDomainPolicy();
|
||||
}
|
||||
}
|
||||
return $oids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all mapped issuer domain policy OIDs.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function issuerDomainPolicies(): array
|
||||
{
|
||||
$idps = array_map(static fn (PolicyMapping $mapping) => $mapping->issuerDomainPolicy(), $this->mappings);
|
||||
return array_values(array_unique($idps));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether policy mappings have anyPolicy mapped.
|
||||
*
|
||||
* RFC 5280 section 4.2.1.5 states that "Policies MUST NOT be mapped either to or from the special value anyPolicy".
|
||||
*/
|
||||
public function hasAnyPolicyMapping(): bool
|
||||
{
|
||||
foreach ($this->mappings as $mapping) {
|
||||
if ($mapping->issuerDomainPolicy() === PolicyInformation::OID_ANY_POLICY) {
|
||||
return true;
|
||||
}
|
||||
if ($mapping->subjectDomainPolicy() === PolicyInformation::OID_ANY_POLICY) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of mappings.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->mappings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for policy mappings.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->mappings);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$mappings = array_map(
|
||||
static fn (UnspecifiedType $el) => PolicyMapping::fromASN1($el->asSequence()),
|
||||
UnspecifiedType::fromDER($data)->asSequence()->elements()
|
||||
);
|
||||
if (count($mappings) === 0) {
|
||||
throw new UnexpectedValueException('PolicyMappings must have at least one mapping.');
|
||||
}
|
||||
return self::create($critical, ...$mappings);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
if (count($this->mappings) === 0) {
|
||||
throw new LogicException('No mappings.');
|
||||
}
|
||||
$elements = array_map(static fn (PolicyMapping $mapping) => $mapping->toASN1(), $this->mappings);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralNames;
|
||||
|
||||
/**
|
||||
* Implements 'Subject Alternative Name' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
final class SubjectAlternativeNameExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly GeneralNames $names
|
||||
) {
|
||||
parent::__construct(self::OID_SUBJECT_ALT_NAME, $critical);
|
||||
}
|
||||
|
||||
public static function create(bool $critical, GeneralNames $names): self
|
||||
{
|
||||
return new self($critical, $names);
|
||||
}
|
||||
|
||||
public function names(): GeneralNames
|
||||
{
|
||||
return $this->names;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
return self::create($critical, GeneralNames::fromASN1(UnspecifiedType::fromDER($data)->asSequence()));
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
return $this->names->toASN1();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Attribute;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Collection\SequenceOfAttributes;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements 'Subject Directory Attributes' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.8
|
||||
*/
|
||||
final class SubjectDirectoryAttributesExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Attributes.
|
||||
*/
|
||||
private readonly SequenceOfAttributes $attributes;
|
||||
|
||||
/**
|
||||
* @param Attribute ...$attribs One or more Attribute objects
|
||||
*/
|
||||
private function __construct(bool $critical, Attribute ...$attribs)
|
||||
{
|
||||
parent::__construct(self::OID_SUBJECT_DIRECTORY_ATTRIBUTES, $critical);
|
||||
$this->attributes = SequenceOfAttributes::create(...$attribs);
|
||||
}
|
||||
|
||||
public static function create(bool $critical, Attribute ...$attribs): self
|
||||
{
|
||||
return new self($critical, ...$attribs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether attribute is present.
|
||||
*
|
||||
* @param string $name OID or attribute name
|
||||
*/
|
||||
public function has(string $name): bool
|
||||
{
|
||||
return $this->attributes->has($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get first attribute by OID or attribute name.
|
||||
*
|
||||
* @param string $name OID or attribute name
|
||||
*/
|
||||
public function firstOf(string $name): Attribute
|
||||
{
|
||||
return $this->attributes->firstOf($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all attributes of given name.
|
||||
*
|
||||
* @param string $name OID or attribute name
|
||||
*
|
||||
* @return Attribute[]
|
||||
*/
|
||||
public function allOf(string $name): array
|
||||
{
|
||||
return $this->attributes->allOf($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all attributes.
|
||||
*
|
||||
* @return Attribute[]
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->attributes->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of attributes.
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for attributes.
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return $this->attributes->getIterator();
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$attribs = SequenceOfAttributes::fromASN1(UnspecifiedType::fromDER($data)->asSequence());
|
||||
if (count($attribs) === 0) {
|
||||
throw new UnexpectedValueException('SubjectDirectoryAttributes must have at least one Attribute.');
|
||||
}
|
||||
return self::create($critical, ...$attribs->all());
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
if (count($this->attributes) === 0) {
|
||||
throw new LogicException('No attributes');
|
||||
}
|
||||
return $this->attributes->toASN1();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\AccessDescription\AccessDescription;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\AccessDescription\SubjectAccessDescription;
|
||||
|
||||
/**
|
||||
* Implements 'Subject Information Access' extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.2.2
|
||||
*/
|
||||
final class SubjectInformationAccessExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Access descriptions.
|
||||
*
|
||||
* @var SubjectAccessDescription[]
|
||||
*/
|
||||
private readonly array $accessDescriptions;
|
||||
|
||||
private function __construct(bool $critical, SubjectAccessDescription ...$accessDescriptions)
|
||||
{
|
||||
parent::__construct(self::OID_SUBJECT_INFORMATION_ACCESS, $critical);
|
||||
$this->accessDescriptions = $accessDescriptions;
|
||||
}
|
||||
|
||||
public static function create(bool $critical, SubjectAccessDescription ...$accessDescriptions): self
|
||||
{
|
||||
return new self($critical, ...$accessDescriptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the access descriptions.
|
||||
*
|
||||
* @return SubjectAccessDescription[]
|
||||
*/
|
||||
public function accessDescriptions(): array
|
||||
{
|
||||
return $this->accessDescriptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of access descriptions.
|
||||
*
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->accessDescriptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for access descriptions.
|
||||
*
|
||||
* @return ArrayIterator List of SubjectAccessDescription objects
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->accessDescriptions);
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$access = array_map(
|
||||
static fn (UnspecifiedType $el) => SubjectAccessDescription::fromASN1($el->asSequence()),
|
||||
UnspecifiedType::fromDER($data)->asSequence()->elements()
|
||||
);
|
||||
return self::create($critical, ...$access);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = array_map(static fn (AccessDescription $access) => $access->toASN1(), $this->accessDescriptions);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements 'Subject Key Identifier' certificate extension.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.2
|
||||
*/
|
||||
final class SubjectKeyIdentifierExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
bool $critical,
|
||||
private readonly string $keyIdentifier
|
||||
) {
|
||||
parent::__construct(self::OID_SUBJECT_KEY_IDENTIFIER, $critical);
|
||||
}
|
||||
|
||||
public static function create(bool $critical, string $keyIdentifier): self
|
||||
{
|
||||
return new self($critical, $keyIdentifier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get key identifier.
|
||||
*/
|
||||
public function keyIdentifier(): string
|
||||
{
|
||||
return $this->keyIdentifier;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
return self::create($critical, UnspecifiedType::fromDER($data)->asOctetString()->string());
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
return OctetString::create($this->keyIdentifier);
|
||||
}
|
||||
}
|
||||
79
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/Target.php
vendored
Normal file
79
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/Target.php
vendored
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\Target;
|
||||
|
||||
use RuntimeException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Base class for *Target* ASN.1 CHOICE type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.3.2
|
||||
*/
|
||||
abstract class Target
|
||||
{
|
||||
public const TYPE_NAME = 0;
|
||||
|
||||
public const TYPE_GROUP = 1;
|
||||
|
||||
public const TYPE_CERT = 2;
|
||||
|
||||
protected function __construct(
|
||||
protected int $type
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 element.
|
||||
*/
|
||||
abstract public function toASN1(): Element;
|
||||
|
||||
/**
|
||||
* Get string value of the target.
|
||||
*/
|
||||
abstract public function string(): string;
|
||||
|
||||
/**
|
||||
* Initialize concrete object from the chosen ASN.1 element.
|
||||
*/
|
||||
abstract public static function fromChosenASN1(TaggedType $el): self;
|
||||
|
||||
/**
|
||||
* Parse from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(TaggedType $el): self
|
||||
{
|
||||
return match ($el->tag()) {
|
||||
self::TYPE_NAME => TargetName::fromChosenASN1($el->asExplicit()->asTagged()),
|
||||
self::TYPE_GROUP => TargetGroup::fromChosenASN1($el->asExplicit()->asTagged()),
|
||||
self::TYPE_CERT => throw new RuntimeException('targetCert not supported.'),
|
||||
default => throw new UnexpectedValueException('Target type ' . $el->tag() . ' not supported.'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get type tag.
|
||||
*/
|
||||
public function type(): int
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether target is equal to another.
|
||||
*/
|
||||
public function equals(self $other): bool
|
||||
{
|
||||
if ($this->type !== $other->type) {
|
||||
return false;
|
||||
}
|
||||
if ($this->toASN1()->toDER() !== $other->toASN1()->toDER()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
55
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/TargetGroup.php
vendored
Normal file
55
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/TargetGroup.php
vendored
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\Target;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* Implements 'targetGroup' CHOICE of the *Target* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.3.2
|
||||
*/
|
||||
final class TargetGroup extends Target
|
||||
{
|
||||
private function __construct(
|
||||
private readonly GeneralName $name
|
||||
) {
|
||||
parent::__construct(self::TYPE_GROUP);
|
||||
}
|
||||
|
||||
public static function create(GeneralName $name): self
|
||||
{
|
||||
return new self($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(TaggedType $el): Target
|
||||
{
|
||||
return self::create(GeneralName::fromASN1($el));
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return $this->name->string();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get group name.
|
||||
*/
|
||||
public function name(): GeneralName
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function toASN1(): Element
|
||||
{
|
||||
return ExplicitlyTaggedType::create($this->type, $this->name->toASN1());
|
||||
}
|
||||
}
|
||||
52
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/TargetName.php
vendored
Normal file
52
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/TargetName.php
vendored
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\Target;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\X509\GeneralName\GeneralName;
|
||||
|
||||
/**
|
||||
* Implements 'targetName' CHOICE of the *Target* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.3.2
|
||||
*/
|
||||
final class TargetName extends Target
|
||||
{
|
||||
private function __construct(
|
||||
private readonly GeneralName $name
|
||||
) {
|
||||
parent::__construct(self::TYPE_NAME);
|
||||
}
|
||||
|
||||
public static function create(GeneralName $name): self
|
||||
{
|
||||
return new self($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(TaggedType $el): Target
|
||||
{
|
||||
return self::create(GeneralName::fromASN1($el));
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return $this->name->string();
|
||||
}
|
||||
|
||||
public function name(): GeneralName
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function toASN1(): Element
|
||||
{
|
||||
return ExplicitlyTaggedType::create($this->type, $this->name->toASN1());
|
||||
}
|
||||
}
|
||||
126
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/Targets.php
vendored
Normal file
126
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/Target/Targets.php
vendored
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension\Target;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *Targets* ASN.1 type as a *SEQUENCE OF Target*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.3.2
|
||||
*/
|
||||
final class Targets implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Target elements.
|
||||
*
|
||||
* @var Target[]
|
||||
*/
|
||||
private readonly array $targets;
|
||||
|
||||
private function __construct(Target ...$targets)
|
||||
{
|
||||
$this->targets = $targets;
|
||||
}
|
||||
|
||||
public static function create(Target ...$targets): self
|
||||
{
|
||||
return new self(...$targets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$targets = array_map(static fn (UnspecifiedType $el) => Target::fromASN1($el->asTagged()), $seq->elements());
|
||||
return self::create(...$targets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all targets.
|
||||
*
|
||||
* @return Target[]
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->targets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all name targets.
|
||||
*
|
||||
* @return Target[]
|
||||
*/
|
||||
public function nameTargets(): array
|
||||
{
|
||||
return $this->allOfType(Target::TYPE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all group targets.
|
||||
*
|
||||
* @return Target[]
|
||||
*/
|
||||
public function groupTargets(): array
|
||||
{
|
||||
return $this->allOfType(Target::TYPE_GROUP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether given target is present.
|
||||
*/
|
||||
public function hasTarget(Target $target): bool
|
||||
{
|
||||
foreach ($this->allOfType($target->type()) as $t) {
|
||||
if ($target->equals($t)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = array_map(static fn (Target $target) => $target->toASN1(), $this->targets);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->targets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for targets.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->targets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all targets of given type.
|
||||
*
|
||||
* @return Target[]
|
||||
*/
|
||||
private function allOfType(int $type): array
|
||||
{
|
||||
return array_values(array_filter($this->targets, static fn (Target $target) => $target->type() === $type));
|
||||
}
|
||||
}
|
||||
137
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/TargetInformationExtension.php
vendored
Normal file
137
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/TargetInformationExtension.php
vendored
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Target\Target;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Target\Targets;
|
||||
|
||||
/**
|
||||
* Implements 'AC Targeting' certificate extension.
|
||||
*
|
||||
* NOTE**: Syntax is *SEQUENCE OF Targets*, but only one *Targets* element must be used. Multiple *Targets* elements
|
||||
* shall be merged into single *Targets*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5755#section-4.3.2
|
||||
*/
|
||||
final class TargetInformationExtension extends Extension implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Targets elements.
|
||||
*
|
||||
* @var Targets[]
|
||||
*/
|
||||
protected array $targets;
|
||||
|
||||
/**
|
||||
* Targets[] merged to single Targets.
|
||||
*/
|
||||
private ?Targets $merged = null;
|
||||
|
||||
private function __construct(bool $critical, Targets ...$targets)
|
||||
{
|
||||
parent::__construct(self::OID_TARGET_INFORMATION, $critical);
|
||||
$this->targets = $targets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset internal state on clone.
|
||||
*/
|
||||
public function __clone()
|
||||
{
|
||||
$this->merged = null;
|
||||
}
|
||||
|
||||
public static function create(bool $critical, Targets ...$targets): self
|
||||
{
|
||||
return new self($critical, ...$targets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from one or more Target objects.
|
||||
*
|
||||
* Extension criticality shall be set to true as specified by RFC 5755.
|
||||
*/
|
||||
public static function fromTargets(Target ...$target): self
|
||||
{
|
||||
return self::create(true, Targets::create(...$target));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all targets.
|
||||
*/
|
||||
public function targets(): Targets
|
||||
{
|
||||
if ($this->merged === null) {
|
||||
$a = [];
|
||||
foreach ($this->targets as $targets) {
|
||||
$a = array_merge($a, $targets->all());
|
||||
}
|
||||
$this->merged = Targets::create(...$a);
|
||||
}
|
||||
return $this->merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all name targets.
|
||||
*
|
||||
* @return Target[]
|
||||
*/
|
||||
public function names(): array
|
||||
{
|
||||
return $this->targets()
|
||||
->nameTargets();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all group targets.
|
||||
*
|
||||
* @return Target[]
|
||||
*/
|
||||
public function groups(): array
|
||||
{
|
||||
return $this->targets()
|
||||
->groupTargets();
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->targets());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for targets.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->targets()->all());
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
$targets = array_map(
|
||||
static fn (UnspecifiedType $el) => Targets::fromASN1($el->asSequence()),
|
||||
UnspecifiedType::fromDER($data)->asSequence()->elements()
|
||||
);
|
||||
return self::create($critical, ...$targets);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
$elements = array_map(static fn (Targets $targets) => $targets->toASN1(), $this->targets);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
}
|
||||
61
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/UnknownExtension.php
vendored
Normal file
61
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extension/UnknownExtension.php
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate\Extension;
|
||||
|
||||
use BadMethodCallException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\NullType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
|
||||
|
||||
/**
|
||||
* Class to park payload of an unknown extension.
|
||||
*/
|
||||
final class UnknownExtension extends Extension
|
||||
{
|
||||
private function __construct(
|
||||
string $oid,
|
||||
bool $critical,
|
||||
private readonly Element $element,
|
||||
private readonly string $data
|
||||
) {
|
||||
parent::__construct($oid, $critical);
|
||||
}
|
||||
|
||||
public static function create(string $oid, bool $critical, Element $element): self
|
||||
{
|
||||
return new self($oid, $critical, $element, $element->toDER());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create instance from a raw encoded extension value.
|
||||
*/
|
||||
public static function fromRawString(string $oid, bool $critical, string $data): self
|
||||
{
|
||||
return new self($oid, $critical, NullType::create(), $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the encoded extension value.
|
||||
*/
|
||||
public function extensionValue(): string
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
protected function extnValue(): OctetString
|
||||
{
|
||||
return OctetString::create($this->data);
|
||||
}
|
||||
|
||||
protected function valueASN1(): Element
|
||||
{
|
||||
return $this->element;
|
||||
}
|
||||
|
||||
protected static function fromDER(string $data, bool $critical): static
|
||||
{
|
||||
throw new BadMethodCallException(__FUNCTION__ . ' must be implemented in derived class.');
|
||||
}
|
||||
}
|
||||
361
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extensions.php
vendored
Normal file
361
vendor/spomky-labs/pki-framework/src/X509/Certificate/Extensions.php
vendored
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\AuthorityKeyIdentifierExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\BasicConstraintsExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\CertificatePoliciesExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\CRLDistributionPointsExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\ExtendedKeyUsageExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Extension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\InhibitAnyPolicyExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\IssuerAlternativeNameExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\KeyUsageExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\NameConstraintsExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\PolicyConstraintsExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\PolicyMappingsExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\SubjectAlternativeNameExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\SubjectKeyIdentifierExtension;
|
||||
use function sprintf;
|
||||
use Traversable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *Extensions* ASN.1 type.
|
||||
*
|
||||
* Several convenience methods are provided to fetch commonly used standard extensions. Others can be accessed using
|
||||
* `get($oid)`.
|
||||
*
|
||||
* @implements IteratorAggregate<string, Extension>
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.1.2.9
|
||||
*/
|
||||
final class Extensions implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Extensions.
|
||||
*
|
||||
* @var Extension[]
|
||||
*/
|
||||
private array $extensions;
|
||||
|
||||
/**
|
||||
* @param Extension ...$extensions Extension objects
|
||||
*/
|
||||
private function __construct(Extension ...$extensions)
|
||||
{
|
||||
$this->extensions = [];
|
||||
foreach ($extensions as $ext) {
|
||||
$this->extensions[$ext->oid()] = $ext;
|
||||
}
|
||||
}
|
||||
|
||||
public static function create(Extension ...$extensions): self
|
||||
{
|
||||
return new self(...$extensions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$extensions = array_map(
|
||||
static fn (UnspecifiedType $el) => Extension::fromASN1($el->asSequence()),
|
||||
$seq->elements()
|
||||
);
|
||||
// RFC 5280 section 4.2: a certificate MUST NOT include more than one instance of a particular extension.
|
||||
// Extensions are held in a map keyed by OID, so a duplicate would silently overwrite the earlier one and
|
||||
// the certificate would mean different things to this library and to a peer keeping the first occurrence.
|
||||
$seen = [];
|
||||
foreach ($extensions as $extension) {
|
||||
$oid = $extension->oid();
|
||||
if (isset($seen[$oid])) {
|
||||
throw new UnexpectedValueException(sprintf('Extension %s occurs more than once.', $oid));
|
||||
}
|
||||
$seen[$oid] = true;
|
||||
}
|
||||
return self::create(...$extensions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = array_values(array_map(static fn ($ext) => $ext->toASN1(), $this->extensions));
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with extensions added.
|
||||
*
|
||||
* @param Extension ...$exts One or more extensions to add
|
||||
*/
|
||||
public function withExtensions(Extension ...$exts): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
foreach ($exts as $ext) {
|
||||
$obj->extensions[$ext->oid()] = $ext;
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether extension is present.
|
||||
*
|
||||
* @param string $oid Extensions OID
|
||||
*/
|
||||
public function has(string $oid): bool
|
||||
{
|
||||
return isset($this->extensions[$oid]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get extension by OID.
|
||||
*/
|
||||
public function get(string $oid): Extension
|
||||
{
|
||||
if (! $this->has($oid)) {
|
||||
throw new LogicException("No extension by OID {$oid}.");
|
||||
}
|
||||
return $this->extensions[$oid];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Authority Key Identifier' extension is present.
|
||||
*/
|
||||
public function hasAuthorityKeyIdentifier(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_AUTHORITY_KEY_IDENTIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Authority Key Identifier' extension.
|
||||
*/
|
||||
public function authorityKeyIdentifier(): AuthorityKeyIdentifierExtension
|
||||
{
|
||||
return $this->get(Extension::OID_AUTHORITY_KEY_IDENTIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Subject Key Identifier' extension is present.
|
||||
*/
|
||||
public function hasSubjectKeyIdentifier(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_SUBJECT_KEY_IDENTIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Subject Key Identifier' extension.
|
||||
*/
|
||||
public function subjectKeyIdentifier(): SubjectKeyIdentifierExtension
|
||||
{
|
||||
return $this->get(Extension::OID_SUBJECT_KEY_IDENTIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Key Usage' extension is present.
|
||||
*/
|
||||
public function hasKeyUsage(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_KEY_USAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Key Usage' extension.
|
||||
*/
|
||||
public function keyUsage(): KeyUsageExtension
|
||||
{
|
||||
return $this->get(Extension::OID_KEY_USAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Certificate Policies' extension is present.
|
||||
*/
|
||||
public function hasCertificatePolicies(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_CERTIFICATE_POLICIES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Certificate Policies' extension.
|
||||
*/
|
||||
public function certificatePolicies(): CertificatePoliciesExtension
|
||||
{
|
||||
return $this->get(Extension::OID_CERTIFICATE_POLICIES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Policy Mappings' extension is present.
|
||||
*/
|
||||
public function hasPolicyMappings(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_POLICY_MAPPINGS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Policy Mappings' extension.
|
||||
*/
|
||||
public function policyMappings(): PolicyMappingsExtension
|
||||
{
|
||||
return $this->get(Extension::OID_POLICY_MAPPINGS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Subject Alternative Name' extension is present.
|
||||
*/
|
||||
public function hasSubjectAlternativeName(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_SUBJECT_ALT_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Subject Alternative Name' extension.
|
||||
*/
|
||||
public function subjectAlternativeName(): SubjectAlternativeNameExtension
|
||||
{
|
||||
return $this->get(Extension::OID_SUBJECT_ALT_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Issuer Alternative Name' extension is present.
|
||||
*/
|
||||
public function hasIssuerAlternativeName(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_ISSUER_ALT_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Issuer Alternative Name' extension.
|
||||
*/
|
||||
public function issuerAlternativeName(): IssuerAlternativeNameExtension
|
||||
{
|
||||
return $this->get(Extension::OID_ISSUER_ALT_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Basic Constraints' extension is present.
|
||||
*/
|
||||
public function hasBasicConstraints(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_BASIC_CONSTRAINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Basic Constraints' extension.
|
||||
*/
|
||||
public function basicConstraints(): BasicConstraintsExtension
|
||||
{
|
||||
return $this->get(Extension::OID_BASIC_CONSTRAINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Name Constraints' extension is present.
|
||||
*/
|
||||
public function hasNameConstraints(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_NAME_CONSTRAINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Name Constraints' extension.
|
||||
*/
|
||||
public function nameConstraints(): NameConstraintsExtension
|
||||
{
|
||||
return $this->get(Extension::OID_NAME_CONSTRAINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Policy Constraints' extension is present.
|
||||
*/
|
||||
public function hasPolicyConstraints(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_POLICY_CONSTRAINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Policy Constraints' extension.
|
||||
*/
|
||||
public function policyConstraints(): PolicyConstraintsExtension
|
||||
{
|
||||
return $this->get(Extension::OID_POLICY_CONSTRAINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Extended Key Usage' extension is present.
|
||||
*/
|
||||
public function hasExtendedKeyUsage(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_EXT_KEY_USAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Extended Key Usage' extension.
|
||||
*/
|
||||
public function extendedKeyUsage(): ExtendedKeyUsageExtension
|
||||
{
|
||||
return $this->get(Extension::OID_EXT_KEY_USAGE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'CRL Distribution Points' extension is present.
|
||||
*/
|
||||
public function hasCRLDistributionPoints(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_CRL_DISTRIBUTION_POINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'CRL Distribution Points' extension.
|
||||
*/
|
||||
public function crlDistributionPoints(): CRLDistributionPointsExtension
|
||||
{
|
||||
return $this->get(Extension::OID_CRL_DISTRIBUTION_POINTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 'Inhibit anyPolicy' extension is present.
|
||||
*/
|
||||
public function hasInhibitAnyPolicy(): bool
|
||||
{
|
||||
return $this->has(Extension::OID_INHIBIT_ANY_POLICY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get 'Inhibit anyPolicy' extension.
|
||||
*/
|
||||
public function inhibitAnyPolicy(): InhibitAnyPolicyExtension
|
||||
{
|
||||
return $this->get(Extension::OID_INHIBIT_ANY_POLICY);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->extensions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for extensions.
|
||||
*
|
||||
* @return Traversable<string, Extension>
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): Traversable
|
||||
{
|
||||
return new ArrayIterator($this->extensions);
|
||||
}
|
||||
}
|
||||
697
vendor/spomky-labs/pki-framework/src/X509/Certificate/TBSCertificate.php
vendored
Normal file
697
vendor/spomky-labs/pki-framework/src/X509/Certificate/TBSCertificate.php
vendored
Normal file
|
|
@ -0,0 +1,697 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use Brick\Math\BigInteger;
|
||||
use function chr;
|
||||
use function count;
|
||||
use const E_USER_DEPRECATED;
|
||||
use function func_num_args;
|
||||
use function implode;
|
||||
use function in_array;
|
||||
use InvalidArgumentException;
|
||||
use LogicException;
|
||||
use function ord;
|
||||
use const PHP_INT_MAX;
|
||||
use const PHP_INT_MIN;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Exception\DecodeException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\CryptoBridge\Crypto;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKeyInfo;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Name;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\AuthorityKeyIdentifierExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\Extension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\SubjectKeyIdentifierExtension;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
|
||||
use SpomkyLabs\Pki\X509\CertificationRequest\CertificationRequest;
|
||||
use function sprintf;
|
||||
use function strval;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *TBSCertificate* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.1.2
|
||||
*/
|
||||
final class TBSCertificate
|
||||
{
|
||||
// Certificate version enumerations
|
||||
public const VERSION_1 = 0;
|
||||
|
||||
public const VERSION_2 = 1;
|
||||
|
||||
public const VERSION_3 = 2;
|
||||
|
||||
/**
|
||||
* Certificate version.
|
||||
*/
|
||||
private ?int $version = null;
|
||||
|
||||
/**
|
||||
* Serial number.
|
||||
*/
|
||||
private ?string $serialNumber = null;
|
||||
|
||||
/**
|
||||
* Signature algorithm.
|
||||
*/
|
||||
private ?SignatureAlgorithmIdentifier $signature = null;
|
||||
|
||||
/**
|
||||
* Issuer unique identifier.
|
||||
*/
|
||||
private ?UniqueIdentifier $issuerUniqueID = null;
|
||||
|
||||
/**
|
||||
* Subject unique identifier.
|
||||
*/
|
||||
private ?UniqueIdentifier $subjectUniqueID = null;
|
||||
|
||||
/**
|
||||
* Extensions.
|
||||
*/
|
||||
private Extensions $extensions;
|
||||
|
||||
/**
|
||||
* @param Name $subject Certificate subject
|
||||
* @param PublicKeyInfo $subjectPublicKeyInfo Subject public key
|
||||
* @param Name $issuer Certificate issuer
|
||||
* @param Validity $validity Validity period
|
||||
*/
|
||||
private function __construct(
|
||||
private Name $subject,
|
||||
private PublicKeyInfo $subjectPublicKeyInfo,
|
||||
private Name $issuer,
|
||||
private Validity $validity
|
||||
) {
|
||||
$this->extensions = Extensions::create();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extensions that are never taken from a certification request.
|
||||
*
|
||||
* These decide what the certificate is allowed to do, so they belong to the issuer.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
public const FORBIDDEN_CSR_EXTENSIONS = [
|
||||
Extension::OID_BASIC_CONSTRAINTS,
|
||||
Extension::OID_KEY_USAGE,
|
||||
Extension::OID_EXT_KEY_USAGE,
|
||||
Extension::OID_NAME_CONSTRAINTS,
|
||||
Extension::OID_POLICY_CONSTRAINTS,
|
||||
Extension::OID_POLICY_MAPPINGS,
|
||||
Extension::OID_INHIBIT_ANY_POLICY,
|
||||
Extension::OID_CERTIFICATE_POLICIES,
|
||||
Extension::OID_AUTHORITY_KEY_IDENTIFIER,
|
||||
];
|
||||
|
||||
/**
|
||||
* Smallest random serial number that meets the CA/Browser Forum Baseline Requirements, in octets.
|
||||
*
|
||||
* They ask for at least 64 bits of CSPRNG output. The sign bit costs one, so eight octets fall just short
|
||||
* and nine are needed. Smaller sizes are still accepted, with a deprecation notice.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const MIN_RANDOM_SERIAL_SIZE = 9;
|
||||
|
||||
/**
|
||||
* Default random serial number size, in octets. RFC 5280 section 4.1.2.2 caps serial numbers at 20 octets.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const DEFAULT_RANDOM_SERIAL_SIZE = 20;
|
||||
|
||||
public static function create(
|
||||
Name $subject,
|
||||
PublicKeyInfo $subjectPublicKeyInfo,
|
||||
Name $issuer,
|
||||
Validity $validity
|
||||
): self {
|
||||
return new self($subject, $subjectPublicKeyInfo, $issuer, $validity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
// the optional fields of a TBSCertificate are distinct, so a repeated tag is not a field but a second copy
|
||||
// of one; hasTagged() would keep only the last of them and silently drop what came before
|
||||
$seq->assertUniqueTaggedElements('TBSCertificate');
|
||||
$idx = 0;
|
||||
if ($seq->hasTagged(0)) {
|
||||
++$idx;
|
||||
$number = $seq->getTagged(0)
|
||||
->asExplicit()
|
||||
->asInteger()
|
||||
->getValue();
|
||||
// calling intNumber() straight away would let brick/math's IntegerOverflowException escape the
|
||||
// decoding contract; a version that does not fit in an int cannot be a supported version anyway
|
||||
if ($number->isLessThan(PHP_INT_MIN) || $number->isGreaterThan(PHP_INT_MAX)) {
|
||||
throw new UnexpectedValueException(
|
||||
sprintf('Unsupported certificate version %s.', $number->toBase(10))
|
||||
);
|
||||
}
|
||||
$version = $number->toInt();
|
||||
} else {
|
||||
$version = self::VERSION_1;
|
||||
}
|
||||
$serial = $seq->at($idx++)
|
||||
->asInteger()
|
||||
->number();
|
||||
$algo = AlgorithmIdentifier::fromASN1($seq->at($idx++)->asSequence());
|
||||
if (! $algo instanceof SignatureAlgorithmIdentifier) {
|
||||
throw new UnexpectedValueException('Unsupported signature algorithm ' . $algo->name() . '.');
|
||||
}
|
||||
$issuer = Name::fromASN1($seq->at($idx++)->asSequence());
|
||||
$validity = Validity::fromASN1($seq->at($idx++)->asSequence());
|
||||
$subject = Name::fromASN1($seq->at($idx++)->asSequence());
|
||||
$pki = PublicKeyInfo::fromASN1($seq->at($idx++)->asSequence());
|
||||
$tbs_cert = self::create($subject, $pki, $issuer, $validity)
|
||||
->withVersion($version)
|
||||
->withSerialNumber($serial)
|
||||
->withSignature($algo)
|
||||
;
|
||||
if ($seq->hasTagged(1)) {
|
||||
$tbs_cert = $tbs_cert->withIssuerUniqueID(UniqueIdentifier::fromASN1(
|
||||
$seq->getTagged(1)
|
||||
->asImplicit(Element::TYPE_BIT_STRING)
|
||||
->asBitString()
|
||||
));
|
||||
}
|
||||
if ($seq->hasTagged(2)) {
|
||||
$tbs_cert = $tbs_cert->withSubjectUniqueID(UniqueIdentifier::fromASN1(
|
||||
$seq->getTagged(2)
|
||||
->asImplicit(Element::TYPE_BIT_STRING)
|
||||
->asBitString()
|
||||
));
|
||||
}
|
||||
if ($seq->hasTagged(3)) {
|
||||
$tbs_cert = $tbs_cert->withExtensions(Extensions::fromASN1($seq->getTagged(3)->asExplicit()->asSequence()));
|
||||
}
|
||||
self::assertOptionalTrailingFields($seq, $idx);
|
||||
return $tbs_cert;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that everything past subjectPublicKeyInfo is at most one [1], one [2] and one [3], in that order.
|
||||
*
|
||||
* The fixed fields are read by position and the optional ones by tag, so nothing else looks at the elements in
|
||||
* between or after. An element the template does not define is then carried along unnoticed, and the encoding
|
||||
* no longer means what a conforming decoder reads from it.
|
||||
*
|
||||
* @param int $offset Index of the first element past subjectPublicKeyInfo
|
||||
*
|
||||
* @throws DecodeException If any other element is present.
|
||||
*/
|
||||
private static function assertOptionalTrailingFields(Sequence $seq, int $offset): void
|
||||
{
|
||||
$previous = 0;
|
||||
$count = count($seq);
|
||||
for ($i = $offset; $i < $count; ++$i) {
|
||||
$element = $seq->at($i)
|
||||
->asElement();
|
||||
$tag = $element->isTagged() ? $element->tag() : -1;
|
||||
if ($tag <= $previous || $tag > 3) {
|
||||
throw new DecodeException(
|
||||
sprintf('TBSCertificate has an unexpected element at index %d.', $i)
|
||||
);
|
||||
}
|
||||
$previous = $tag;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from certification request.
|
||||
*
|
||||
* The extensions a request asks for are chosen by the requester. Those in FORBIDDEN_CSR_EXTENSIONS decide
|
||||
* what a certificate is allowed to do, so they are never copied: a requester asking for basicConstraints
|
||||
* cA:TRUE and keyUsage keyCertSign is asking to become a certificate authority. The issuer sets those
|
||||
* itself.
|
||||
*
|
||||
* Name the extensions to copy in $allowedExtensionOids. Leaving the argument out copies every requested
|
||||
* extension that is not forbidden, which is a deny list: the set of extensions that matter grows over time
|
||||
* and every future one would be copied by default. A request can currently carry a subjectAltName naming an
|
||||
* identity the subject DN says nothing about, or an authorityInformationAccess choosing the OCSP responder a
|
||||
* relying party will ask. That default is deprecated and becomes the empty allow list in the next major
|
||||
* release; pass null explicitly to ask for it.
|
||||
*
|
||||
* An unknown extension marked critical is never copied, whatever the allow list says: it would be signed
|
||||
* verbatim and then no RFC 5280 validator would accept the certificate, this library's own included.
|
||||
*
|
||||
* Note that signature is not verified and must be done by the caller.
|
||||
*
|
||||
* @param CertificationRequest $cr Certification request
|
||||
* @param null|string[] $allowedExtensionOids OIDs of the requested extensions to copy, null for all of them
|
||||
* except the forbidden ones
|
||||
*/
|
||||
public static function fromCSR(CertificationRequest $cr, ?array $allowedExtensionOids = null): self
|
||||
{
|
||||
$allowListGiven = func_num_args() > 1;
|
||||
if ($allowedExtensionOids !== null) {
|
||||
$forbidden = array_intersect($allowedExtensionOids, self::FORBIDDEN_CSR_EXTENSIONS);
|
||||
if (count($forbidden) !== 0) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Extensions %s cannot be taken from a certification request.',
|
||||
implode(', ', $forbidden)
|
||||
));
|
||||
}
|
||||
}
|
||||
$cri = $cr->certificationRequestInfo();
|
||||
$tbs_cert = self::create(
|
||||
$cri->subject(),
|
||||
$cri->subjectPKInfo(),
|
||||
Name::create(),
|
||||
Validity::fromStrings(null, null)
|
||||
);
|
||||
// if CSR has Extension Request attribute
|
||||
if ($cri->hasAttributes()) {
|
||||
$attribs = $cri->attributes();
|
||||
if ($attribs->hasExtensionRequest()) {
|
||||
$requested = $attribs->extensionRequest()
|
||||
->extensions();
|
||||
$accepted = [];
|
||||
foreach ($requested as $extension) {
|
||||
$oid = $extension->oid();
|
||||
if (in_array($oid, self::FORBIDDEN_CSR_EXTENSIONS, true)) {
|
||||
continue;
|
||||
}
|
||||
if ($allowedExtensionOids !== null && ! in_array($oid, $allowedExtensionOids, true)) {
|
||||
continue;
|
||||
}
|
||||
// an extension this library cannot even parse, signed as critical, produces a certificate
|
||||
// that is dead on arrival: no conforming validator will accept it
|
||||
if ($extension->isCritical() && $extension instanceof UnknownExtension) {
|
||||
continue;
|
||||
}
|
||||
$accepted[] = $extension;
|
||||
}
|
||||
if (! $allowListGiven && count($accepted) !== 0) {
|
||||
@trigger_error(sprintf(
|
||||
'Copying requested extensions from a certification request without naming them is '
|
||||
. 'deprecated and will stop copying anything in the next major release. %s '
|
||||
. 'were taken from the request. Pass the OIDs to copy as the second argument of '
|
||||
. 'fromCSR(), or pass null explicitly to keep the current behaviour.',
|
||||
implode(', ', array_map(static fn (Extension $e) => $e->oid(), $accepted))
|
||||
), E_USER_DEPRECATED);
|
||||
}
|
||||
$tbs_cert = $tbs_cert->withExtensions(Extensions::create(...$accepted));
|
||||
}
|
||||
}
|
||||
// add Subject Key Identifier extension
|
||||
return $tbs_cert->withAdditionalExtensions(
|
||||
SubjectKeyIdentifierExtension::create(false, $cri->subjectPKInfo()->keyIdentifier())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with fields set from the issuer's certificate.
|
||||
*
|
||||
* Issuer shall be set to issuing certificate's subject. Authority key identifier extensions shall be added with a
|
||||
* key identifier set to issuing certificate's public key identifier.
|
||||
*
|
||||
* @param Certificate $cert Issuing party's certificate
|
||||
*/
|
||||
public function withIssuerCertificate(Certificate $cert): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
// set issuer DN from cert's subject
|
||||
$obj->issuer = $cert->tbsCertificate()
|
||||
->subject();
|
||||
// add authority key identifier extension
|
||||
$key_id = $cert->tbsCertificate()
|
||||
->subjectPublicKeyInfo()
|
||||
->keyIdentifier();
|
||||
$obj->extensions = $obj->extensions->withExtensions(AuthorityKeyIdentifierExtension::create(false, $key_id));
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given version.
|
||||
*
|
||||
* If version is not set, appropriate version is automatically determined during signing.
|
||||
*/
|
||||
public function withVersion(int $version): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->version = $version;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given serial number.
|
||||
*
|
||||
* @param int|string $serial Base 10 number
|
||||
*/
|
||||
public function withSerialNumber(int|string $serial): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->serialNumber = strval($serial);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with random positive serial number.
|
||||
*
|
||||
* @param int $size Number of random bytes
|
||||
*/
|
||||
public function withRandomSerialNumber(int $size = self::DEFAULT_RANDOM_SERIAL_SIZE): self
|
||||
{
|
||||
return $this->withSerialNumber(self::generateSerialNumber($size));
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw a serial number from a CSPRNG.
|
||||
*
|
||||
* The most significant bit is cleared so the DER INTEGER encodes a positive value, which is why 64 bits of
|
||||
* entropy need nine octets rather than eight.
|
||||
*
|
||||
* @param int $size Number of random octets
|
||||
*/
|
||||
private static function generateSerialNumber(int $size): string
|
||||
{
|
||||
if ($size < 1) {
|
||||
throw new InvalidArgumentException('Serial number size must be at least one octet.');
|
||||
}
|
||||
if ($size < self::MIN_RANDOM_SERIAL_SIZE) {
|
||||
@trigger_error(sprintf(
|
||||
'A %d octet serial number carries %.2f bits of entropy, below the 64 bits the CA/Browser Forum'
|
||||
. ' Baseline Requirements ask for. Use at least %d octets.',
|
||||
$size,
|
||||
8 * $size - 1,
|
||||
self::MIN_RANDOM_SERIAL_SIZE
|
||||
), E_USER_DEPRECATED);
|
||||
}
|
||||
$octets = random_bytes($size);
|
||||
$octets[0] = chr(ord($octets[0]) & 0x7F);
|
||||
$num = BigInteger::fromBytes($octets, false);
|
||||
|
||||
return $num->isZero() ? '1' : $num->toBase(10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given signature algorithm.
|
||||
*/
|
||||
public function withSignature(SignatureAlgorithmIdentifier $algo): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->signature = $algo;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given issuer.
|
||||
*/
|
||||
public function withIssuer(Name $issuer): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->issuer = $issuer;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given validity.
|
||||
*/
|
||||
public function withValidity(Validity $validity): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->validity = $validity;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given subject.
|
||||
*/
|
||||
public function withSubject(Name $subject): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->subject = $subject;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given subject public key info.
|
||||
*/
|
||||
public function withSubjectPublicKeyInfo(PublicKeyInfo $pub_key_info): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->subjectPublicKeyInfo = $pub_key_info;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with issuer unique ID.
|
||||
*/
|
||||
public function withIssuerUniqueID(UniqueIdentifier $id): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->issuerUniqueID = $id;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with subject unique ID.
|
||||
*/
|
||||
public function withSubjectUniqueID(UniqueIdentifier $id): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->subjectUniqueID = $id;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with given extensions.
|
||||
*/
|
||||
public function withExtensions(Extensions $extensions): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->extensions = $extensions;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with extensions added.
|
||||
*
|
||||
* @param Extension ...$exts One or more Extension objects
|
||||
*/
|
||||
public function withAdditionalExtensions(Extension ...$exts): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->extensions = $obj->extensions->withExtensions(...$exts);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether version is set.
|
||||
*/
|
||||
public function hasVersion(): bool
|
||||
{
|
||||
return isset($this->version);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certificate version.
|
||||
*/
|
||||
public function version(): int
|
||||
{
|
||||
if (! $this->hasVersion()) {
|
||||
throw new LogicException('version not set.');
|
||||
}
|
||||
return $this->version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether serial number is set.
|
||||
*/
|
||||
public function hasSerialNumber(): bool
|
||||
{
|
||||
return isset($this->serialNumber);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get serial number.
|
||||
*
|
||||
* @return string Base 10 integer
|
||||
*/
|
||||
public function serialNumber(): string
|
||||
{
|
||||
if (! $this->hasSerialNumber()) {
|
||||
throw new LogicException('serialNumber not set.');
|
||||
}
|
||||
return $this->serialNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether signature algorithm is set.
|
||||
*/
|
||||
public function hasSignature(): bool
|
||||
{
|
||||
return isset($this->signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signature algorithm.
|
||||
*/
|
||||
public function signature(): SignatureAlgorithmIdentifier
|
||||
{
|
||||
if (! $this->hasSignature()) {
|
||||
throw new LogicException('signature not set.');
|
||||
}
|
||||
return $this->signature;
|
||||
}
|
||||
|
||||
public function issuer(): Name
|
||||
{
|
||||
return $this->issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validity period.
|
||||
*/
|
||||
public function validity(): Validity
|
||||
{
|
||||
return $this->validity;
|
||||
}
|
||||
|
||||
public function subject(): Name
|
||||
{
|
||||
return $this->subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get subject public key.
|
||||
*/
|
||||
public function subjectPublicKeyInfo(): PublicKeyInfo
|
||||
{
|
||||
return $this->subjectPublicKeyInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether issuer unique identifier is present.
|
||||
*/
|
||||
public function hasIssuerUniqueID(): bool
|
||||
{
|
||||
return isset($this->issuerUniqueID);
|
||||
}
|
||||
|
||||
public function issuerUniqueID(): UniqueIdentifier
|
||||
{
|
||||
if (! $this->hasIssuerUniqueID()) {
|
||||
throw new LogicException('issuerUniqueID not set.');
|
||||
}
|
||||
return $this->issuerUniqueID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether subject unique identifier is present.
|
||||
*/
|
||||
public function hasSubjectUniqueID(): bool
|
||||
{
|
||||
return isset($this->subjectUniqueID);
|
||||
}
|
||||
|
||||
public function subjectUniqueID(): UniqueIdentifier
|
||||
{
|
||||
if (! $this->hasSubjectUniqueID()) {
|
||||
throw new LogicException('subjectUniqueID not set.');
|
||||
}
|
||||
return $this->subjectUniqueID;
|
||||
}
|
||||
|
||||
public function extensions(): Extensions
|
||||
{
|
||||
return $this->extensions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [];
|
||||
$version = $this->version();
|
||||
// if version is not default
|
||||
if ($version !== self::VERSION_1) {
|
||||
$elements[] = ExplicitlyTaggedType::create(0, Integer::create($version));
|
||||
}
|
||||
$serial = $this->serialNumber();
|
||||
$signature = $this->signature();
|
||||
// add required elements
|
||||
array_push(
|
||||
$elements,
|
||||
Integer::create($serial),
|
||||
$signature->toASN1(),
|
||||
$this->issuer->toASN1(),
|
||||
$this->validity->toASN1(),
|
||||
$this->subject->toASN1(),
|
||||
$this->subjectPublicKeyInfo->toASN1()
|
||||
);
|
||||
if (isset($this->issuerUniqueID)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(1, $this->issuerUniqueID->toASN1());
|
||||
}
|
||||
if (isset($this->subjectUniqueID)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(2, $this->subjectUniqueID->toASN1());
|
||||
}
|
||||
if (count($this->extensions) !== 0) {
|
||||
$elements[] = ExplicitlyTaggedType::create(3, $this->extensions->toASN1());
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create signed certificate.
|
||||
*
|
||||
* @param SignatureAlgorithmIdentifier $algo Algorithm used for signing
|
||||
* @param PrivateKeyInfo $privkey_info Private key used for signing
|
||||
* @param null|Crypto $crypto Crypto engine, use default if not set
|
||||
*/
|
||||
public function sign(
|
||||
SignatureAlgorithmIdentifier $algo,
|
||||
PrivateKeyInfo $privkey_info,
|
||||
?Crypto $crypto = null
|
||||
): Certificate {
|
||||
$crypto ??= Crypto::getDefault();
|
||||
$tbs_cert = clone $this;
|
||||
if (! isset($tbs_cert->version)) {
|
||||
$tbs_cert->version = $tbs_cert->_determineVersion();
|
||||
}
|
||||
if (! isset($tbs_cert->serialNumber)) {
|
||||
// RFC 5280 section 4.1.2.2 requires a positive integer, and a constant serial number removes the
|
||||
// unpredictability that protects issuance against collision attacks while breaking CRL revocation,
|
||||
// which identifies certificates by the (issuer, serial number) pair. Draw one rather than use zero.
|
||||
$tbs_cert->serialNumber = self::generateSerialNumber(self::DEFAULT_RANDOM_SERIAL_SIZE);
|
||||
}
|
||||
$tbs_cert->signature = $algo;
|
||||
$data = $tbs_cert->toASN1()
|
||||
->toDER();
|
||||
$signature = $crypto->sign($data, $privkey_info, $algo);
|
||||
return Certificate::create($tbs_cert, $algo, $signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine minimum version for the certificate.
|
||||
*/
|
||||
private function _determineVersion(): int
|
||||
{
|
||||
// if extensions are present
|
||||
if (count($this->extensions) !== 0) {
|
||||
return self::VERSION_3;
|
||||
}
|
||||
// if UniqueIdentifier is present
|
||||
if (isset($this->issuerUniqueID) || isset($this->subjectUniqueID)) {
|
||||
return self::VERSION_2;
|
||||
}
|
||||
return self::VERSION_1;
|
||||
}
|
||||
}
|
||||
103
vendor/spomky-labs/pki-framework/src/X509/Certificate/Time.php
vendored
Normal file
103
vendor/spomky-labs/pki-framework/src/X509/Certificate/Time.php
vendored
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\GeneralizedTime;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\UTCTime;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TimeType;
|
||||
use SpomkyLabs\Pki\X509\Feature\DateTimeHelper;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *Time* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.1
|
||||
*/
|
||||
final class Time
|
||||
{
|
||||
use DateTimeHelper;
|
||||
|
||||
/**
|
||||
* Time ASN.1 type tag.
|
||||
*/
|
||||
private readonly int $type;
|
||||
|
||||
private function __construct(
|
||||
protected DateTimeImmutable $dt,
|
||||
?int $type
|
||||
) {
|
||||
$this->type = $type ?? self::determineType($dt);
|
||||
}
|
||||
|
||||
public static function create(DateTimeImmutable $dt, ?int $time = null): self
|
||||
{
|
||||
return new self($dt, $time);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(TimeType $el): self
|
||||
{
|
||||
// Pass the type of the original ASN.1 primitive
|
||||
if ($el instanceof UTCTime) {
|
||||
return self::create($el->dateTime(), Element::TYPE_UTC_TIME);
|
||||
}
|
||||
if ($el instanceof GeneralizedTime) {
|
||||
return self::create($el->dateTime(), Element::TYPE_GENERALIZED_TIME);
|
||||
}
|
||||
|
||||
return self::create($el->dateTime()); // TODO: should never happen?
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from date string.
|
||||
*/
|
||||
public static function fromString(?string $time, ?string $tz = null): self
|
||||
{
|
||||
return self::create(self::createDateTime($time, $tz));
|
||||
}
|
||||
|
||||
public function dateTime(): DateTimeImmutable
|
||||
{
|
||||
return $this->dt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1.
|
||||
*/
|
||||
public function toASN1(): TimeType
|
||||
{
|
||||
$dt = $this->dt;
|
||||
switch ($this->type) {
|
||||
case Element::TYPE_UTC_TIME:
|
||||
return UTCTime::create($dt);
|
||||
case Element::TYPE_GENERALIZED_TIME:
|
||||
// GeneralizedTime must not contain fractional seconds
|
||||
// (rfc5280 4.1.2.5.2)
|
||||
if ((int) $dt->format('u') !== 0) {
|
||||
// remove fractional seconds (round down)
|
||||
$dt = self::roundDownFractionalSeconds($dt);
|
||||
}
|
||||
return GeneralizedTime::create($dt);
|
||||
}
|
||||
throw new UnexpectedValueException('Time type ' . Element::tagToName($this->type) . ' not supported.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether to use UTCTime or GeneralizedTime ASN.1 type.
|
||||
*
|
||||
* @return int Type tag
|
||||
*/
|
||||
protected static function determineType(DateTimeImmutable $dt): int
|
||||
{
|
||||
if ($dt->format('Y') >= 2050) {
|
||||
return Element::TYPE_GENERALIZED_TIME;
|
||||
}
|
||||
return Element::TYPE_UTC_TIME;
|
||||
}
|
||||
}
|
||||
65
vendor/spomky-labs/pki-framework/src/X509/Certificate/UniqueIdentifier.php
vendored
Normal file
65
vendor/spomky-labs/pki-framework/src/X509/Certificate/UniqueIdentifier.php
vendored
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
|
||||
|
||||
/**
|
||||
* Implements *UniqueIdentifier* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.1.2.8
|
||||
*/
|
||||
final class UniqueIdentifier
|
||||
{
|
||||
private function __construct(
|
||||
private readonly BitString $uid
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(BitString $uid): self
|
||||
{
|
||||
return new self($uid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(BitString $bs): self
|
||||
{
|
||||
return self::create($bs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from string.
|
||||
*/
|
||||
public static function fromString(string $str): self
|
||||
{
|
||||
return self::create(BitString::create($str));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unique identifier as a string.
|
||||
*/
|
||||
public function string(): string
|
||||
{
|
||||
return $this->uid->string();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unique identifier as a bit string.
|
||||
*/
|
||||
public function bitString(): BitString
|
||||
{
|
||||
return $this->uid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ASN.1 element.
|
||||
*/
|
||||
public function toASN1(): BitString
|
||||
{
|
||||
return $this->uid;
|
||||
}
|
||||
}
|
||||
72
vendor/spomky-labs/pki-framework/src/X509/Certificate/Validity.php
vendored
Normal file
72
vendor/spomky-labs/pki-framework/src/X509/Certificate/Validity.php
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Certificate;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
|
||||
/**
|
||||
* Implements *Validity* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.1.2.5
|
||||
*/
|
||||
final class Validity
|
||||
{
|
||||
private function __construct(
|
||||
private readonly Time $notBefore,
|
||||
private readonly Time $notAfter
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(Time $notBefore, Time $notAfter): self
|
||||
{
|
||||
return new self($notBefore, $notAfter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$nb = Time::fromASN1($seq->at(0)->asTime());
|
||||
$na = Time::fromASN1($seq->at(1)->asTime());
|
||||
return self::create($nb, $na);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from date strings.
|
||||
*
|
||||
* @param null|string $nb_date Not before date
|
||||
* @param null|string $na_date Not after date
|
||||
* @param null|string $tz Timezone string
|
||||
*/
|
||||
public static function fromStrings(?string $nb_date, ?string $na_date, ?string $tz = null): self
|
||||
{
|
||||
return self::create(Time::fromString($nb_date, $tz), Time::fromString($na_date, $tz));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get not before time.
|
||||
*/
|
||||
public function notBefore(): Time
|
||||
{
|
||||
return $this->notBefore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get not after time.
|
||||
*/
|
||||
public function notAfter(): Time
|
||||
{
|
||||
return $this->notAfter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create($this->notBefore->toASN1(), $this->notAfter->toASN1());
|
||||
}
|
||||
}
|
||||
254
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/CertificationPath.php
vendored
Normal file
254
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/CertificationPath.php
vendored
Normal 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);
|
||||
}
|
||||
}
|
||||
14
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/Exception/PathBuildingException.php
vendored
Normal file
14
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/Exception/PathBuildingException.php
vendored
Normal 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
|
||||
{
|
||||
}
|
||||
|
|
@ -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
|
||||
{
|
||||
}
|
||||
|
|
@ -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];
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
421
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/PathValidationConfig.php
vendored
Normal file
421
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/PathValidationConfig.php
vendored
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
719
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/PathValidator.php
vendored
Normal file
719
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/PathValidator.php
vendored
Normal 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);
|
||||
}
|
||||
}
|
||||
63
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/SignaturePolicy.php
vendored
Normal file
63
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/SignaturePolicy.php
vendored
Normal 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;
|
||||
}
|
||||
}
|
||||
418
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/ValidatorState.php
vendored
Normal file
418
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/PathValidation/ValidatorState.php
vendored
Normal 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;
|
||||
}
|
||||
}
|
||||
240
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/Policy/PolicyNode.php
vendored
Normal file
240
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/Policy/PolicyNode.php
vendored
Normal 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);
|
||||
}
|
||||
}
|
||||
422
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/Policy/PolicyTree.php
vendored
Normal file
422
vendor/spomky-labs/pki-framework/src/X509/CertificationPath/Policy/PolicyTree.php
vendored
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\CertificationRequest\Attribute;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\BinaryMatch;
|
||||
use SpomkyLabs\Pki\X501\MatchingRule\MatchingRule;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extensions;
|
||||
|
||||
/**
|
||||
* Implements value for 'Extension request' attribute.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc2985#page-17
|
||||
*/
|
||||
final class ExtensionRequestValue extends AttributeValue
|
||||
{
|
||||
public const OID = '1.2.840.113549.1.9.14';
|
||||
|
||||
/**
|
||||
* @param Extensions $extensions Extensions.
|
||||
*/
|
||||
private function __construct(
|
||||
protected Extensions $extensions
|
||||
) {
|
||||
parent::__construct(self::OID);
|
||||
}
|
||||
|
||||
public static function create(Extensions $extensions): self
|
||||
{
|
||||
return new self($extensions);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromASN1(UnspecifiedType $el): AttributeValue
|
||||
{
|
||||
return self::create(Extensions::fromASN1($el->asSequence()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get requested extensions.
|
||||
*/
|
||||
public function extensions(): Extensions
|
||||
{
|
||||
return $this->extensions;
|
||||
}
|
||||
|
||||
public function toASN1(): Element
|
||||
{
|
||||
return $this->extensions->toASN1();
|
||||
}
|
||||
|
||||
public function stringValue(): string
|
||||
{
|
||||
return '#' . bin2hex($this->toASN1()->toDER());
|
||||
}
|
||||
|
||||
public function equalityMatchingRule(): MatchingRule
|
||||
{
|
||||
return new BinaryMatch();
|
||||
}
|
||||
|
||||
public function rfc2253String(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
|
||||
protected function _transcodedString(): string
|
||||
{
|
||||
return $this->stringValue();
|
||||
}
|
||||
}
|
||||
68
vendor/spomky-labs/pki-framework/src/X509/CertificationRequest/Attributes.php
vendored
Normal file
68
vendor/spomky-labs/pki-framework/src/X509/CertificationRequest/Attributes.php
vendored
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\CertificationRequest;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Attribute;
|
||||
use SpomkyLabs\Pki\X501\ASN1\AttributeValue\AttributeValue;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Collection\SetOfAttributes;
|
||||
use SpomkyLabs\Pki\X509\CertificationRequest\Attribute\ExtensionRequestValue;
|
||||
|
||||
/**
|
||||
* Implements *Attributes* ASN.1 type of *CertificationRequestInfo*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc2986#section-4
|
||||
*/
|
||||
final class Attributes extends SetOfAttributes
|
||||
{
|
||||
/**
|
||||
* Mapping from OID to attribute value class name.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const MAP_OID_TO_CLASS = [
|
||||
ExtensionRequestValue::OID => ExtensionRequestValue::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Initialize from attribute values.
|
||||
*
|
||||
* @param AttributeValue ...$values List of attribute values
|
||||
*/
|
||||
public static function fromAttributeValues(AttributeValue ...$values): static
|
||||
{
|
||||
return static::create(...array_map(static fn (AttributeValue $value) => $value->toAttribute(), $values));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether extension request attribute is present.
|
||||
*/
|
||||
public function hasExtensionRequest(): bool
|
||||
{
|
||||
return $this->has(ExtensionRequestValue::OID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get extension request attribute value.
|
||||
*/
|
||||
public function extensionRequest(): ExtensionRequestValue
|
||||
{
|
||||
if (! $this->hasExtensionRequest()) {
|
||||
throw new LogicException('No extension request attribute.');
|
||||
}
|
||||
return $this->firstOf(ExtensionRequestValue::OID)->first();
|
||||
}
|
||||
|
||||
protected static function _castAttributeValues(Attribute $attribute): Attribute
|
||||
{
|
||||
$oid = $attribute->oid();
|
||||
if (isset(self::MAP_OID_TO_CLASS[$oid])) {
|
||||
return $attribute->castValues(self::MAP_OID_TO_CLASS[$oid]);
|
||||
}
|
||||
return $attribute;
|
||||
}
|
||||
}
|
||||
171
vendor/spomky-labs/pki-framework/src/X509/CertificationRequest/CertificationRequest.php
vendored
Normal file
171
vendor/spomky-labs/pki-framework/src/X509/CertificationRequest/CertificationRequest.php
vendored
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\CertificationRequest;
|
||||
|
||||
use RuntimeException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\CryptoBridge\Crypto;
|
||||
use SpomkyLabs\Pki\CryptoEncoding\PEM;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Signature\Signature;
|
||||
use SpomkyLabs\Pki\X509\Feature\SignedDER;
|
||||
use Stringable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *CertificationRequest* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc2986#section-4
|
||||
*/
|
||||
final class CertificationRequest implements Stringable
|
||||
{
|
||||
use SignedDER;
|
||||
|
||||
/**
|
||||
* @param CertificationRequestInfo $certificationRequestInfo Certification request information.
|
||||
* @param SignatureAlgorithmIdentifier $signatureAlgorithm Signature algorithm.
|
||||
* @param Signature $signature Signature value.
|
||||
* @param null|string $certificationRequestInfoDER Encoding of the certificationRequestInfo as it was received,
|
||||
* when decoded from DER.
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly CertificationRequestInfo $certificationRequestInfo,
|
||||
private readonly SignatureAlgorithmIdentifier $signatureAlgorithm,
|
||||
private readonly Signature $signature,
|
||||
private readonly ?string $certificationRequestInfoDER = null
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certification request as a PEM formatted string.
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->toPEM()
|
||||
->string();
|
||||
}
|
||||
|
||||
public static function create(
|
||||
CertificationRequestInfo $_certificationRequestInfo,
|
||||
SignatureAlgorithmIdentifier $_signatureAlgorithm,
|
||||
Signature $_signature
|
||||
): self {
|
||||
return new self($_certificationRequestInfo, $_signatureAlgorithm, $_signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
$info = CertificationRequestInfo::fromASN1($seq->at(0)->asSequence());
|
||||
$algo = AlgorithmIdentifier::fromASN1($seq->at(1)->asSequence());
|
||||
if (! $algo instanceof SignatureAlgorithmIdentifier) {
|
||||
throw new UnexpectedValueException('Unsupported signature algorithm ' . $algo->oid() . '.');
|
||||
}
|
||||
$signature = Signature::fromSignatureData($seq->at(2)->asBitString()->string(), $algo);
|
||||
return self::create($info, $algo, $signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from DER.
|
||||
*/
|
||||
public static function fromDER(string $data): self
|
||||
{
|
||||
[$seq, $infoDER] = self::decodeSignedDER($data, 'CertificationRequest');
|
||||
$csr = self::fromASN1($seq);
|
||||
// Keep the certificationRequestInfo exactly as it arrived, so that verify() checks the signature over the
|
||||
// bytes the requester signed rather than over what the parser produced.
|
||||
return new self($csr->certificationRequestInfo, $csr->signatureAlgorithm, $csr->signature, $infoDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from PEM.
|
||||
*/
|
||||
public static function fromPEM(PEM $pem): self
|
||||
{
|
||||
if ($pem->type() !== PEM::TYPE_CERTIFICATE_REQUEST) {
|
||||
throw new UnexpectedValueException('Invalid PEM type.');
|
||||
}
|
||||
return self::fromDER($pem->data());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certification request info.
|
||||
*/
|
||||
public function certificationRequestInfo(): CertificationRequestInfo
|
||||
{
|
||||
return $this->certificationRequestInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get signature algorithm.
|
||||
*/
|
||||
public function signatureAlgorithm(): SignatureAlgorithmIdentifier
|
||||
{
|
||||
return $this->signatureAlgorithm;
|
||||
}
|
||||
|
||||
public function signature(): Signature
|
||||
{
|
||||
return $this->signature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
return Sequence::create(
|
||||
$this->certificationRequestInfo->toASN1(),
|
||||
$this->signatureAlgorithm->toASN1(),
|
||||
$this->signature->bitString()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certification request as a DER.
|
||||
*/
|
||||
public function toDER(): string
|
||||
{
|
||||
return $this->toASN1()
|
||||
->toDER();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get certification request as a PEM.
|
||||
*/
|
||||
public function toPEM(): PEM
|
||||
{
|
||||
return PEM::create(PEM::TYPE_CERTIFICATE_REQUEST, $this->toDER());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify certification request signature.
|
||||
*
|
||||
* @param null|Crypto $crypto Crypto engine, use default if not set
|
||||
*
|
||||
* @return bool True if signature matches
|
||||
*/
|
||||
public function verify(?Crypto $crypto = null): bool
|
||||
{
|
||||
$crypto ??= Crypto::getDefault();
|
||||
// A request built in memory was never received as bytes; re-encoding it is then the only option, and the
|
||||
// correct one.
|
||||
$data = $this->certificationRequestInfoDER ?? $this->certificationRequestInfo->toASN1()
|
||||
->toDER();
|
||||
$pk_info = $this->certificationRequestInfo->subjectPKInfo();
|
||||
// a bool returning predicate must not throw on a signature it cannot check: the algorithm is named by
|
||||
// the certificate, so an attacker picks it, and `if (! $cert->verify($key))` in application code would
|
||||
// otherwise become an unhandled fatal. An unsupported algorithm, a key the algorithm does not match and
|
||||
// an engine level failure all mean the same thing to the caller: the signature was not verified.
|
||||
try {
|
||||
return $crypto->verify($data, $this->signature, $pk_info, $this->signatureAlgorithm);
|
||||
} catch (RuntimeException|UnexpectedValueException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
184
vendor/spomky-labs/pki-framework/src/X509/CertificationRequest/CertificationRequestInfo.php
vendored
Normal file
184
vendor/spomky-labs/pki-framework/src/X509/CertificationRequest/CertificationRequestInfo.php
vendored
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\CertificationRequest;
|
||||
|
||||
use LogicException;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\CryptoBridge\Crypto;
|
||||
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Feature\SignatureAlgorithmIdentifier;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKeyInfo;
|
||||
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Attribute;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Name;
|
||||
use SpomkyLabs\Pki\X509\Certificate\Extensions;
|
||||
use SpomkyLabs\Pki\X509\CertificationRequest\Attribute\ExtensionRequestValue;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *CertificationRequestInfo* ASN.1 type.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc2986#section-4
|
||||
*/
|
||||
final class CertificationRequestInfo
|
||||
{
|
||||
public const VERSION_1 = 0;
|
||||
|
||||
/**
|
||||
* Version.
|
||||
*/
|
||||
private readonly int $version;
|
||||
|
||||
/**
|
||||
* Attributes.
|
||||
*/
|
||||
private ?Attributes $attributes = null;
|
||||
|
||||
/**
|
||||
* @param Name $subject Subject
|
||||
* @param PublicKeyInfo $subjectPKInfo Public key info
|
||||
*/
|
||||
private function __construct(
|
||||
private Name $subject,
|
||||
private readonly PublicKeyInfo $subjectPKInfo
|
||||
) {
|
||||
$this->version = self::VERSION_1;
|
||||
}
|
||||
|
||||
public static function create(Name $subject, PublicKeyInfo $subjectPKInfo): self
|
||||
{
|
||||
return new self($subject, $subjectPKInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
// attributes is the only tagged field, so a second [0] is a second copy of it and hasTagged() would keep
|
||||
// only the last
|
||||
$seq->assertUniqueTaggedElements('CertificationRequestInfo');
|
||||
$version = $seq->at(0)
|
||||
->asInteger()
|
||||
->intNumber();
|
||||
if ($version !== self::VERSION_1) {
|
||||
throw new UnexpectedValueException("Version {$version} not supported.");
|
||||
}
|
||||
$subject = Name::fromASN1($seq->at(1)->asSequence());
|
||||
$pkinfo = PublicKeyInfo::fromASN1($seq->at(2)->asSequence());
|
||||
$obj = self::create($subject, $pkinfo);
|
||||
if ($seq->hasTagged(0)) {
|
||||
$obj = $obj->withAttributes(
|
||||
Attributes::fromASN1($seq->getTagged(0)->asImplicit(Element::TYPE_SET)->asSet())
|
||||
);
|
||||
}
|
||||
|
||||
return $obj;
|
||||
}
|
||||
|
||||
public function version(): int
|
||||
{
|
||||
return $this->version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with subject.
|
||||
*/
|
||||
public function withSubject(Name $subject): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->subject = $subject;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
public function subject(): Name
|
||||
{
|
||||
return $this->subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get subject public key info.
|
||||
*/
|
||||
public function subjectPKInfo(): PublicKeyInfo
|
||||
{
|
||||
return $this->subjectPKInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether certification request info has attributes.
|
||||
*/
|
||||
public function hasAttributes(): bool
|
||||
{
|
||||
return isset($this->attributes);
|
||||
}
|
||||
|
||||
public function attributes(): Attributes
|
||||
{
|
||||
if (! $this->hasAttributes()) {
|
||||
throw new LogicException('No attributes.');
|
||||
}
|
||||
return $this->attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get instance of self with attributes.
|
||||
*/
|
||||
public function withAttributes(Attributes $attribs): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
$obj->attributes = $attribs;
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get self with extension request attribute.
|
||||
*
|
||||
* @param Extensions $extensions Extensions to request
|
||||
*/
|
||||
public function withExtensionRequest(Extensions $extensions): self
|
||||
{
|
||||
$obj = clone $this;
|
||||
if (! isset($obj->attributes)) {
|
||||
$obj->attributes = Attributes::create();
|
||||
}
|
||||
$obj->attributes = $obj->attributes->withUnique(
|
||||
Attribute::fromAttributeValues(ExtensionRequestValue::create($extensions))
|
||||
);
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
$elements = [Integer::create($this->version), $this->subject->toASN1(), $this->subjectPKInfo->toASN1()];
|
||||
if (isset($this->attributes)) {
|
||||
$elements[] = ImplicitlyTaggedType::create(0, $this->attributes->toASN1());
|
||||
}
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create signed CertificationRequest.
|
||||
*
|
||||
* @param SignatureAlgorithmIdentifier $algo Algorithm used for signing
|
||||
* @param PrivateKeyInfo $privkey_info Private key used for signing
|
||||
* @param null|Crypto $crypto Crypto engine, use default if not set
|
||||
*/
|
||||
public function sign(
|
||||
SignatureAlgorithmIdentifier $algo,
|
||||
PrivateKeyInfo $privkey_info,
|
||||
?Crypto $crypto = null
|
||||
): CertificationRequest {
|
||||
$crypto ??= Crypto::getDefault();
|
||||
$data = $this->toASN1()
|
||||
->toDER();
|
||||
$signature = $crypto->sign($data, $privkey_info, $algo);
|
||||
return CertificationRequest::create($this, $algo, $signature);
|
||||
}
|
||||
}
|
||||
11
vendor/spomky-labs/pki-framework/src/X509/Exception/X509ValidationException.php
vendored
Normal file
11
vendor/spomky-labs/pki-framework/src/X509/Exception/X509ValidationException.php
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Exception;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class X509ValidationException extends RuntimeException
|
||||
{
|
||||
}
|
||||
59
vendor/spomky-labs/pki-framework/src/X509/Feature/DateTimeHelper.php
vendored
Normal file
59
vendor/spomky-labs/pki-framework/src/X509/Feature/DateTimeHelper.php
vendored
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Feature;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Exception;
|
||||
use RuntimeException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Helper trait for classes employing date and time handling.
|
||||
*/
|
||||
trait DateTimeHelper
|
||||
{
|
||||
/**
|
||||
* Create DateTime object from time string and timezone.
|
||||
*
|
||||
* @param null|string $time Time string, default to 'now'
|
||||
* @param null|string $tz Timezone, default if omitted
|
||||
*/
|
||||
private static function createDateTime(?string $time = null, ?string $tz = null): DateTimeImmutable
|
||||
{
|
||||
if (! isset($time)) {
|
||||
$time = 'now';
|
||||
}
|
||||
if (! isset($tz)) {
|
||||
$tz = date_default_timezone_get();
|
||||
}
|
||||
try {
|
||||
$dt = new DateTimeImmutable($time, self::createTimeZone($tz));
|
||||
return self::roundDownFractionalSeconds($dt);
|
||||
} catch (Exception $e) {
|
||||
throw new RuntimeException('Failed to create DateTime:', 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rounds a \DateTimeImmutable value such that fractional seconds are removed.
|
||||
*/
|
||||
private static function roundDownFractionalSeconds(DateTimeImmutable $dt): DateTimeImmutable
|
||||
{
|
||||
return DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $dt->format('Y-m-d H:i:s'), $dt->getTimezone());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create DateTimeZone object from string.
|
||||
*/
|
||||
private static function createTimeZone(string $tz): DateTimeZone
|
||||
{
|
||||
try {
|
||||
return new DateTimeZone($tz);
|
||||
} catch (Exception $e) {
|
||||
throw new UnexpectedValueException('Invalid timezone.', 0, $e);
|
||||
}
|
||||
}
|
||||
}
|
||||
61
vendor/spomky-labs/pki-framework/src/X509/Feature/SignedDER.php
vendored
Normal file
61
vendor/spomky-labs/pki-framework/src/X509/Feature/SignedDER.php
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\Feature;
|
||||
|
||||
use function count;
|
||||
use function mb_strlen;
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Exception\DecodeException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Structure;
|
||||
use function sprintf;
|
||||
|
||||
/**
|
||||
* Helper trait for the signed structures of X.509 — a sequence whose first element is the part the signature
|
||||
* covers, followed by the signature algorithm and the signature value.
|
||||
*
|
||||
* Verifying a signature over a re-encoding of the parsed first element checks what the parser produced rather
|
||||
* than what the signer signed. Every encoding the parser normalises away then yields another byte string that
|
||||
* verifies just as well, so a single signed object can be presented under any number of digests. Decoding
|
||||
* therefore keeps the first element exactly as it arrived, and refuses input the signer cannot have produced.
|
||||
*/
|
||||
trait SignedDER
|
||||
{
|
||||
/**
|
||||
* Decode a signed structure, returning the parsed sequence along with the untouched encoding of the element
|
||||
* the signature covers.
|
||||
*
|
||||
* @param string $data DER encoding of the whole structure
|
||||
* @param string $name Name of the type, used in error messages
|
||||
*
|
||||
* @return array{Sequence, string}
|
||||
*/
|
||||
private static function decodeSignedDER(string $data, string $name): array
|
||||
{
|
||||
$offset = 0;
|
||||
$seq = Element::fromDER($data, $offset)->asUnspecified()
|
||||
->asSequence();
|
||||
// Trailing bytes never reach the caller yet travel with the encoding, and they let one signed object be
|
||||
// presented under any number of distinct byte strings.
|
||||
$consumed = $offset ?? 0;
|
||||
$length = mb_strlen($data, '8bit');
|
||||
if ($consumed !== $length) {
|
||||
throw new DecodeException(
|
||||
sprintf('%s encoding is %d bytes but %d bytes were given.', $name, $consumed, $length)
|
||||
);
|
||||
}
|
||||
try {
|
||||
$parts = Structure::explodeDER($data);
|
||||
} catch (DecodeException $e) {
|
||||
// An indefinite length encoding is BER, not DER; the signed bytes cannot be isolated and re-encoding
|
||||
// them would bring the malleability back.
|
||||
throw new DecodeException(sprintf('%s must be DER encoded.', $name), 0, $e);
|
||||
}
|
||||
if (count($parts) === 0) {
|
||||
throw new DecodeException(sprintf('%s must not be empty.', $name));
|
||||
}
|
||||
return [$seq, $parts[0]];
|
||||
}
|
||||
}
|
||||
67
vendor/spomky-labs/pki-framework/src/X509/GeneralName/DNSName.php
vendored
Normal file
67
vendor/spomky-labs/pki-framework/src/X509/GeneralName/DNSName.php
vendored
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use function mb_strlen;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\IA5String;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use function sprintf;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *dNSName* CHOICE type of *GeneralName*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
final class DNSName extends GeneralName
|
||||
{
|
||||
/**
|
||||
* @param string $name Domain name
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly string $name
|
||||
) {
|
||||
self::assertNoControlCharacters($name, 'dNSName');
|
||||
if (mb_strlen($name, '8bit') > self::MAX_DNS_NAME_LENGTH) {
|
||||
throw new UnexpectedValueException(
|
||||
sprintf('dNSName must be at most %d octets.', self::MAX_DNS_NAME_LENGTH)
|
||||
);
|
||||
}
|
||||
parent::__construct(self::TAG_DNS_NAME);
|
||||
}
|
||||
|
||||
public static function create(string $name): self
|
||||
{
|
||||
return new self($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(UnspecifiedType $el): GeneralName
|
||||
{
|
||||
return self::create($el->asIA5String()->string());
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get DNS name.
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
protected function choiceASN1(): TaggedType
|
||||
{
|
||||
return ImplicitlyTaggedType::create($this->tag, IA5String::create($this->name));
|
||||
}
|
||||
}
|
||||
65
vendor/spomky-labs/pki-framework/src/X509/GeneralName/DirectoryName.php
vendored
Normal file
65
vendor/spomky-labs/pki-framework/src/X509/GeneralName/DirectoryName.php
vendored
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Name;
|
||||
|
||||
/**
|
||||
* Implements *directoryName* CHOICE type of *GeneralName*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
final class DirectoryName extends GeneralName
|
||||
{
|
||||
private function __construct(
|
||||
private readonly Name $directoryName
|
||||
) {
|
||||
parent::__construct(self::TAG_DIRECTORY_NAME);
|
||||
}
|
||||
|
||||
public static function create(Name $directoryName): self
|
||||
{
|
||||
return new self($directoryName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(UnspecifiedType $el): GeneralName
|
||||
{
|
||||
return self::create(Name::fromASN1($el->asSequence()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from distinguished name string.
|
||||
*/
|
||||
public static function fromDNString(string $str): self
|
||||
{
|
||||
return self::create(Name::fromString($str));
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return $this->directoryName->toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get directory name.
|
||||
*/
|
||||
public function dn(): Name
|
||||
{
|
||||
return $this->directoryName;
|
||||
}
|
||||
|
||||
protected function choiceASN1(): TaggedType
|
||||
{
|
||||
// Name type is itself a CHOICE, so explicit tagging must be
|
||||
// employed to avoid ambiguities
|
||||
return ExplicitlyTaggedType::create($this->tag, $this->directoryName->toASN1());
|
||||
}
|
||||
}
|
||||
51
vendor/spomky-labs/pki-framework/src/X509/GeneralName/EDIPartyName.php
vendored
Normal file
51
vendor/spomky-labs/pki-framework/src/X509/GeneralName/EDIPartyName.php
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *ediPartyName* CHOICE type of *GeneralName*.
|
||||
*
|
||||
* Currently acts as a parking object for decoding.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*
|
||||
* @todo Implement EDIPartyName type
|
||||
*/
|
||||
final class EDIPartyName extends GeneralName
|
||||
{
|
||||
private function __construct(
|
||||
protected Sequence $element
|
||||
) {
|
||||
parent::__construct(self::TAG_EDI_PARTY_NAME);
|
||||
}
|
||||
|
||||
public static function create(Sequence $element): self
|
||||
{
|
||||
return new self($element);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(UnspecifiedType $el): GeneralName
|
||||
{
|
||||
return self::create($el->asSequence());
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return bin2hex($this->element->toDER());
|
||||
}
|
||||
|
||||
protected function choiceASN1(): TaggedType
|
||||
{
|
||||
return ImplicitlyTaggedType::create($this->tag, $this->element);
|
||||
}
|
||||
}
|
||||
144
vendor/spomky-labs/pki-framework/src/X509/GeneralName/GeneralName.php
vendored
Normal file
144
vendor/spomky-labs/pki-framework/src/X509/GeneralName/GeneralName.php
vendored
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use function sprintf;
|
||||
use Stringable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *GeneralName* CHOICE with implicit tagging.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
abstract class GeneralName implements Stringable
|
||||
{
|
||||
// GeneralName CHOICE tags
|
||||
public const TAG_OTHER_NAME = 0;
|
||||
|
||||
public const TAG_RFC822_NAME = 1;
|
||||
|
||||
public const TAG_DNS_NAME = 2;
|
||||
|
||||
public const TAG_X400_ADDRESS = 3;
|
||||
|
||||
public const TAG_DIRECTORY_NAME = 4;
|
||||
|
||||
public const TAG_EDI_PARTY_NAME = 5;
|
||||
|
||||
public const TAG_URI = 6;
|
||||
|
||||
public const TAG_IP_ADDRESS = 7;
|
||||
|
||||
public const TAG_REGISTERED_ID = 8;
|
||||
|
||||
/**
|
||||
* Longest accepted dNSName, in octets. A fully qualified domain name is capped at 253 by DNS itself.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const MAX_DNS_NAME_LENGTH = 255;
|
||||
|
||||
protected function __construct(
|
||||
protected int $tag
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get general name as a string.
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->string();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get string value of the type.
|
||||
*/
|
||||
abstract public function string(): string;
|
||||
|
||||
/**
|
||||
* Initialize concrete object from the chosen ASN.1 element.
|
||||
*/
|
||||
abstract public static function fromChosenASN1(UnspecifiedType $el): self;
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(TaggedType $el): self
|
||||
{
|
||||
return match ($el->tag()) {
|
||||
self::TAG_OTHER_NAME => OtherName::fromChosenASN1($el->asImplicit(Element::TYPE_SEQUENCE)),
|
||||
self::TAG_RFC822_NAME => RFC822Name::fromChosenASN1($el->asImplicit(Element::TYPE_IA5_STRING)),
|
||||
self::TAG_DNS_NAME => DNSName::fromChosenASN1($el->asImplicit(Element::TYPE_IA5_STRING)),
|
||||
self::TAG_X400_ADDRESS => X400Address::fromChosenASN1($el->asImplicit(Element::TYPE_SEQUENCE)),
|
||||
self::TAG_DIRECTORY_NAME => DirectoryName::fromChosenASN1($el->asExplicit()),
|
||||
self::TAG_EDI_PARTY_NAME => EDIPartyName::fromChosenASN1($el->asImplicit(Element::TYPE_SEQUENCE)),
|
||||
self::TAG_URI => UniformResourceIdentifier::fromChosenASN1($el->asImplicit(Element::TYPE_IA5_STRING)),
|
||||
self::TAG_IP_ADDRESS => IPAddress::fromChosenASN1($el->asImplicit(Element::TYPE_OCTET_STRING)),
|
||||
self::TAG_REGISTERED_ID => RegisteredID::fromChosenASN1($el->asImplicit(Element::TYPE_OBJECT_IDENTIFIER)),
|
||||
default => throw new UnexpectedValueException('GeneralName type ' . $el->tag() . ' not supported.'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get type tag.
|
||||
*/
|
||||
public function tag(): int
|
||||
{
|
||||
return $this->tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 element.
|
||||
*/
|
||||
public function toASN1(): Element
|
||||
{
|
||||
return $this->choiceASN1();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether GeneralName is equal to others.
|
||||
*
|
||||
* @param GeneralName $other GeneralName to compare to
|
||||
*
|
||||
* @return bool True if names are equal
|
||||
*/
|
||||
public function equals(self $other): bool
|
||||
{
|
||||
if ($this->tag !== $other->tag) {
|
||||
return false;
|
||||
}
|
||||
if ($this->choiceASN1()->toDER() !== $other->choiceASN1()->toDER()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject control characters in a textual name.
|
||||
*
|
||||
* IA5String legitimately spans 0x00 to 0x7f, so a NUL byte is a valid IA5 character and the ASN.1 decoder has
|
||||
* no reason to refuse it. A name is not an arbitrary string though: an embedded NUL is the historic prefix
|
||||
* attack, and it makes any comparison that leaves PHP's binary-safe domain diverge from the encoded value.
|
||||
*
|
||||
* @param string $value Name to check
|
||||
* @param string $type Name type, for the error message
|
||||
*/
|
||||
protected static function assertNoControlCharacters(string $value, string $type): void
|
||||
{
|
||||
if (preg_match('/[\x00-\x1f\x7f]/', $value) === 1) {
|
||||
throw new UnexpectedValueException(sprintf('%s must not contain control characters.', $type));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ASN.1 value in GeneralName CHOICE context.
|
||||
*/
|
||||
abstract protected function choiceASN1(): TaggedType;
|
||||
}
|
||||
184
vendor/spomky-labs/pki-framework/src/X509/GeneralName/GeneralNames.php
vendored
Normal file
184
vendor/spomky-labs/pki-framework/src/X509/GeneralName/GeneralNames.php
vendored
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use ArrayIterator;
|
||||
use function count;
|
||||
use Countable;
|
||||
use IteratorAggregate;
|
||||
use LogicException;
|
||||
use RuntimeException;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use SpomkyLabs\Pki\X501\ASN1\Name;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *GeneralNames* ASN.1 type.
|
||||
*
|
||||
* Provides convenience methods to retrieve the first value of commonly used CHOICE types.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
final class GeneralNames implements Countable, IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* GeneralName objects.
|
||||
*
|
||||
* @var GeneralName[]
|
||||
*/
|
||||
private readonly array $_names;
|
||||
|
||||
/**
|
||||
* @param GeneralName ...$names One or more GeneralName objects
|
||||
*/
|
||||
private function __construct(GeneralName ...$names)
|
||||
{
|
||||
$this->_names = $names;
|
||||
}
|
||||
|
||||
public static function create(GeneralName ...$names): self
|
||||
{
|
||||
return new self(...$names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from ASN.1.
|
||||
*/
|
||||
public static function fromASN1(Sequence $seq): self
|
||||
{
|
||||
if (count($seq) === 0) {
|
||||
throw new UnexpectedValueException('GeneralNames must have at least one GeneralName.');
|
||||
}
|
||||
$names = array_map(static fn (UnspecifiedType $el) => GeneralName::fromASN1($el->asTagged()), $seq->elements());
|
||||
return self::create(...$names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all GeneralName objects.
|
||||
*
|
||||
* @return GeneralName[]
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->_names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether GeneralNames contains a GeneralName of given type.
|
||||
*
|
||||
* @param int $tag One of `GeneralName::TAG_*` enumerations
|
||||
*/
|
||||
public function has(int $tag): bool
|
||||
{
|
||||
return $this->findFirst($tag) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get first GeneralName of given type.
|
||||
*
|
||||
* @param int $tag One of `GeneralName::TAG_*` enumerations
|
||||
*/
|
||||
public function firstOf(int $tag): GeneralName
|
||||
{
|
||||
$name = $this->findFirst($tag);
|
||||
if ($name === null) {
|
||||
throw new UnexpectedValueException("No GeneralName by tag {$tag}.");
|
||||
}
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all GeneralName objects of given type.
|
||||
*
|
||||
* @param int $tag One of `GeneralName::TAG_*` enumerations
|
||||
*
|
||||
* @return GeneralName[]
|
||||
*/
|
||||
public function allOf(int $tag): array
|
||||
{
|
||||
$names = array_filter($this->_names, fn (GeneralName $name) => $name->tag() === $tag);
|
||||
return array_values($names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value of the first 'dNSName' type.
|
||||
*/
|
||||
public function firstDNS(): string
|
||||
{
|
||||
$gn = $this->firstOf(GeneralName::TAG_DNS_NAME);
|
||||
if (! $gn instanceof DNSName) {
|
||||
throw new RuntimeException(DNSName::class . ' expected, got ' . $gn::class);
|
||||
}
|
||||
return $gn->name();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value of the first 'directoryName' type.
|
||||
*/
|
||||
public function firstDN(): Name
|
||||
{
|
||||
$gn = $this->firstOf(GeneralName::TAG_DIRECTORY_NAME);
|
||||
if (! $gn instanceof DirectoryName) {
|
||||
throw new RuntimeException(DirectoryName::class . ' expected, got ' . $gn::class);
|
||||
}
|
||||
return $gn->dn();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value of the first 'uniformResourceIdentifier' type.
|
||||
*/
|
||||
public function firstURI(): string
|
||||
{
|
||||
$gn = $this->firstOf(GeneralName::TAG_URI);
|
||||
if (! $gn instanceof UniformResourceIdentifier) {
|
||||
throw new RuntimeException(UniformResourceIdentifier::class . ' expected, got ' . $gn::class);
|
||||
}
|
||||
return $gn->uri();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate ASN.1 structure.
|
||||
*/
|
||||
public function toASN1(): Sequence
|
||||
{
|
||||
if (count($this->_names) === 0) {
|
||||
throw new LogicException('GeneralNames must have at least one GeneralName.');
|
||||
}
|
||||
$elements = array_map(static fn (GeneralName $name) => $name->toASN1(), $this->_names);
|
||||
return Sequence::create(...$elements);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \Countable::count()
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->_names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get iterator for GeneralName objects.
|
||||
*
|
||||
* @see \IteratorAggregate::getIterator()
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator($this->_names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find first GeneralName by given tag.
|
||||
*/
|
||||
private function findFirst(int $tag): ?GeneralName
|
||||
{
|
||||
foreach ($this->_names as $name) {
|
||||
if ($name->tag() === $tag) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
111
vendor/spomky-labs/pki-framework/src/X509/GeneralName/IPAddress.php
vendored
Normal file
111
vendor/spomky-labs/pki-framework/src/X509/GeneralName/IPAddress.php
vendored
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use LogicException;
|
||||
use function mb_strlen;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
use function sprintf;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* Implements *iPAddress* CHOICE type of *GeneralName*.
|
||||
*
|
||||
* Concrete classes `IPv4Address` and `IPv6Address` furthermore implement the parsing semantics.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
abstract class IPAddress extends GeneralName
|
||||
{
|
||||
protected function __construct(
|
||||
protected string $ip,
|
||||
protected ?string $mask = null
|
||||
) {
|
||||
parent::__construct(self::TAG_IP_ADDRESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(UnspecifiedType $el): GeneralName
|
||||
{
|
||||
$octets = $el->asOctetString()
|
||||
->string();
|
||||
return match (mb_strlen($octets, '8bit')) {
|
||||
4, 8 => IPv4Address::fromOctets($octets),
|
||||
16, 32 => IPv6Address::fromOctets($octets),
|
||||
default => throw new UnexpectedValueException('Invalid octet length for IP address.'),
|
||||
};
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return $this->ip . (isset($this->mask) ? '/' . $this->mask : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get IP address as a string.
|
||||
*/
|
||||
public function address(): string
|
||||
{
|
||||
return $this->ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether mask is present.
|
||||
*/
|
||||
public function hasMask(): bool
|
||||
{
|
||||
return isset($this->mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get subnet mask as a string.
|
||||
*/
|
||||
public function mask(): string
|
||||
{
|
||||
if (! $this->hasMask()) {
|
||||
throw new LogicException('mask is not set.');
|
||||
}
|
||||
return $this->mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get octet representation of the IP address.
|
||||
*/
|
||||
abstract protected function octets(): string;
|
||||
|
||||
/**
|
||||
* Convert a textual address to its network octets, refusing anything that is not an address of the expected
|
||||
* family.
|
||||
*
|
||||
* Splitting the string on its separators and packing the parts accepts input that is not an address at all:
|
||||
* a compressed IPv6 address yields as many parts as it has written groups, so it packs to fewer than sixteen
|
||||
* octets and is then decoded as a different name form entirely. inet_pton() is the only conversion that is
|
||||
* total on what it accepts and rejects everything else.
|
||||
*
|
||||
* @param string $address Textual address
|
||||
* @param int $length Expected number of octets, 4 for IPv4 and 16 for IPv6
|
||||
* @param string $what Name of the value, used in the error message
|
||||
*/
|
||||
protected static function addressToOctets(string $address, int $length, string $what): string
|
||||
{
|
||||
$octets = inet_pton($address);
|
||||
if ($octets === false || mb_strlen($octets, '8bit') !== $length) {
|
||||
throw new InvalidArgumentException(sprintf('%s is not a valid %s address.', $what, $length === 4 ? 'IPv4' : 'IPv6'));
|
||||
}
|
||||
|
||||
return $octets;
|
||||
}
|
||||
|
||||
protected function choiceASN1(): TaggedType
|
||||
{
|
||||
return ImplicitlyTaggedType::create($this->tag, OctetString::create($this->octets()));
|
||||
}
|
||||
}
|
||||
64
vendor/spomky-labs/pki-framework/src/X509/GeneralName/IPv4Address.php
vendored
Normal file
64
vendor/spomky-labs/pki-framework/src/X509/GeneralName/IPv4Address.php
vendored
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use function array_map;
|
||||
use function array_slice;
|
||||
use function count;
|
||||
use function implode;
|
||||
use UnexpectedValueException;
|
||||
use function unpack;
|
||||
|
||||
final class IPv4Address extends IPAddress
|
||||
{
|
||||
/**
|
||||
* @param string $ip Dotted quad address
|
||||
* @param null|string $mask Optional subnet mask, as a dotted quad
|
||||
*/
|
||||
public static function create(string $ip, ?string $mask = null): self
|
||||
{
|
||||
// refuse here rather than when the name is encoded, so that a caller cannot build a constraint whose
|
||||
// meaning differs from what it wrote
|
||||
self::addressToOctets($ip, 4, 'Address');
|
||||
if ($mask !== null) {
|
||||
self::addressToOctets($mask, 4, 'Mask');
|
||||
}
|
||||
|
||||
return new self($ip, $mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from octets.
|
||||
*/
|
||||
public static function fromOctets(string $octets): self
|
||||
{
|
||||
$mask = null;
|
||||
$bytes = unpack('C*', $octets);
|
||||
/** @var array<int, int> $bytes */
|
||||
$bytes = $bytes === false ? [] : $bytes;
|
||||
switch (count($bytes)) {
|
||||
case 4:
|
||||
$ip = implode('.', array_map(static fn (int $v): string => (string) $v, $bytes));
|
||||
break;
|
||||
case 8:
|
||||
$ip = implode('.', array_map(static fn (int $v): string => (string) $v, array_slice($bytes, 0, 4)));
|
||||
$mask = implode('.', array_map(static fn (int $v): string => (string) $v, array_slice($bytes, 4, 4)));
|
||||
break;
|
||||
default:
|
||||
throw new UnexpectedValueException('Invalid IPv4 octet length.');
|
||||
}
|
||||
return self::create($ip, $mask);
|
||||
}
|
||||
|
||||
protected function octets(): string
|
||||
{
|
||||
$octets = self::addressToOctets($this->ip, 4, 'Address');
|
||||
if (isset($this->mask)) {
|
||||
$octets .= self::addressToOctets($this->mask, 4, 'Mask');
|
||||
}
|
||||
|
||||
return $octets;
|
||||
}
|
||||
}
|
||||
75
vendor/spomky-labs/pki-framework/src/X509/GeneralName/IPv6Address.php
vendored
Normal file
75
vendor/spomky-labs/pki-framework/src/X509/GeneralName/IPv6Address.php
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use function array_map;
|
||||
use function array_slice;
|
||||
use function count;
|
||||
use function implode;
|
||||
use function sprintf;
|
||||
use UnexpectedValueException;
|
||||
use function unpack;
|
||||
|
||||
final class IPv6Address extends IPAddress
|
||||
{
|
||||
/**
|
||||
* @param string $ip Address, in any notation inet_pton() accepts, compressed included
|
||||
* @param null|string $mask Optional subnet mask, in the same notation
|
||||
*/
|
||||
public static function create(string $ip, ?string $mask = null): self
|
||||
{
|
||||
// refuse here rather than when the name is encoded, so that a caller cannot build a constraint whose
|
||||
// meaning differs from what it wrote
|
||||
self::addressToOctets($ip, 16, 'Address');
|
||||
if ($mask !== null) {
|
||||
self::addressToOctets($mask, 16, 'Mask');
|
||||
}
|
||||
|
||||
return new self($ip, $mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize from octets.
|
||||
*/
|
||||
public static function fromOctets(string $octets): self
|
||||
{
|
||||
$mask = null;
|
||||
$words = unpack('n*', $octets);
|
||||
$words = $words === false ? [] : $words;
|
||||
switch (count($words)) {
|
||||
case 8:
|
||||
$ip = self::wordsToIPv6String($words);
|
||||
break;
|
||||
case 16:
|
||||
$ip = self::wordsToIPv6String(array_slice($words, 0, 8));
|
||||
$mask = self::wordsToIPv6String(array_slice($words, 8, 8));
|
||||
break;
|
||||
default:
|
||||
throw new UnexpectedValueException('Invalid IPv6 octet length.');
|
||||
}
|
||||
return self::create($ip, $mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an array of 16 bit words to an IPv6 string representation.
|
||||
*
|
||||
* @param int[] $words
|
||||
*/
|
||||
protected static function wordsToIPv6String(array $words): string
|
||||
{
|
||||
$groups = array_map(static fn ($word) => sprintf('%04x', $word), $words);
|
||||
return implode(':', $groups);
|
||||
}
|
||||
|
||||
protected function octets(): string
|
||||
{
|
||||
$octets = self::addressToOctets($this->ip, 16, 'Address');
|
||||
if (isset($this->mask)) {
|
||||
$octets .= self::addressToOctets($this->mask, 16, 'Mask');
|
||||
}
|
||||
|
||||
return $octets;
|
||||
}
|
||||
}
|
||||
80
vendor/spomky-labs/pki-framework/src/X509/GeneralName/OtherName.php
vendored
Normal file
80
vendor/spomky-labs/pki-framework/src/X509/GeneralName/OtherName.php
vendored
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Element;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *otherName* CHOICE type of *GeneralName*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
final class OtherName extends GeneralName
|
||||
{
|
||||
/**
|
||||
* @param string $type OID
|
||||
*/
|
||||
private function __construct(
|
||||
private readonly string $type,
|
||||
private readonly Element $element
|
||||
) {
|
||||
parent::__construct(self::TAG_OTHER_NAME);
|
||||
}
|
||||
|
||||
public static function create(string $type, Element $element): self
|
||||
{
|
||||
return new self($type, $element);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(UnspecifiedType $el): GeneralName
|
||||
{
|
||||
$seq = $el->asSequence();
|
||||
$type_id = $seq->at(0)
|
||||
->asObjectIdentifier()
|
||||
->oid();
|
||||
$value = $seq->getTagged(0)
|
||||
->asExplicit()
|
||||
->asElement();
|
||||
return self::create($type_id, $value);
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return $this->type . '/#' . bin2hex($this->element->toDER());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get type OID.
|
||||
*/
|
||||
public function type(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get value element.
|
||||
*/
|
||||
public function value(): Element
|
||||
{
|
||||
return $this->element;
|
||||
}
|
||||
|
||||
protected function choiceASN1(): TaggedType
|
||||
{
|
||||
return ImplicitlyTaggedType::create(
|
||||
$this->tag,
|
||||
Sequence::create(ObjectIdentifier::create($this->type), ExplicitlyTaggedType::create(0, $this->element))
|
||||
);
|
||||
}
|
||||
}
|
||||
53
vendor/spomky-labs/pki-framework/src/X509/GeneralName/RFC822Name.php
vendored
Normal file
53
vendor/spomky-labs/pki-framework/src/X509/GeneralName/RFC822Name.php
vendored
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace SpomkyLabs\Pki\X509\GeneralName;
|
||||
|
||||
use SpomkyLabs\Pki\ASN1\Type\Primitive\IA5String;
|
||||
use SpomkyLabs\Pki\ASN1\Type\Tagged\ImplicitlyTaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\TaggedType;
|
||||
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
|
||||
|
||||
/**
|
||||
* Implements *rfc822Name* CHOICE type of *GeneralName*.
|
||||
*
|
||||
* @see https://tools.ietf.org/html/rfc5280#section-4.2.1.6
|
||||
*/
|
||||
final class RFC822Name extends GeneralName
|
||||
{
|
||||
private function __construct(
|
||||
private readonly string $email
|
||||
) {
|
||||
self::assertNoControlCharacters($email, 'rfc822Name');
|
||||
parent::__construct(self::TAG_RFC822_NAME);
|
||||
}
|
||||
|
||||
public static function create(string $email): self
|
||||
{
|
||||
return new self($email);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function fromChosenASN1(UnspecifiedType $el): GeneralName
|
||||
{
|
||||
return self::create($el->asIA5String()->string());
|
||||
}
|
||||
|
||||
public function string(): string
|
||||
{
|
||||
return $this->email;
|
||||
}
|
||||
|
||||
public function email(): string
|
||||
{
|
||||
return $this->email;
|
||||
}
|
||||
|
||||
protected function choiceASN1(): TaggedType
|
||||
{
|
||||
return ImplicitlyTaggedType::create($this->tag, IA5String::create($this->email));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue