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

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

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

View file

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@spomky-labs.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

21
vendor/web-auth/cose-lib/LICENSE vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Spomky-Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

622
vendor/web-auth/cose-lib/README.md vendored Normal file
View file

@ -0,0 +1,622 @@
# COSE Library for PHP
[![CI](https://github.com/web-auth/cose-lib/actions/workflows/ci.yml/badge.svg)](https://github.com/web-auth/cose-lib/actions/workflows/ci.yml)
[![Latest Stable Version](https://poser.pugx.org/web-auth/cose-lib/v)](https://packagist.org/packages/web-auth/cose-lib)
[![Total Downloads](https://poser.pugx.org/web-auth/cose-lib/downloads)](https://packagist.org/packages/web-auth/cose-lib)
[![License](https://poser.pugx.org/web-auth/cose-lib/license)](https://packagist.org/packages/web-auth/cose-lib)
**CBOR Object Signing and Encryption (COSE) for PHP** is a comprehensive library that provides full support for COSE operations including signing, encryption, and MAC (Message Authentication Code) operations.
This library implements:
- **[RFC 9052](https://datatracker.ietf.org/doc/html/rfc9052)** - COSE: Structures and Process
- **[RFC 9053](https://datatracker.ietf.org/doc/html/rfc9053)** - COSE: Initial Algorithms
- **[RFC 9864](https://www.rfc-editor.org/rfc/rfc9864.html)** - COSE: Fully-Specified Algorithms
## Features
✅ **RFC 9052 Cryptographic Structures**
- `Sig_structure`: `Signature1` (§4.4) and `Signature`, which also covers the signer's own protected header
- `MAC_structure`: `Mac0Structure` and `MacStructure` (§6.3) — a MAC tag covers this, never the bare payload
- `Enc_structure`: `Encrypt0Structure`, `EncryptStructure` and `RecipientStructure` (§5.3)
- Each takes the optional `external_aad`, defaulting to the zero-length byte string the RFC prescribes
✅ **RFC 9052 Header and Structure Rules**
- `CoseHeaders` reads the two buckets of any COSE message: a label is an integer *or* a text string (§1.5) and the
two never answer for each other, the zero-length protected header is accepted (§3), trailing bytes in the
protected bucket are not, and the protected value wins a combined lookup
- `CoseSignature` and `CoseRecipient` are the checked views over the `signatures` and `recipients` lists (`[+ ...]`)
- Works on the COSE message classes of spomky-labs/cbor-php 3.4.0
✅ **COSE Tag Support** (via [spomky-labs/cbor-php](https://github.com/Spomky-Labs/cbor-php) 3.4.0)
- `CBOR\Tag\CoseSign1Tag` (18), `CoseSignTag` (98), `CoseEncrypt0Tag` (16), `CoseEncryptTag` (96),
`CoseMac0Tag` (17), `CoseMacTag` (97), plus `CwtTag` (61), all registered in the default decoder
- The `Cose\...Tag` classes of this library are **deprecated since 4.8.0** and removed in 5.0.0; see
[Upgrading](doc/Usage.md#upgrading-from-the-cosetag-classes)
✅ **Cryptographic Algorithms**
- **Signatures**: ECDSA (ES256, ES384, ES512, ES256K), EdDSA (Ed25519, Ed448), RSA (RS256/384/512, PS256/384/512)
- **Fully-specified identifiers** ([RFC 9864](https://www.rfc-editor.org/rfc/rfc9864.html)): ESP256/384/512, ESB256/320/384/512, Ed25519, Ed448
- **MAC**: HMAC with SHA-256/384/512
- Compatible with WebAuthn, FIDO2, and digital COVID certificates
✅ **Key Restrictions** ([RFC 9052](https://www.rfc-editor.org/rfc/rfc9052.html#section-7.1) §7.1)
- Opt-in enforcement of the `alg` (label 3) and `key_ops` (label 4) parameters a COSE key carries
- Turned on per algorithm or for a whole `Manager`: `ES256::create()->withKeyRestrictionsEnforced()`
- See [Key Restrictions](doc/Usage.md#key-restrictions-alg-and-key_ops)
✅ **Modern PHP**
- PHP 8.1+ with strict types
- Full type safety and PHPStan compliance
- Comprehensive test coverage
## Installation
Install the library with Composer:
```bash
composer require web-auth/cose-lib
```
For COSE tag support (Sign, Encrypt, Mac operations), also install:
```bash
composer require "spomky-labs/cbor-php:^3.3.4"
```
3.4.0 is the floor this library declares (`conflict: <3.4.0`). Two things come from there rather than from here: the
CBOR decoder enforces the header-map rules of [RFC 9052](https://datatracker.ietf.org/doc/html/rfc9052) — a label
appearing twice in a map makes the message malformed (§3, §9), and nesting is bounded so that a crafted header cannot
exhaust the memory of the process — and, since 3.4.0, the six COSE message classes themselves.
## Quick Start
### Verifying a COSE_Sign1 Signature
```php
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\OtherObject\NullObject;
use CBOR\StringStream;
use CBOR\Tag\CoseSign1Tag;
use Cose\Algorithm\Signature\ECDSA\ES256;
use Cose\Key\Ec2Key;
use Cose\Signature\Signature1;
use Cose\Structure\CoseHeaders;
// The key of the signer you trust, and the algorithm you expect it to be used with.
$key = Ec2Key::create($theCoseKeyYouPinned);
$algorithm = ES256::create();
// The protected header labels this application knows how to process (1 = alg, 2 = crit).
$understoodLabels = [1, 2];
// cbor-php 3.4.0 registers the six COSE tags in the default decoder: tag 18 resolves on its own.
$coseSign1 = Decoder::create()->decode(new StringStream($encodedData));
if (! $coseSign1 instanceof CoseSign1Tag) {
throw new RuntimeException('Not a COSE_Sign1 message');
}
// cbor-php carries the header buckets; this library reads them the way RFC 9052 defines them.
$headers = CoseHeaders::fromMessage($coseSign1);
// RFC 9052 §3.1: bind the signature to the algorithm the protected header declares.
// The label is matched by type as well as by value, so the text string "1" — a different label under §1.5 —
// never answers a lookup for the integer label 1.
$alg = $headers->getProtectedHeaderParameter(1);
if ($alg === null || (int) $alg->normalize() !== $algorithm::identifier()) {
throw new RuntimeException('Unexpected or missing "alg" in the protected header');
}
// RFC 9052 §3.1: every parameter listed in "crit" must be processed, or the message must be rejected.
$crit = $headers->getProtectedHeaderParameter(2);
if ($crit !== null) {
if (! $crit instanceof ListObject) {
throw new RuntimeException('"crit" is not an array');
}
foreach ($crit as $label) {
if (! in_array((int) $label->normalize(), $understoodLabels, true)) {
throw new RuntimeException('Unsupported critical header parameter');
}
}
}
// RFC 9052 §4.2: a nil payload is detached and the application supplies the content itself.
$payload = $coseSign1->getPayload();
if ($payload instanceof NullObject) {
throw new RuntimeException('The payload is detached; supply it from the application');
}
// Verify the Sig_structure the signature covers
$sigStructure = Signature1::create($coseSign1->getProtectedHeader(), $payload);
$isValid = $algorithm->verify((string) $sigStructure, $key, $coseSign1->getSignature()->getValue());
```
> [!IMPORTANT]
> The library verifies signatures; it does not decide what a message is allowed to say. Checking that `alg` is the one
> expected for that key, and refusing any `crit` label the application does not process, are the caller's
> responsibility ([RFC 9052 §3.1](https://datatracker.ietf.org/doc/html/rfc9052#section-3.1)) — the snippet above is
> the shape they take. `tests/Signature/DocumentedVerifierTest.php` runs exactly this code.
### Creating a COSE_Sign1 Message
```php
use CBOR\ByteStringObject;
use CBOR\ListObject;
use CBOR\MapItem;
use CBOR\MapObject;
use CBOR\NegativeIntegerObject;
use CBOR\Tag\CoseSign1Tag;
use CBOR\UnsignedIntegerObject;
use Cose\Algorithm\Signature\ECDSA\ES256;
use Cose\Key\Ec2Key;
use Cose\Signature\Signature1;
use Cose\Structure\HeaderMapHelper;
$algorithm = ES256::create();
$key = Ec2Key::create($yourPrivateCoseKey);
// Define headers
$protectedHeader = MapObject::create([
MapItem::create(
UnsignedIntegerObject::create(1), // alg
NegativeIntegerObject::create(ES256::identifier()) // ES256 (-7)
),
]);
$unprotectedHeader = MapObject::create([
MapItem::create(
UnsignedIntegerObject::create(4), // kid
ByteStringObject::create('my-key-id')
),
]);
$payload = ByteStringObject::create('Message to sign');
// The signature covers the Sig_structure, never the payload on its own. Encode the protected bucket once, so the
// bytes that are signed are the bytes the message carries. HeaderMapHelper applies RFC 9052 §3 on the way out: an
// empty map becomes h'' rather than h'a0', and the labels are checked (§1.5, §9).
$protectedHeaderAsBytes = HeaderMapHelper::encodeProtected($protectedHeader);
$toBeSigned = Signature1::create($protectedHeaderAsBytes, $payload);
$signature = ByteStringObject::create($algorithm->sign((string) $toBeSigned, $key));
// Assemble the message around those exact bytes
$coseSign1 = CoseSign1Tag::create(ListObject::create([
$protectedHeaderAsBytes,
$unprotectedHeader,
$payload,
$signature,
]));
// Encode to CBOR
$encoded = (string) $coseSign1;
```
> [!NOTE]
> `CoseSign1Tag::createFromComponents($protectedHeader, $unprotectedHeader, $payload, $signature)` takes the protected
> header as a **map** and encodes it itself, which is shorter but re-encodes what you already signed. Use it when the
> signature is computed after the message, and `create()` — as above — when the bytes have to travel verbatim.
> [`examples/01-sign1.php`](examples/01-sign1.php) is the whole round trip, key generation included, and runs as it
> stands.
## Documentation
- **[Examples](examples/)** - A runnable program per topic; `php examples/01-sign1.php` to start
- **[Usage Guide](doc/Usage.md)** - Complete documentation with examples
- **[RFC 9052](https://datatracker.ietf.org/doc/html/rfc9052)** - COSE Structures
- **[RFC 9053](https://datatracker.ietf.org/doc/html/rfc9053)** - COSE Algorithms
## Use Cases
This library is perfect for:
- 🏥 **Digital Health Certificates** - COVID-19 vaccination passes (EU Digital COVID Certificate)
- 🔐 **WebAuthn/FIDO2** - Authenticator attestation and assertion signatures
- 📱 **IoT Security** - Secure messaging for constrained devices
- 🌐 **Web PKI** - CBOR-based certificate chains
- 📄 **Document Signing** - Compact digital signatures
## Supported Algorithms
### Signature Algorithms
| Algorithm | Identifier | Description |
|-----------|------------|-------------|
| ES256 | -7 | ECDSA with SHA-256 |
| ES384 | -35 | ECDSA with SHA-384 |
| ES512 | -36 | ECDSA with SHA-512 |
| ES256K | -47 | ECDSA with secp256k1 |
| EdDSA | -8 | EdDSA |
| Ed25519 | -8 | Alias of EdDSA (Curve25519); see -19 below for the fully-specified form |
| Ed256 | -260 | Ed25519 over a SHA-256 digest — non-standard, see below |
| Ed512 | -261 | Ed25519 over a SHA-512 digest — non-standard, see below |
| RS256 | -257 | RSASSA-PKCS1-v1_5 with SHA-256 |
| RS384 | -258 | RSASSA-PKCS1-v1_5 with SHA-384 |
| RS512 | -259 | RSASSA-PKCS1-v1_5 with SHA-512 |
| PS256 | -37 | RSASSA-PSS with SHA-256 |
| PS384 | -38 | RSASSA-PSS with SHA-384 |
| PS512 | -39 | RSASSA-PSS with SHA-512 |
| RS1 | -65535 | RSASSA-PKCS1-v1_5 with SHA-1 — legacy only, see below |
#### Fully-Specified Algorithms ([RFC 9864](https://www.rfc-editor.org/rfc/rfc9864.html))
These identifiers determine the curve and the hash on their own, instead of leaving them to the other parameters of
the key. They live in the `Cose\Algorithm\Signature\FullySpecified` namespace.
| Algorithm | Identifier | Description |
|-----------|------------|-------------|
| ESP256 | -9 | ECDSA with the P-256 curve and SHA-256 |
| ESP384 | -51 | ECDSA with the P-384 curve and SHA-384 |
| ESP512 | -52 | ECDSA with the P-521 curve and SHA-512 |
| ESB256 | -265 | ECDSA with the brainpoolP256r1 curve and SHA-256 |
| ESB320 | -266 | ECDSA with the brainpoolP320r1 curve and SHA-384 |
| ESB384 | -267 | ECDSA with the brainpoolP384r1 curve and SHA-384 |
| ESB512 | -268 | ECDSA with the brainpoolP512r1 curve and SHA-512 |
| Ed25519 | -19 | EdDSA with the Ed25519 parameter set |
| Ed448 | -53 | EdDSA with the Ed448 parameter set — requires PHP 8.4 or later |
> [!NOTE]
> `Cose\Algorithm\Signature\FullySpecified\Ed25519` (-19) and `Cose\Algorithm\Signature\EdDSA\Ed25519` (-8)
> compute the same signatures; only the algorithm identifier differs.
>
> Ed448 is not covered by the sodium extension and goes through OpenSSL, which PHP only wires up for Edwards curves
> as of PHP 8.4. Call `Ed448::isSupported()` when the platform is not known in advance.
> [!WARNING]
> **`Ed256` (-260) and `Ed512` (-261) are not defined by any specification, and their identifiers are not theirs.**
> Both hash the message and sign the digest with pure **Ed25519**, without the `dom2` prefix that would make it the
> Ed25519ph of [RFC 8032](https://www.rfc-editor.org/rfc/rfc8032) §5.1 — whose §8.5 says prehashed variants
> "SHOULD NOT be used" anyway. IANA has since assigned -260 to WalnutDSA
> ([RFC 9021](https://www.rfc-editor.org/rfc/rfc9021)) and -261 to TurboSHAKE128
> ([RFC 9861](https://www.rfc-editor.org/rfc/rfc9861)), so a conforming implementation reads objects produced by these
> classes as those algorithms. Despite its name, `Ed512` is not Ed448 and rejects an Ed448 key; EdDSA with Curve448 is
> `Cose\Algorithm\Signature\FullySpecified\Ed448` (-53).
>
> No authenticator emits these identifiers. Prefer `Ed25519` (-8 or -19). They are kept for the deployments that
> already use the construction on both ends, and only against an explicit acknowledgement:
>
> ```php
> use Cose\Algorithm\Signature\EdDSA\Ed256;
>
> $algorithm = Ed256::create(acknowledgeNonStandardAlgorithm: true);
> ```
>
> As of the next major version, omitting that acknowledgement will throw an exception, and the identifiers will move
> out of the range IANA administers.
> [!WARNING]
> **RS1 (SHA-1) is not secure.** It is kept only for the legacy authenticators that still rely on it.
> Creating it emits an `E_USER_WARNING` unless you explicitly acknowledge the risk:
>
> ```php
> use Cose\Algorithm\Signature\RSA\RS1;
>
> $algorithm = RS1::create(acknowledgeInsecureAlgorithm: true);
> ```
>
> The same acknowledgement applies to `Algorithms::getOpensslAlgorithmFor()` and `Algorithms::getHashAlgorithmFor()`,
> which hand out the very same primitive without any object being created:
>
> ```php
> use Cose\Algorithms;
>
> $digest = Algorithms::getOpensslAlgorithmFor(Algorithms::COSE_ALGORITHM_RS1, acknowledgeInsecureAlgorithm: true);
> ```
>
> As of the next major version, omitting that acknowledgement will throw an exception instead of warning.
### MAC Algorithms
| Algorithm | Identifier | Description |
|-----------|------------|-------------|
| HS256 | 5 | HMAC with SHA-256 |
| HS384 | 6 | HMAC with SHA-384 |
| HS512 | 7 | HMAC with SHA-512 |
| HS256/64 | 4 | HMAC with SHA-256 truncated to 64 bits |
#### The HMAC Key
[RFC 9053, section 3.1](https://www.rfc-editor.org/rfc/rfc9053#section-3.1) requires implementations "creating and
validating MAC values" to validate the key type, the key length and the algorithm. The key value `k` is a `bstr`
(section 7.3), so `hash()` and `verify()` reject — with an `InvalidArgumentException` — a key that is not symmetric,
or whose `k` is missing, is not a PHP string, or is empty. A decoded CBOR object has to be normalized to its value
first: a `CBOR\ByteStringObject` is not a byte string.
A key shorter than the output of the underlying hash function (32 bytes for HS256 and HS256/64, 48 for HS384, 64 for
HS512) is "strongly discouraged" by [RFC 2104, section 3](https://www.rfc-editor.org/rfc/rfc2104#section-3) but stays
accepted, because deployments do key HS384 and HS512 with 32 bytes. It emits an `E_USER_WARNING` unless you
acknowledge it:
```php
use Cose\Algorithm\Mac\HS512;
$algorithm = HS512::create(acknowledgeShortKey: true);
```
As of the next major version, omitting that acknowledgement will throw an exception instead of warning.
To fail hard on a short key today, validate it before handing it to the algorithm:
```php
use Cose\Algorithm\Mac\HS256;
use Cose\Key\SymmetricKey;
use Cose\Key\SymmetricKeyValidator;
$algorithm = HS256::create();
$key = SymmetricKey::create($data);
// Throws an InvalidArgumentException when the key is shorter than 32 bytes
SymmetricKeyValidator::create($algorithm->minimumKeyLength())->check($key);
// …or ask without the exception
if (! SymmetricKeyValidator::create()->isValid($key)) {
// reject the key
}
```
## Signature Verification Contract
`Cose\Algorithm\Signature\Signature::verify()` is total for every condition the governing specifications define as an
"invalid signature" outcome. A malformed, truncated, over-long or out-of-range signature, and key material that the
crypto layer cannot decode — a point that is not on the named curve, a public key that is not a valid group element —
all return `false`. No PHP warning is raised on the way.
It throws an `InvalidArgumentException` in one case only: the key cannot be used with the algorithm at all, i.e. its
key type or its curve does not match. Structurally invalid key components — an empty or zero RSA modulus, an `x`, `y`
or `d` whose length does not fit the curve — are rejected earlier, by the `Key` constructors, so the exception is
raised when the key is first seen rather than at every verification.
```php
use Cose\Key\Key;
use InvalidArgumentException;
try {
// Throws only when $key is an RSA key, an EC key on another curve, …
$key = Key::createFromData($credentialPublicKey);
} catch (InvalidArgumentException $e) {
// The credential cannot be used with this algorithm: reject it at registration.
}
// From here on, verification is a plain boolean, whatever the client sent.
$isValid = $algorithm->verify($data, $key, $signature);
```
`sign()` throws an `InvalidArgumentException` when the key is public, when the crypto layer cannot load it, or when the
signature operation itself fails, for instance for an RSA modulus too short for the digest.
## Key Parameter Forms
RFC 9052 and RFC 9053 type `kty` and `crv` as `tstr / int`, so the same key reaches this library under several
shapes. The `Key` classes settle them all at construction time:
- a key type or a curve given as the numeric string spomky-labs/cbor-php produces when it decodes a CBOR integer
(`'2'`, `'-1'`) is stored as the integer it denotes, so `Key::type()` always compares equal to `Key::TYPE_EC2` and
friends, whether the key was decoded from CBOR or built by hand;
- a key type may also be given by name: `EC`, `OKP`, `RSA` or `oct`;
- a curve may be given by name — `P-256`, `P-384`, `P-521`, `secp256k1`, `brainpoolP256r1` and so on. `curve()`
returns the form the key carries, and `Ec2Key::curveId()` / `OkpKey::curveId()` return the value of the IANA
[COSE Elliptic Curves](https://www.iana.org/assignments/cose/cose.xhtml#elliptic-curves) registry whatever that
form is. The algorithm classes compare the latter, so a key that names its curve signs and verifies exactly like
the same key that numbers it.
```php
use Cose\Key\Ec2Key;
$key = Ec2Key::create([
Ec2Key::TYPE => Ec2Key::TYPE_EC2,
Ec2Key::DATA_CURVE => Ec2Key::CURVE_NAME_SECP256K1, // or Ec2Key::CURVE_P256K
Ec2Key::DATA_X => $x,
Ec2Key::DATA_Y => $y,
]);
$key->curve(); // 'secp256k1', as supplied
$key->curveId(); // 8, the registry value
```
Curve 8 is named `secp256k1` by [RFC 8812, section 4.2](https://datatracker.ietf.org/doc/html/rfc8812#section-4.2).
`Ec2Key::CURVE_NAME_P256K` (`'P-256K'`), the spelling of a draft that was renamed before its first revision, is
deprecated but still accepted.
Anything else — a float, a numeric string that is not an integer, a name no registry defines, an `x` that is not a
byte string — is refused by the constructor with an `InvalidArgumentException`, before any of it is used.
## Validating RSA Keys
The RSA algorithms reject, on their own, any key whose public parameters are not those
[RFC 8017, section 3.1](https://datatracker.ietf.org/doc/html/rfc8017#section-3.1) defines: an odd modulus and a
public exponent that is an odd integer between 3 and `n - 1`. `sign()` throws and `verify()` returns `false` for
such a key; nothing has to be done to get that behaviour.
The modulus length is a different matter. [RFC 8812](https://datatracker.ietf.org/doc/html/rfc8812) defers to
[RFC 8230, section 6.1](https://www.rfc-editor.org/rfc/rfc8230#section-6.1), which requires a modulus of 2048 bits or
larger and expects implementations to handle up to 16K bits.
Both bounds are applied automatically, before the algorithm computes anything with the key.
The **upper** bounds are not negotiable: every RSA algorithm rejects a key whose modulus is longer than 16384 bits or
whose public exponent is longer than 256 bits. `verify()` returns `false` for such a key and `sign()` throws.
The **minimum** modulus length is applied too, with `RsaKeyValidator::create()`, so that nothing has to be done to
get the bound RFC 8230 requires. Because legacy authenticators holding 1024 bit keys still exist, a key below it only
emits an `E_USER_WARNING` for now:
```php
use Cose\Algorithm\Signature\RSA\RS256;
// Warns: "The RSA key does not satisfy RFC 8230 section 6.1: The modulus of the key is 1024 bits long; …"
// The signature is still verified, so no deployment breaks on upgrade.
$isValid = RS256::create()->verify($data, $weakKey, $signature);
```
As of the next major version, that warning becomes an `InvalidArgumentException` on `sign()` and a `false` on
`verify()`.
To keep accepting weaker keys, hand the algorithm a validator carrying the bound you actually accept. Writing the
bound down is the acknowledgement: a key below *it* is still refused, right away and with an exception, because you
chose that bound.
```php
use Cose\Algorithm\Signature\RSA\RS256;
use Cose\Key\RsaKeyValidator;
// 1024 bit keys accepted silently; 512 bit ones still rejected
$algorithm = RS256::create(RsaKeyValidator::create(minimumModulusLength: 1024));
// The other way round: a stricter policy than the RFC, enforced now rather than in the next major version
$algorithm = RS256::create(RsaKeyValidator::create(minimumModulusLength: 3072, maximumModulusLength: 8192));
```
Every RSA algorithm takes it: `RS256`, `RS384`, `RS512`, `PS256`, `PS384` and `PS512` as their only argument, `RS1`
after its `acknowledgeInsecureAlgorithm` flag — `RS1::create(true, RsaKeyValidator::create(minimumModulusLength: 1024))`.
The validator can also be run on its own, on a key you are about to store:
```php
use Cose\Key\RsaKey;
use Cose\Key\RsaKeyValidator;
$key = RsaKey::create($data);
// Throws an InvalidArgumentException when the key does not comply
RsaKeyValidator::create()->check($key);
// …or ask without the exception
if (! RsaKeyValidator::create()->isValid($key)) {
// reject the key
}
```
`check()` and `isValid()` also cover the public parameter constraints described above. They are available on their
own, without any modulus length policy:
```php
// Throws an InvalidArgumentException unless the modulus is odd and 3 <= e < n
RsaKeyValidator::checkPublicParameters($key);
```
## Verifying a Signature Made by a Certificate
WebAuthn Level 3 §8.2 to §8.4 ask a relying party to verify a packed (`x5c`), TPM or android-key attestation statement
"with the algorithm specified in `alg`", against the key of the attestation certificate. Going through
`Algorithms::getOpensslAlgorithmFor()` and `openssl_verify()` only reaches the algorithms an `OPENSSL_ALGO_*` digest
can describe — ECDSA and RSASSA-PKCS1-v1_5 — because that digest implies PKCS #1 v1.5 padding; RSASSA-PSS, EdDSA,
Ed25519 and Ed448 cannot be expressed that way at all.
`Cose\Algorithm\Signature\CertificateSignatureVerifier` takes the other route: the key of the certificate becomes a
`Cose\Key\Key`, and the `Signature` class registered for the identifier verifies with it.
```php
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\CertificateSignatureVerifier;
use Cose\Algorithm\Signature\ECDSA\ES256;
use Cose\Algorithm\Signature\RSA\PS256;
$manager = Manager::create()->add(ES256::create(), PS256::create());
$verifier = CertificateSignatureVerifier::create($manager);
$isValid = $verifier->verify($alg, $certificatePem, $data, $signature);
```
The set of acceptable algorithms is the `Manager` the operator built, not a constant of this library: an `alg` that
comes from the wire cannot select a verifier that was never registered. Nothing is configured twice either — it is the
registered instance that verifies, so the minimum modulus length an RSA algorithm was created with applies unchanged to
the key of the certificate.
`verify()` returns `false` for every signature the algorithm rejects, and throws an `InvalidArgumentException` when the
certificate cannot be read, when no signature algorithm is registered for the identifier, or when the key of the
certificate cannot be used with that algorithm.
The key alone is enough when the certificate is not at hand — `verifySubjectPublicKeyInfo()` takes a
SubjectPublicKeyInfo, and `Cose\Key\PublicKeyLoader` exposes the conversion on its own. Both accept PEM or DER.
```php
use Cose\Key\PublicKeyLoader;
$key = PublicKeyLoader::fromCertificate($certificatePem);
$key = PublicKeyLoader::fromSubjectPublicKeyInfo($spkiPem);
```
## Registering Algorithms
`Cose\Algorithm\Manager` registers each algorithm under the identifier it declares, and
`Cose\Algorithm\ManagerFactory` registers algorithms under aliases so that a `Manager` can be generated from a
subset of them.
A later registration for an identifier (or an alias) that is already taken replaces the earlier one. When the
replacement is an instance of **another** class, that is a misconfiguration rather than an intent — `list()` keeps
reporting a single entry, and which verifier answers for the identifier is decided by registration order alone — so an
`E_USER_WARNING` is emitted. Registering the same class twice stays silent, so a container that autoconfigures an
algorithm more than once keeps working.
As of the next major version, a duplicate bound to a different class will throw an `InvalidArgumentException`, and an
explicit `replace()` will be the way to override a registration on purpose.
## Performance
**ext-gmp** (recommended) or **ext-bcmath** is worth installing, but no longer required for RSA verification to be
cheap: `RsaKey::asPem()`, `RsaKeyValidator` and the public operation of every RSA algorithm are computed without
`brick/math`. Signing with RSASSA-PSS (`PS256`, `PS384`, `PS512`) still uses it for the blinding of the private
exponentiation, and falls back to a pure PHP calculator when neither extension is loaded — which is the configuration
of the stock `php` and `php-fpm` Docker images.
## Testing
Run the test suite in the project QA container (nothing to install):
```bash
castor phpunit
```
Or directly, on a host that provides PHPUnit 11 as `phpunit-11`:
```bash
composer test
```
The library includes comprehensive tests including:
- Unit tests for all COSE tag types
- Integration tests with real cryptographic operations
- COVID-19 certificate verification examples
- Test fixtures with actual certificates
## Requirements
- PHP 8.1 or higher
- ext-json
- ext-openssl
- brick/math
- spomky-labs/pki-framework
Optional, depending on what you use:
- **ext-sodium** — required by every Ed25519 algorithm (`EdDSA` -8, `Ed25519` -8 and -19, `Ed256` -260, `Ed512` -261)
and to recompute an OKP public key from its private key. Sodium ships with PHP and is enabled by default, but a
build can leave it out: creating one of these algorithms then throws a `RuntimeException` instead of reporting
valid signatures as invalid. Call `EdDSA::isSupported()` when the platform is not known in advance.
- **spomky-labs/cbor-php** `^3.3.4` — required by the COSE tag classes (Sign, Encrypt, Mac). Versions below 3.3.4 are
rejected by a `conflict` entry, because that decoder is what enforces the RFC 9052 header-map rules.
- **ext-gmp** or **ext-bcmath** — see [Performance](#performance).
## Contributing
Contributions are welcome! Please see [CONTRIBUTING.md](.github/CONTRIBUTING.md) for details.
For security vulnerabilities, do not open an issue: report them privately through GitHub private vulnerability
reporting or by e-mail to **security [at] spomky-labs.com**. See [SECURITY.md](SECURITY.md).
## Support
I bring solutions to your problems and answer your questions.
If you really love this project and the work I have done, or if you want me to prioritize your issues, you can support me:
- [Become a sponsor on GitHub](https://github.com/sponsors/Spomky)
- [Become a Patreon](https://www.patreon.com/FlorentMorselli)
## License
This software is released under the [MIT License](LICENSE).
## Credits
Maintained by [Florent Morselli](https://github.com/Spomky) and [contributors](https://github.com/web-auth/cose-lib/contributors).
---
Made with ❤️ for the PHP community

57
vendor/web-auth/cose-lib/RELEASES.md vendored Normal file
View file

@ -0,0 +1,57 @@
# Versioning and Release
This document describes the versioning and release process of the COSE Library for PHP.
This document is a living document, contents will be updated according to each release.
## Releases
Releases will be versioned using dotted triples, similar to [Semantic Version](http://semver.org/).
For this specific document, we will refer to the respective components of this triple as `<major>.<minor>.<patch>`.
The version number may have additional information, such as "-rc1,-rc2,-rc3" to mark release candidate builds for earlier access.
Such releases will be considered as "pre-releases".
## Minor Release Support Matrix
This matrix is the single source of truth for the branches under support; [SECURITY.md](SECURITY.md) refers to it.
| Version | Supported |
|---------|----------------------------------------|
| 4.8.x | :white_check_mark: (in development) |
| 4.7.x | :white_check_mark: |
| 4.6.x | :white_check_mark: (security fix only) |
| 4.5.x | :white_check_mark: (security fix only) |
| < 4.5.x | :x: |
## Upgrading
### 4.7.x to 4.8.x
**The six COSE message classes are deprecated.** `Cose\Signature\CoseSign1Tag`, `Cose\Signature\CoseSignTag`,
`Cose\Mac\CoseMac0Tag`, `Cose\Mac\CoseMacTag`, `Cose\Encryption\CoseEncrypt0Tag` and `Cose\Encryption\CoseEncryptTag`
raise an `E_USER_DEPRECATED` on construction and are removed in 5.0.0. They were ported into
spomky-labs/cbor-php 3.4.0, as `CBOR\Tag\CoseSign1Tag` and its siblings, which is where a description of a CBOR
structure belongs. The wire format is identical, so a message written by a deprecated class is read by its
replacement and the reverse; the migration is documented in
[doc/Usage.md](doc/Usage.md#upgrading-from-the-cosetag-classes). Two points are not mechanical: the four-argument
`create()` becomes `createFromComponents()`, and the header accessors move to `Cose\Structure\CoseHeaders`.
Their behaviour is otherwise frozen for the whole 4.8.x line: a deprecation is not the place to change what a class
accepts.
**The cbor-php floor moves to 3.4.0** (`conflict: <3.4.0`), so the classes the deprecation points at are guaranteed
to be installable.
**New: the RFC 9052 rules that sit above the CBOR shape.** These are what stays in this library after 5.0.0, and they
work on the upstream message classes:
- `Cose\Structure\CoseHeaders` reads the two header buckets of any COSE message. A label is an integer *or* a text
string (§1.5) and the two never answer for each other, even though cbor-php normalizes them to the same map offset;
the zero-length protected header is accepted (§3) and trailing bytes inside the protected bucket are not; the
protected value wins a combined lookup.
- `Cose\Signature\CoseSignature` and `Cose\Structure\CoseRecipient` are the checked views over the `signatures` and
`recipients` lists, applying the `[+ ...]` rule of §§4.1 and 5.1, nested recipients included.
- `Cose\Structure\HeaderMapHelper` holds the same rules as static functions, including `encodeProtected()` (which
emits the `h''` §3 prefers for an empty map) and `assertTagNumber()`.
- The cryptographic structures are complete: `Signature` (§4.4, with `sign_protected`), `Mac0Structure` and
`MacStructure` (§6.3), `Encrypt0Structure`, `EncryptStructure` and `RecipientStructure` (§5.3) join `Signature1`,
which gained the optional `external_aad` every structure now takes.

16
vendor/web-auth/cose-lib/SECURITY.md vendored Normal file
View file

@ -0,0 +1,16 @@
# Security Policy
## Supported Versions
The maintained branches and what each one receives are listed in a single place, [RELEASES.md](RELEASES.md#minor-release-support-matrix),
so that this file cannot drift away from it.
## Reporting a Vulnerability
If you think you have found a security issue, **do not open a public issue**. Report it privately, either way:
- through GitHub private vulnerability reporting, from the [Security tab](https://github.com/web-auth/cose-lib/security/advisories/new) of this repository, or
- by e-mail to **security [at] spomky-labs.com**.
Please include the affected version, a description of the issue and, when possible, a reproduction script. You will
get an acknowledgement of the report, and a fix will be prepared privately before any public disclosure.

53
vendor/web-auth/cose-lib/composer.json vendored Normal file
View file

@ -0,0 +1,53 @@
{
"name": "web-auth/cose-lib",
"description": "CBOR Object Signing and Encryption (COSE) For PHP",
"license": "MIT",
"type": "library",
"keywords": [
"COSE",
"RFC8152"
],
"authors": [
{
"name": "Florent Morselli",
"homepage": "https://github.com/Spomky"
},
{
"name": "All contributors",
"homepage": "https://github.com/web-auth/cose/contributors"
}
],
"homepage": "https://github.com/web-auth",
"require": {
"php": ">=8.1",
"ext-json": "*",
"ext-openssl": "*",
"brick/math": "^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13 || ^0.14 || ^0.15 || ^0.16 || ^0.17 || ^0.18 || ^0.19 || ^0.20 || ^1.0",
"spomky-labs/pki-framework": "^1.0"
},
"require-dev": {
"spomky-labs/cbor-php": "^3.4"
},
"conflict": {
"spomky-labs/cbor-php": "<3.4.0"
},
"suggest": {
"ext-bcmath": "Recommended: without GMP or BCMath, signing with RSASSA-PSS (PS256/PS384/PS512) blinds its private exponentiation in pure PHP",
"ext-gmp": "Recommended: without GMP or BCMath, signing with RSASSA-PSS (PS256/PS384/PS512) blinds its private exponentiation in pure PHP",
"ext-sodium": "Required by the EdDSA/Ed25519 signature algorithms (-8, -19, -260, -261) and to recompute an OKP public key from its private key",
"spomky-labs/cbor-php": "Required by the RFC 9052 header reader and cryptographic structures. 3.4.0 or later: it ships the six COSE message classes (CBOR\\Tag\\CoseSign1Tag and its siblings) that replace the deprecated Cose\\...Tag classes, and its decoder is what enforces the RFC 9052 label uniqueness and nesting bounds this library relies on"
},
"autoload": {
"psr-4": {
"Cose\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Cose\\Tests\\": "tests/"
}
},
"scripts": {
"test": "@composer exec -- phpunit-11 --configuration .ci-tools/phpunit.xml.dist"
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
interface Algorithm
{
public static function identifier(): int;
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use Cose\Key\Key;
/**
* An algorithm that can enforce the restrictions a COSE key carries: "alg" (label 3) and "key_ops" (label 4), as
* defined by RFC 9052, section 7.1.
*
* Enforcement is opt-in and off by default, so that a key whose labels contradict the operation keeps behaving as it
* did before this library read them. Turn it on with `withKeyRestrictionsEnforced()`, on a single algorithm or on a
* whole `Manager`, to get the behaviour the RFC requires: the operation is refused with an
* `InvalidArgumentException` naming the restriction the key carries.
*
* @see https://www.rfc-editor.org/rfc/rfc9052.html#section-7.1
* @see Key::assertUsableWith()
*/
interface KeyRestrictionAware extends Algorithm
{
/**
* Returns the same algorithm, enforcing - or no longer enforcing - the restrictions of the keys it is given. The
* algorithm this is called on is left untouched.
*/
public function withKeyRestrictionsEnforced(bool $enforce = true): static;
public function enforcesKeyRestrictions(): bool;
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use Cose\Key\Key;
use InvalidArgumentException;
/**
* The opt-in enforcement of the key restrictions of RFC 9052, section 7.1, shared by every algorithm.
*
* @see KeyRestrictionAware
*
* @phpstan-require-implements KeyRestrictionAware
*/
trait KeyRestrictionEnforcement
{
private bool $enforceKeyRestrictions = false;
public function withKeyRestrictionsEnforced(bool $enforce = true): static
{
$clone = clone $this;
$clone->enforceKeyRestrictions = $enforce;
return $clone;
}
public function enforcesKeyRestrictions(): bool
{
return $this->enforceKeyRestrictions;
}
/**
* @param int $operation one of the `Key::OP_*` constants
*
* @throws InvalidArgumentException when enforcement is on and the key is restricted to another algorithm, or
* does not allow the operation
*/
private function checkKeyRestrictions(Key $key, int $operation): void
{
if (! $this->enforceKeyRestrictions) {
return;
}
// static::identifier() is the identifier of the concrete algorithm, so ES256 and ESP256, or EdDSA (-8) and
// the fully-specified Ed25519 (-19), each enforce their own value.
$key->assertUsableWith(static::identifier(), $operation);
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS256 extends Hmac
{
public const ID = 5;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha256';
}
protected function getSignatureLength(): int
{
return 256;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS256Truncated64 extends Hmac
{
public const ID = 4;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha256';
}
protected function getSignatureLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS384 extends Hmac
{
public const ID = 6;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha384';
}
protected function getSignatureLength(): int
{
return 384;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
final class HS512 extends Hmac
{
public const ID = 7;
public static function create(bool $acknowledgeShortKey = false): self
{
return new self($acknowledgeShortKey);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): string
{
return 'sha512';
}
protected function getSignatureLength(): int
{
return 512;
}
}

View file

@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Key\Key;
use Cose\Key\SymmetricKey;
use const E_USER_WARNING;
use function hash;
use function hash_hmac;
use InvalidArgumentException;
use function is_string;
use function sprintf;
use function strlen;
use function trigger_error;
/**
* HMAC-based Message Authentication Codes (RFC 9053, section 3.1).
*
* RFC 9053, section 3.1 requires that "implementations creating and validating MAC values MUST validate that the key
* type, key length, and algorithm are correct and appropriate for the entities involved", and section 7.3 types the
* key value `k` as a byte string. Accordingly, a key whose `k` is absent, not a PHP string or empty is rejected: none
* of them is ever a legitimate HMAC key, and coercing such a value would silently key the MAC with a constant an
* outsider can guess ("Array", "1", the empty string, …).
*
* The key length is a softer matter. RFC 2104, section 3 states that a key shorter than the output of the hash
* function is "strongly discouraged", and RFC 9053, section 3.1 only makes the hash output size a SHOULD for keys
* that are transported or derived by a recipient algorithm - neither of which this library implements. A shorter key
* is therefore accepted, but it emits an E_USER_WARNING unless the caller explicitly acknowledges the risk by
* creating the algorithm with `acknowledgeShortKey: true`, following the same shape as
* Cose\Algorithm\Signature\RSA\RS1. From v5.0.0 the same call without that acknowledgement will throw an
* InvalidArgumentException instead of warning.
*
* @see https://www.rfc-editor.org/rfc/rfc9053#section-3.1
* @see https://www.rfc-editor.org/rfc/rfc2104#section-3
* @see \Cose\Tests\Algorithm\Mac\HmacTest
*/
abstract class Hmac implements Mac, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public const SHORT_KEY_MESSAGE = 'The HMAC key is %d bytes long, shorter than the %d-byte hash output (RFC 2104, section 3). Create the algorithm with "acknowledgeShortKey: true" to acknowledge it; as of v5.0.0 this will throw.';
public function __construct(
private readonly bool $acknowledgeShortKey = false
) {
}
public function hash(string $data, Key $key): string
{
// RFC 9053, section 3.1: "If the 'key_ops' field is present, it MUST include 'MAC create' when creating an
// HMAC authentication tag."
return $this->compute($data, $this->checKey($key, Key::OP_MAC_CREATE));
}
public function verify(string $data, Key $key, string $signature): bool
{
// ... and it MUST include 'MAC verify' when verifying one, so the two operations cannot share a code path.
return hash_equals($this->compute($data, $this->checKey($key, Key::OP_MAC_VERIFY)), $signature);
}
/**
* The length, in bytes, of the output of the underlying hash function: the shortest key RFC 2104, section 3 does
* not discourage for this algorithm.
*/
public function minimumKeyLength(): int
{
return strlen(hash($this->getHashAlgorithm(), '', true));
}
abstract protected function getHashAlgorithm(): string;
abstract protected function getSignatureLength(): int;
private function compute(string $data, string $k): string
{
$signature = hash_hmac($this->getHashAlgorithm(), $data, $k, true);
return substr($signature, 0, intdiv($this->getSignatureLength(), 8));
}
/**
* @param int $operation the Key::OP_* constant of the operation the key is about to be used for
*
* @throws InvalidArgumentException when the key cannot be used with this algorithm
*/
private function checKey(Key $key, int $operation): string
{
if ($key->type() !== Key::TYPE_OCT && $key->type() !== Key::TYPE_NAME_OCT) {
throw new InvalidArgumentException('Invalid key. Must be of type symmetric');
}
if (! $key->has(SymmetricKey::DATA_K)) {
throw new InvalidArgumentException('Invalid key. The value of the key is missing');
}
$k = $key->get(SymmetricKey::DATA_K);
if (! is_string($k)) {
throw new InvalidArgumentException(
'Invalid key. The value of the key must be a byte string (CBOR objects shall be normalized first)'
);
}
if ($k === '') {
throw new InvalidArgumentException('Invalid key. The value of the key is empty');
}
$minimumKeyLength = $this->minimumKeyLength();
if (strlen($k) < $minimumKeyLength && ! $this->acknowledgeShortKey) {
trigger_error(sprintf(self::SHORT_KEY_MESSAGE, strlen($k), $minimumKeyLength), E_USER_WARNING);
}
$this->checkKeyRestrictions($key, $operation);
return $k;
}
}

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Mac;
use Cose\Algorithm\Algorithm;
use Cose\Key\Key;
use InvalidArgumentException;
interface Mac extends Algorithm
{
/**
* Computes the authentication tag of the data, the "MAC create" operation of RFC 9052, section 7.1, Table 5.
*
* @throws InvalidArgumentException when the key cannot be used with this algorithm (wrong key type, missing key
* value, or - when the algorithm enforces them, see KeyRestrictionAware - an
* "alg" or a "key_ops" that forbids creating a tag with it)
*/
public function hash(string $data, Key $key): string;
/**
* Verifies an authentication tag, the "MAC verify" operation of RFC 9052, section 7.1, Table 5. It is a distinct
* operation from the one above: a key may be allowed to perform one and not the other.
*
* @throws InvalidArgumentException when the key cannot be used with this algorithm, as above
*/
public function verify(string $data, Key $key, string $signature): bool;
}

View file

@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use function array_key_exists;
use const E_USER_WARNING;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* @see \Cose\Tests\Algorithm\ManagerTest
*/
final class Manager
{
/**
* @var array<int, Algorithm>
*/
private array $algorithms = [];
public static function create(): self
{
return new self();
}
/**
* Registers algorithms, each under the identifier it declares.
*
* A later registration for an identifier that is already taken replaces the earlier one. When the replacement is
* an instance of another class, that is a misconfiguration rather than an intent: nothing in the Algorithm
* contract reserves an identifier, list() keeps reporting one entry, and the verifier that ends up answering for
* the identifier is decided by registration order alone - which, for the Symfony bundle, is decided by the
* service container. Such a replacement therefore emits an E_USER_WARNING; as of v5.0.0 it will throw an
* InvalidArgumentException, and an explicit replace() will be the way to override a registration on purpose.
*
* Re-registering the same class stays silent, so that a container that autoconfigures the same algorithm twice
* keeps working.
*/
public function add(Algorithm ...$algorithms): self
{
foreach ($algorithms as $algorithm) {
$identifier = $algorithm::identifier();
$registered = $this->algorithms[$identifier] ?? null;
if ($registered !== null && $registered::class !== $algorithm::class) {
trigger_error(sprintf(
'The algorithm identifier %d is already registered with "%s" and is being replaced by "%s". As of v5.0.0, this will throw an exception.',
$identifier,
$registered::class,
$algorithm::class
), E_USER_WARNING);
}
$this->algorithms[$identifier] = $algorithm;
}
return $this;
}
/**
* @return iterable<int>
*/
public function list(): iterable
{
yield from array_keys($this->algorithms);
}
/**
* @return iterable<int, Algorithm>
*/
public function all(): iterable
{
yield from $this->algorithms;
}
/**
* Returns the same set of algorithms, each enforcing - or no longer enforcing - the "alg" and "key_ops"
* restrictions of the keys it is given, as RFC 9052, section 7.1 requires. Algorithms that cannot enforce them
* are carried over unchanged. This manager is left untouched.
*
* @see KeyRestrictionAware
*/
public function withKeyRestrictionsEnforced(bool $enforce = true): self
{
$manager = self::create();
foreach ($this->algorithms as $algorithm) {
$manager->add(
$algorithm instanceof KeyRestrictionAware
? $algorithm->withKeyRestrictionsEnforced($enforce)
: $algorithm
);
}
return $manager;
}
public function has(int $identifier): bool
{
return array_key_exists($identifier, $this->algorithms);
}
public function get(int $identifier): Algorithm
{
if (! $this->has($identifier)) {
throw new InvalidArgumentException('Unsupported algorithm');
}
return $this->algorithms[$identifier];
}
}

View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm;
use function array_key_exists;
use const E_USER_WARNING;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* @see \Cose\Tests\Algorithm\ManagerFactoryTest
*/
final class ManagerFactory
{
/**
* @var array<string, Algorithm>
*/
private array $algorithms = [];
public static function create(): self
{
return new self();
}
/**
* Registers an algorithm under an alias.
*
* A later registration for an alias that is already taken replaces the earlier one. When the replacement is an
* instance of another class, that is a misconfiguration rather than an intent, so it emits an E_USER_WARNING; as
* of v5.0.0 it will throw an InvalidArgumentException. Re-registering the same class under the same alias stays
* silent.
*
* Two aliases may legitimately point at the same algorithm, but two aliases whose algorithms share an identifier
* collide as soon as generate() is given both: the Manager it builds keeps only one of them, and warns about the
* replacement.
*/
public function add(string $alias, Algorithm $algorithm): self
{
$registered = $this->algorithms[$alias] ?? null;
if ($registered !== null && $registered::class !== $algorithm::class) {
trigger_error(sprintf(
'The alias "%s" is already registered with "%s" and is being replaced by "%s". As of v5.0.0, this will throw an exception.',
$alias,
$registered::class,
$algorithm::class
), E_USER_WARNING);
}
$this->algorithms[$alias] = $algorithm;
return $this;
}
/**
* @return string[]
*/
public function list(): iterable
{
yield from array_keys($this->algorithms);
}
/**
* @return Algorithm[]
*/
public function all(): iterable
{
yield from $this->algorithms;
}
public function generate(string ...$aliases): Manager
{
$manager = Manager::create();
foreach ($aliases as $alias) {
if (! array_key_exists($alias, $this->algorithms)) {
throw new InvalidArgumentException(sprintf('The algorithm with alias "%s" is not supported', $alias));
}
$manager->add($this->algorithms[$alias]);
}
return $manager;
}
}

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature;
use Cose\Algorithm\Manager;
use Cose\Key\Key;
use Cose\Key\PublicKeyLoader;
use InvalidArgumentException;
use function sprintf;
/**
* Verifies a signature made by the public key of an X.509 certificate, with the algorithm a COSE identifier names.
*
* WebAuthn Level 3 sections 8.2 to 8.4 ask a relying party to verify a packed (x5c), TPM or android-key attestation
* statement "with the algorithm specified in alg", against the key of the attestation certificate. The obvious route,
* openssl_verify() with Algorithms::getOpensslAlgorithmFor(), only reaches the algorithms an OPENSSL_ALGO_* digest can
* describe - ECDSA and RSASSA-PKCS1-v1_5 - because that digest implies PKCS #1 v1.5 padding; ES256K is missing from
* the map altogether, and RSASSA-PSS, EdDSA, Ed25519 and Ed448 cannot be expressed by it at all.
*
* This class takes the other route: the certificate's key becomes a Cose\Key\Key and the Signature class registered
* for the identifier verifies with it. Three consequences are worth stating.
*
* First, the set of acceptable algorithms is the Manager the operator built, not a constant of this library: an
* identifier that was never registered is refused, so `alg`, which comes from the wire, cannot select a verifier the
* operator did not choose. RS1 in particular is only reachable when the operator registered an RS1 instance, which
* they can only build by acknowledging what SHA-1 is.
*
* Second, every policy a registered algorithm carries applies unchanged, because it is that very instance which
* verifies: the minimum modulus length an RSA algorithm was created with (RsaKeyPolicy, RFC 8230 section 6.1) is the
* one enforced against the key of the certificate. Nothing here overrides it, and nothing has to be configured twice.
*
* Third, verify() is as total as the Signature contract is: it returns false for every signature the algorithm
* rejects, and throws an InvalidArgumentException when the certificate, the identifier or the key type make the
* verification impossible to even attempt.
*
* @see https://www.w3.org/TR/webauthn-3/#sctn-packed-attestation
* @see \Cose\Tests\Algorithm\Signature\CertificateSignatureVerifierTest
*/
final class CertificateSignatureVerifier
{
private function __construct(
private readonly Manager $manager
) {
}
public static function create(Manager $manager): self
{
return new self($manager);
}
/**
* @param string $certificate a PEM or DER encoded X.509 certificate
*
* @throws InvalidArgumentException when the certificate cannot be read, when no signature algorithm is
* registered for the identifier, or when the key of the certificate cannot be used with that algorithm
*/
public function verify(int $algorithmIdentifier, string $certificate, string $data, string $signature): bool
{
return $this->verifyWithKey(
$algorithmIdentifier,
PublicKeyLoader::fromCertificate($certificate),
$data,
$signature
);
}
/**
* The same verification against a bare SubjectPublicKeyInfo (RFC 5280, section 4.1.2.7), PEM or DER encoded, for
* the callers that already hold the key rather than the certificate carrying it.
*
* @throws InvalidArgumentException see verify()
*/
public function verifySubjectPublicKeyInfo(
int $algorithmIdentifier,
string $subjectPublicKeyInfo,
string $data,
string $signature
): bool {
return $this->verifyWithKey(
$algorithmIdentifier,
PublicKeyLoader::fromSubjectPublicKeyInfo($subjectPublicKeyInfo),
$data,
$signature
);
}
private function verifyWithKey(int $algorithmIdentifier, Key $key, string $data, string $signature): bool
{
$algorithm = $this->manager->get($algorithmIdentifier);
if (! $algorithm instanceof Signature) {
throw new InvalidArgumentException(sprintf(
'The algorithm identifier %d is not registered with a signature algorithm',
$algorithmIdentifier
));
}
return $algorithm->verify($data, $key, $signature);
}
}

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\OpenSslError;
use Cose\Algorithm\Signature\Signature;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use InvalidArgumentException;
use function openssl_pkey_get_private;
use function openssl_pkey_get_public;
use function openssl_sign;
use function openssl_verify;
use function strlen;
use Throwable;
/**
* @see \Cose\Tests\Algorithm\Signature\ECDSA\ECDSATest
*/
abstract class ECDSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
$privateKey = openssl_pkey_get_private($key->asPEM());
if ($privateKey === false) {
throw new InvalidArgumentException('Unable to load the EC private key');
}
OpenSslError::clear();
// openssl_sign() reports failure with a boolean and never throws: an unusable key would otherwise leave
// $signature null and raise a TypeError inside ECSignature::fromAsn1().
if (! openssl_sign($data, $signature, $privateKey, $this->getHashAlgorithm())) {
throw new InvalidArgumentException('Unable to sign the data: ' . OpenSslError::lastMessage());
}
return ECSignature::fromAsn1($signature, $this->getSignaturePartLength());
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
$length = $this->getSignaturePartLength();
// A signature that does not hold exactly the two coordinates of this curve is an invalid signature, not a
// caller error: webauthn-lib hands the bytes of an assertion straight to verify().
if (strlen($signature) !== $length) {
return false;
}
try {
$signature = ECSignature::toAsn1($signature, $length);
} catch (InvalidArgumentException) {
// A well-formed but invalid signature (e.g. R = 0) is a verification failure, not an error.
return false;
}
// The key is loaded before use: openssl_verify() would raise an E_WARNING for key material OpenSSL cannot
// coerce into a public key, e.g. a point that is not on the named curve.
$publicKey = openssl_pkey_get_public($key->toPublic()->asPEM());
if ($publicKey === false) {
return false;
}
return openssl_verify($data, $signature, $publicKey, $this->getHashAlgorithm()) === 1;
}
abstract protected function getCurve(): int;
abstract protected function getHashAlgorithm(): int;
abstract protected function getSignaturePartLength(): int;
private function handleKey(Key $key, int $operation): Ec2Key
{
$this->checkKeyRestrictions($key, $operation);
try {
$key = Ec2Key::create($key->getData());
} catch (InvalidArgumentException $e) {
throw $e;
} catch (Throwable $e) {
// A last resort: key material comes from the wire, and every rejection of it has to reach the caller as
// the exception type this library documents, never as a TypeError or an Error.
throw new InvalidArgumentException('Invalid EC2 key', 0, $e);
}
// RFC 9053 section 7.1 lets a key name its curve instead of numbering it, so the two are compared through
// the registry value rather than through whichever of the two forms the key happens to carry.
if ($key->curveId() !== $this->getCurve()) {
throw new InvalidArgumentException('This key cannot be used with this algorithm');
}
return $key;
}
}

View file

@ -0,0 +1,218 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use function bin2hex;
use function hex2bin;
use function hexdec;
use InvalidArgumentException;
use function is_string;
use function sprintf;
use function str_pad;
use const STR_PAD_LEFT;
use function strlen;
use function substr;
/**
* Converts between the COSE signature format (`I2OSP(R, n) | I2OSP(S, n)`, RFC 9053 §2.1) and the DER structure
* `Ecdsa-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER }` (RFC 3279 §2.2.3) that OpenSSL consumes.
*
* The encoder emits DER as required by X.690 §10.1 and the decoder only accepts DER: every encoding OpenSSL
* refuses (indefinite or non-minimal lengths, negative or non-minimal integers, trailing data) is rejected here.
*
* @internal
*
* @see \Cose\Tests\Algorithm\Signature\ECDSA\ECSignatureTest
*/
final class ECSignature
{
private const ASN1_SEQUENCE = '30';
private const ASN1_INTEGER = '02';
private const ASN1_LENGTH_2BYTES = '81';
private const ASN1_BIG_INTEGER_LIMIT = '7f';
private const ASN1_NEGATIVE_INTEGER = '00';
private const BYTE_SIZE = 2;
public static function toAsn1(string $signature, int $length): string
{
$signature = bin2hex($signature);
if (self::octetLength($signature) !== $length) {
throw new InvalidArgumentException('Invalid signature length.');
}
$pointR = self::preparePositiveInteger(substr($signature, 0, $length));
$pointS = self::preparePositiveInteger(substr($signature, $length));
if ($pointR === '' || $pointS === '') {
// R = 0 or S = 0 is never a valid ECDSA signature (SEC 1 v2 §4.1.4 step 1) and would be encoded
// as an INTEGER without content octets, which X.690 §8.3.1 forbids.
throw new InvalidArgumentException('Invalid signature. R and S must be positive integers.');
}
$lengthR = self::octetLength($pointR);
$lengthS = self::octetLength($pointS);
$totalLength = $lengthR + $lengthS + self::BYTE_SIZE + self::BYTE_SIZE;
$der = hex2bin(
self::ASN1_SEQUENCE . self::encodeAsn1Length($totalLength)
. self::ASN1_INTEGER . self::encodeAsn1Length($lengthR) . $pointR
. self::ASN1_INTEGER . self::encodeAsn1Length($lengthS) . $pointS
);
if (! is_string($der)) {
throw new InvalidArgumentException('Unable to encode the signature.');
}
return $der;
}
public static function fromAsn1(string $signature, int $length): string
{
$message = bin2hex($signature);
$position = 0;
if (self::readAsn1Content($message, $position, self::BYTE_SIZE) !== self::ASN1_SEQUENCE) {
throw new InvalidArgumentException('Invalid data. Should start with a sequence.');
}
$sequenceLength = self::readAsn1Length($message, $position);
if ($sequenceLength * self::BYTE_SIZE !== strlen($message) - $position) {
// X.690 §8.1.3: the length octets cover exactly the contents octets; no trailing data is allowed.
throw new InvalidArgumentException('Invalid data. Sequence length mismatch.');
}
$pointR = self::readAsn1Integer($message, $position, $length);
$pointS = self::readAsn1Integer($message, $position, $length);
$raw = hex2bin(str_pad($pointR, $length, '0', STR_PAD_LEFT) . str_pad($pointS, $length, '0', STR_PAD_LEFT));
if (! is_string($raw)) {
throw new InvalidArgumentException('Unable to decode the signature.');
}
return $raw;
}
private static function octetLength(string $data): int
{
return intdiv(strlen($data), self::BYTE_SIZE);
}
/**
* X.690 §8.1.3.4, §8.1.3.5 and §10.1: short form below 128 octets, minimal long form above. The largest
* `Ecdsa-Sig-Value` contents on the supported curves is 138 octets (P-521), so the `82` form is never needed.
*/
private static function encodeAsn1Length(int $length): string
{
if ($length < 0x80) {
return sprintf('%02x', $length);
}
if ($length <= 0xFF) {
return self::ASN1_LENGTH_2BYTES . sprintf('%02x', $length);
}
throw new InvalidArgumentException('Invalid signature. The length is too large.');
}
private static function preparePositiveInteger(string $data): string
{
if (substr($data, 0, self::BYTE_SIZE) > self::ASN1_BIG_INTEGER_LIMIT) {
return self::ASN1_NEGATIVE_INTEGER . $data;
}
while (
str_starts_with($data, self::ASN1_NEGATIVE_INTEGER)
&& substr($data, 2, self::BYTE_SIZE) <= self::ASN1_BIG_INTEGER_LIMIT
) {
$data = substr($data, 2);
}
return $data;
}
private static function readAsn1Content(string $message, int &$position, int $length): string
{
$content = substr($message, $position, $length);
$position += $length;
return $content;
}
private static function readAsn1Length(string $message, int &$position): int
{
$firstOctet = self::readAsn1Content($message, $position, self::BYTE_SIZE);
if (strlen($firstOctet) !== self::BYTE_SIZE) {
throw new InvalidArgumentException('Invalid data. Truncated length.');
}
$first = (int) hexdec($firstOctet);
if ($first < 0x80) {
// Short form (X.690 §8.1.3.4).
return $first;
}
if ($first === 0x81) {
$secondOctet = self::readAsn1Content($message, $position, self::BYTE_SIZE);
if (strlen($secondOctet) !== self::BYTE_SIZE) {
throw new InvalidArgumentException('Invalid data. Truncated length.');
}
$value = (int) hexdec($secondOctet);
if ($value < 0x80) {
// X.690 §10.1: the length is encoded in the minimum number of octets.
throw new InvalidArgumentException('Invalid data. Non-minimal length encoding.');
}
return $value;
}
// 0x80 is the indefinite form, forbidden in DER (X.690 §8.1.3.6 and §10.1); 0x82 and above are never
// needed for an Ecdsa-Sig-Value on the supported curves.
throw new InvalidArgumentException('Invalid data. Unsupported length encoding.');
}
private static function readAsn1Integer(string $message, int &$position, int $length): string
{
if (self::readAsn1Content($message, $position, self::BYTE_SIZE) !== self::ASN1_INTEGER) {
throw new InvalidArgumentException('Invalid data. Should contain an integer.');
}
$contentLength = self::readAsn1Length($message, $position);
if ($contentLength === 0) {
// X.690 §8.3.1: the contents octets consist of one or more octets.
throw new InvalidArgumentException('Invalid data. Empty integer.');
}
$content = self::readAsn1Content($message, $position, $contentLength * self::BYTE_SIZE);
if (strlen($content) !== $contentLength * self::BYTE_SIZE) {
throw new InvalidArgumentException('Invalid data. Truncated integer.');
}
$first = (int) hexdec(substr($content, 0, self::BYTE_SIZE));
if ($first >= 0x80) {
// X.690 §8.3.3: the contents octets are a two's complement number, so this integer is negative.
throw new InvalidArgumentException('Invalid data. Negative integer.');
}
if ($first === 0) {
if ($contentLength === 1) {
// SEC 1 v2 §4.1.4 step 1: R and S must lie in [1, n-1].
throw new InvalidArgumentException('Invalid signature. R and S must be positive integers.');
}
if ((int) hexdec(substr($content, self::BYTE_SIZE, self::BYTE_SIZE)) < 0x80) {
// X.690 §8.3.2 b): the first nine bits must not all be zero.
throw new InvalidArgumentException('Invalid data. Non-minimal integer.');
}
// Drop the single sign octet the encoding is allowed to carry.
$content = substr($content, self::BYTE_SIZE);
}
if (strlen($content) > $length) {
throw new InvalidArgumentException('Invalid data. The integer is too large for the curve.');
}
return $content;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
final class ES256 extends ECDSA
{
public const ID = -7;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P256;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
final class ES256K extends ECDSA
{
public const ID = -47;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P256K;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
final class ES384 extends ECDSA
{
public const ID = -35;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P384;
}
protected function getSignaturePartLength(): int
{
return 96;
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA512;
final class ES512 extends ECDSA
{
public const ID = -36;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P521;
}
protected function getSignaturePartLength(): int
{
return 132;
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
final class Ed25519 extends EdDSA
{
public const ID = -8;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
}

View file

@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
use Cose\Key\Key;
use const E_USER_WARNING;
use function hash;
use function trigger_error;
/**
* Pure Ed25519 over the SHA-256 digest of the payload.
*
* This construction is defined by no specification. It is neither the EdDSA of RFC 8032, section 5.1 - which signs
* the message itself - nor Ed25519ph of the same section, whose challenge covers a "dom2" prefix this class does not
* add. RFC 9053, section 2.2 is explicit that "for use with COSE, only the pure EdDSA version is used", and RFC 8032,
* section 8.5 warns that prehashing "makes the functions greatly more vulnerable to weaknesses in hash functions
* used. These variants SHOULD NOT be used."
*
* Worse, the identifier it carries is not free: IANA has since assigned -260 to WalnutDSA (RFC 9021, section 6.1), so
* a COSE object signed here is read as WalnutDSA by every conforming implementation, and a genuine WalnutDSA object
* is routed to this class. No WebAuthn authenticator emits -260, so the only deployments this construction can serve
* are those that use it on both ends. The fully-specified EdDSA identifiers are
* {@see \Cose\Algorithm\Signature\FullySpecified\Ed25519} (-19) and
* {@see \Cose\Algorithm\Signature\FullySpecified\Ed448} (-53).
*
* Because of that, creating this algorithm emits an E_USER_WARNING unless the caller explicitly acknowledges what it
* is by passing `acknowledgeNonStandardAlgorithm: true`. From v5.0.0 the same call without that acknowledgement will
* throw an InvalidArgumentException instead of warning, and the identifier will move out of the range IANA
* administers.
*
* @see https://www.rfc-editor.org/rfc/rfc9021#section-6.1
* @see https://www.rfc-editor.org/rfc/rfc8032#section-8.5
* @see \Cose\Tests\Algorithm\Signature\EdDSA\PrehashedEdDSATest
*/
final class Ed256 extends EdDSA
{
public const ID = -260;
public const NON_STANDARD_ALGORITHM_MESSAGE = 'The algorithm Ed256 (-260) signs the SHA-256 digest of the payload with pure Ed25519, a construction no specification defines, and its identifier is assigned by IANA to WalnutDSA. If you know what you are doing, create it with "acknowledgeNonStandardAlgorithm: true"; as of v5.0.0, omitting that acknowledgement will throw an exception.';
public function __construct(bool $acknowledgeNonStandardAlgorithm = false)
{
parent::__construct();
if (! $acknowledgeNonStandardAlgorithm) {
trigger_error(self::NON_STANDARD_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
public static function create(bool $acknowledgeNonStandardAlgorithm = false): self
{
return new self($acknowledgeNonStandardAlgorithm);
}
public static function identifier(): int
{
return self::ID;
}
public function sign(string $data, Key $key): string
{
$hashedData = hash('sha256', $data, true);
return parent::sign($hashedData, $key);
}
public function verify(string $data, Key $key, string $signature): bool
{
$hashedData = hash('sha256', $data, true);
return parent::verify($hashedData, $key, $signature);
}
}

View file

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
use Cose\Key\Key;
use const E_USER_WARNING;
use function hash;
use function trigger_error;
/**
* Pure Ed25519 over the SHA-512 digest of the payload.
*
* Despite its name this is not EdDSA with Curve448, and it rejects an Ed448 key: the signature is computed by
* {@see EdDSA}, whose curve check accepts Ed25519 only. EdDSA with Curve448, RFC 8032 section 5.2, is
* {@see \Cose\Algorithm\Signature\FullySpecified\Ed448} (-53).
*
* The construction is defined by no specification. It is neither the EdDSA of RFC 8032, section 5.1 - which signs the
* message itself - nor Ed25519ph of the same section, whose challenge covers a "dom2" prefix this class does not add.
* RFC 9053, section 2.2 is explicit that "for use with COSE, only the pure EdDSA version is used", and RFC 8032,
* section 8.5 warns that prehashing "makes the functions greatly more vulnerable to weaknesses in hash functions
* used. These variants SHOULD NOT be used."
*
* Worse, the identifier it carries is not free: IANA has since assigned -261 to TurboSHAKE128 (RFC 9861, section 6),
* so a COSE object signed here is read as TurboSHAKE128 by every conforming implementation, and a genuine
* TurboSHAKE128 object is routed to this class. No WebAuthn authenticator emits -261, so the only deployments this
* construction can serve are those that use it on both ends.
*
* Because of that, creating this algorithm emits an E_USER_WARNING unless the caller explicitly acknowledges what it
* is by passing `acknowledgeNonStandardAlgorithm: true`. From v5.0.0 the same call without that acknowledgement will
* throw an InvalidArgumentException instead of warning, and the identifier will move out of the range IANA
* administers.
*
* @see https://www.rfc-editor.org/rfc/rfc9861#section-6
* @see https://www.rfc-editor.org/rfc/rfc8032#section-8.5
* @see \Cose\Tests\Algorithm\Signature\EdDSA\PrehashedEdDSATest
*/
final class Ed512 extends EdDSA
{
public const ID = -261;
public const NON_STANDARD_ALGORITHM_MESSAGE = 'The algorithm Ed512 (-261) signs the SHA-512 digest of the payload with pure Ed25519, a construction no specification defines, and its identifier is assigned by IANA to TurboSHAKE128. If you know what you are doing, create it with "acknowledgeNonStandardAlgorithm: true"; as of v5.0.0, omitting that acknowledgement will throw an exception.';
public function __construct(bool $acknowledgeNonStandardAlgorithm = false)
{
parent::__construct();
if (! $acknowledgeNonStandardAlgorithm) {
trigger_error(self::NON_STANDARD_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
public static function create(bool $acknowledgeNonStandardAlgorithm = false): self
{
return new self($acknowledgeNonStandardAlgorithm);
}
public static function identifier(): int
{
return self::ID;
}
public function sign(string $data, Key $key): string
{
$hashedData = hash('sha512', $data, true);
return parent::sign($hashedData, $key);
}
public function verify(string $data, Key $key, string $signature): bool
{
$hashedData = hash('sha512', $data, true);
return parent::verify($hashedData, $key, $signature);
}
}

View file

@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\EdDSA;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\Signature;
use Cose\Algorithms;
use Cose\Key\Key;
use Cose\Key\OkpKey;
use function extension_loaded;
use function hash_equals;
use InvalidArgumentException;
use RuntimeException;
use function sodium_crypto_sign_detached;
use function sodium_crypto_sign_publickey;
use function sodium_crypto_sign_secretkey;
use function sodium_crypto_sign_seed_keypair;
use function sodium_crypto_sign_verify_detached;
use function sodium_memzero;
use SodiumException;
use Throwable;
/**
* @see \Cose\Tests\Algorithm\Signature\EdDSA\EdDSATest
*/
class EdDSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public function __construct()
{
if (! self::isSupported()) {
throw new RuntimeException(
'The EdDSA algorithms require the Sodium extension, which is not loaded.'
);
}
}
/**
* Ed25519 is computed with the sodium extension. It ships with PHP and is enabled by default, but a build can
* leave it out; the algorithm is then unusable, and verify() would report every signature as invalid instead of
* saying why, because it turns any error into a verification outcome. Availability is therefore settled once,
* when the algorithm is instantiated.
*/
public static function isSupported(): bool
{
return extension_loaded('sodium');
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
if ($key->curveId() !== OkpKey::CURVE_ED25519) {
throw new InvalidArgumentException('Unsupported curve');
}
// RFC 8032 section 5.1.5 defines the public key A as a function of the private seed, and section 5.1.6 puts
// that very A into the challenge k = SHA-512(R || A || M). Sodium uses the public half of the secret key
// verbatim, so handing it a caller-supplied "x" would let two signatures of the same message under two
// different halves share their nonce R and disclose the private scalar. A is therefore always re-derived
// from "d" here, and a stored "x" is only ever compared against it.
$keyPair = sodium_crypto_sign_seed_keypair($key->d());
$secret = sodium_crypto_sign_secretkey($keyPair);
$public = sodium_crypto_sign_publickey($keyPair);
sodium_memzero($keyPair);
$x = $key->has(OkpKey::DATA_X) ? $key->x() : null;
if ($x !== null && ! hash_equals($public, $x)) {
sodium_memzero($secret);
throw new InvalidArgumentException(
'Invalid key: the public key "x" does not correspond to the private key "d".'
);
}
try {
return sodium_crypto_sign_detached($data, $secret);
} finally {
sodium_memzero($secret);
}
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
if ($key->curveId() !== OkpKey::CURVE_ED25519) {
throw new InvalidArgumentException('Unsupported curve');
}
// Sodium reports a signature or a public key whose size is not the one Ed25519 defines with a
// SodiumException; that is an invalid signature, not an error. Anything else — a missing extension above
// all — is a platform fault and must not be reported as a verification outcome.
try {
return sodium_crypto_sign_verify_detached($signature, $data, $key->x());
} catch (SodiumException) {
return false;
}
}
public static function identifier(): int
{
return Algorithms::COSE_ALGORITHM_EDDSA;
}
private function handleKey(Key $key, int $operation): OkpKey
{
$this->checkKeyRestrictions($key, $operation);
try {
return OkpKey::create($key->getData());
} catch (InvalidArgumentException $e) {
throw $e;
} catch (Throwable $e) {
// A last resort: key material comes from the wire, and every rejection of it has to reach the caller as
// the exception type this library documents, never as a TypeError or an Error.
throw new InvalidArgumentException('Invalid OKP key', 0, $e);
}
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
/**
* ECDSA using the brainpoolP256r1 curve and SHA-256.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB256 extends ECDSA
{
public const ID = -265;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP256;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
/**
* ECDSA using the brainpoolP320r1 curve and SHA-384.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB320 extends ECDSA
{
public const ID = -266;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP320;
}
protected function getSignaturePartLength(): int
{
return 80;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
/**
* ECDSA using the brainpoolP384r1 curve and SHA-384.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB384 extends ECDSA
{
public const ID = -267;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP384;
}
protected function getSignaturePartLength(): int
{
return 96;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA512;
/**
* ECDSA using the brainpoolP512r1 curve and SHA-512.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESB512 extends ECDSA
{
public const ID = -268;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_BP512;
}
protected function getSignaturePartLength(): int
{
return 128;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA256;
/**
* ECDSA using the P-256 curve and SHA-256.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESP256 extends ECDSA
{
public const ID = -9;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P256;
}
protected function getSignaturePartLength(): int
{
return 64;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA384;
/**
* ECDSA using the P-384 curve and SHA-384.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESP384 extends ECDSA
{
public const ID = -51;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P384;
}
protected function getSignaturePartLength(): int
{
return 96;
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\ECDSA\ECDSA;
use Cose\Key\Ec2Key;
use const OPENSSL_ALGO_SHA512;
/**
* ECDSA using the P-521 curve and SHA-512.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.1
*/
final class ESP512 extends ECDSA
{
public const ID = -52;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
protected function getCurve(): int
{
return Ec2Key::CURVE_P521;
}
protected function getSignaturePartLength(): int
{
return 132;
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\Signature\EdDSA\EdDSA;
/**
* EdDSA using the Ed25519 parameter set of RFC 8032, section 5.1.
*
* This is the fully-specified counterpart of the polymorphic EdDSA identifier (-8). The cryptography is identical;
* only the algorithm identifier differs.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.2
*/
final class Ed25519 extends EdDSA
{
public const ID = -19;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
}

View file

@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\FullySpecified;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\OpenSslError;
use Cose\Algorithm\Signature\Signature;
use Cose\Key\Key;
use Cose\Key\OkpKey;
use InvalidArgumentException;
use function openssl_pkey_get_private;
use function openssl_pkey_get_public;
use function openssl_sign;
use function openssl_verify;
use const PHP_VERSION_ID;
use RuntimeException;
use Throwable;
/**
* EdDSA using the Ed448 parameter set of RFC 8032, section 5.2.
*
* Unlike Ed25519, Ed448 is not covered by the sodium extension; it is computed through OpenSSL, which PHP only wires
* up for Edwards curves as of PHP 8.4. Call `isSupported()` before use when the platform is not known in advance.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html#section-2.2
*/
final class Ed448 implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
public const ID = -53;
/**
* EdDSA is a one-shot signature scheme: the message is not hashed beforehand, which OpenSSL expects to be
* expressed by an empty digest algorithm.
*/
private const NO_DIGEST = 0;
public static function create(): self
{
return new self();
}
public static function identifier(): int
{
return self::ID;
}
/**
* Ed448 requires PHP 8.4 or later: earlier versions reject the digest-less signature OpenSSL needs for Edwards
* curves.
*/
public static function isSupported(): bool
{
return PHP_VERSION_ID >= 80400;
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
$privateKey = openssl_pkey_get_private($key->asPEM());
if ($privateKey === false) {
throw new InvalidArgumentException('Unable to load the Ed448 private key');
}
OpenSslError::clear();
if (! openssl_sign($data, $signature, $privateKey, self::NO_DIGEST)) {
throw new InvalidArgumentException('Unable to sign the data: ' . OpenSslError::lastMessage());
}
return $signature;
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
// RFC 8032 section 5.2.7: a public key that cannot be decoded as a point makes the signature invalid; it is
// a verification outcome, not an error.
$publicKey = openssl_pkey_get_public($key->toPublic()->asPEM());
if ($publicKey === false) {
return false;
}
return openssl_verify($data, $signature, $publicKey, self::NO_DIGEST) === 1;
}
private function handleKey(Key $key, int $operation): OkpKey
{
if (! self::isSupported()) {
throw new RuntimeException(
'The Ed448 algorithm requires PHP 8.4 or later, as earlier versions cannot sign or verify with Edwards curves through OpenSSL.'
);
}
$this->checkKeyRestrictions($key, $operation);
try {
$key = OkpKey::create($key->getData());
} catch (InvalidArgumentException $e) {
throw $e;
} catch (Throwable $e) {
// A last resort: key material comes from the wire, and every rejection of it has to reach the caller as
// the exception type this library documents, never as a TypeError or an Error.
throw new InvalidArgumentException('Invalid OKP key', 0, $e);
}
if ($key->curveId() !== OkpKey::CURVE_ED448) {
throw new InvalidArgumentException('This key cannot be used with this algorithm');
}
return $key;
}
}

View file

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature;
use function openssl_error_string;
/**
* Reads the OpenSSL error queue so that a failed signature operation can say why it failed.
*
* @internal
*/
final class OpenSslError
{
/**
* Empties the queue, so that lastMessage() reports the errors of the next operation only. The queue is
* process-wide and is not cleared by successful calls.
*/
public static function clear(): void
{
while (openssl_error_string() !== false) {
// Nothing to do: the call itself pops one entry off the queue.
}
}
/**
* Returns the most recent message of the queue, emptying it.
*/
public static function lastMessage(): string
{
$message = false;
while (($entry = openssl_error_string()) !== false) {
$message = $entry;
}
return $message === false ? 'unknown OpenSSL error' : $message;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Hash;
use Cose\Key\RsaKeyValidator;
final class PS256 extends PSSRSA
{
public const ID = -37;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): Hash
{
return Hash::sha256();
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Hash;
use Cose\Key\RsaKeyValidator;
final class PS384 extends PSSRSA
{
public const ID = -38;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): Hash
{
return Hash::sha384();
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Hash;
use Cose\Key\RsaKeyValidator;
final class PS512 extends PSSRSA
{
public const ID = -39;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): Hash
{
return Hash::sha512();
}
}

View file

@ -0,0 +1,538 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Brick\Math\Exception\MathException;
use function chr;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\Signature;
use Cose\BigInteger;
use Cose\Hash;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use Cose\Key\RsaKeyValidator;
use function hash_equals;
use function intdiv;
use InvalidArgumentException;
use function is_string;
use function ltrim;
use function openssl_error_string;
use const OPENSSL_NO_PADDING;
use function openssl_pkey_get_public;
use function openssl_private_encrypt;
use function openssl_public_decrypt;
use function ord;
use function pack;
use function random_bytes;
use RuntimeException;
use function str_pad;
use const STR_PAD_LEFT;
use function str_repeat;
use function strcmp;
use function strlen;
use function substr;
use Throwable;
/**
* RSASSA-PSS as defined by RFC 8017, section 8.1.
*
* The length of the key is bounded before it is used. RFC 8017, section 3.1 places no upper bound on the modulus nor
* on the public exponent, and the primitives of section 5.2 are modular exponentiations whose cost is proportional to
* the size of both - which a verifier takes from whoever produced the message. RFC 8230, section 6.1 asks for the
* bound: "It is highly recommended that checks on the key length be done before starting a cryptographic operation."
* The same section requires "a key size of 2048 bits or larger": that bound is applied by RsaKeyPolicy, with the
* validator this algorithm was created with or, by default, with RsaKeyValidator::create().
*
* @see https://www.rfc-editor.org/rfc/rfc8017#section-8.1
* @see https://www.rfc-editor.org/rfc/rfc8230#section-6.1
*
* @internal
*/
abstract class PSSRSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
use RsaKeyPolicy;
public function __construct(?RsaKeyValidator $keyValidator = null)
{
$this->initializeKeyValidator($keyValidator);
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
$this->checkKeyPolicy($key);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
// RFC 8017, section 3.1: modBits is the length in bits of the modulus and k its length in octets. Both are
// derived from the integer value of n, not from the number of octets used to encode it.
$modBits = RsaKeyValidator::modulusLength($key);
$k = intdiv($modBits + 7, 8);
// RFC 8017, section 8.1.1, steps 1 and 2.
$em = $this->encodeEMSAPSS($data, $modBits - 1, $this->getHashAlgorithm());
$signature = $this->rsasp1($key, BigInteger::createFromBinaryString($em));
return $this->convertIntegerToOctetString($signature, $k);
}
public function verify(string $data, Key $key, string $signature): bool
{
// RFC 8017, section 8.1.2: the verification operation uses the public key (n, e) only.
$key = $this->handleKey($key, Key::OP_VERIFY)
->toPublic();
try {
// Section 8.1.2 applies RSAVP1 under the assumption that the public key is valid (section 3.1). Nothing
// downstream re-establishes it, and with e = 1 the exponentiation below is the identity map: the EMSA-PSS
// encoding of any message, which anyone can build, would then be accepted as its signature. Section 3.1
// bounds neither parameter either, and the cost of the exponentiation grows with the size of both. A key
// that cannot be verified with, or that is too large to compute with, is reported as an invalid
// signature, per the contract of Signature::verify().
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
// A key below the bound the caller asked for is a key it declared it does not verify with, which is an
// invalid signature rather than an error here too. The implicit default only warns.
$this->checkKeyPolicy($key);
} catch (InvalidArgumentException) {
return false;
}
$modBits = RsaKeyValidator::modulusLength($key);
$k = intdiv($modBits + 7, 8);
// RFC 8017, section 8.1.2, step 1: "If the length of the signature S is not k octets, output 'invalid
// signature' and stop."
if (strlen($signature) !== $k) {
return false;
}
// Step 2.b: "If RSAVP1 output 'signature representative out of range', output 'invalid signature' and stop."
if (self::compareMagnitudes($signature, $key->n()) >= 0) {
return false;
}
$em = $this->rsavp1WithOpenSSL($key, $signature);
if ($em === null) {
return false;
}
// RFC 8017, section 8.1.2, step 2.c: emLen = ceil((modBits - 1) / 8). "If I2OSP outputs 'integer too large',
// output 'invalid signature' and stop." OpenSSL returns k octets, one more than emLen when the modulus is
// byte aligned, and the octets it drops have to be zero for the integer to fit.
$emLen = intdiv($modBits - 1 + 7, 8);
if ($emLen < $k) {
if (ltrim(substr($em, 0, $k - $emLen), "\0") !== '') {
return false;
}
$em = substr($em, $k - $emLen);
}
return $this->verifyEMSAPSS($data, $em, $modBits - 1, $this->getHashAlgorithm());
}
/**
* Exponentiate with or without Chinese Remainder Theorem. Operation with primes 'p' and 'q' is appox. 2x faster.
*
* The operation is selected from the key: RSASP1 (RFC 8017, section 5.2.1) for a private key, RSAVP1 (section
* 5.2.2) for a public one.
*
* @throws InvalidArgumentException when the public parameters of the key are not those of a valid RSA key, or
* when it is rejected by the validator this algorithm was created with
*/
public function exponentiate(RsaKey $key, BigInteger $c): BigInteger
{
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
$this->checkKeyPolicy($key);
return $key->isPrivate() ? $this->rsasp1($key, $c) : $this->rsavp1($key, $c);
}
abstract protected function getHashAlgorithm(): Hash;
private function handleKey(Key $key, int $operation): RsaKey
{
$this->checkKeyRestrictions($key, $operation);
return RsaKey::create($key->getData());
}
/**
* RSAVP1 (RFC 8017, section 5.2.2).
*
* Only exponentiate() reaches this method: verify() applies the primitive to the octet strings themselves. The
* in-process exponentiation is kept here as a fallback so that a key OpenSSL declines still gets an answer, which
* is the behaviour this method has always had.
*/
private function rsavp1(RsaKey $key, BigInteger $s): BigInteger
{
$n = BigInteger::createFromBinaryString($key->n());
if ($s->compare(BigInteger::createFromDecimal(0)) < 0 || $s->compare($n) >= 0) {
throw new RuntimeException('Signature representative out of range');
}
$k = intdiv(RsaKeyValidator::modulusLength($key) + 7, 8);
$m = $this->rsavp1WithOpenSSL($key, $this->convertIntegerToOctetString($s, $k));
return $m === null
? $s->modPow(BigInteger::createFromBinaryString($key->e()), $n)
: BigInteger::createFromBinaryString($m);
}
/**
* RSAVP1 computed by OpenSSL, on the octet strings themselves.
*
* The public operation is a modular exponentiation, and brick/math computes it in PHP whenever neither ext-gmp
* nor ext-bcmath is loaded - the configuration of the stock php and php-fpm images. That costs seconds of CPU per
* verification even for a 2048 bit key, and grows with the square of the modulus up to the largest one RFC 8230
* asks implementations to accept: a verifier takes its key from whoever produced the message, so the work it is
* asked to do must not depend on an extension being installed. ext-openssl is a hard requirement of this package,
* and RSASP1 already goes through it.
*
* Returns null when OpenSSL will not use the key, which for a verifier is an invalid signature: RFC 8017, section
* 8.1.2 is defined for a valid public key, and a key OpenSSL rejects is not one.
*
* @param string $s the signature representative, exactly k octets long and below the modulus
*/
private function rsavp1WithOpenSSL(RsaKey $key, string $s): ?string
{
try {
// The key is loaded before use so that key material OpenSSL cannot decode yields null instead of an
// E_WARNING raised from inside openssl_public_decrypt().
$publicKey = openssl_pkey_get_public($key->toPublic()->asPem());
if ($publicKey === false) {
$this->clearOpenSSLErrors();
return null;
}
$computed = openssl_public_decrypt($s, $m, $publicKey, OPENSSL_NO_PADDING);
} catch (Throwable) {
$this->clearOpenSSLErrors();
return null;
}
if (! $computed || ! is_string($m)) {
$this->clearOpenSSLErrors();
return null;
}
return $m;
}
/**
* Compares two non-negative integers given as big-endian octet strings: the longer one, once the leading zero
* octets are gone, is the larger, and equal lengths are decided octet by octet. Comparing the values rather than
* the strings would mean converting them, which is the very base conversion this class avoids.
*/
private static function compareMagnitudes(string $left, string $right): int
{
$left = ltrim($left, "\0");
$right = ltrim($right, "\0");
$byLength = strlen($left) <=> strlen($right);
return $byLength === 0 ? strcmp($left, $right) : $byLength;
}
/**
* RSASP1 (RFC 8017, section 5.2.1).
*/
private function rsasp1(RsaKey $key, BigInteger $m): BigInteger
{
$n = BigInteger::createFromBinaryString($key->n());
if ($m->compare(BigInteger::createFromDecimal(0)) < 0 || $m->compare($n) >= 0) {
throw new RuntimeException('Message representative out of range');
}
$e = BigInteger::createFromBinaryString($key->e());
$hasCrtParameters = $key->hasPrimes() && $key->hasExponents() && $key->hasCoefficient();
if ($hasCrtParameters && ! $key->has(RsaKey::DATA_OTHER)) {
// A two-prime key with a complete CRT quintuple is the only shape RsaKey::asPem() can express, and the
// only one OpenSSL can therefore compute. Its exponentiation is blinded and runs in constant time, which
// neither gmp_powm() nor bcpowmod() nor the native brick/math loop does.
$this->checkCrtParameters($key, $n);
$signature = $this->rsasp1WithOpenSSL($key, $m);
} else {
// Multi-prime keys (RFC 8230, section 4) and (n, e, d) keys have no PEM representation, so they keep the
// in-process exponentiation. Blinding the base hides it from an attacker timing the operation or watching
// the cache while it runs; it does not make the exponentiation itself constant-time.
[$blindingFactor, $unblindingFactor] = $this->blindingFactors($n, $e);
$blinded = $m->multiply($blindingFactor)
->mod($n)
;
$signature = $hasCrtParameters
? $this->rsasp1WithCrt($key, $blinded)
// RFC 8017, section 5.2.1, step 2.a: first form (n, d).
: $blinded->modPow(BigInteger::createFromBinaryString($key->d()), $n);
$signature = $signature->multiply($unblindingFactor)
->mod($n)
;
}
// A wrong CRT result must never leave this class: it would be a silently invalid signature and, on faulty
// hardware, a private key recovery oracle. OpenSSL applies the very same check.
if ($signature->modPow($e, $n)->compare($m) !== 0) {
throw new RuntimeException(
'Inconsistent RSA private key: the CRT parameters do not describe the modulus'
);
}
return $signature;
}
/**
* RSASP1 computed by OpenSSL: base blinding and BN_mod_exp_mont_consttime on the private exponent, plus its own
* check of the CRT result against the public operation.
*/
private function rsasp1WithOpenSSL(RsaKey $key, BigInteger $m): BigInteger
{
$k = intdiv(RsaKeyValidator::modulusLength($key) + 7, 8);
try {
$computed = openssl_private_encrypt(
$this->convertIntegerToOctetString($m, $k),
$signature,
$key->asPem(),
OPENSSL_NO_PADDING
);
} catch (Throwable $throwable) {
$this->clearOpenSSLErrors();
throw new RuntimeException('Unable to compute the RSA signature primitive', 0, $throwable);
}
if (! $computed || ! is_string($signature)) {
$this->clearOpenSSLErrors();
throw new RuntimeException('Unable to compute the RSA signature primitive');
}
return BigInteger::createFromBinaryString($signature);
}
/**
* OpenSSL repairs a key whose CRT parameters do not describe the modulus instead of reporting it, so the
* consistency of the quintuple is established before the exponentiation rather than after it.
*/
private function checkCrtParameters(RsaKey $key, BigInteger $n): void
{
$one = BigInteger::createFromDecimal(1);
[$pS, $qS] = $key->primes();
[$dPS, $dQS] = $key->exponents();
$p = BigInteger::createFromBinaryString($pS);
$q = BigInteger::createFromBinaryString($qS);
$e = BigInteger::createFromBinaryString($key->e());
// A prime of 0 or 1 would make the reductions below meaningless, and n = p * q rules it out on its own only
// for the other factor.
$this->assertCrtParameter($p->compare($one) > 0 && $q->compare($one) > 0);
$this->assertCrtParameter($this->isEqual($p->multiply($q), $n));
// e * dP = 1 mod (p - 1), e * dQ = 1 mod (q - 1) and q * qInv = 1 mod p (RFC 8017, section 3.2).
$this->assertCrtParameter(
$this->isEqual($e->multiply(BigInteger::createFromBinaryString($dPS))->mod($p->subtract($one)), $one)
);
$this->assertCrtParameter(
$this->isEqual($e->multiply(BigInteger::createFromBinaryString($dQS))->mod($q->subtract($one)), $one)
);
$this->assertCrtParameter(
$this->isEqual($q->multiply(BigInteger::createFromBinaryString($key->QInv()))->mod($p), $one)
);
}
private function assertCrtParameter(bool $isConsistent): void
{
if (! $isConsistent) {
throw new RuntimeException(
'Inconsistent RSA private key: the CRT parameters do not describe the modulus'
);
}
}
private function isEqual(BigInteger $left, BigInteger $right): bool
{
return $left->compare($right) === 0;
}
/**
* A random r coprime with n, returned as the pair (r^e mod n, r^-1 mod n): multiplying the message representative
* by the first before the exponentiation and the result by the second after it leaves the signature unchanged,
* while the value actually exponentiated is unpredictable.
*
* @return array{BigInteger, BigInteger}
*/
private function blindingFactors(BigInteger $n, BigInteger $e): array
{
$two = BigInteger::createFromDecimal(2);
// Eight bytes beyond the modulus keep the bias of the reduction below negligible.
$length = strlen($n->toBytes()) + 8;
$upperBound = $n->subtract(BigInteger::createFromDecimal(3));
while (true) {
$r = BigInteger::createFromBinaryString(random_bytes($length))
->mod($upperBound)
->add($two)
;
try {
// Drawing an r sharing a factor with n means having factored n, so this never loops in practice.
$unblindingFactor = $r->modInverse($n);
} catch (MathException) {
continue;
}
return [$r->modPow($e, $n), $unblindingFactor];
}
}
/**
* RFC 8017, section 5.2.1, step 2.b.
*/
private function rsasp1WithCrt(RsaKey $key, BigInteger $m): BigInteger
{
[$pS, $qS] = $key->primes();
[$dPS, $dQS] = $key->exponents();
$p = BigInteger::createFromBinaryString($pS);
$q = BigInteger::createFromBinaryString($qS);
// Steps 2.b.1, 2.b.3 and 2.b.4.
$s1 = $m->modPow(BigInteger::createFromBinaryString($dPS), $p);
$s2 = $m->modPow(BigInteger::createFromBinaryString($dQS), $q);
$h = $s1->subtract($s2)
->multiply(BigInteger::createFromBinaryString($key->QInv()))
->mod($p)
;
$signature = $s2->add($h->multiply($q));
if (! $key->has(RsaKey::DATA_OTHER)) {
return $signature;
}
// Steps 2.b.2 and 2.b.5, for the third to u-th primes of a multi-prime key (RFC 8230, section 4).
$r = $p->multiply($q);
foreach ($key->other() as $primeInfo) {
$rI = BigInteger::createFromBinaryString($primeInfo[RsaKey::DATA_RI]);
$sI = $m->modPow(BigInteger::createFromBinaryString($primeInfo[RsaKey::DATA_DI]), $rI);
$h = $sI->subtract($signature)
->multiply(BigInteger::createFromBinaryString($primeInfo[RsaKey::DATA_TI]))
->mod($rI)
;
$signature = $signature->add($r->multiply($h));
$r = $r->multiply($rI);
}
return $signature;
}
/**
* Drains the OpenSSL error queue so that a failure here is not reported by an unrelated later call.
*/
private function clearOpenSSLErrors(): void
{
while (openssl_error_string() !== false) {
}
}
private function convertIntegerToOctetString(BigInteger $x, int $xLen): string
{
$xB = $x->toBytes();
if (strlen($xB) > $xLen) {
throw new RuntimeException('Unable to convert the integer');
}
return str_pad($xB, $xLen, chr(0), STR_PAD_LEFT);
}
/**
* MGF1.
*/
private function getMGF1(string $mgfSeed, int $maskLen, Hash $mgfHash): string
{
$t = '';
$count = intdiv($maskLen + $mgfHash->getLength() - 1, $mgfHash->getLength());
for ($i = 0; $i < $count; ++$i) {
$c = pack('N', $i);
$t .= $mgfHash->hash($mgfSeed . $c);
}
return substr($t, 0, $maskLen);
}
/**
* The mask of the leftmost 8emLen - emBits bits of the leftmost octet of maskedDB (RFC 8017, section 9.1.1, step
* 11 and section 9.1.2, steps 6 and 9). It is 0x00 when the encoded message is byte aligned and nothing has to be
* cleared.
*/
private function leftmostBitsMask(int $emBits): string
{
$bitsToClear = 8 * intdiv($emBits + 7, 8) - $emBits;
return chr((0xFF << (8 - $bitsToClear)) & 0xFF);
}
/**
* EMSA-PSS-ENCODE (RFC 8017, section 9.1.1).
*/
private function encodeEMSAPSS(string $message, int $emBits, Hash $hash): string
{
$emLen = intdiv($emBits + 7, 8);
$hLen = $hash->getLength();
$sLen = $hLen;
$mHash = $hash->hash($message);
if ($emLen < $hLen + $sLen + 2) {
throw new RuntimeException(
'Encoding error: the modulus is too short for this hash and salt length'
);
}
$salt = random_bytes($sLen);
$m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
$h = $hash->hash($m2);
$ps = str_repeat(chr(0), $emLen - $sLen - $hLen - 2);
$db = $ps . chr(1) . $salt;
$dbMask = $this->getMGF1($h, $emLen - $hLen - 1, $hash);
$maskedDB = $db ^ $dbMask;
$maskedDB[0] = ~$this->leftmostBitsMask($emBits) & $maskedDB[0];
return $maskedDB . $h . chr(0xBC);
}
/**
* EMSA-PSS-VERIFY (RFC 8017, section 9.1.2).
*/
private function verifyEMSAPSS(string $m, string $em, int $emBits, Hash $hash): bool
{
$emLen = intdiv($emBits + 7, 8);
$hLen = $hash->getLength();
$sLen = $hLen;
$mHash = $hash->hash($m);
// Every check below is a step whose failure RFC 8017, section 9.1.2 defines as "output 'inconsistent' and
// stop", i.e. an invalid signature rather than an error.
// Step 3: the modulus is too short for this hash and salt length.
if ($emLen < $hLen + $sLen + 2) {
return false;
}
// Step 4: the trailer field is not 0xBC.
if ($em[strlen($em) - 1] !== chr(0xBC)) {
return false;
}
$maskedDB = substr($em, 0, -$hLen - 1);
$h = substr($em, -$hLen - 1, $hLen);
$mask = $this->leftmostBitsMask($emBits);
// Step 6: the leftmost bits of maskedDB are not zero.
if (($maskedDB[0] & $mask) !== chr(0)) {
return false;
}
$dbMask = $this->getMGF1($h, $emLen - $hLen - 1, $hash/* MGF */);
$db = $maskedDB ^ $dbMask;
$db[0] = ~$mask & $db[0];
$temp = $emLen - $hLen - $sLen - 2;
// Step 10: the padding string is not zero, or the separator octet is not 0x01.
if (! str_starts_with($db, str_repeat(chr(0), $temp))) {
return false;
}
if (ord($db[$temp]) !== 1) {
return false;
}
$salt = substr($db, $temp + 1); // should be $sLen long
$m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
$h2 = $hash->hash($m2);
return hash_equals($h, $h2);
}
}

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const E_USER_WARNING;
use const OPENSSL_ALGO_SHA1;
use function trigger_error;
/**
* RSASSA-PKCS1-v1_5 using SHA-1.
*
* SHA-1 is no longer acceptable for digital signatures: NIST has recommended against generating signatures with it
* since the end of 2010 and forbidden its use by U.S. federal agencies for sensitive but unclassified information
* since the end of 2013 (see RFC 6194 and NIST SP 800-131A). The algorithm is kept for the legacy authenticators
* that still rely on it.
*
* Because of that, creating this algorithm emits an E_USER_WARNING unless the caller explicitly acknowledges the risk
* by passing `acknowledgeInsecureAlgorithm: true`. From v5.0.0 the same call without that acknowledgement will throw
* an InvalidArgumentException instead of warning.
*
* @see https://datatracker.ietf.org/doc/html/rfc6194
*/
final class RS1 extends RSA
{
public const ID = -65535;
public const INSECURE_ALGORITHM_MESSAGE = 'The algorithm RS1 (RSASSA-PKCS1-v1_5 with SHA-1) is not secure and shall only be used to verify signatures produced by legacy authenticators. If you know what you are doing, create it with "acknowledgeInsecureAlgorithm: true"; as of v5.0.0, omitting that acknowledgement will throw an exception.';
public function __construct(bool $acknowledgeInsecureAlgorithm = false, ?RsaKeyValidator $keyValidator = null)
{
parent::__construct($keyValidator);
if (! $acknowledgeInsecureAlgorithm) {
trigger_error(self::INSECURE_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
public static function create(
bool $acknowledgeInsecureAlgorithm = false,
?RsaKeyValidator $keyValidator = null
): self {
return new self($acknowledgeInsecureAlgorithm, $keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA1;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const OPENSSL_ALGO_SHA256;
final class RS256 extends RSA
{
public const ID = -257;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA256;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const OPENSSL_ALGO_SHA384;
final class RS384 extends RSA
{
public const ID = -258;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA384;
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKeyValidator;
use const OPENSSL_ALGO_SHA512;
final class RS512 extends RSA
{
public const ID = -259;
public static function create(?RsaKeyValidator $keyValidator = null): self
{
return new self($keyValidator);
}
public static function identifier(): int
{
return self::ID;
}
protected function getHashAlgorithm(): int
{
return OPENSSL_ALGO_SHA512;
}
}

View file

@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Algorithm\KeyRestrictionAware;
use Cose\Algorithm\KeyRestrictionEnforcement;
use Cose\Algorithm\Signature\OpenSslError;
use Cose\Algorithm\Signature\Signature;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use Cose\Key\RsaKeyValidator;
use InvalidArgumentException;
use function openssl_pkey_get_private;
use function openssl_pkey_get_public;
use function openssl_sign;
use function openssl_verify;
/**
* RSASSA-PKCS1-v1_5 as defined by RFC 8017, section 8.2.
*
* Section 8.2.2 applies RSAVP1 under the assumption that the public key is valid, i.e. that its exponent is an odd
* integer between 3 and n - 1 (section 3.1). openssl_verify() does not re-check it: with e = 1 the public operation
* is the identity map, so the EMSA-PKCS1-v1_5 encoding of a message - public data anyone can compute - would be
* accepted as a signature of that message under an attacker chosen key. Every key is therefore checked here.
*
* Its length is bounded too, before it is used. RFC 8230, section 6.1 asks for it - "It is highly recommended that
* checks on the key length be done before starting a cryptographic operation" - because the work an RSA operation
* costs grows with the size of the key it is given, and a verifier takes that key from whoever produced the message.
* The same section requires "a key size of 2048 bits or larger": that bound is applied by RsaKeyPolicy, with the
* validator this algorithm was created with or, by default, with RsaKeyValidator::create().
*
* @see https://www.rfc-editor.org/rfc/rfc8017#section-8.2
* @see \Cose\Tests\Algorithm\Signature\RSA\RSATest
*/
abstract class RSA implements Signature, KeyRestrictionAware
{
use KeyRestrictionEnforcement;
use RsaKeyPolicy;
public function __construct(?RsaKeyValidator $keyValidator = null)
{
$this->initializeKeyValidator($keyValidator);
}
public function sign(string $data, Key $key): string
{
$key = $this->handleKey($key, Key::OP_SIGN);
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
$this->checkKeyPolicy($key);
if (! $key->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
$privateKey = openssl_pkey_get_private($key->asPem());
if ($privateKey === false) {
throw new InvalidArgumentException('Unable to load the RSA private key');
}
OpenSslError::clear();
// openssl_sign() reports failure with a boolean and never throws: a modulus too short for the digest would
// otherwise leave $signature null and raise a TypeError on the way out.
if (! openssl_sign($data, $signature, $privateKey, $this->getHashAlgorithm())) {
throw new InvalidArgumentException('Unable to sign the data: ' . OpenSslError::lastMessage());
}
return $signature;
}
public function verify(string $data, Key $key, string $signature): bool
{
$key = $this->handleKey($key, Key::OP_VERIFY);
try {
RsaKeyValidator::checkPublicParameters($key);
RsaKeyValidator::checkLengthBounds($key);
// A key below the bound the caller asked for is a key it declared it does not verify with, which is an
// invalid signature rather than an error here too. The implicit default only warns.
$this->checkKeyPolicy($key);
} catch (InvalidArgumentException) {
// A key too large to compute with, or one that does not satisfy RFC 8017, section 3.1, is key material no
// verification can be performed with: the contract of Signature::verify() reports it as an invalid
// signature, not as an error.
return false;
}
// The key is loaded before use so that key material OpenSSL cannot decode yields false instead of an
// E_WARNING raised from inside openssl_verify().
$publicKey = openssl_pkey_get_public($key->toPublic()->asPem());
if ($publicKey === false) {
return false;
}
return openssl_verify($data, $signature, $publicKey, $this->getHashAlgorithm()) === 1;
}
abstract protected function getHashAlgorithm(): int;
private function handleKey(Key $key, int $operation): RsaKey
{
$this->checkKeyRestrictions($key, $operation);
return RsaKey::create($key->getData());
}
}

View file

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature\RSA;
use Cose\Key\RsaKey;
use Cose\Key\RsaKeyValidator;
use const E_USER_WARNING;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* The minimum modulus length every RSA algorithm of this library applies to the keys it is given.
*
* RFC 8230, section 6.1 - to which RFC 8812 defers for the WebAuthn registrations - states that "a key size of 2048
* bits or larger MUST be used with these algorithms" and that "it is highly recommended that checks on the key length
* be done before starting a cryptographic operation". That recommendation is addressed to the component performing
* the operation, which is this library, so RsaKeyValidator::create() is applied by default rather than left to the
* caller.
*
* Legacy authenticators holding 1024 bit keys exist, so the default bound cannot be enforced with an exception
* without breaking them: it emits an E_USER_WARNING in 4.x and will throw as of v5.0.0, following the schedule RS1
* already uses. A caller who has to accept a weaker key says so by handing the algorithm a validator of its own -
* RsaKeyValidator::create(minimumModulusLength: 1024) - which both records the bound actually accepted and applies it
* immediately, with an exception, instead of silencing the check altogether.
*
* Only the *minimum* modulus length goes through here. The public parameter constraints of RFC 8017, section 3.1 and
* the upper bounds on the size of the key are not a policy and are applied unconditionally by the algorithms
* themselves, before this check runs; nothing a validator rejects here has been left unchecked by them.
*
* @see https://www.rfc-editor.org/rfc/rfc8230#section-6.1
*
* @internal
*/
trait RsaKeyPolicy
{
private RsaKeyValidator $keyValidator;
/**
* Whether the validator was chosen by the caller, in which case the bound it carries is enforced with an
* exception, as opposed to the implicit default, which only warns until v5.0.0.
*/
private bool $keyValidatorIsExplicit;
private function initializeKeyValidator(?RsaKeyValidator $keyValidator): void
{
$this->keyValidatorIsExplicit = $keyValidator !== null;
$this->keyValidator = $keyValidator ?? RsaKeyValidator::create();
}
/**
* @throws InvalidArgumentException when the key is rejected by a validator the caller provided
*/
private function checkKeyPolicy(RsaKey $key): void
{
if (! isset($this->keyValidator)) {
// Both abstract classes gained their constructor in 4.8.0: an algorithm extending one of them from
// outside this library and overriding it without calling the parent gets the default rather than an
// error on an uninitialised property.
$this->initializeKeyValidator(null);
}
try {
$this->keyValidator->check($key);
} catch (InvalidArgumentException $exception) {
if ($this->keyValidatorIsExplicit) {
throw $exception;
}
trigger_error(
sprintf(RsaKeyValidator::WEAK_KEY_MESSAGE, $exception->getMessage()),
E_USER_WARNING
);
}
}
}

View file

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Cose\Algorithm\Signature;
use Cose\Algorithm\Algorithm;
use Cose\Key\Key;
use InvalidArgumentException;
interface Signature extends Algorithm
{
/**
* @throws InvalidArgumentException when the key cannot be used to sign with this algorithm (wrong key type, wrong
* curve, public key, key material the crypto layer refuses, or - when the
* algorithm enforces them, see KeyRestrictionAware - an "alg" or a "key_ops"
* that forbids signing with it)
*/
public function sign(string $data, Key $key): string;
/**
* Verification is total for every condition the underlying specification defines as an "invalid signature"
* outcome: a malformed, truncated, over-long or out-of-range signature, and key material no verification can be
* performed with (an off-curve point, a public key that is not a valid group element, an RSA key whose public
* parameters are not those RFC 8017 defines, …) all yield false.
*
* @throws InvalidArgumentException when $key cannot be used with this algorithm at all, i.e. its key type or its
* curve does not match, or - when the algorithm enforces them, see
* KeyRestrictionAware - its "alg" or its "key_ops" forbids the verification.
* Structurally invalid key components are rejected earlier, by the Key
* constructors.
*/
public function verify(string $data, Key $key, string $signature): bool;
}

View file

@ -0,0 +1,290 @@
<?php
declare(strict_types=1);
namespace Cose;
use function array_key_exists;
use Cose\Algorithm\Signature\RSA\RS1;
use const E_USER_WARNING;
use InvalidArgumentException;
use const OPENSSL_ALGO_SHA1;
use const OPENSSL_ALGO_SHA256;
use const OPENSSL_ALGO_SHA384;
use const OPENSSL_ALGO_SHA512;
use function trigger_error;
/**
* @see https://www.iana.org/assignments/cose/cose.xhtml#algorithms
*/
abstract class Algorithms
{
final public const COSE_ALGORITHM_AES_CCM_64_128_256 = 33;
final public const COSE_ALGORITHM_AES_CCM_64_128_128 = 32;
final public const COSE_ALGORITHM_AES_CCM_16_128_256 = 31;
final public const COSE_ALGORITHM_AES_CCM_16_128_128 = 30;
final public const COSE_ALGORITHM_AES_MAC_256_128 = 26;
final public const COSE_ALGORITHM_AES_MAC_128_128 = 25;
final public const COSE_ALGORITHM_CHACHA20_POLY1305 = 24;
final public const COSE_ALGORITHM_AES_MAC_256_64 = 15;
final public const COSE_ALGORITHM_AES_MAC_128_64 = 14;
final public const COSE_ALGORITHM_AES_CCM_64_64_256 = 13;
final public const COSE_ALGORITHM_AES_CCM_64_64_128 = 12;
final public const COSE_ALGORITHM_AES_CCM_16_64_256 = 11;
final public const COSE_ALGORITHM_AES_CCM_16_64_128 = 10;
final public const COSE_ALGORITHM_HS512 = 7;
final public const COSE_ALGORITHM_HS384 = 6;
final public const COSE_ALGORITHM_HS256 = 5;
final public const COSE_ALGORITHM_HS256_64 = 4;
final public const COSE_ALGORITHM_A256GCM = 3;
final public const COSE_ALGORITHM_A192GCM = 2;
final public const COSE_ALGORITHM_A128GCM = 1;
final public const COSE_ALGORITHM_A128KW = -3;
final public const COSE_ALGORITHM_A192KW = -4;
final public const COSE_ALGORITHM_A256KW = -5;
final public const COSE_ALGORITHM_DIRECT = -6;
final public const COSE_ALGORITHM_ES256 = -7;
/**
* @deprecated since v4.0.6. Please use COSE_ALGORITHM_EDDSA instead. Will be removed in v5.0.0
*/
final public const COSE_ALGORITHM_EdDSA = -8;
final public const COSE_ALGORITHM_EDDSA = -8;
/**
* Ed25519 over a SHA-256 (-260) or SHA-512 (-261) digest of the message. These pre-hash variants are not
* registered anywhere and are not EdDSA identifiers: the IANA COSE Algorithms registry assigns -260 to WalnutDSA
* and -261 to TurboSHAKE128. They are kept for the authenticators that already produce them; new code should use
* COSE_ALGORITHM_ED25519 (-19) or COSE_ALGORITHM_ED448 (-53).
*/
final public const COSE_ALGORITHM_ED256 = -260;
final public const COSE_ALGORITHM_ED512 = -261;
final public const COSE_ALGORITHM_DIRECT_HKDF_SHA_256 = -10;
final public const COSE_ALGORITHM_DIRECT_HKDF_SHA_512 = -11;
final public const COSE_ALGORITHM_DIRECT_HKDF_AES_128 = -12;
final public const COSE_ALGORITHM_DIRECT_HKDF_AES_256 = -13;
final public const COSE_ALGORITHM_ECDH_ES_HKDF_256 = -25;
final public const COSE_ALGORITHM_ECDH_ES_HKDF_512 = -26;
final public const COSE_ALGORITHM_ECDH_SS_HKDF_256 = -27;
final public const COSE_ALGORITHM_ECDH_SS_HKDF_512 = -28;
final public const COSE_ALGORITHM_ECDH_ES_A128KW = -29;
final public const COSE_ALGORITHM_ECDH_ES_A192KW = -30;
final public const COSE_ALGORITHM_ECDH_ES_A256KW = -31;
final public const COSE_ALGORITHM_ECDH_SS_A128KW = -32;
final public const COSE_ALGORITHM_ECDH_SS_A192KW = -33;
final public const COSE_ALGORITHM_ECDH_SS_A256KW = -34;
final public const COSE_ALGORITHM_ES384 = -35;
final public const COSE_ALGORITHM_ES512 = -36;
final public const COSE_ALGORITHM_PS256 = -37;
final public const COSE_ALGORITHM_PS384 = -38;
final public const COSE_ALGORITHM_PS512 = -39;
final public const COSE_ALGORITHM_RSAES_OAEP = -40;
final public const COSE_ALGORITHM_RSAES_OAEP_256 = -41;
final public const COSE_ALGORITHM_RSAES_OAEP_512 = -42;
final public const COSE_ALGORITHM_ES256K = -47;
final public const COSE_ALGORITHM_RS256 = -257;
final public const COSE_ALGORITHM_RS384 = -258;
final public const COSE_ALGORITHM_RS512 = -259;
final public const COSE_ALGORITHM_RS1 = -65535;
/**
* Fully-specified algorithm identifiers: unlike the polymorphic identifiers above, these determine the curve and
* the hash on their own instead of leaving them to the other parameters of the key.
*
* @see https://www.rfc-editor.org/rfc/rfc9864.html
*/
final public const COSE_ALGORITHM_ESP256 = -9;
final public const COSE_ALGORITHM_ESP384 = -51;
final public const COSE_ALGORITHM_ESP512 = -52;
final public const COSE_ALGORITHM_ESB256 = -265;
final public const COSE_ALGORITHM_ESB320 = -266;
final public const COSE_ALGORITHM_ESB384 = -267;
final public const COSE_ALGORITHM_ESB512 = -268;
final public const COSE_ALGORITHM_ED25519 = -19;
final public const COSE_ALGORITHM_ED448 = -53;
/**
* The digest to hand to openssl_sign() / openssl_verify() for the ECDSA and RSASSA-PKCS1-v1_5 algorithms, and
* for those only.
*
* openssl_verify() called with an OPENSSL_ALGO_* digest implies PKCS #1 v1.5 padding, so PS256, PS384 and PS512
* (RSASSA-PSS) are deliberately absent, and so are EdDSA (-8), Ed25519 (-19) and Ed448 (-53), which are one-shot
* schemes that hash the message themselves. Verifying with one of those identifiers goes through the matching
* Cose\Algorithm\Signature\Signature class instead - Cose\Algorithm\Signature\CertificateSignatureVerifier
* does exactly that for a signature made by the key of an X.509 certificate.
*
* @internal this constant bypasses getOpensslAlgorithmFor() and the acknowledgement it requires for RS1; it will
* become private in the next major version
* @var array<int, int>
*/
final public const COSE_ALGORITHM_MAP = [
self::COSE_ALGORITHM_ES256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ES256K => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ES384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ES512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_ESP256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ESP384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ESP512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_ESB256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_ESB320 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ESB384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_ESB512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_RS256 => OPENSSL_ALGO_SHA256,
self::COSE_ALGORITHM_RS384 => OPENSSL_ALGO_SHA384,
self::COSE_ALGORITHM_RS512 => OPENSSL_ALGO_SHA512,
self::COSE_ALGORITHM_RS1 => OPENSSL_ALGO_SHA1,
];
/**
* The name of the digest each algorithm identifier uses, as hash() spells it.
*
* The EdDSA identifiers (-8, -19, -53) are absent: they name one-shot signature schemes with no separately
* applicable digest.
*
* @internal this constant bypasses getHashAlgorithmFor() and the acknowledgement it requires for RS1; it will
* become private in the next major version
* @var array<int, string>
*/
final public const COSE_HASH_MAP = [
self::COSE_ALGORITHM_ES256K => 'sha256',
self::COSE_ALGORITHM_ES256 => 'sha256',
self::COSE_ALGORITHM_ES384 => 'sha384',
self::COSE_ALGORITHM_ES512 => 'sha512',
self::COSE_ALGORITHM_ESP256 => 'sha256',
self::COSE_ALGORITHM_ESP384 => 'sha384',
self::COSE_ALGORITHM_ESP512 => 'sha512',
self::COSE_ALGORITHM_ESB256 => 'sha256',
self::COSE_ALGORITHM_ESB320 => 'sha384',
self::COSE_ALGORITHM_ESB384 => 'sha384',
self::COSE_ALGORITHM_ESB512 => 'sha512',
self::COSE_ALGORITHM_RS256 => 'sha256',
self::COSE_ALGORITHM_RS384 => 'sha384',
self::COSE_ALGORITHM_RS512 => 'sha512',
self::COSE_ALGORITHM_PS256 => 'sha256',
self::COSE_ALGORITHM_PS384 => 'sha384',
self::COSE_ALGORITHM_PS512 => 'sha512',
self::COSE_ALGORITHM_RS1 => 'sha1',
];
/**
* The digest to hand to openssl_sign() / openssl_verify() for an ECDSA or RSASSA-PKCS1-v1_5 identifier.
*
* @see self::COSE_ALGORITHM_MAP for the identifiers this covers, and for those it deliberately does not
*
* @param bool $acknowledgeInsecureAlgorithm see Cose\Algorithm\Signature\RSA\RS1: SHA-1 is only handed out
* against an explicit acknowledgement, as creating the RS1 algorithm itself is
*
* @throws InvalidArgumentException when the identifier is not one this map describes
*/
public static function getOpensslAlgorithmFor(
int $algorithmIdentifier,
bool $acknowledgeInsecureAlgorithm = false
): int {
if (! array_key_exists($algorithmIdentifier, self::COSE_ALGORITHM_MAP)) {
throw new InvalidArgumentException('The specified algorithm identifier is not supported');
}
self::checkInsecureAlgorithm($algorithmIdentifier, $acknowledgeInsecureAlgorithm);
return self::COSE_ALGORITHM_MAP[$algorithmIdentifier];
}
/**
* The name of the digest an identifier uses, as hash() spells it.
*
* @see self::COSE_HASH_MAP for the identifiers this covers, and for those it deliberately does not
*
* @param bool $acknowledgeInsecureAlgorithm see Cose\Algorithm\Signature\RSA\RS1: SHA-1 is only handed out
* against an explicit acknowledgement, as creating the RS1 algorithm itself is
*
* @throws InvalidArgumentException when the identifier is not one this map describes
*/
public static function getHashAlgorithmFor(
int $algorithmIdentifier,
bool $acknowledgeInsecureAlgorithm = false
): string {
if (! array_key_exists($algorithmIdentifier, self::COSE_HASH_MAP)) {
throw new InvalidArgumentException('The specified algorithm identifier is not supported');
}
self::checkInsecureAlgorithm($algorithmIdentifier, $acknowledgeInsecureAlgorithm);
return self::COSE_HASH_MAP[$algorithmIdentifier];
}
/**
* The RS1 class refuses to be created without an acknowledgement, but the two accessors above expose the very
* same primitive - SHA-1 with PKCS #1 v1.5 padding - without any object ever being built, and their result is
* handed straight to openssl_verify(). The policy therefore has to hold here too, otherwise the operator's
* decision not to register RS1 has no effect on the code paths that go through these maps.
*
* Unlike RS1::__construct(), this fires per verification rather than once at configuration time, which is
* precisely what makes an unacknowledged SHA-1 verification visible in the logs.
*/
private static function checkInsecureAlgorithm(int $algorithmIdentifier, bool $acknowledgeInsecureAlgorithm): void
{
if ($algorithmIdentifier === self::COSE_ALGORITHM_RS1 && ! $acknowledgeInsecureAlgorithm) {
// As of v5.0.0, this will throw an InvalidArgumentException instead of warning.
trigger_error(RS1::INSECURE_ALGORITHM_MESSAGE, E_USER_WARNING);
}
}
}

View file

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace Cose;
use Brick\Math\BigInteger as BrickBigInteger;
use Brick\Math\Exception\MathException;
use function chr;
use function hex2bin;
use function strlen;
use function unpack;
/**
* @internal
*/
final class BigInteger
{
private function __construct(
private readonly BrickBigInteger $value
) {
}
public static function createFromBinaryString(string $value): self
{
$res = unpack('H*', $value);
/** @var non-empty-string $data */
$data = current($res);
return new self(BrickBigInteger::fromBase($data, 16));
}
public static function createFromDecimal(int $value): self
{
return new self(BrickBigInteger::of($value));
}
/**
* Converts a BigInteger to a binary string.
*/
public function toBytes(): string
{
if ($this->value->isEqualTo(BrickBigInteger::zero())) {
return '';
}
$temp = $this->value->toBase(16);
$temp = 0 !== (strlen($temp) & 1) ? '0' . $temp : $temp;
$temp = hex2bin($temp);
return ltrim($temp, chr(0));
}
/**
* Adds two BigIntegers.
*/
public function add(self $y): self
{
$value = $this->value->plus($y->value);
return new self($value);
}
/**
* Subtracts two BigIntegers.
*/
public function subtract(self $y): self
{
$value = $this->value->minus($y->value);
return new self($value);
}
/**
* Multiplies two BigIntegers.
*/
public function multiply(self $x): self
{
$value = $this->value->multipliedBy($x->value);
return new self($value);
}
/**
* Performs modular exponentiation.
*/
public function modPow(self $e, self $n): self
{
$value = $this->value->modPow($e->value, $n->value);
return new self($value);
}
/**
* Returns the modular multiplicative inverse of this number modulo $m.
*
* @throws MathException if this number is not invertible modulo $m, i.e. if they are not coprime
*/
public function modInverse(self $m): self
{
$value = $this->value->modInverse($m->value);
return new self($value);
}
/**
* Performs modular exponentiation.
*/
public function mod(self $d): self
{
$value = $this->value->mod($d->value);
return new self($value);
}
/**
* Compares two numbers.
*/
public function compare(self $y): int
{
return $this->value->compareTo($y->value);
}
}

View file

@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseEncrypt0Tag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Encrypt0 (RFC 9052, CBOR tag 16).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseEncrypt0Tag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 16 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseEncrypt0Tag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 16;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $ciphertext;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt0 object. No list.');
}
if ($object->count() !== 3) {
throw new InvalidArgumentException('Not a valid CoseEncrypt0 object. The list shall have 3 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$ciphertext = $object->get(2);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt0 object. The item 1 shall be a ByteString object.'
);
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt0 object. The item 2 shall be a Map object.');
}
if (! $ciphertext instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt0 object. The item 3 shall be a ByteString object.'
);
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->ciphertext = $ciphertext;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $ciphertext
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $ciphertext]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getCiphertext(): ByteStringObject
{
return $this->ciphertext;
}
}

View file

@ -0,0 +1,173 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseEncryptTag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Encrypt (RFC 9052, CBOR tag 96).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseEncryptTag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 96 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseEncryptTag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 96;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $ciphertext;
private readonly ListObject $recipients;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$ciphertext = $object->get(2);
$recipients = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt object. The item 1 shall be a ByteString object.'
);
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. The item 2 shall be a Map object.');
}
if (! $ciphertext instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseEncrypt object. The item 3 shall be a ByteString object.'
);
}
if (! $recipients instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseEncrypt object. The item 4 shall be a List object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->ciphertext = $ciphertext;
$this->recipients = $recipients;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $ciphertext,
ListObject $recipients
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([
$protectedHeaderAsBytesString,
$unprotectedHeader,
$ciphertext,
$recipients,
]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getCiphertext(): ByteStringObject
{
return $this->ciphertext;
}
public function getRecipients(): ListObject
{
return $this->recipients;
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Enc_structure of a COSE_Encrypt0 (RFC 9052 section 5.3).
*
* Enc_structure = [ "Encrypt0", protected : empty_or_serialized_map, external_aad : bstr ]
*
* This is the additional authenticated data of the content encryption. Unlike the signature and MAC structures it
* carries no payload: the content itself is what the AEAD encrypts, and this structure is what it authenticates
* alongside it.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class Encrypt0Structure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Encrypt0';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad];
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Enc_structure of a COSE_Encrypt (RFC 9052 section 5.3).
*
* Enc_structure = [ "Encrypt", protected : empty_or_serialized_map, external_aad : bstr ]
*
* This is the additional authenticated data of the content encryption. Unlike the signature and MAC structures it
* carries no payload: the content itself is what the AEAD encrypts, and this structure is what it authenticates
* alongside it.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class EncryptStructure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Encrypt';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad];
}
}

View file

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Cose\Encryption;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Enc_structure of a recipient (RFC 9052 section 5.3).
*
* Enc_structure = [ context : "Enc_Recipient" / "Mac_Recipient" / "Rec_Recipient", protected :
* empty_or_serialized_map, external_aad : bstr ]
*
* The three remaining contexts of Enc_structure name where the key being wrapped comes from: the recipient of a
* COSE_Encrypt, the recipient of a COSE_Mac, or a recipient nested inside another recipient. Binding the context is
* what stops a wrapped key from being replayed at a different level of the same structure, so it is a named
* constructor rather than a free string.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class RecipientStructure extends CoseStructure
{
/**
* The recipient of a COSE_Encrypt.
*/
public const CONTEXT_ENC_RECIPIENT = 'Enc_Recipient';
/**
* The recipient of a COSE_Mac.
*/
public const CONTEXT_MAC_RECIPIENT = 'Mac_Recipient';
/**
* A recipient nested inside another recipient.
*/
public const CONTEXT_REC_RECIPIENT = 'Rec_Recipient';
private readonly ByteStringObject $externalAad;
private function __construct(
private readonly string $context,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function forEncryptRecipient(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self(self::CONTEXT_ENC_RECIPIENT, $protectedHeader, $externalAad);
}
public static function forMacRecipient(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self(self::CONTEXT_MAC_RECIPIENT, $protectedHeader, $externalAad);
}
public static function forNestedRecipient(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?ByteStringObject $externalAad = null
): self {
return new self(self::CONTEXT_REC_RECIPIENT, $protectedHeader, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return $this->context;
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad];
}
}

61
vendor/web-auth/cose-lib/src/Hash.php vendored Normal file
View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Cose;
/**
* @internal
*/
final class Hash
{
private function __construct(
private readonly string $hash,
private readonly int $length,
private readonly string $t
) {
}
public static function sha1(): self
{
return new self('sha1', 20, "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14");
}
public static function sha256(): self
{
return new self('sha256', 32, "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20");
}
public static function sha384(): self
{
return new self('sha384', 48, "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30");
}
public static function sha512(): self
{
return new self('sha512', 64, "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40");
}
public function getLength(): int
{
return $this->length;
}
/**
* Compute the HMAC.
*/
public function hash(string $text): string
{
return hash($this->hash, $text, true);
}
public function name(): string
{
return $this->hash;
}
public function t(): string
{
return $this->t;
}
}

View file

@ -0,0 +1,282 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function in_array;
use InvalidArgumentException;
use function is_int;
use function is_string;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitlyTaggedType;
use function sprintf;
use function strlen;
/**
* @final
* @see \Cose\Tests\Key\Ec2KeyTest
*/
class Ec2Key extends Key
{
final public const CURVE_P256 = 1;
final public const CURVE_P256K = 8;
final public const CURVE_P384 = 2;
final public const CURVE_P521 = 3;
final public const CURVE_NAME_P256 = 'P-256';
/**
* The registered name of COSE curve 8 (RFC 8812, sections 3.1 and 4.2) and the name OpenSSL gives it.
*/
final public const CURVE_NAME_SECP256K1 = 'secp256k1';
/**
* @deprecated The draft-era spelling of curve 8, from draft-ietf-cose-webauthn-algorithms-00, renamed to
* "secp256k1" before -01 and never registered. Still accepted; use CURVE_NAME_SECP256K1 instead.
*/
final public const CURVE_NAME_P256K = 'P-256K';
final public const CURVE_NAME_P384 = 'P-384';
final public const CURVE_NAME_P521 = 'P-521';
final public const CURVE_BP256 = 256;
final public const CURVE_BP320 = 257;
final public const CURVE_BP384 = 258;
final public const CURVE_BP512 = 259;
final public const CURVE_NAME_BP256 = 'brainpoolP256r1';
final public const CURVE_NAME_BP320 = 'brainpoolP320r1';
final public const CURVE_NAME_BP384 = 'brainpoolP384r1';
final public const CURVE_NAME_BP512 = 'brainpoolP512r1';
final public const DATA_CURVE = -1;
final public const DATA_X = -2;
final public const DATA_Y = -3;
final public const DATA_D = -4;
private const SUPPORTED_CURVES_INT = [
self::CURVE_P256,
self::CURVE_P256K,
self::CURVE_P384,
self::CURVE_P521,
self::CURVE_BP256,
self::CURVE_BP320,
self::CURVE_BP384,
self::CURVE_BP512,
];
/**
* RFC 9053, section 7.1, table 19 types "crv" as "int / tstr": a curve may be named instead of numbered. Each of
* these names maps to the identifier of the "COSE Elliptic Curves" registry that curveId() exposes.
*
* @var array<string, int>
*/
private const CURVE_NAME_TO_ID = [
self::CURVE_NAME_P256 => self::CURVE_P256,
self::CURVE_NAME_SECP256K1 => self::CURVE_P256K,
// The deprecated alias is listed on purpose: it is what keeps the draft-era name working.
// @phpstan-ignore classConstant.deprecated
self::CURVE_NAME_P256K => self::CURVE_P256K,
self::CURVE_NAME_P384 => self::CURVE_P384,
self::CURVE_NAME_P521 => self::CURVE_P521,
self::CURVE_NAME_BP256 => self::CURVE_BP256,
self::CURVE_NAME_BP320 => self::CURVE_BP320,
self::CURVE_NAME_BP384 => self::CURVE_BP384,
self::CURVE_NAME_BP512 => self::CURVE_BP512,
];
private const NAMED_CURVE_OID = [
self::CURVE_P256 => '1.2.840.10045.3.1.7',
// NIST P-256 / secp256r1
self::CURVE_P256K => '1.3.132.0.10',
// SECG secp256k1 (RFC 8812)
self::CURVE_P384 => '1.3.132.0.34',
// NIST P-384 / secp384r1
self::CURVE_P521 => '1.3.132.0.35',
// NIST P-521 / secp521r1
self::CURVE_BP256 => '1.3.36.3.3.2.8.1.1.7',
// brainpoolP256r1
self::CURVE_BP320 => '1.3.36.3.3.2.8.1.1.9',
// brainpoolP320r1
self::CURVE_BP384 => '1.3.36.3.3.2.8.1.1.11',
// brainpoolP384r1
self::CURVE_BP512 => '1.3.36.3.3.2.8.1.1.13',
// brainpoolP512r1
];
private const CURVE_KEY_LENGTH = [
self::CURVE_P256 => 32,
self::CURVE_P256K => 32,
self::CURVE_P384 => 48,
self::CURVE_P521 => 66,
self::CURVE_BP256 => 32,
self::CURVE_BP320 => 40,
self::CURVE_BP384 => 48,
self::CURVE_BP512 => 64,
];
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
// Everything below is read from attacker-supplied CBOR: each entry is checked to be present and of the
// expected PHP type before it is used, so that a malformed key always leaves through the
// InvalidArgumentException this library documents rather than through a warning, a TypeError or an Error.
$data = self::normalizeIntegerEntries($data, self::DATA_CURVE, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_EC2 && $data[self::TYPE] !== self::TYPE_NAME_EC2) {
throw new InvalidArgumentException('Invalid EC2 key. The key type does not correspond to an EC2 key');
}
// RFC 9053 section 7.1.1: "For public keys, it is REQUIRED that 'crv', 'x', and 'y' be present".
if (! isset($data[self::DATA_CURVE], $data[self::DATA_X], $data[self::DATA_Y])) {
throw new InvalidArgumentException('Invalid EC2 key. The curve or the "x/y" coordinates are missing');
}
// The curve is checked first: the coordinate lengths below are read from a table indexed by the curve.
$curveId = self::toCurveId($data[self::DATA_CURVE]);
if ($curveId === null) {
throw new InvalidArgumentException('The curve is not supported');
}
$length = self::CURVE_KEY_LENGTH[$curveId];
// RFC 9053 section 7.1, table 19 types "x", "y" and "d" as byte strings.
foreach ([
self::DATA_X => 'x',
self::DATA_Y => 'y',
] as $index => $name) {
if (! is_string($data[$index])) {
throw new InvalidArgumentException(sprintf('Invalid type for %s coordinate', $name));
}
if (strlen($data[$index]) !== $length) {
throw new InvalidArgumentException(sprintf('Invalid length for %s coordinate', $name));
}
}
// RFC 5915 section 3: the private key is "an octet string of length ceiling (log2(n)/8)".
if (array_key_exists(self::DATA_D, $data)
&& (! is_string($data[self::DATA_D]) || strlen($data[self::DATA_D]) !== $length)) {
throw new InvalidArgumentException('Invalid length for d');
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function toPublic(): self
{
$data = $this->getData();
unset($data[self::DATA_D]);
return new self($data);
}
public function x(): string
{
return $this->get(self::DATA_X);
}
public function y(): string
{
return $this->get(self::DATA_Y);
}
public function isPrivate(): bool
{
return array_key_exists(self::DATA_D, $this->getData());
}
public function d(): string
{
if (! $this->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
return $this->get(self::DATA_D);
}
/**
* The curve as the key carries it, which RFC 9053 section 7.1 allows to be either the identifier of the "COSE
* Elliptic Curves" registry or a name. Use curveId() to get the identifier whatever form was supplied.
*/
public function curve(): int|string
{
return $this->get(self::DATA_CURVE);
}
/**
* The value of the curve in the IANA "COSE Elliptic Curves" registry, whichever of the two forms the key uses.
*/
public function curveId(): int
{
$curve = $this->curve();
return is_int($curve) ? $curve : self::CURVE_NAME_TO_ID[$curve];
}
public function asPEM(): string
{
if ($this->isPrivate()) {
$der = Sequence::create(
Integer::create(1),
OctetString::create($this->d()),
ExplicitlyTaggedType::create(0, ObjectIdentifier::create($this->getCurveOid())),
ExplicitlyTaggedType::create(1, BitString::create($this->getUncompressedCoordinates())),
);
return $this->pem('EC PRIVATE KEY', $der->toDER());
}
$der = Sequence::create(
Sequence::create(
ObjectIdentifier::create('1.2.840.10045.2.1'),
ObjectIdentifier::create($this->getCurveOid())
),
BitString::create($this->getUncompressedCoordinates())
);
return $this->pem('PUBLIC KEY', $der->toDER());
}
public function getUncompressedCoordinates(): string
{
return "\x04" . $this->x() . $this->y();
}
private function getCurveOid(): string
{
return self::NAMED_CURVE_OID[$this->curveId()];
}
/**
* The registry value of a supported curve, or null when the value denotes no curve this class supports.
*/
private static function toCurveId(mixed $curve): ?int
{
if (is_int($curve)) {
return in_array($curve, self::SUPPORTED_CURVES_INT, true) ? $curve : null;
}
return is_string($curve) ? (self::CURVE_NAME_TO_ID[$curve] ?? null) : null;
}
}

308
vendor/web-auth/cose-lib/src/Key/Key.php vendored Normal file
View file

@ -0,0 +1,308 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function array_values;
use const FILTER_VALIDATE_INT;
use function filter_var;
use function implode;
use function in_array;
use InvalidArgumentException;
use function is_array;
use function is_int;
use function is_string;
use function preg_match;
use function sprintf;
class Key
{
public const TYPE = 1;
public const TYPE_OKP = 1;
public const TYPE_EC2 = 2;
public const TYPE_RSA = 3;
public const TYPE_OCT = 4;
public const TYPE_NAME_OKP = 'OKP';
public const TYPE_NAME_EC2 = 'EC';
public const TYPE_NAME_RSA = 'RSA';
public const TYPE_NAME_OCT = 'oct';
public const KID = 2;
public const ALG = 3;
public const KEY_OPS = 4;
public const BASE_IV = 5;
/**
* Key operations, RFC 9052 section 7.1, Table 5. They are the values the "key_ops" parameter (label 4) is made of.
*/
public const OP_SIGN = 1;
public const OP_VERIFY = 2;
public const OP_ENCRYPT = 3;
public const OP_DECRYPT = 4;
public const OP_WRAP_KEY = 5;
public const OP_UNWRAP_KEY = 6;
public const OP_DERIVE_KEY = 7;
public const OP_DERIVE_BITS = 8;
public const OP_MAC_CREATE = 9;
public const OP_MAC_VERIFY = 10;
/**
* The names of Table 5. A COSE key carries the integer values, but a key converted from a JWK may carry the text
* names JOSE uses for the same operations, so both are accepted when "key_ops" is read.
*
* @var array<int, string>
*/
private const OP_NAMES = [
self::OP_SIGN => 'sign',
self::OP_VERIFY => 'verify',
self::OP_ENCRYPT => 'encrypt',
self::OP_DECRYPT => 'decrypt',
self::OP_WRAP_KEY => 'wrap key',
self::OP_UNWRAP_KEY => 'unwrap key',
self::OP_DERIVE_KEY => 'derive key',
self::OP_DERIVE_BITS => 'derive bits',
self::OP_MAC_CREATE => 'MAC create',
self::OP_MAC_VERIFY => 'MAC verify',
];
/**
* @var array<int|string, mixed>
*/
private readonly array $data;
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
if (! array_key_exists(self::TYPE, $data)) {
throw new InvalidArgumentException('Invalid key: the type is not defined');
}
// The key type is normalised for every key, the generic one included, so that type() answers with the
// registry value whether the key was decoded from CBOR - where spomky-labs/cbor-php renders an integer as a
// numeric string - or built by hand. Everything that checks a key type, from the subclasses below to the
// MAC algorithms, then compares against Key::TYPE_* and sees the same value on both paths.
$this->data = self::normalizeIntegerEntries($data, self::TYPE);
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
/**
* Builds the key class the "kty" of the data designates.
*
* The data is expected to be the output of spomky-labs/cbor-php's normalize(), which renders a CBOR integer as a
* numeric string, or an equivalent PHP array: both the string and the native integer form of a registered key
* type are dispatched, as is its name (RFC 9052, section 7.1, table 4 types "kty" as "tstr / int").
*
* @param array<int|string, mixed> $data
*/
public static function createFromData(array $data): self
{
if (! array_key_exists(self::TYPE, $data)) {
throw new InvalidArgumentException('Invalid key: the type is not defined');
}
return match ($data[self::TYPE]) {
self::TYPE_OKP, '1', self::TYPE_NAME_OKP => new OkpKey($data),
self::TYPE_EC2, '2', self::TYPE_NAME_EC2 => new Ec2Key($data),
self::TYPE_RSA, '3', self::TYPE_NAME_RSA => new RsaKey($data),
self::TYPE_OCT, '4', self::TYPE_NAME_OCT => new SymmetricKey($data),
default => self::create($data),
};
}
public function type(): int|string
{
return $this->data[self::TYPE];
}
/**
* The algorithm identifier the key is restricted to, RFC 9052 section 7.1, label 3.
*
* @throws InvalidArgumentException when the key has no "alg", or when its value is not an algorithm identifier.
* A text value such as "RS256" is not one: the COSE registry is made of
* integers, and casting it would silently yield 0, an identifier no algorithm
* is registered under.
*/
public function alg(): int
{
$alg = $this->get(self::ALG);
if (is_int($alg)) {
return $alg;
}
// An integer written as a string is accepted, as the key constructors do for "kty" and "crv".
if (is_string($alg) && filter_var($alg, FILTER_VALIDATE_INT) !== false) {
return (int) $alg;
}
throw new InvalidArgumentException(
'Invalid key: the "alg" parameter must be an integer algorithm identifier'
);
}
/**
* The operations the key is restricted to, RFC 9052 section 7.1, label 4, or null when it carries no such
* restriction.
*
* @throws InvalidArgumentException when "key_ops" is present but is not an array of integers or text names
* @return list<int|string>|null
*/
public function keyOps(): ?array
{
if (! $this->has(self::KEY_OPS)) {
return null;
}
$keyOps = $this->get(self::KEY_OPS);
if (! is_array($keyOps)) {
throw new InvalidArgumentException('Invalid key: the "key_ops" parameter must be an array');
}
foreach ($keyOps as $keyOp) {
if (! is_int($keyOp) && ! is_string($keyOp)) {
throw new InvalidArgumentException(
'Invalid key: the "key_ops" parameter must only contain integers or text names'
);
}
}
return array_values($keyOps);
}
/**
* Whether the restrictions the key carries allow the operation to be performed with the given algorithm.
*
* @see self::assertUsableWith() for the conditions and the specifications behind them
*/
public function isUsableWith(int $algorithmIdentifier, int $operation): bool
{
try {
$this->assertUsableWith($algorithmIdentifier, $operation);
} catch (InvalidArgumentException) {
return false;
}
return true;
}
/**
* RFC 9052, section 7.1: a key that carries "alg" (label 3) MUST NOT be used with another algorithm - "If the
* algorithms do not match, then this key object MUST NOT be used to perform the cryptographic operation" - and
* one that carries "key_ops" (label 4) MUST list the operation being performed. RFC 9053 sections 2.1, 2.2 and
* 3.1 repeat both as a per-algorithm requirement for ECDSA, EdDSA and HMAC.
*
* The comparison is a plain equality of identifiers: the fully-specified identifiers of RFC 9864 and their
* polymorphic counterparts are distinct values here, ES256 (-7) and ESP256 (-9) among them. Section 7 of that
* RFC asks for it - "A cryptographic key MUST be used with only a single algorithm unless the use of the same
* key with different algorithms is proven secure." A caller who wants one key to serve both removes label 3
* from the key data, which is an explicit act.
*
* A key that carries neither parameter is usable with every algorithm and for every operation.
*
* @throws InvalidArgumentException when the key forbids the combination
*
* @see https://www.rfc-editor.org/rfc/rfc9052.html#section-7.1
*/
public function assertUsableWith(int $algorithmIdentifier, int $operation): void
{
if ($this->has(self::ALG) && $this->alg() !== $algorithmIdentifier) {
throw new InvalidArgumentException(sprintf(
'The key is restricted to the algorithm %d and cannot be used with the algorithm %d',
$this->alg(),
$algorithmIdentifier
));
}
$keyOps = $this->keyOps();
if ($keyOps === null) {
return;
}
$name = self::OP_NAMES[$operation] ?? throw new InvalidArgumentException(sprintf(
'Unknown key operation %d. Expected one of: %s',
$operation,
implode(', ', self::OP_NAMES)
));
if (! in_array($operation, $keyOps, true) && ! in_array($name, $keyOps, true)) {
throw new InvalidArgumentException(sprintf('The key does not allow the "%s" operation', $name));
}
}
/**
* @return array<int|string, mixed>
*/
public function getData(): array
{
return $this->data;
}
public function has(int|string $key): bool
{
return array_key_exists($key, $this->data);
}
public function get(int|string $key): mixed
{
if (! array_key_exists($key, $this->data)) {
throw new InvalidArgumentException(sprintf('The key has no data at index %d', $key));
}
return $this->data[$key];
}
/**
* spomky-labs/cbor-php normalises a CBOR integer to a numeric string (UnsignedIntegerObject::normalize()), so a
* key decoded from CBOR carries its "kty" and its "crv" as such a string. Each listed entry that holds one is
* replaced by the integer it denotes, before anything compares it against a registry value.
*
* Only an integer-looking string is converted. A float, or a string such as "1.5", " 1" or "4abc", is left as it
* is so that the checks that follow reject it, instead of a lenient cast silently turning it into a valid
* identifier.
*
* @param array<int|string, mixed> $data
* @return array<int|string, mixed>
*/
protected static function normalizeIntegerEntries(array $data, int|string ...$keys): array
{
foreach ($keys as $key) {
if (array_key_exists($key, $data) && is_string($data[$key])
&& preg_match('/^-?\\d+$/', $data[$key]) === 1) {
$data[$key] = (int) $data[$key];
}
}
return $data;
}
protected function pem(string $type, string $der): string
{
return sprintf("-----BEGIN %s-----\n", strtoupper($type)) .
chunk_split(base64_encode($der), 64, "\n") .
sprintf("-----END %s-----\n", strtoupper($type));
}
}

View file

@ -0,0 +1,251 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function extension_loaded;
use function in_array;
use InvalidArgumentException;
use function is_int;
use function is_string;
use RuntimeException;
use function sodium_crypto_scalarmult_base;
use function sodium_crypto_sign_publickey;
use function sodium_crypto_sign_seed_keypair;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\BitString;
use SpomkyLabs\Pki\ASN1\Type\Primitive\Integer;
use SpomkyLabs\Pki\ASN1\Type\Primitive\ObjectIdentifier;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use function strlen;
/**
* @final
* @see \Cose\Tests\Key\OkpKeyTest
*/
class OkpKey extends Key
{
final public const CURVE_X25519 = 4;
final public const CURVE_X448 = 5;
final public const CURVE_ED25519 = 6;
final public const CURVE_ED448 = 7;
final public const CURVE_NAME_X25519 = 'X25519';
final public const CURVE_NAME_X448 = 'X448';
final public const CURVE_NAME_ED25519 = 'Ed25519';
final public const CURVE_NAME_ED448 = 'Ed448';
final public const DATA_CURVE = -1;
final public const DATA_X = -2;
final public const DATA_D = -4;
private const SUPPORTED_CURVES_INT = [
self::CURVE_X25519,
self::CURVE_X448,
self::CURVE_ED25519,
self::CURVE_ED448,
];
/**
* RFC 9053, section 7.2, table 20 types "crv" as "int / tstr": a curve may be named instead of numbered. Each of
* these names maps to the identifier of the "COSE Elliptic Curves" registry that curveId() exposes.
*
* @var array<string, int>
*/
private const CURVE_NAME_TO_ID = [
self::CURVE_NAME_X25519 => self::CURVE_X25519,
self::CURVE_NAME_X448 => self::CURVE_X448,
self::CURVE_NAME_ED25519 => self::CURVE_ED25519,
self::CURVE_NAME_ED448 => self::CURVE_ED448,
];
/**
* RFC 8032 section 5.1.5 / 5.2.5 for the Edwards curves and RFC 7748 section 5 for the Montgomery ones: the
* public key and the private scalar are byte strings of exactly this length.
*/
private const CURVE_KEY_LENGTH = [
self::CURVE_X25519 => 32,
self::CURVE_X448 => 56,
self::CURVE_ED25519 => 32,
self::CURVE_ED448 => 57,
];
/**
* The curves whose public key the Sodium extension can recompute from the private one. Ed448 and X448 have no
* such primitive in PHP, so a key on those curves still has to carry its "x".
*/
private const DERIVABLE_CURVES = [
self::CURVE_X25519,
self::CURVE_ED25519,
];
private const CURVE_OID = [
self::CURVE_X25519 => '1.3.101.110',
self::CURVE_X448 => '1.3.101.111',
self::CURVE_ED25519 => '1.3.101.112',
self::CURVE_ED448 => '1.3.101.113',
];
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
// Everything below is read from attacker-supplied CBOR: each entry is checked to be present and of the
// expected PHP type before it is used, so that a malformed key always leaves through the
// InvalidArgumentException this library documents rather than through a warning, a TypeError or an Error.
$data = self::normalizeIntegerEntries($data, self::DATA_CURVE, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_OKP && $data[self::TYPE] !== self::TYPE_NAME_OKP) {
throw new InvalidArgumentException('Invalid OKP key. The key type does not correspond to an OKP key');
}
// RFC 9053 section 7.2: "d" is the authoritative private key material and "x" is only RECOMMENDED for a
// private key, "it can be recomputed from the required elements". A private key carrying "crv" and "d"
// alone is therefore valid, and is the safest way to build a signing key: nothing can hand over an "x"
// inconsistent with the seed.
if (! isset($data[self::DATA_CURVE]) || (! isset($data[self::DATA_X]) && ! isset($data[self::DATA_D]))) {
throw new InvalidArgumentException('Invalid OKP key. The curve or the "x" coordinate is missing');
}
// The curve is checked first: the key lengths below are read from a table indexed by the curve.
$curveId = self::toCurveId($data[self::DATA_CURVE]);
if ($curveId === null) {
throw new InvalidArgumentException('The curve is not supported');
}
// RFC 8032 section 5.1.5 / 5.2.5 and RFC 7748 section 5: both halves are byte strings of this exact length.
$length = self::CURVE_KEY_LENGTH[$curveId];
if (array_key_exists(self::DATA_X, $data)
&& (! is_string($data[self::DATA_X]) || strlen($data[self::DATA_X]) !== $length)) {
throw new InvalidArgumentException('Invalid length for x coordinate');
}
if (array_key_exists(self::DATA_D, $data)
&& (! is_string($data[self::DATA_D]) || strlen($data[self::DATA_D]) !== $length)) {
throw new InvalidArgumentException('Invalid length for d');
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function x(): string
{
if ($this->has(self::DATA_X)) {
return $this->get(self::DATA_X);
}
return $this->derivePublicKey();
}
public function isPrivate(): bool
{
return array_key_exists(self::DATA_D, $this->getData());
}
public function d(): string
{
if (! $this->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
return $this->get(self::DATA_D);
}
/**
* The curve as the key carries it, which RFC 9053 section 7.2 allows to be either the identifier of the "COSE
* Elliptic Curves" registry or a name. Use curveId() to get the identifier whatever form was supplied.
*/
public function curve(): int|string
{
return $this->get(self::DATA_CURVE);
}
/**
* The value of the curve in the IANA "COSE Elliptic Curves" registry, whichever of the two forms the key uses.
*/
public function curveId(): int
{
$curve = $this->curve();
return is_int($curve) ? $curve : self::CURVE_NAME_TO_ID[$curve];
}
public function toPublic(): self
{
$data = $this->getData();
$data[self::DATA_X] = $this->x();
unset($data[self::DATA_D]);
return new self($data);
}
/**
* Recomputes the public key from the private one, as RFC 9053 section 7.2 allows when "x" was omitted.
*/
private function derivePublicKey(): string
{
$curve = $this->curveId();
if (! in_array($curve, self::DERIVABLE_CURVES, true)) {
throw new InvalidArgumentException(
'The "x" coordinate is missing and cannot be computed from "d" for this curve'
);
}
if (! extension_loaded('sodium')) {
throw new RuntimeException(
'The "x" coordinate is missing and computing it from "d" requires the Sodium extension, which is not loaded.'
);
}
$d = $this->d();
return $curve === self::CURVE_X25519
? sodium_crypto_scalarmult_base($d)
: sodium_crypto_sign_publickey(sodium_crypto_sign_seed_keypair($d));
}
/**
* The registry value of a supported curve, or null when the value denotes no curve this class supports.
*/
private static function toCurveId(mixed $curve): ?int
{
if (is_int($curve)) {
return in_array($curve, self::SUPPORTED_CURVES_INT, true) ? $curve : null;
}
return is_string($curve) ? (self::CURVE_NAME_TO_ID[$curve] ?? null) : null;
}
/**
* Returns the key as a PEM encoded RFC 8410 OneAsymmetricKey (private) or SubjectPublicKeyInfo (public) structure.
*/
public function asPEM(): string
{
$oid = ObjectIdentifier::create(self::CURVE_OID[$this->curveId()]);
if ($this->isPrivate()) {
$der = Sequence::create(
Integer::create(0),
Sequence::create($oid),
OctetString::create(OctetString::create($this->d())->toDER())
);
return $this->pem('PRIVATE KEY', $der->toDER());
}
$der = Sequence::create(Sequence::create($oid), BitString::create($this->x()));
return $this->pem('PUBLIC KEY', $der->toDER());
}
}

View file

@ -0,0 +1,273 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function in_array;
use function intdiv;
use InvalidArgumentException;
use function ltrim;
use function ord;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\Asymmetric\ECPublicKeyAlgorithmIdentifier;
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKeyInfo;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use function sprintf;
use function str_contains;
use function strlen;
use function substr;
use Throwable;
/**
* Turns the public key of an X.509 certificate, or a bare SubjectPublicKeyInfo, into the Cose\Key\Key the signature
* algorithms of this library take.
*
* WebAuthn Level 3 sections 8.2 to 8.4 ask a relying party to verify a certificate-based attestation statement "with
* the algorithm specified in alg". Doing so through Algorithms::getOpensslAlgorithmFor() and openssl_verify() only
* covers ECDSA and RSASSA-PKCS1-v1_5, because an OPENSSL_ALGO_* digest implies PKCS #1 v1.5 padding; RSASSA-PSS and
* the EdDSA family cannot be expressed that way. This loader is the missing half of the other route: it produces the
* key, and the Signature class registered for the identifier does the verification. See
* Cose\Algorithm\Signature\CertificateSignatureVerifier for the two put together.
*
* Both methods accept PEM or raw DER.
*
* @see \Cose\Tests\Key\PublicKeyLoaderTest
*/
final class PublicKeyLoader
{
/**
* The named curves of RFC 5480, section 2.1.1.1 and RFC 5639, section 4.1 this library has a COSE identifier for
* (RFC 9053, section 7.1 and the IANA COSE Elliptic Curves registry).
*/
private const CURVE_OID_TO_COSE_CURVE = [
'1.2.840.10045.3.1.7' => Ec2Key::CURVE_P256,
'1.3.132.0.10' => Ec2Key::CURVE_P256K,
'1.3.132.0.34' => Ec2Key::CURVE_P384,
'1.3.132.0.35' => Ec2Key::CURVE_P521,
'1.3.36.3.3.2.8.1.1.7' => Ec2Key::CURVE_BP256,
'1.3.36.3.3.2.8.1.1.9' => Ec2Key::CURVE_BP320,
'1.3.36.3.3.2.8.1.1.11' => Ec2Key::CURVE_BP384,
'1.3.36.3.3.2.8.1.1.13' => Ec2Key::CURVE_BP512,
];
/**
* The RFC 8410, section 3 algorithm identifiers, whose subjectPublicKey is the public key itself.
*/
private const RFC8410_OID_TO_COSE_CURVE = [
'1.3.101.110' => OkpKey::CURVE_X25519,
'1.3.101.111' => OkpKey::CURVE_X448,
'1.3.101.112' => OkpKey::CURVE_ED25519,
'1.3.101.113' => OkpKey::CURVE_ED448,
];
/**
* rsaEncryption (RFC 8017, appendix A.1) and RSASSA-PSS (RFC 4055, section 1.2). The latter carries the same
* RSAPublicKey structure behind its own object identifier; the COSE key knows nothing of the padding, which the
* algorithm identifier of the signature decides, so both are read the same way.
*/
private const RSA_OIDS = ['1.2.840.113549.1.1.1', '1.2.840.113549.1.1.10'];
/**
* id-ecPublicKey, RFC 5480, section 2.1.1.
*/
private const OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1';
private const DER_TAG_SEQUENCE = 0x30;
private const DER_TAG_INTEGER = 0x02;
/**
* The public key of an X.509 certificate, PEM or DER encoded.
*
* @throws InvalidArgumentException when the certificate cannot be read, or carries a key this library has no
* COSE representation for
*/
public static function fromCertificate(string $certificate): Key
{
try {
$parsed = Certificate::fromDER(self::der($certificate, PEM::TYPE_CERTIFICATE));
} catch (Throwable $throwable) {
throw new InvalidArgumentException('Unable to read the certificate', 0, $throwable);
}
return self::fromPublicKeyInfo($parsed->tbsCertificate()->subjectPublicKeyInfo());
}
/**
* A bare SubjectPublicKeyInfo (RFC 5280, section 4.1.2.7), PEM or DER encoded.
*
* @throws InvalidArgumentException when the structure cannot be read, or carries a key this library has no COSE
* representation for
*/
public static function fromSubjectPublicKeyInfo(string $subjectPublicKeyInfo): Key
{
try {
$parsed = PublicKeyInfo::fromDER(self::der($subjectPublicKeyInfo, PEM::TYPE_PUBLIC_KEY));
} catch (Throwable $throwable) {
throw new InvalidArgumentException('Unable to read the public key', 0, $throwable);
}
return self::fromPublicKeyInfo($parsed);
}
private static function fromPublicKeyInfo(PublicKeyInfo $publicKeyInfo): Key
{
$algorithm = $publicKeyInfo->algorithmIdentifier();
$oid = $algorithm->oid();
$publicKey = $publicKeyInfo->publicKeyData()
->string();
if (in_array($oid, self::RSA_OIDS, true)) {
return self::rsaKey($publicKey);
}
if (array_key_exists($oid, self::RFC8410_OID_TO_COSE_CURVE)) {
return OkpKey::create([
Key::TYPE => Key::TYPE_OKP,
OkpKey::DATA_CURVE => self::RFC8410_OID_TO_COSE_CURVE[$oid],
OkpKey::DATA_X => $publicKey,
]);
}
if ($oid === self::OID_EC_PUBLIC_KEY && $algorithm instanceof ECPublicKeyAlgorithmIdentifier) {
return self::ec2Key($algorithm->namedCurve(), $publicKey);
}
throw new InvalidArgumentException(sprintf('Unsupported public key algorithm "%s"', $oid));
}
private static function ec2Key(string $namedCurve, string $ecPoint): Ec2Key
{
if (! array_key_exists($namedCurve, self::CURVE_OID_TO_COSE_CURVE)) {
throw new InvalidArgumentException(sprintf('Unsupported elliptic curve "%s"', $namedCurve));
}
// RFC 5480, section 2.2: the subjectPublicKey is the ECPoint of SEC 1, section 2.3.3. Only its uncompressed
// form is read here, as it is the only one Cose\Key\Ec2Key stores; decompressing a point would mean
// computing a square root modulo the field prime for every curve this library names.
if ($ecPoint === '' || ord($ecPoint[0]) !== 0x04) {
throw new InvalidArgumentException(
'Unsupported elliptic curve public key: only the uncompressed point format is supported'
);
}
$coordinates = substr($ecPoint, 1);
if (strlen($coordinates) === 0 || strlen($coordinates) % 2 !== 0) {
throw new InvalidArgumentException('Invalid elliptic curve public key');
}
$length = intdiv(strlen($coordinates), 2);
// Ec2Key rejects coordinates whose length does not match the curve.
return Ec2Key::create([
Key::TYPE => Key::TYPE_EC2,
Ec2Key::DATA_CURVE => self::CURVE_OID_TO_COSE_CURVE[$namedCurve],
Ec2Key::DATA_X => substr($coordinates, 0, $length),
Ec2Key::DATA_Y => substr($coordinates, $length),
]);
}
/**
* Reads the RSAPublicKey of RFC 8017, appendix A.1.1 - SEQUENCE { modulus INTEGER, publicExponent INTEGER } - and
* stores both integers as the unsigned big-endian octet strings RFC 8230, section 4 defines a COSE RSA key with.
*
* The two INTEGERs are taken as the octet strings they already are, and never turned into numbers: brick/math
* falls back to a pure PHP calculator whenever neither ext-gmp nor ext-bcmath is loaded, and its generic base
* conversion is superlinear, so decoding an attacker supplied modulus into a decimal string and back would cost
* more than the verification it precedes. Cose\Key\RsaKey builds its DER the same way, and for the same reason.
*/
private static function rsaKey(string $rsaPublicKey): RsaKey
{
$offset = 0;
$content = self::readValue($rsaPublicKey, self::DER_TAG_SEQUENCE, $offset);
if ($offset !== strlen($rsaPublicKey)) {
throw new InvalidArgumentException('Invalid RSA public key: trailing data');
}
$inner = 0;
$modulus = self::readValue($content, self::DER_TAG_INTEGER, $inner);
$exponent = self::readValue($content, self::DER_TAG_INTEGER, $inner);
if ($inner !== strlen($content)) {
throw new InvalidArgumentException('Invalid RSA public key: trailing data');
}
return RsaKey::create([
Key::TYPE => Key::TYPE_RSA,
RsaKey::DATA_N => self::magnitude($modulus, 'modulus'),
RsaKey::DATA_E => self::magnitude($exponent, 'public exponent'),
]);
}
/**
* The content octets of the TLV of the expected tag starting at $offset, which is advanced past the whole TLV.
*
* Only the definite form of X.690, section 8.1.3 is accepted, which is all DER allows (section 10.1).
*/
private static function readValue(string $der, int $expectedTag, int &$offset): string
{
if (strlen($der) < $offset + 2) {
throw new InvalidArgumentException('Invalid RSA public key: truncated structure');
}
if (ord($der[$offset]) !== $expectedTag) {
throw new InvalidArgumentException('Invalid RSA public key: unexpected structure');
}
++$offset;
$length = ord($der[$offset]);
++$offset;
if ($length > 0x80) {
$lengthOfLength = $length & 0x7F;
// A length that needs more than four octets describes a value no PHP string can hold anyway.
if ($lengthOfLength > 4 || strlen($der) < $offset + $lengthOfLength) {
throw new InvalidArgumentException('Invalid RSA public key: unsupported length');
}
$length = 0;
for ($i = 0; $i < $lengthOfLength; ++$i) {
$length = ($length << 8) | ord($der[$offset + $i]);
}
$offset += $lengthOfLength;
} elseif ($length === 0x80) {
// X.690, section 10.1: the indefinite form is not DER.
throw new InvalidArgumentException('Invalid RSA public key: indefinite length');
}
if (strlen($der) < $offset + $length) {
throw new InvalidArgumentException('Invalid RSA public key: truncated structure');
}
$content = substr($der, $offset, $length);
$offset += $length;
return $content;
}
/**
* X.690, section 8.3.2 encodes the content octets of an INTEGER in two's complement, so a leading 0x00 is only
* there to keep a non-negative value from reading as a negative one; RFC 8230, section 4 stores the magnitude
* alone. A value whose first bit is set is negative, which no RSA parameter ever is.
*/
private static function magnitude(string $integer, string $name): string
{
if ($integer === '') {
throw new InvalidArgumentException(sprintf('Invalid RSA public key: the %s is empty', $name));
}
if ((ord($integer[0]) & 0x80) !== 0) {
throw new InvalidArgumentException(sprintf('Invalid RSA public key: the %s is negative', $name));
}
$magnitude = ltrim($integer, "\x00");
if ($magnitude === '') {
throw new InvalidArgumentException(sprintf('Invalid RSA public key: the %s is zero', $name));
}
return $magnitude;
}
/**
* The DER of a structure given either as PEM or as DER already.
*/
private static function der(string $data, string $pemType): string
{
if (! str_contains($data, '-----BEGIN')) {
return $data;
}
$pem = PEM::fromString($data);
if ($pem->type() !== $pemType) {
throw new InvalidArgumentException(sprintf('Invalid PEM type "%s", expected "%s"', $pem->type(), $pemType));
}
return $pem->data();
}
}

View file

@ -0,0 +1,362 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use function array_key_exists;
use function base64_encode;
use function chunk_split;
use function implode;
use function in_array;
use InvalidArgumentException;
use function is_string;
use function ltrim;
use function ord;
use function pack;
use function sprintf;
use function strlen;
use function trim;
/**
* @final
* @see \Cose\Tests\Key\RsaKeyTest
*/
class RsaKey extends Key
{
final public const DATA_N = -1;
final public const DATA_E = -2;
final public const DATA_D = -3;
final public const DATA_P = -4;
final public const DATA_Q = -5;
final public const DATA_DP = -6;
final public const DATA_DQ = -7;
final public const DATA_QI = -8;
final public const DATA_OTHER = -9;
final public const DATA_RI = -10;
final public const DATA_DI = -11;
final public const DATA_TI = -12;
/**
* The DER of the rsaEncryption object identifier, 1.2.840.113549.1.1.1 (RFC 8017, appendix A.1).
*/
private const OID_RSA_ENCRYPTION = "\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01";
private const DER_NULL = "\x05\x00";
/**
* @var array<int>
*/
private const PRIVATE_PARAMETERS = [
self::DATA_D,
self::DATA_P,
self::DATA_Q,
self::DATA_DP,
self::DATA_DQ,
self::DATA_QI,
];
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
$data = self::normalizeIntegerEntries($data, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_RSA && $data[self::TYPE] !== self::TYPE_NAME_RSA) {
throw new InvalidArgumentException('Invalid RSA key. The key type does not correspond to a RSA key');
}
if (! isset($data[self::DATA_N], $data[self::DATA_E])) {
throw new InvalidArgumentException('Invalid RSA key. The modulus or the exponent is missing');
}
$modulus = $data[self::DATA_N];
$exponent = $data[self::DATA_E];
if (! is_string($modulus) || $modulus === '' || ! is_string($exponent) || $exponent === '') {
throw new InvalidArgumentException(
'Invalid RSA key. The modulus and the exponent shall be non-empty byte strings'
);
}
if (ltrim($modulus, "\0") === '') {
throw new InvalidArgumentException('Invalid RSA key. The modulus shall not be zero');
}
foreach (self::PRIVATE_PARAMETERS as $parameter) {
if (array_key_exists($parameter, $data) && ! is_string($data[$parameter])) {
throw new InvalidArgumentException('Invalid RSA key. The private parameters shall be byte strings');
}
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function n(): string
{
return $this->get(self::DATA_N);
}
public function e(): string
{
return $this->get(self::DATA_E);
}
public function d(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_D);
}
public function p(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_P);
}
public function q(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_Q);
}
public function dP(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_DP);
}
public function dQ(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_DQ);
}
public function QInv(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_QI);
}
/**
* The "other prime infos" of a multi-prime key (RFC 8230, section 4): one map per prime from the third one on,
* each holding the DATA_RI, DATA_DI and DATA_TI entries.
*
* @return array<int, array<int, string>>
*/
public function other(): array
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_OTHER);
}
public function rI(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_RI);
}
public function dI(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_DI);
}
public function tI(): string
{
$this->checkKeyIsPrivate();
return $this->get(self::DATA_TI);
}
public function hasPrimes(): bool
{
return $this->has(self::DATA_P) && $this->has(self::DATA_Q);
}
/**
* @return string[]
*/
public function primes(): array
{
return [$this->p(), $this->q()];
}
public function hasExponents(): bool
{
return $this->has(self::DATA_DP) && $this->has(self::DATA_DQ);
}
/**
* @return string[]
*/
public function exponents(): array
{
return [$this->dP(), $this->dQ()];
}
public function hasCoefficient(): bool
{
return $this->has(self::DATA_QI);
}
public function isPublic(): bool
{
return ! $this->isPrivate();
}
public function isPrivate(): bool
{
return array_key_exists(self::DATA_D, $this->getData());
}
/**
* A key carrying "other prime infos" (RFC 8230, section 4) is exported as a version 0, two-prime RSAPrivateKey in
* which p*q is not the modulus: the PKCS #1 OtherPrimeInfos sequence is not emitted. RS1, RS256, RS384 and RS512
* keep working with such a key only because OpenSSL checks its CRT result against s^e mod n and falls back to
* m^d mod n when the two disagree. RSASSA-PSS does not go through this method and handles the additional primes
* itself.
*
* The DER is built from the octet strings of the key as they are, without ever turning them into numbers. X.690,
* section 8.3 defines the content octets of an ASN.1 INTEGER as the two's complement big-endian representation of
* its value, which for a non-negative integer is its raw big-endian magnitude with a leading 0x00 whenever the
* first bit is set - and RFC 8230, section 4 already stores every parameter of a COSE RSA key in exactly that
* form. Routing them through a big integer library instead would convert each of them to a decimal string and
* back: brick/math falls back to a pure PHP calculator whenever neither ext-gmp nor ext-bcmath is loaded, and its
* generic base conversion is superlinear, so that round trip alone costs seconds of CPU on a large modulus - paid
* on every verification, before OpenSSL sees anything.
*/
public function asPem(): string
{
if ($this->isPrivate()) {
return self::toPem('RSA PRIVATE KEY', self::derSequence(
// RFC 8017, appendix A.1.2: version is 0 for a two-prime key.
self::derInteger("\0"),
self::derInteger($this->n()),
self::derInteger($this->e()),
self::derInteger($this->d()),
self::derInteger($this->p()),
self::derInteger($this->q()),
self::derInteger($this->dP()),
self::derInteger($this->dQ()),
self::derInteger($this->QInv())
));
}
// RFC 5280, section 4.1: SubjectPublicKeyInfo wraps the DER of an RFC 8017 RSAPublicKey in a BIT STRING,
// behind the rsaEncryption algorithm identifier and its mandatory NULL parameters (RFC 3279, section 2.3.1).
$rsaPublicKey = self::derSequence(self::derInteger($this->n()), self::derInteger($this->e()));
return self::toPem('PUBLIC KEY', self::derSequence(
self::derSequence(self::OID_RSA_ENCRYPTION, self::DER_NULL),
self::derBitString($rsaPublicKey)
));
}
public function toPublic(): static
{
$toBeRemoved = [
self::DATA_D,
self::DATA_P,
self::DATA_Q,
self::DATA_DP,
self::DATA_DQ,
self::DATA_QI,
self::DATA_OTHER,
self::DATA_RI,
self::DATA_DI,
self::DATA_TI,
];
$data = $this->getData();
foreach ($data as $k => $v) {
if (in_array($k, $toBeRemoved, true)) {
unset($data[$k]);
}
}
return new static($data);
}
private function checkKeyIsPrivate(): void
{
if (! $this->isPrivate()) {
throw new InvalidArgumentException('The key is not private.');
}
}
/**
* An ASN.1 INTEGER holding the non-negative integer whose big-endian magnitude is $value (X.690, section 8.3).
*/
private static function derInteger(string $value): string
{
$value = ltrim($value, "\0");
if ($value === '') {
// Section 8.3.1: the content octets are never empty, so zero is a single 0x00 octet.
$value = "\0";
} elseif ((ord($value[0]) & 0x80) !== 0) {
// Section 8.3.2: without this octet the value would be read as a negative number.
$value = "\0" . $value;
}
return self::der(0x02, $value);
}
private static function derSequence(string ...$elements): string
{
return self::der(0x30, implode('', $elements));
}
private static function derBitString(string $value): string
{
// X.690, section 8.6.2.2: the leading octet is the number of unused bits of the final octet, none here since
// the value being wrapped is a whole number of octets.
return self::der(0x03, "\0" . $value);
}
private static function der(int $tag, string $content): string
{
$length = strlen($content);
if ($length < 0x80) {
// X.690, section 8.1.3.4: short form.
$encodedLength = pack('C', $length);
} else {
// Section 8.1.3.5: long form, the length itself in the fewest octets that can hold it.
$octets = ltrim(pack('J', $length), "\0");
$encodedLength = pack('C', 0x80 | strlen($octets)) . $octets;
}
return pack('C', $tag) . $encodedLength . $content;
}
private static function toPem(string $type, string $der): string
{
return sprintf(
"-----BEGIN %s-----\n%s\n-----END %s-----",
$type,
trim(chunk_split(base64_encode($der), 64, "\n")),
$type
);
}
}

View file

@ -0,0 +1,260 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use InvalidArgumentException;
use function ltrim;
use function ord;
use function sprintf;
use function strcmp;
use function strlen;
use Throwable;
/**
* Checks an RSA key against the constraints the COSE and WebAuthn algorithm registrations rely on.
*
* RFC 8812 registers the RSA algorithms for WebAuthn and defers to RFC 8230, whose section 6.1 states that "a key
* size of 2048 bits or larger MUST be used with these algorithms" and that implementations "SHOULD be able to encrypt
* and decrypt with modulus between 2048 and 16K bits in length". The public exponent constraints come from RFC 8017,
* section 3.1, which defines it as an odd integer between 3 and n - 1.
*
* Two families of constraints are applied by the RSA algorithms of this library to every key they are given, both
* through Cose\Algorithm\Signature\RSA\RSA and Cose\Algorithm\Signature\RSA\PSSRSA: the public parameter constraints
* of RFC 8017, section 3.1 (checkPublicParameters()), and the upper bounds on the size of the key
* (checkLengthBounds()). Neither depends on a policy - an RSA operation costs an amount of CPU proportional to the
* size of the key it is given, and that key is attacker supplied whenever it comes from the wire.
*
* The *minimum* modulus length is the policy choice, and the algorithms apply it too: each of them runs check() on
* every key it is handed, with the validator it was created with or, by default, with create(). Legacy
* authenticators holding 1024 bit keys exist, so the default bound only emits an E_USER_WARNING in 4.x and will
* throw as of v5.0.0; a validator passed explicitly to the algorithm - RS256::create(RsaKeyValidator::create(
* minimumModulusLength: 1024)) - is enforced with an exception right away, because the caller chose the bound.
*
* Every check below reads the parameters as the octet strings they are. Turning one into a number is a base
* conversion, and brick/math falls back to a pure PHP calculator - whose generic base conversion is superlinear -
* whenever neither ext-gmp nor ext-bcmath is loaded. A validator that runs before every operation must not grow
* expensive with the size of the key it is handed.
*
* @see https://datatracker.ietf.org/doc/html/rfc8812
* @see https://www.rfc-editor.org/rfc/rfc8230#section-6.1
* @see \Cose\Tests\Key\RsaKeyValidatorTest
*/
final class RsaKeyValidator
{
/**
* The smallest modulus length RFC 8230 allows, in bits.
*/
public const MINIMUM_MODULUS_LENGTH = 2048;
/**
* The largest modulus length RFC 8230 expects implementations to cope with, in bits.
*/
public const MAXIMUM_MODULUS_LENGTH = 16384;
/**
* The largest public exponent length any RSA operation of this library accepts, in bits.
*
* FIPS 186-5, appendix A.1.1 requires 2^16 < e < 2^256 of a generated key; RFC 8017, section 3.1 places no upper
* bound at all, which is precisely why one has to be imposed here. The public operation is a modular
* exponentiation whose cost is proportional to the length of the exponent, so an unbounded e is an unbounded
* amount of work: at the largest modulus RFC 8230 asks for, e = n - 2 costs sixty four times as much as this
* bound allows.
*/
public const MAXIMUM_EXPONENT_LENGTH = 256;
/**
* The warning an RSA algorithm emits when the key it is given is rejected by the validator it defaulted to. Its
* only placeholder receives the message of the underlying InvalidArgumentException.
*
* @see \Cose\Algorithm\Signature\RSA\RsaKeyPolicy
*/
public const WEAK_KEY_MESSAGE = 'The RSA key does not satisfy RFC 8230 section 6.1: %s. Accept it explicitly with "RsaKeyValidator::create(minimumModulusLength: 1024)"; as of v5.0.0, it will be rejected with an exception.';
private function __construct(
private readonly int $minimumModulusLength,
private readonly int $maximumModulusLength
) {
if ($minimumModulusLength < 1) {
throw new InvalidArgumentException('The minimum modulus length shall be a positive integer');
}
if ($maximumModulusLength < $minimumModulusLength) {
throw new InvalidArgumentException(
'The maximum modulus length shall be greater than or equal to the minimum modulus length'
);
}
}
public static function create(
int $minimumModulusLength = self::MINIMUM_MODULUS_LENGTH,
int $maximumModulusLength = self::MAXIMUM_MODULUS_LENGTH
): self {
return new self($minimumModulusLength, $maximumModulusLength);
}
/**
* Returns the length of the modulus of the key, in bits.
*/
public static function modulusLength(RsaKey $key): int
{
return self::bitLength($key->n());
}
/**
* Returns the length of the public exponent of the key, in bits.
*/
public static function exponentLength(RsaKey $key): int
{
return self::bitLength($key->e());
}
/**
* The upper bounds on the size of a key that every RSA algorithm of this library applies before it does anything
* with it. They are not a policy the caller opts into: an RSA operation costs an amount of CPU proportional to
* the size of the modulus and of the exponent it is given, both of which are attacker supplied whenever the key
* travels on the wire, and that cost is paid before anything is known about the signature. RFC 8230, section 6.1
* asks for exactly this: "It is highly recommended that checks on the key length be done before starting a
* cryptographic operation."
*
* No minimum is applied here, so that this method never rejects a key an earlier release accepted.
*
* @throws InvalidArgumentException when the key is larger than this library is willing to compute with
*/
public static function checkLengthBounds(RsaKey $key): void
{
self::checkMaximumModulusLength($key, self::MAXIMUM_MODULUS_LENGTH);
self::checkMaximumExponentLength($key);
}
/**
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public function check(RsaKey $key): void
{
$modulusLength = self::modulusLength($key);
if ($modulusLength < $this->minimumModulusLength) {
throw new InvalidArgumentException(sprintf(
'The modulus of the key is %d bits long; at least %d bits are required',
$modulusLength,
$this->minimumModulusLength
));
}
self::checkMaximumModulusLength($key, $this->maximumModulusLength);
self::checkPublicParameters($key);
}
/**
* The constraints RFC 8017, section 3.1 places on the public parameters of an RSA key: an odd modulus and a
* public exponent that is an odd integer between 3 and n - 1. Both primitives of section 5.2 are defined under
* the assumption that the key satisfies them, and none of their guarantees survives a key that does not: with
* e = 1 the public operation is the identity map, so a padded message encoding - data that is entirely public -
* is accepted as a signature of the message it encodes.
*
* Unlike the modulus length bounds, these constraints depend on no policy and admit no legitimate exception,
* which is why the RSA algorithms apply them on their own.
*
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public static function checkPublicParameters(RsaKey $key): void
{
self::checkModulus($key);
self::checkExponent($key);
}
public function isValid(RsaKey $key): bool
{
try {
$this->check($key);
} catch (Throwable) {
return false;
}
return true;
}
/**
* The modulus is the product of at least two odd primes (RFC 8017, section 3.1), hence odd and non-zero. An even
* modulus is not merely out of specification: taking e-th roots modulo a power of two is easy, so a signature
* under an attacker chosen even modulus can be computed without any private key.
*/
private static function checkModulus(RsaKey $key): void
{
$rawModulus = ltrim($key->n(), "\x00");
if ($rawModulus === '') {
throw new InvalidArgumentException('The modulus of the key shall not be zero');
}
if ((ord($rawModulus[strlen($rawModulus) - 1]) & 1) !== 1) {
throw new InvalidArgumentException('The modulus of the key shall be odd');
}
}
private static function checkExponent(RsaKey $key): void
{
$exponent = ltrim($key->e(), "\x00");
if ($exponent === '' || (ord($exponent[strlen($exponent) - 1]) & 1) !== 1) {
throw new InvalidArgumentException('The public exponent of the key shall be odd');
}
if (strlen($exponent) === 1 && ord($exponent[0]) < 3) {
throw new InvalidArgumentException('The public exponent of the key shall be greater than or equal to 3');
}
if (self::compareMagnitudes($exponent, ltrim($key->n(), "\x00")) >= 0) {
throw new InvalidArgumentException('The public exponent of the key shall be lower than its modulus');
}
self::checkMaximumExponentLength($key);
}
private static function checkMaximumModulusLength(RsaKey $key, int $maximumModulusLength): void
{
$modulusLength = self::modulusLength($key);
if ($modulusLength > $maximumModulusLength) {
throw new InvalidArgumentException(sprintf(
'The modulus of the key is %d bits long; at most %d bits are allowed',
$modulusLength,
$maximumModulusLength
));
}
}
private static function checkMaximumExponentLength(RsaKey $key): void
{
$exponentLength = self::exponentLength($key);
if ($exponentLength > self::MAXIMUM_EXPONENT_LENGTH) {
throw new InvalidArgumentException(sprintf(
'The public exponent of the key is %d bits long; at most %d bits are allowed',
$exponentLength,
self::MAXIMUM_EXPONENT_LENGTH
));
}
}
/**
* Compares two non-negative integers given as big-endian octet strings stripped of their leading zero octets: the
* longer one is the larger, and equal lengths are decided octet by octet.
*/
private static function compareMagnitudes(string $left, string $right): int
{
$byLength = strlen($left) <=> strlen($right);
return $byLength === 0 ? strcmp($left, $right) : $byLength;
}
/**
* The length in bits of the non-negative integer whose big-endian octet string is $value.
*/
private static function bitLength(string $value): int
{
$value = ltrim($value, "\x00");
if ($value === '') {
return 0;
}
$length = (strlen($value) - 1) * 8;
for ($mostSignificantByte = ord($value[0]); $mostSignificantByte > 0; $mostSignificantByte >>= 1) {
++$length;
}
return $length;
}
}

View file

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use InvalidArgumentException;
use function is_string;
/**
* A symmetric COSE key (RFC 9053, section 7.3).
*
* Table 21 of that section types the key value `k` as a `bstr`, which is what the k() accessor of this class has
* always returned. The constructor enforces the same contract: a `k` that is not a PHP string, or that is empty, is
* rejected where the mistake is easiest to attribute rather than at the first cryptographic operation.
*
* @see https://www.rfc-editor.org/rfc/rfc9053#section-7.3
* @see \Cose\Tests\Key\SymmetricKeyTest
*
* @final
*/
class SymmetricKey extends Key
{
final public const DATA_K = -1;
/**
* @param array<int|string, mixed> $data
*/
public function __construct(array $data)
{
// The three sibling key classes normalise and store the key type; this one used to cast it inside its own
// comparison only, so a key decoded from CBOR kept the string "4" that every HMAC algorithm then rejected.
$data = self::normalizeIntegerEntries($data, self::TYPE);
parent::__construct($data);
if ($data[self::TYPE] !== self::TYPE_OCT && $data[self::TYPE] !== self::TYPE_NAME_OCT) {
throw new InvalidArgumentException(
'Invalid symmetric key. The key type does not correspond to a symmetric key'
);
}
if (! isset($data[self::DATA_K])) {
throw new InvalidArgumentException('Invalid symmetric key. The parameter "k" is missing');
}
if (! is_string($data[self::DATA_K])) {
throw new InvalidArgumentException(
'Invalid symmetric key. The parameter "k" shall be a byte string (CBOR objects shall be normalized first)'
);
}
if ($data[self::DATA_K] === '') {
throw new InvalidArgumentException('Invalid symmetric key. The parameter "k" is empty');
}
}
/**
* @param array<int|string, mixed> $data
*/
public static function create(array $data): self
{
return new self($data);
}
public function k(): string
{
return $this->get(self::DATA_K);
}
}

View file

@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace Cose\Key;
use InvalidArgumentException;
use function is_string;
use function sprintf;
use function strlen;
use Throwable;
/**
* Checks a symmetric key against the constraints the COSE MAC algorithms rely on.
*
* RFC 9053, section 3.1 requires implementations to "validate that the key type, key length, and algorithm are
* correct and appropriate for the entities involved". The key type and the byte string nature of `k` admit no
* exception and are therefore applied by the algorithms themselves: Cose\Algorithm\Mac\Hmac rejects a key that is
* not symmetric, whose `k` is missing, is not a PHP string, or is empty.
*
* The *minimum* key length is the policy choice, and it stays opt-in, exactly like the minimum modulus length of
* RsaKeyValidator: RFC 2104, section 3 only states that a key shorter than the output of the hash function is
* "strongly discouraged", and existing deployments do key HS384/HS512 with 32 bytes. Run this validator explicitly
* on a key before handing it to an algorithm to turn that discouragement into a hard failure today, instead of the
* E_USER_WARNING the algorithms emit.
*
* @see https://www.rfc-editor.org/rfc/rfc9053#section-3.1
* @see https://www.rfc-editor.org/rfc/rfc2104#section-3
* @see \Cose\Tests\Key\SymmetricKeyValidatorTest
*/
final class SymmetricKeyValidator
{
/**
* The output length of SHA-256, in bytes: the shortest key RFC 2104, section 3 does not discourage for HS256 and
* HS256/64, and the smallest of the three lengths the MAC algorithms of this library use.
*
* Cose\Algorithm\Mac\Hmac::minimumKeyLength() gives the value that matches a given algorithm (32, 48 or 64).
*/
public const MINIMUM_KEY_LENGTH = 32;
private function __construct(
private readonly int $minimumKeyLength
) {
if ($minimumKeyLength < 1) {
throw new InvalidArgumentException('The minimum key length shall be a positive integer');
}
}
public static function create(int $minimumKeyLength = self::MINIMUM_KEY_LENGTH): self
{
return new self($minimumKeyLength);
}
/**
* Returns the length of the key value, in bytes.
*
* @throws InvalidArgumentException when the key is not a usable symmetric key
*/
public static function keyLength(Key $key): int
{
return strlen(self::keyValue($key));
}
/**
* The constraints every MAC algorithm of this library applies on its own: a symmetric key whose `k` is present,
* is a byte string and is not empty. None of them depends on a policy - a `k` that is not a byte string is
* outside RFC 9053, section 7.3, and an empty key makes every tag computable by anyone.
*
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public static function checkKeyValue(Key $key): void
{
self::keyValue($key);
}
/**
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
public function check(Key $key): void
{
$keyLength = strlen(self::keyValue($key));
if ($keyLength < $this->minimumKeyLength) {
throw new InvalidArgumentException(sprintf(
'The key is %d bytes long; at least %d bytes are required',
$keyLength,
$this->minimumKeyLength
));
}
}
public function isValid(Key $key): bool
{
try {
$this->check($key);
} catch (Throwable) {
return false;
}
return true;
}
/**
* @throws InvalidArgumentException when the key does not satisfy the constraints
*/
private static function keyValue(Key $key): string
{
if ($key->type() !== Key::TYPE_OCT && $key->type() !== Key::TYPE_NAME_OCT) {
throw new InvalidArgumentException('Invalid key. Must be of type symmetric');
}
if (! $key->has(SymmetricKey::DATA_K)) {
throw new InvalidArgumentException('Invalid key. The value of the key is missing');
}
$k = $key->get(SymmetricKey::DATA_K);
if (! is_string($k)) {
throw new InvalidArgumentException(
'Invalid key. The value of the key must be a byte string (CBOR objects shall be normalized first)'
);
}
if ($k === '') {
throw new InvalidArgumentException('Invalid key. The value of the key is empty');
}
return $k;
}
}

View file

@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseMac0Tag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Mac0 (RFC 9052, CBOR tag 17).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseMac0Tag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 17 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseMac0Tag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 17;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ByteStringObject $tag;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$tag = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 1 shall be a ByteString object.');
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 3 shall be a ByteString object.');
}
if (! $tag instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac0 object. The item 4 shall be a ByteString object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->tag = $tag;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ByteStringObject $tag
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $payload, $tag]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getTag(): ByteStringObject
{
return $this->tag;
}
}

View file

@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseMacTag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Mac (RFC 9052, CBOR tag 97).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseMacTag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 97 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseMacTag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 97;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ByteStringObject $tag;
private readonly ListObject $recipients;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. No list.');
}
if ($object->count() !== 5) {
throw new InvalidArgumentException('Not a valid CoseMac object. The list shall have 5 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$tag = $object->get(3);
$recipients = $object->get(4);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 1 shall be a ByteString object.');
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 3 shall be a ByteString object.');
}
if (! $tag instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 4 shall be a ByteString object.');
}
if (! $recipients instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseMac object. The item 5 shall be a List object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->tag = $tag;
$this->recipients = $recipients;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ByteStringObject $tag,
ListObject $recipients
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([
$protectedHeaderAsBytesString,
$unprotectedHeader,
$payload,
$tag,
$recipients,
]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getTag(): ByteStringObject
{
return $this->tag;
}
public function getRecipients(): ListObject
{
return $this->recipients;
}
}

View file

@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The MAC_structure of a COSE_Mac0 (RFC 9052 section 6.3).
*
* MAC_structure = [ "MAC0", protected : empty_or_serialized_map, external_aad : bstr, payload : bstr ]
*
* This is what the MAC algorithm authenticates. MACing the payload on its own instead binds the tag neither to the
* protected header -- the algorithm and the key identifier the sender chose -- nor to the message type, so a tag
* computed for a COSE_Mac0 would be accepted for a COSE_Mac and the reverse.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-6.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class Mac0Structure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $payload, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'MAC0';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Cose\Mac;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The MAC_structure of a COSE_Mac (RFC 9052 section 6.3).
*
* MAC_structure = [ "MAC", protected : empty_or_serialized_map, external_aad : bstr, payload : bstr ]
*
* This is what the MAC algorithm authenticates, over the body protected header of the message. The context string
* is the only difference with {@see Mac0Structure}, and it is what keeps a tag computed for a multi-recipient
* COSE_Mac from being accepted on a COSE_Mac0 built over the same header and payload.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-6.3
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class MacStructure extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $payload, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'MAC';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,170 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseSign1Tag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Sign1 (RFC 9052, CBOR tag 18).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseSign1Tag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 18 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseSign1Tag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 18;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ByteStringObject $signature;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseSign1 object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseSign1 object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$signature = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseSign1 object. The item 1 shall be a ByteString object.'
);
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseSign1 object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseSign1 object. The item 3 shall be a ByteString object.'
);
}
if (! $signature instanceof ByteStringObject) {
throw new InvalidArgumentException(
'Not a valid CoseSign1 object. The item 4 shall be a ByteString object.'
);
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->signature = $signature;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ByteStringObject $signature
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $payload, $signature]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getSignature(): ByteStringObject
{
return $this->signature;
}
}

View file

@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\OtherObjectManager;
use CBOR\StringStream;
use CBOR\Tag;
use CBOR\Tag\CoseSignTag as UpstreamTag;
use CBOR\Tag\TagManager;
use const E_USER_DEPRECATED;
use InvalidArgumentException;
use function sprintf;
use function trigger_error;
/**
* A tagged COSE_Sign (RFC 9052, CBOR tag 98).
*
* @deprecated since 4.8.0, use \CBOR\Tag\CoseSignTag from spomky-labs/cbor-php 3.4.0 or later instead. Will be removed
* in 5.0.0.
*
* The six COSE structures were ported upstream in cbor-php 3.4.0, where they share AbstractCoseTag and are
* registered in the default decoder, so Decoder::create() resolves tag 98 on its own. The replacement accepts what
* this class rejects -- a zero-length protected header, a detached (nil) payload, the indefinite-length encodings --
* and reads every item through the list it carries, so its accessors cannot drift from the bytes it serializes.
*
* What does not move upstream is the RFC 9052 layer above the CBOR shape, and that stays here: {@see \Cose\Structure\CoseHeaders}
* for header labels typed as RFC 9052 section 1.5 defines them, and the Sig_structure, MAC_structure and
* Enc_structure builders that a signature or a MAC is actually computed over. Both work on the upstream classes.
*
* Migrating: the class name changes, and the four-argument create() becomes createFromComponents() -- upstream
* create() takes the whole list instead.
*
* @see https://github.com/web-auth/cose-lib/issues/176
* @see \Cose\Tests\Structure\DeprecatedTagClassesTest
*/
final class CoseSignTag extends Tag
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
private const TAG_ID = 98;
private readonly ByteStringObject $protectedHeader;
private readonly MapObject $unprotectedHeader;
private readonly ByteStringObject $payload;
private readonly ListObject $signatures;
public function __construct(int $additionalInformation, ?string $data, CBORObject $object)
{
trigger_error(sprintf(
'The class "%s" is deprecated since 4.8.0 and will be removed in 5.0.0. Use "%s" from spomky-labs/cbor-php 3.4.0 or later instead.',
self::class,
UpstreamTag::class
), E_USER_DEPRECATED);
if (! $object instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. No list.');
}
if ($object->count() !== 4) {
throw new InvalidArgumentException('Not a valid CoseSign object. The list shall have 4 items.');
}
$protectedHeader = $object->get(0);
$unprotectedHeader = $object->get(1);
$payload = $object->get(2);
$signatures = $object->get(3);
if (! $protectedHeader instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 1 shall be a ByteString object.');
}
if (! $unprotectedHeader instanceof MapObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 2 shall be a Map object.');
}
if (! $payload instanceof ByteStringObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 3 shall be a ByteString object.');
}
if (! $signatures instanceof ListObject) {
throw new InvalidArgumentException('Not a valid CoseSign object. The item 4 shall be a List object.');
}
parent::__construct($additionalInformation, $data, $object);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->payload = $payload;
$this->signatures = $signatures;
}
public static function getTagId(): int
{
return self::TAG_ID;
}
public static function createFromLoadedData(int $additionalInformation, ?string $data, CBORObject $object): self
{
return new self($additionalInformation, $data, $object);
}
public static function create(
MapObject $protectedHeader,
MapObject $unprotectedHeader,
ByteStringObject $payload,
ListObject $signatures
): self {
$protectedHeaderAsBytesString = ByteStringObject::create((string) $protectedHeader);
$object = ListObject::create([$protectedHeaderAsBytesString, $unprotectedHeader, $payload, $signatures]);
[$additionalInformation, $data] = self::determineComponents(self::TAG_ID);
return new self($additionalInformation, $data, $object);
}
public function getProtectedHeader(): ByteStringObject
{
return $this->protectedHeader;
}
/**
* The nesting bound only applies to the decoder created here: a caller passing its own $decoder sets its own
* bound, and $maxDepth is then ignored.
*/
public function getProtectedHeaderAsMap(
?Decoder $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$stream = new StringStream($this->protectedHeader->getValue());
$decoder ??= Decoder::create(TagManager::create(), OtherObjectManager::create(), $maxDepth);
$decoded = $decoder->decode($stream);
if (! $decoded instanceof MapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return $decoded;
}
public function getUnprotectedHeader(): MapObject
{
return $this->unprotectedHeader;
}
public function getPayload(): ByteStringObject
{
return $this->payload;
}
public function getSignatures(): ListObject
{
return $this->signatures;
}
}

View file

@ -0,0 +1,136 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\ListObject;
use CBOR\MapObject;
use Cose\Structure\CoseHeaders;
use Cose\Structure\HeaderMapHelper;
use InvalidArgumentException;
/**
* One entry of the "signatures" list of a COSE_Sign (RFC 9052 section 4.1).
*
* COSE_Signature = [ Headers, signature : bstr ]
*
* The raw list a message carries says nothing about what is inside it, and neither cbor-php nor the deprecated
* Cose\Signature\CoseSignTag looks: both accept an empty list and entries of any shape. This view is the checked
* form, and it carries the same header reader as the message, because a signer of a COSE_Sign has a protected
* bucket of its own that its signature commits to.
*
* ```php
* foreach ($message->getSignatures() as $entry) {
* $signer = CoseSignature::create($entry);
* $toBeSigned = Signature::create(
* $message->getProtectedHeader(),
* $signer->getProtectedHeader(),
* $message->getPayload(),
* );
* }
* ```
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.1
* @see \Cose\Tests\Structure\CoseSignatureTest
*/
final class CoseSignature
{
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader;
private readonly MapObject|IndefiniteLengthMapObject $unprotectedHeader;
private readonly ByteStringObject|IndefiniteLengthByteStringObject $signature;
public function __construct(ListObject|IndefiniteLengthListObject $signature)
{
HeaderMapHelper::assertSignatureList(ListObject::create([$signature]));
/** @var ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader */
$protectedHeader = $signature->get(0);
/** @var IndefiniteLengthMapObject|MapObject $unprotectedHeader */
$unprotectedHeader = $signature->get(1);
/** @var ByteStringObject|IndefiniteLengthByteStringObject $signatureValue */
$signatureValue = $signature->get(2);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->signature = $signatureValue;
}
public static function create(ListObject|IndefiniteLengthListObject $signature): self
{
return new self($signature);
}
/**
* Every entry of a "signatures" list, checked and wrapped.
*
* @return list<self>
*/
public static function all(ListObject|IndefiniteLengthListObject $signatures): array
{
HeaderMapHelper::assertSignatureList($signatures);
$result = [];
foreach ($signatures as $signature) {
if (! $signature instanceof ListObject && ! $signature instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('Not a valid COSE_Signature object. It shall be a List object.');
}
$result[] = new self($signature);
}
return $result;
}
/**
* The protected bucket of this signer, as it is carried: what its Sig_structure covers verbatim.
*/
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getUnprotectedHeader(): MapObject|IndefiniteLengthMapObject
{
return $this->unprotectedHeader;
}
/**
* The headers of this signer, read the way RFC 9052 defines them.
*/
public function headers(): CoseHeaders
{
return CoseHeaders::of($this->protectedHeader, $this->unprotectedHeader);
}
public function getProtectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getProtectedHeaderParameter($label);
}
public function getUnprotectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getUnprotectedHeaderParameter($label);
}
public function getSignature(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->signature;
}
/**
* The list this view was built from, rebuilt so that nothing the caller does to it reaches the message.
*/
public function toListObject(): ListObject
{
return ListObject::create([$this->protectedHeader, $this->unprotectedHeader, $this->signature]);
}
}

View file

@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Sig_structure of one signer of a COSE_Sign (RFC 9052 section 4.4).
*
* Sig_structure = [ "Signature", body_protected : empty_or_serialized_map, sign_protected : empty_or_serialized_map,
* external_aad : bstr, payload : bstr ]
*
* The sign_protected field is what tells this structure apart from {@see Signature1}: a signature of a COSE_Sign
* commits to the protected bucket of the message *and* to the one of its own COSE_Signature entry. Without it, a
* per-signer signature would be byte-identical to a COSE_Sign1 signature over the same header and payload.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.4
* @see \Cose\Tests\Structure\CoseStructureTest
*/
final class Signature extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $bodyProtectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $signProtectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $bodyProtectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $signProtectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($bodyProtectedHeader, $signProtectedHeader, $payload, $externalAad);
}
public function getBodyProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->bodyProtectedHeader;
}
public function getSignProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->signProtectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Signature';
}
protected function items(): array
{
return [$this->bodyProtectedHeader, $this->signProtectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Cose\Signature;
use CBOR\ByteStringObject;
use CBOR\IndefiniteLengthByteStringObject;
use Cose\Structure\CoseStructure;
/**
* The Sig_structure of a COSE_Sign1 (RFC 9052 section 4.4).
*
* Sig_structure = [ "Signature1", body_protected : empty_or_serialized_map, external_aad : bstr, payload : bstr ]
*
* The payload is a parameter rather than something read back from the message so that a detached payload -- the nil
* form of RFC 9052 section 4.2 -- is supplied by the application, which is what the RFC requires of it.
*
*
* The fields a decoded message supplies are typed to accept the indefinite-length byte strings the cbor-php
* accessors can hand back, and are kept exactly as they were given: a cryptographic structure has to embed the
* protected bucket byte for byte, or the signature the sender computed over it no longer verifies.
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.4
* @see \Cose\Tests\Signature\CoseSign1CreateAndVerifyTest
*/
final class Signature1 extends CoseStructure
{
private readonly ByteStringObject $externalAad;
public function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
) {
$this->externalAad = $externalAad ?? self::emptyExternalAad();
}
public static function create(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
ByteStringObject|IndefiniteLengthByteStringObject $payload,
?ByteStringObject $externalAad = null
): self {
return new self($protectedHeader, $payload, $externalAad);
}
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getPayload(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->payload;
}
public function getExternalAad(): ByteStringObject
{
return $this->externalAad;
}
protected function context(): string
{
return 'Signature1';
}
protected function items(): array
{
return [$this->protectedHeader, $this->externalAad, $this->payload];
}
}

View file

@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\DecoderInterface;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\MapObject;
use CBOR\Tag\AbstractCoseTag;
/**
* The two header buckets of a COSE message, read the way RFC 9052 defines them.
*
* cbor-php 3.4.0 owns the shape of a COSE message and hands back the buckets as they were encoded. What it does not
* do -- and what a CBOR library has no business doing -- is apply the header rules of RFC 9052 sections 1.5 and 3 on
* top: a label is an integer or a text string and nothing else, the two are distinct even when they normalize to the
* same map offset, a label appears at most once, and the protected bucket holds exactly one CBOR item.
*
* That is what this reads. It works on any COSE message: the upstream classes through fromMessage(), the deprecated
* Cose\...Tag classes and the per-signer or per-recipient entries through of().
*
* ```php
* $message = Decoder::create()->decode(StringStream::create($bytes)); // CBOR\Tag\CoseSign1Tag
* $headers = CoseHeaders::fromMessage($message);
*
* $alg = $headers->getProtectedHeaderParameter(1); // never answered by the text string "1"
* $kid = $headers->getHeaderParameter(4); // protected bucket first
* ```
*
* The protected bucket is decoded once, on first use.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-3
* @see https://github.com/web-auth/cose-lib/issues/166
* @see \Cose\Tests\Structure\CoseHeadersTest
*/
final class CoseHeaders
{
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = HeaderMapHelper::DEFAULT_PROTECTED_HEADER_MAX_DEPTH;
private ?MapObject $decodedProtectedHeader = null;
private function __construct(
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
private readonly MapObject|IndefiniteLengthMapObject $unprotectedHeader,
private readonly ?DecoderInterface $decoder,
private readonly int $maxDepth
) {
}
/**
* The buckets of a COSE message, given as they are carried.
*
* This is the form to use for a per-signer COSE_Signature or a COSE_recipient -- {@see CoseSignature} and
* {@see CoseRecipient} build it for you -- and for the deprecated Cose\...Tag classes.
*/
public static function of(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
MapObject|IndefiniteLengthMapObject $unprotectedHeader,
?DecoderInterface $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): self {
return new self($protectedHeader, $unprotectedHeader, $decoder, $maxDepth);
}
/**
* The buckets of one of the six COSE messages of cbor-php 3.4.0 or later.
*
* The nesting bound only applies to the decoder built when none is given: a caller passing its own $decoder sets
* its own bound, and $maxDepth is then ignored.
*/
public static function fromMessage(
AbstractCoseTag $message,
?DecoderInterface $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): self {
return new self($message->getProtectedHeader(), $message->getUnprotectedHeader(), $decoder, $maxDepth);
}
/**
* The protected bucket as it is carried: the byte string the cryptographic structure covers verbatim.
*/
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
/**
* The protected bucket, decoded and checked: the zero-length byte string of RFC 9052 section 3 is an empty
* header, trailing bytes after the header map are rejected, and every key is a label.
*/
public function getProtectedHeaderAsMap(): MapObject
{
return $this->decodedProtectedHeader ??= HeaderMapHelper::decodeProtected(
$this->protectedHeader,
$this->decoder,
$this->maxDepth
);
}
/**
* The unprotected bucket, with its labels checked.
*/
public function getUnprotectedHeaderAsMap(): MapObject
{
return HeaderMapHelper::assertValidLabels($this->unprotectedHeader);
}
/**
* The unprotected bucket as it is carried.
*/
public function getUnprotectedHeader(): MapObject|IndefiniteLengthMapObject
{
return $this->unprotectedHeader;
}
/**
* The value of a label in the protected bucket, or null when the bucket does not carry it.
*
* The label is matched by type as well as by value, so the integer 1 -- the algorithm -- is never answered by
* the text string "1" or by a byte string that happens to normalize the same way.
*/
public function getProtectedHeaderParameter(int|string $label): ?CBORObject
{
return HeaderMapHelper::findLabel($this->getProtectedHeaderAsMap(), $label);
}
/**
* The value of a label in the unprotected bucket, or null when the bucket does not carry it.
*/
public function getUnprotectedHeaderParameter(int|string $label): ?CBORObject
{
return HeaderMapHelper::findLabel($this->unprotectedHeader, $label);
}
/**
* The value of a label, looked up in the protected bucket first.
*
* A parameter found there is the one the signature or the MAC commits to, so it wins over an unprotected copy of
* the same label. A message carrying a label in both buckets is malformed anyway (RFC 9052 section 3: "The same
* label MUST NOT occur in both buckets"); preferring the protected value keeps the answer on the authenticated
* side of that mistake.
*/
public function getHeaderParameter(int|string $label): ?CBORObject
{
return $this->getProtectedHeaderParameter($label) ?? $this->getUnprotectedHeaderParameter($label);
}
}

View file

@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\OtherObject\NullObject;
use InvalidArgumentException;
use LogicException;
/**
* One entry of the "recipients" list of a COSE_Encrypt or of a COSE_Mac (RFC 9052 sections 5.1 and 6.1).
*
* COSE_recipient = [ Headers, ciphertext : bstr / nil, ? recipients : [+COSE_recipient] ]
*
* The raw list a message carries says nothing about what is inside it, and neither cbor-php nor the deprecated
* Cose\...Tag classes look: both accept an empty list and entries of any shape. This view is the checked form.
*
* A recipient may itself carry recipients, which is how RFC 9052 expresses key layering; getRecipients() walks that
* tree one level at a time and each level is a view of the same kind.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.1
* @see \Cose\Tests\Structure\CoseRecipientTest
*/
final class CoseRecipient
{
private readonly ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader;
private readonly MapObject|IndefiniteLengthMapObject $unprotectedHeader;
private readonly ByteStringObject|IndefiniteLengthByteStringObject|null $ciphertext;
private readonly ListObject|IndefiniteLengthListObject|null $recipients;
public function __construct(ListObject|IndefiniteLengthListObject $recipient)
{
HeaderMapHelper::assertRecipientList(ListObject::create([$recipient]));
/** @var ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader */
$protectedHeader = $recipient->get(0);
/** @var IndefiniteLengthMapObject|MapObject $unprotectedHeader */
$unprotectedHeader = $recipient->get(1);
// assertRecipientList() has just ruled out everything but a byte string and nil at this position.
/** @var ByteStringObject|IndefiniteLengthByteStringObject|null $ciphertext */
$ciphertext = HeaderMapHelper::isNil($recipient->get(2)) ? null : $recipient->get(2);
$this->protectedHeader = $protectedHeader;
$this->unprotectedHeader = $unprotectedHeader;
$this->ciphertext = $ciphertext;
$nested = $recipient->count() === 4 ? $recipient->get(3) : null;
$this->recipients = $nested instanceof ListObject || $nested instanceof IndefiniteLengthListObject
? $nested
: null;
}
public static function create(ListObject|IndefiniteLengthListObject $recipient): self
{
return new self($recipient);
}
/**
* Every entry of a "recipients" list, checked and wrapped.
*
* @return list<self>
*/
public static function all(ListObject|IndefiniteLengthListObject $recipients): array
{
HeaderMapHelper::assertRecipientList($recipients);
$result = [];
foreach ($recipients as $recipient) {
if (! $recipient instanceof ListObject && ! $recipient instanceof IndefiniteLengthListObject) {
throw new InvalidArgumentException('Not a valid COSE_recipient object. It shall be a List object.');
}
$result[] = new self($recipient);
}
return $result;
}
/**
* The protected bucket of this recipient, as it is carried.
*/
public function getProtectedHeader(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->protectedHeader;
}
public function getUnprotectedHeader(): MapObject|IndefiniteLengthMapObject
{
return $this->unprotectedHeader;
}
/**
* The headers of this recipient, read the way RFC 9052 defines them.
*/
public function headers(): CoseHeaders
{
return CoseHeaders::of($this->protectedHeader, $this->unprotectedHeader);
}
public function getProtectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getProtectedHeaderParameter($label);
}
public function getUnprotectedHeaderParameter(int|string $label): ?CBORObject
{
return $this->headers()
->getUnprotectedHeaderParameter($label);
}
/**
* Whether the ciphertext of this recipient travels outside the message.
*/
public function hasDetachedCiphertext(): bool
{
return $this->ciphertext === null;
}
/**
* @throws LogicException when the ciphertext is detached; hasDetachedCiphertext() tells the two cases apart
*/
public function getCiphertext(): ByteStringObject|IndefiniteLengthByteStringObject
{
return $this->ciphertext ?? throw new LogicException(
'The ciphertext of this COSE_recipient is detached (RFC 9052 section 5.1); the application supplies it separately.'
);
}
public function hasRecipients(): bool
{
return $this->recipients !== null;
}
/**
* The recipients nested under this one, empty when it carries none.
*
* @return list<self>
*/
public function getRecipients(): array
{
return $this->recipients === null ? [] : self::all($this->recipients);
}
/**
* The list this view was built from, rebuilt so that nothing the caller does to it reaches the message.
*/
public function toListObject(): ListObject
{
$items = [$this->protectedHeader, $this->unprotectedHeader, $this->ciphertext ?? NullObject::create()];
if ($this->recipients !== null) {
$items[] = $this->recipients;
}
return ListObject::create($items);
}
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\ListObject;
use CBOR\TextStringObject;
use Stringable;
/**
* The shape every RFC 9052 cryptographic structure has: a context string that names what is being computed,
* followed by the fields that structure commits to.
*
* These are the byte strings that are signed, MACed or fed as additional authenticated data -- never the payload on
* its own. Casting an instance to string yields the CBOR encoding to hand to the algorithm.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-4.4
* @see https://www.rfc-editor.org/rfc/rfc9052#section-5.3
* @see https://www.rfc-editor.org/rfc/rfc9052#section-6.3
*/
abstract class CoseStructure implements Stringable
{
/**
* RFC 9052 section 4.4 on external_aad: "If this field is not supplied, it defaults to a zero-length byte
* string."
*/
public static function emptyExternalAad(): ByteStringObject
{
return ByteStringObject::create('');
}
public function __toString(): string
{
return (string) ListObject::create([TextStringObject::create($this->context()), ...$this->items()]);
}
/**
* The context string of this structure, as RFC 9052 spells it.
*/
abstract protected function context(): string;
/**
* The fields following the context, in the order the CDDL gives them.
*
* @return list<CBORObject>
*/
abstract protected function items(): array;
}

View file

@ -0,0 +1,341 @@
<?php
declare(strict_types=1);
namespace Cose\Structure;
use CBOR\ByteStringObject;
use CBOR\CBORObject;
use CBOR\Decoder;
use CBOR\DecoderInterface;
use CBOR\IndefiniteLengthByteStringObject;
use CBOR\IndefiniteLengthListObject;
use CBOR\IndefiniteLengthMapObject;
use CBOR\IndefiniteLengthTextStringObject;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\NegativeIntegerObject;
use CBOR\OtherObject\OtherObjectInterface;
use CBOR\StringStream;
use CBOR\TextStringObject;
use CBOR\UnsignedIntegerObject;
use function in_array;
use InvalidArgumentException;
use function is_int;
use function ord;
use function sprintf;
use function strlen;
/**
* The RFC 9052 rules that sit above the CBOR shape of a COSE message: how a protected bucket is encoded and decoded,
* what a header label may be, which CBOR tag number a message type carries, and the shape of the signature and
* recipient lists.
*
* These are deliberately static functions over plain CBOR objects rather than methods on a message class. Since
* spomky-labs/cbor-php 3.4.0 the six COSE structures live upstream, as CBOR\Tag\CoseSign1Tag and its siblings: that
* library owns the shape of a message, this one owns what RFC 9052 says the shape means. Everything here therefore
* applies to an upstream message, to the deprecated Cose\...Tag classes, and to a header map a caller assembled
* itself.
*
* {@see CoseHeaders} is the ergonomic form of the header half of this: it reads the two buckets of a message once
* and answers label lookups against them.
*
* @see https://www.rfc-editor.org/rfc/rfc9052#section-3
* @see https://www.rfc-editor.org/rfc/rfc9052#section-1.5
* @see https://github.com/web-auth/cose-lib/issues/166
* @see \Cose\Tests\Structure\HeaderMapHelperTest
*/
final class HeaderMapHelper
{
/**
* A COSE header is a flat map of a handful of parameters whose values nest a couple of levels at most, so the
* decoder built when none is given is bounded far below the cbor-php default of 1000: a protected header crafted
* to nest thousands of levels is rejected instead of being walked.
*/
public const DEFAULT_PROTECTED_HEADER_MAX_DEPTH = 32;
/**
* Decode the protected bucket, strictly.
*
* Three RFC 9052 rules the upstream accessor does not apply, in one place:
*
* - Section 3: "Recipients MUST accept both a zero-length byte string and a zero-length map encoded in a byte
* string." The zero-length byte string is the form senders are told to prefer, and decoding it as CBOR yields
* nothing at all, hence the guard before the decoder runs.
* - Section 3 CDDL: "empty_or_serialized_map = bstr .cbor header_map / bstr .size 0". The ".cbor" control of
* RFC 8610 section 3.8.4 carries exactly one data item, so trailing bytes make the bucket malformed.
* - Section 1.5: a key that is neither an integer nor a text string is not a label at all.
*/
public static function decodeProtected(
ByteStringObject|IndefiniteLengthByteStringObject $protectedHeader,
?DecoderInterface $decoder = null,
int $maxDepth = self::DEFAULT_PROTECTED_HEADER_MAX_DEPTH
): MapObject {
$raw = $protectedHeader->getValue();
if ($raw === '') {
return MapObject::create();
}
$stream = new StringStream($raw);
$decoder ??= Decoder::create(null, null, $maxDepth);
$decoded = $decoder->decode($stream);
// cbor-php exposes no end-of-stream predicate, so the probe is a read that has to fail.
$trailing = true;
try {
$stream->read(1);
} catch (InvalidArgumentException) {
$trailing = false;
}
if ($trailing) {
throw new InvalidArgumentException(
'Invalid protected header. The byte string carries trailing data after the header map.'
);
}
if (! $decoded instanceof MapObject && ! $decoded instanceof IndefiniteLengthMapObject) {
throw new InvalidArgumentException('Protected header is not a valid Map object.');
}
return self::assertValidLabels($decoded);
}
/**
* Encode the protected bucket.
*
* RFC 9052 section 3: "Senders SHOULD encode a zero-length map as a zero-length byte string rather than as a
* zero-length map (encoded as h'a0')." Upstream createFromComponents() emits h'a0'; a sender that wants the
* preferred form passes the byte string this returns.
*/
public static function encodeProtected(MapObject|IndefiniteLengthMapObject $protectedHeader): ByteStringObject
{
$checked = self::assertValidLabels($protectedHeader);
return ByteStringObject::create($checked->count() === 0 ? '' : (string) $checked);
}
/**
* Check that every key of a header map is a label and that no label appears twice, and hand back an equivalent
* definite-length map.
*
* RFC 9052 section 1.5: "label = int / tstr" and "the presence a label that is neither a text string nor an
* integer is an error". Section 3: "Labels in each of the maps MUST be unique. When processing messages, if a
* label appears multiple times, the message MUST be rejected as malformed." A byte string key is the case worth
* naming: cbor-php normalizes h'31' to the string "1", so without this check a byte string key would answer a
* lookup for the integer label 1, the algorithm parameter.
*/
public static function assertValidLabels(MapObject|IndefiniteLengthMapObject $header): MapObject
{
$checked = MapObject::create();
foreach ($header as $item) {
$key = $item->getKey();
if (! self::isLabel($key)) {
throw new InvalidArgumentException(sprintf(
'Invalid header label. A label shall be an integer or a text string, got "%s" (RFC 9052 section 1.5).',
$key::class
));
}
$checked->add($key, $item->getValue());
}
return $checked;
}
/**
* Look a label up by value *and* by type.
*
* The map accessors of cbor-php are keyed by the normalized key, and PHP turns the numeric string offset "1"
* into the integer 1, so int 1 and tstr "1" -- two distinct labels for RFC 9052 -- share one offset there. This
* lookup compares the major type as well, which is what makes a lookup for the label 1 mean the algorithm
* parameter and nothing else.
*/
public static function findLabel(MapObject|IndefiniteLengthMapObject $header, int|string $label): ?CBORObject
{
foreach ($header as $item) {
$key = $item->getKey();
$matches = is_int($label)
? ($key instanceof UnsignedIntegerObject || $key instanceof NegativeIntegerObject)
&& $key->normalize() === (string) $label
: ($key instanceof TextStringObject || $key instanceof IndefiniteLengthTextStringObject)
&& $key->normalize() === $label;
if ($matches) {
return $item->getValue();
}
}
return null;
}
/**
* Check that the CBOR tag a message carries is the one its structure claims.
*
* RFC 9052 section 2 maps each message type to one tag number, and the decoder dispatches on that number, so
* this is for the paths that bypass it: a class constructed directly, or createFromLoadedData() called on the
* value of a GenericTag. Neither the upstream classes nor the deprecated ones check it, so a message can
* otherwise keep claiming to be a COSE_Sign1 while serializing as a COSE_Mac0.
*
* The comparison is on the decoded number, not on the raw components, so a non-minimal encoding of the right
* number stays acceptable exactly as it is on the decoder path (RFC 8949 allows it outside deterministic
* encoding).
*/
public static function assertTagNumber(int $additionalInformation, ?string $data, int $expected, string $name): void
{
$number = self::tagNumber($additionalInformation, $data, $name);
if ($number !== $expected) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. Expected the CBOR tag %d, got %d.',
$name,
$expected,
$number
));
}
}
/**
* Check a "signatures" list against "signatures : [+ COSE_Signature]" and "COSE_Signature = [ Headers,
* signature : bstr ]" (RFC 9052 section 4.1), Headers being the protected byte string and the unprotected map.
*/
public static function assertSignatureList(ListObject|IndefiniteLengthListObject $signatures): void
{
if ($signatures->count() === 0) {
throw new InvalidArgumentException(
'Not a valid CoseSign object. The signatures list shall hold at least one COSE_Signature (RFC 9052 section 4.1).'
);
}
foreach ($signatures as $signature) {
if (! self::isList($signature)
|| $signature->count() !== 3
|| ! self::isByteString($signature->get(0))
|| ! self::isMap($signature->get(1))
|| ! self::isByteString($signature->get(2))
) {
throw new InvalidArgumentException(
'Not a valid CoseSign object. Each signature shall be a COSE_Signature [bstr, map, bstr].'
);
}
}
}
/**
* Check a "recipients" list against "recipients : [+COSE_recipient]" and "COSE_recipient = [ Headers,
* ciphertext : bstr / nil, ? recipients : [+COSE_recipient] ]" (RFC 9052 section 5.1).
*
* The nested list is walked with the same rule, which is what bounds a recipient tree to well-formed levels
* rather than to whatever the decoder happened to accept.
*/
public static function assertRecipientList(
ListObject|IndefiniteLengthListObject $recipients,
string $name = 'COSE_recipient'
): void {
if ($recipients->count() === 0) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The recipients list shall hold at least one COSE_recipient (RFC 9052 section 5.1).',
$name
));
}
foreach ($recipients as $recipient) {
if (! self::isList($recipient)
|| ! in_array($recipient->count(), [3, 4], true)
|| ! self::isByteString($recipient->get(0))
|| ! self::isMap($recipient->get(1))
|| ! (self::isByteString($recipient->get(2)) || self::isNil($recipient->get(2)))
) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. Each recipient shall be a COSE_recipient [bstr, map, bstr / nil, ? [+ COSE_recipient]].',
$name
));
}
if ($recipient->count() === 4) {
$nested = $recipient->get(3);
if (! self::isList($nested)) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The nested recipients of a COSE_recipient shall be a List object.',
$name
));
}
self::assertRecipientList($nested, $name);
}
}
}
/**
* Whether an item is the CBOR "nil" simple value, which is how RFC 9052 spells detached content.
*
* The decoder maps simple value 22 to NullObject only when the caller's OtherObjectManager knows that class; an
* empty manager yields a GenericObject carrying the same head. Both are nil on the wire, so both are nil here.
*/
public static function isNil(CBORObject $object): bool
{
return $object instanceof OtherObjectInterface
&& $object->getAdditionalInformation() === CBORObject::OBJECT_NULL;
}
/**
* @phpstan-assert-if-true IndefiniteLengthListObject|ListObject $object
*/
private static function isList(CBORObject $object): bool
{
return $object instanceof ListObject || $object instanceof IndefiniteLengthListObject;
}
private static function isMap(CBORObject $object): bool
{
return $object instanceof MapObject || $object instanceof IndefiniteLengthMapObject;
}
private static function isByteString(CBORObject $object): bool
{
return $object instanceof ByteStringObject || $object instanceof IndefiniteLengthByteStringObject;
}
private static function isLabel(CBORObject $key): bool
{
return $key instanceof UnsignedIntegerObject
|| $key instanceof NegativeIntegerObject
|| $key instanceof TextStringObject
|| $key instanceof IndefiniteLengthTextStringObject;
}
/**
* A tag number is the argument of a major type 6 head: the additional information carries it directly below 24,
* and announces its width above.
*/
private static function tagNumber(int $additionalInformation, ?string $data, string $name): int
{
if ($additionalInformation < 24) {
return $additionalInformation;
}
$width = match ($additionalInformation) {
CBORObject::LENGTH_1_BYTE => 1,
CBORObject::LENGTH_2_BYTES => 2,
CBORObject::LENGTH_4_BYTES => 4,
CBORObject::LENGTH_8_BYTES => 8,
default => throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The additional information %d is not a valid CBOR tag head.',
$name,
$additionalInformation
)),
};
if ($data === null || strlen($data) !== $width) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The CBOR tag head announces %d byte(s) of tag number.',
$name,
$width
));
}
$number = 0;
for ($i = 0; $i < $width; ++$i) {
$number = ($number << 8) | ord($data[$i]);
}
if ($number < 0) {
throw new InvalidArgumentException(sprintf(
'Not a valid %s object. The CBOR tag number exceeds the platform integer range.',
$name
));
}
return $number;
}
}

21
vendor/web-auth/webauthn-lib/LICENSE vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018-2022 Spomky-Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,57 @@
{
"name": "web-auth/webauthn-lib",
"type": "library",
"license": "MIT",
"description": "FIDO2/Webauthn Support For PHP",
"keywords": [
"FIDO",
"FIDO2",
"webauthn"
],
"homepage": "https://github.com/web-auth",
"authors": [
{
"name": "Florent Morselli",
"homepage": "https://github.com/Spomky"
},
{
"name": "All contributors",
"homepage": "https://github.com/web-auth/webauthn-library/contributors"
}
],
"require": {
"php": ">=8.2",
"ext-json": "*",
"ext-openssl": "*",
"paragonie/constant_time_encoding": "^2.6|^3.0",
"phpdocumentor/reflection-docblock": "^5.3|^6.0",
"psr/clock": "^1.0",
"psr/event-dispatcher": "^1.0",
"psr/log": "^1.0|^2.0|^3.0",
"spomky-labs/cbor-php": "^3.4",
"symfony/clock": "^6.4|^7.0|^8.0",
"symfony/uid": "^6.4|^7.0|^8.0",
"spomky-labs/pki-framework": "^1.0",
"symfony/property-info": "^6.4|^7.0|^8.0",
"symfony/property-access": "^6.4|^7.0|^8.0",
"symfony/serializer": "^6.4|^7.0|^8.0",
"symfony/deprecation-contracts": "^3.2",
"web-auth/cose-lib": "^4.8"
},
"autoload": {
"psr-4": {
"Webauthn\\": "src/"
}
},
"extra": {
"thanks": {
"name": "web-auth/webauthn-framework",
"url": "https://github.com/web-auth/webauthn-framework"
}
},
"suggest": {
"psr/log-implementation": "Recommended to receive logs from the library",
"symfony/event-dispatcher": "Recommended to use dispatched events",
"web-token/jwt-library": "Mandatory for fetching Metadata Statement from distant sources"
}
}

View file

@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function array_merge;
use CBOR\Decoder;
use CBOR\Normalizable;
use Cose\Algorithms;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use function count;
use function in_array;
use function openssl_verify;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitTagging;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use function sprintf;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class AndroidKeyAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_ANDROID = '1.3.6.1.4.1.11129.2.1.17';
/**
* Tags of the AuthorizationList members that are inspected during the verification procedure.
*
* @see https://source.android.com/docs/security/features/keystore/attestation#schema
*/
private const ANDROID_TAG_PURPOSE = 1;
private const ANDROID_TAG_ALL_APPLICATIONS = 600;
private const ANDROID_TAG_ORIGIN = 702;
private const KM_PURPOSE_SIGN = 2;
private const KM_ORIGIN_GENERATED = 0;
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'android-key';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create($attestation);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
foreach (['sig', 'x5c', 'alg'] as $key) {
array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('The attestation statement value "%s" is missing.', $key)
);
}
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
(is_countable($certificates) ? count(
$certificates
) : 0) > 0 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createBasic(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid trust path. Shall contain certificates.'
);
$certificates = $trustPath->certificates;
// Decode leaf attestation certificate
$leaf = $certificates[0];
$this->checkCertificate($leaf, $clientDataJSONHash, $authenticatorData);
$signedData = $authenticatorData->authData . $clientDataJSONHash;
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$alg = (int) $algRaw;
/** @var string $sig */
$sig = $attestationStatement->get('sig');
return openssl_verify($signedData, $sig, $leaf, Algorithms::getOpensslAlgorithmFor($alg)) === 1;
}
/**
* @see https://www.w3.org/TR/webauthn-3/#sctn-android-key-attestation
*/
private function checkCertificate(
string $certificate,
string $clientDataHash,
AuthenticatorData $authenticatorData
): void {
// Check that authData publicKey matches the public key in the attestation certificate
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential data found'
);
$publicKeyData = $attestedCredentialData->credentialPublicKey;
$publicKeyData !== null || throw AttestationStatementVerificationException::create(
'No attested public key found'
);
$publicDataStream = new StringStream($publicKeyData);
$coseKey = $this->decoder->decode($publicDataStream);
$coseKey instanceof Normalizable || throw AttestationStatementVerificationException::create(
'Invalid attested public key found'
);
$publicDataStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key data. Presence of extra bytes.'
);
$publicDataStream->close();
/** @var array<int, mixed> $coseKeyData */
$coseKeyData = $coseKey->normalize();
$publicKey = Key::createFromData($coseKeyData);
($publicKey instanceof Ec2Key) || ($publicKey instanceof RsaKey) || throw AttestationStatementVerificationException::create(
'Unsupported key type'
);
/* --------------------------- */
/**
* @see https://w3c.github.io/webauthn/#sctn-key-attstn-cert-requirements
* @see https://source.android.com/docs/security/features/keystore/attestation#attestation-certificate
*/
$cert = Certificate::fromPEM(PEM::fromString($certificate));
// We check the attested key corresponds to the key in the certificate
PEM::fromString($publicKey->asPEM())->string() === $cert->tbsCertificate()
->subjectPublicKeyInfo()
->toPEM()
->string() || throw AttestationStatementVerificationException::create('Invalid key');
$extensions = $cert->tbsCertificate()
->extensions();
// Find Android KeyStore Extension with OID self::OID_ANDROID in certificate extensions
$extensions->has(self::OID_ANDROID) || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_ANDROID . '" is missing'
);
/** @var UnknownExtension $androidExtension */
$androidExtension = $extensions->get(self::OID_ANDROID);
/**
* Parse the Android extension value structure
* @see https://source.android.com/docs/security/features/keystore/attestation#attestation-extension
*/
$extensionAsAsn1 = Sequence::fromDER($androidExtension->extensionValue());
// Check that attestationChallenge is set to the clientDataHash.
$extensionAsAsn1->has(4) || throw AttestationStatementVerificationException::create(
'The attestationChallenge field is missing'
);
$ext = $extensionAsAsn1->at(4)
->asElement();
$ext instanceof OctetString || throw AttestationStatementVerificationException::create(
'The attestationChallenge field must be an OctetString'
);
$clientDataHash === $ext->string() || throw AttestationStatementVerificationException::create(
'The client data hash is not valid'
);
// Check that both teeEnforced and softwareEnforced structures don't contain allApplications(600) tag.
$extensionAsAsn1->has(6) || throw AttestationStatementVerificationException::create(
'The softwareEnforced field is missing'
);
$softwareEnforcedFlags = $extensionAsAsn1->at(6)
->asElement();
$softwareEnforcedFlags instanceof Sequence || throw AttestationStatementVerificationException::create(
'The softwareEnforced field must be a Sequence'
);
$this->checkAbsenceOfAllApplicationsTag($softwareEnforcedFlags);
$extensionAsAsn1->has(7) || throw AttestationStatementVerificationException::create(
'The teeEnforced field is missing'
);
$teeEnforcedFlags = $extensionAsAsn1->at(7)
->asElement();
$teeEnforcedFlags instanceof Sequence || throw AttestationStatementVerificationException::create(
'The teeEnforced field must be a Sequence'
);
$this->checkAbsenceOfAllApplicationsTag($teeEnforcedFlags);
$this->checkKeyOriginAndPurpose($softwareEnforcedFlags, $teeEnforcedFlags);
}
/**
* The union of both authorization lists is used, which is what the specification mandates unless the Relying Party
* decides to accept keys from a trusted execution environment only.
*
* @see https://w3c.github.io/webauthn/#sctn-android-key-attestation
*/
private function checkKeyOriginAndPurpose(Sequence $softwareEnforced, Sequence $teeEnforced): void
{
$origins = [];
$purposes = [];
foreach ([$softwareEnforced, $teeEnforced] as $authorizationList) {
$origin = $this->findOrigin($authorizationList);
if ($origin !== null) {
$origins[] = $origin;
}
$purposes = array_merge($purposes, $this->findPurposes($authorizationList));
}
$origins !== [] || throw AttestationStatementVerificationException::create(
'The origin field is missing from the authorization lists'
);
foreach ($origins as $origin) {
$origin === self::KM_ORIGIN_GENERATED || throw AttestationStatementVerificationException::create(
'The key was not generated by the authenticator'
);
}
$purposes !== [] || throw AttestationStatementVerificationException::create(
'The purpose field is missing from the authorization lists'
);
in_array(self::KM_PURPOSE_SIGN, $purposes, true) || throw AttestationStatementVerificationException::create(
'The key is not allowed to sign'
);
}
private function findOrigin(Sequence $authorizationList): null|int
{
$element = $this->findTaggedElement($authorizationList, self::ANDROID_TAG_ORIGIN);
if ($element === null) {
return null;
}
return $element->explicit()
->asInteger()
->intNumber();
}
/**
* @return list<int>
*/
private function findPurposes(Sequence $authorizationList): array
{
$element = $this->findTaggedElement($authorizationList, self::ANDROID_TAG_PURPOSE);
if ($element === null) {
return [];
}
$purposes = [];
foreach ($element->explicit()->asSet()->elements() as $purpose) {
$purposes[] = $purpose->asInteger()
->intNumber();
}
return $purposes;
}
private function findTaggedElement(Sequence $authorizationList, int $tag): null|ExplicitTagging
{
foreach ($authorizationList->elements() as $item) {
$element = $item->asElement();
$element instanceof ExplicitTagging || throw AttestationStatementVerificationException::create(
'Invalid tag'
);
if ($element->tag() === $tag) {
return $element;
}
}
return null;
}
private function checkAbsenceOfAllApplicationsTag(Sequence $sequence): void
{
foreach ($sequence->elements() as $tag) {
$element = $tag->asElement();
$element instanceof ExplicitTagging || throw AttestationStatementVerificationException::create(
'Invalid tag'
);
$element->tag() !== self::ANDROID_TAG_ALL_APPLICATIONS || throw AttestationStatementVerificationException::create(
'The allApplications tag (' . self::ANDROID_TAG_ALL_APPLICATIONS . ') is forbidden - key must be bound to specific application'
);
}
}
}

View file

@ -0,0 +1,198 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\Normalizable;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use function count;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitTagging;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class AppleAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_APPLE = '1.2.840.113635.100.8.2';
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'apple';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
array_key_exists('x5c', $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" is missing.'
);
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
(is_countable($certificates) ? count(
$certificates
) : 0) > 0 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createAnonymizationCA(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid trust path'
);
$certificates = $trustPath->certificates;
// Decode leaf attestation certificate
$leaf = $certificates[0];
$this->checkCertificateAndGetPublicKey($leaf, $clientDataJSONHash, $authenticatorData);
return true;
}
/**
* @see https://www.w3.org/TR/webauthn-3/#sctn-apple-anonymous-attestation
*/
private function checkCertificateAndGetPublicKey(
string $certificate,
string $clientDataHash,
AuthenticatorData $authenticatorData
): void {
// Check that authData publicKey matches the public key in the attestation certificate
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential data found'
);
$publicKeyData = $attestedCredentialData->credentialPublicKey;
$publicKeyData !== null || throw AttestationStatementVerificationException::create(
'No attested public key found'
);
$publicDataStream = new StringStream($publicKeyData);
$coseKey = $this->decoder->decode($publicDataStream);
$coseKey instanceof Normalizable || throw AttestationStatementVerificationException::create(
'Invalid attested public key found'
);
$publicDataStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key data. Presence of extra bytes.'
);
$publicDataStream->close();
/** @var array<int, mixed> $coseKeyData */
$coseKeyData = $coseKey->normalize();
$publicKey = Key::createFromData($coseKeyData);
($publicKey instanceof Ec2Key) || ($publicKey instanceof RsaKey) || throw AttestationStatementVerificationException::create(
'Unsupported key type'
);
/* --------------------------- */
$cert = Certificate::fromPEM(PEM::fromString($certificate));
// We check the attested key corresponds to the key in the certificate
PEM::fromString($publicKey->asPEM())->string() === $cert->tbsCertificate()
->subjectPublicKeyInfo()
->toPEM()
->string() || throw AttestationStatementVerificationException::create('Invalid key');
$extensions = $cert->tbsCertificate()
->extensions();
// Find Apple Extension with OID "1.2.840.113635.100.8.2" in certificate extensions
$extensions->has(self::OID_APPLE) || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is missing'
);
/** @var UnknownExtension $appleExtension */
$appleExtension = $extensions->get(self::OID_APPLE);
$extensionSequence = Sequence::fromDER($appleExtension->extensionValue());
$extensionSequence->has(0) || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is message'
);
$firstExtension = $extensionSequence->at(0);
$firstExtension->isTagged() || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is invalid'
);
$taggedExtension = $firstExtension->asTagged()
->asElement();
$taggedExtension instanceof ExplicitTagging || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is invalid'
);
$explicitExtension = $taggedExtension->explicit()
->asElement();
$explicitExtension instanceof OctetString || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is invalid'
);
$extensionData = $explicitExtension->string();
$nonceToHash = $authenticatorData->authData . $clientDataHash;
$nonce = hash('sha256', $nonceToHash, true);
hash_equals($nonce, $extensionData) || throw AttestationStatementVerificationException::create(
'The client data hash is not valid'
);
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use Webauthn\AuthenticatorData;
use Webauthn\MetadataService\Statement\MetadataStatement;
class AttestationObject
{
public ?MetadataStatement $metadataStatement = null;
public function __construct(
public readonly string $rawAttestationObject,
public AttestationStatement $attStmt,
public readonly AuthenticatorData $authData
) {
}
public static function create(
string $rawAttestationObject,
AttestationStatement $attStmt,
AuthenticatorData $authData
): self {
return new self($rawAttestationObject, $attStmt, $authData);
}
}

View file

@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\Normalizable;
use function is_array;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Throwable;
use Webauthn\AuthenticatorDataLoader;
use Webauthn\Event\AttestationObjectLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\InvalidDataException;
use Webauthn\MetadataService\CanLogData;
use Webauthn\StringStream;
use Webauthn\Util\Base64;
class AttestationObjectLoader implements CanDispatchEvents, CanLogData
{
private LoggerInterface $logger;
private EventDispatcherInterface $dispatcher;
public function __construct(
private readonly AttestationStatementSupportManager $attestationStatementSupportManager
) {
$this->logger = new NullLogger();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(AttestationStatementSupportManager $attestationStatementSupportManager): self
{
return new self($attestationStatementSupportManager);
}
public function load(string $data): AttestationObject
{
try {
$this->logger->info('Trying to load the data', [
'data' => $data,
]);
$decodedData = Base64::decode($data);
$stream = new StringStream($decodedData);
$parsed = Decoder::create()->decode($stream);
$this->logger->info('Loading the Attestation Statement');
$parsed instanceof Normalizable || throw InvalidDataException::create(
$parsed,
'Invalid attestation object. Unexpected object.'
);
$attestationObject = $parsed->normalize();
$stream->isEOF() || throw InvalidDataException::create(
null,
'Invalid attestation object. Presence of extra bytes.'
);
$stream->close();
is_array($attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
array_key_exists('authData', $attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
array_key_exists('fmt', $attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
array_key_exists('attStmt', $attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
/** @var array{fmt: string, authData: string, attStmt: array<string, mixed>} $attestationObject */
$attestationStatementSupport = $this->attestationStatementSupportManager->get($attestationObject['fmt']);
$attestationStatement = $attestationStatementSupport->load($attestationObject);
$this->logger->info('Attestation Statement loaded');
$this->logger->debug('Attestation Statement loaded', [
'attestationStatement' => $attestationStatement,
]);
$authData = $attestationObject['authData'];
$authDataLoader = AuthenticatorDataLoader::create();
$authenticatorData = $authDataLoader->load($authData);
$attestationObject = AttestationObject::create($data, $attestationStatement, $authenticatorData);
$this->logger->info('Attestation Object loaded');
$this->logger->debug('Attestation Object', [
'ed' => $attestationObject,
]);
$this->dispatcher->dispatch(AttestationObjectLoaded::create($attestationObject));
return $attestationObject;
} catch (Throwable $throwable) {
$this->logger->error('An error occurred', [
'exception' => $throwable,
]);
throw $throwable;
}
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
}

View file

@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function sprintf;
use Webauthn\Exception\InvalidDataException;
use Webauthn\TrustPath\TrustPath;
class AttestationStatement
{
final public const TYPE_NONE = 'none';
final public const TYPE_BASIC = 'basic';
final public const TYPE_SELF = 'self';
final public const TYPE_ATTCA = 'attca';
final public const TYPE_ANONCA = 'anonca';
/**
* @param array<string, mixed> $attStmt
*/
public function __construct(
public readonly string $fmt,
public readonly array $attStmt,
public readonly string $type,
public readonly TrustPath $trustPath
) {
}
/**
* @param array<string, mixed> $attStmt
*/
public static function create(string $fmt, array $attStmt, string $type, TrustPath $trustPath): self
{
return new self($fmt, $attStmt, $type, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createNone(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_NONE, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createBasic(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_BASIC, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createSelf(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_SELF, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createAttCA(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_ATTCA, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createAnonymizationCA(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_ANONCA, $trustPath);
}
public function has(string $key): bool
{
return array_key_exists($key, $this->attStmt);
}
public function get(string $key): mixed
{
$this->has($key) || throw InvalidDataException::create($this->attStmt, sprintf(
'The attestation statement has no key "%s".',
$key
));
return $this->attStmt[$key];
}
}

View file

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use Webauthn\AuthenticatorData;
interface AttestationStatementSupport
{
public function name(): string;
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement;
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool;
}

View file

@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function sprintf;
use Webauthn\Exception\InvalidDataException;
class AttestationStatementSupportManager
{
/**
* @param AttestationStatementSupport[] $attestationStatementSupports
*/
public function __construct(
private array $attestationStatementSupports = []
) {
$this->add(new NoneAttestationStatementSupport());
foreach ($attestationStatementSupports as $attestationStatementSupport) {
if ($attestationStatementSupport instanceof AttestationStatementSupportManagerAwareInterface) {
$attestationStatementSupport->setAttestationStatementSupportManager($this);
}
$this->add($attestationStatementSupport);
}
}
/**
* @param AttestationStatementSupport[] $attestationStatementSupports
*/
public static function create(array $attestationStatementSupports = []): self
{
return new self($attestationStatementSupports);
}
public function add(AttestationStatementSupport $attestationStatementSupport): void
{
$this->attestationStatementSupports[$attestationStatementSupport->name()] = $attestationStatementSupport;
}
public function has(string $name): bool
{
return array_key_exists($name, $this->attestationStatementSupports);
}
public function get(string $name): AttestationStatementSupport
{
$this->has($name) || throw InvalidDataException::create($name, sprintf(
'The attestation statement format "%s" is not supported.',
$name
));
return $this->attestationStatementSupports[$name];
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
interface AttestationStatementSupportManagerAwareInterface
{
public function setAttestationStatementSupportManager(AttestationStatementSupportManager $manager): void;
}

View file

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
trait AttestationStatementSupportManagerAwareTrait
{
private AttestationStatementSupportManager $attestationStatementSupportManager;
public function setAttestationStatementSupportManager(AttestationStatementSupportManager $manager): void
{
$this->attestationStatementSupportManager = $manager;
}
}

View file

@ -0,0 +1,223 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function count;
use InvalidArgumentException;
use function is_array;
use Psr\EventDispatcher\EventDispatcherInterface;
use function sprintf;
use Throwable;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidDataException;
use Webauthn\TrustPath\EmptyTrustPath;
/**
* Compound Attestation Statement Support
*
* Supports the "compound" attestation format as defined in WebAuthn Level 3
* @see https://w3c.github.io/webauthn/#sctn-compound-attestation
*
* The compound format allows multiple attestation statements of different formats
* to be included together. This is useful for hybrid authenticators or scenarios
* where multiple attestation proofs are needed.
*/
final class CompoundAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents, AttestationStatementSupportManagerAwareInterface
{
use AttestationStatementSupportManagerAwareTrait;
private const ATTESTATION_TYPE_TRUST_ORDER = [
AttestationStatement::TYPE_ATTCA,
AttestationStatement::TYPE_ANONCA,
AttestationStatement::TYPE_BASIC,
AttestationStatement::TYPE_SELF,
AttestationStatement::TYPE_NONE,
];
private EventDispatcherInterface $dispatcher;
private ?float $ratio = 1.0;
private ?int $minimum = null;
public function __construct()
{
$this->dispatcher = new NullEventDispatcher();
$this->attestationStatementSupportManager = AttestationStatementSupportManager::create();
}
public function setMinimum(int $minimum): void
{
$this->checkRules(null, $minimum);
$this->minimum = $minimum;
$this->ratio = null;
}
public function setRatio(float $ratio): void
{
$this->checkRules($ratio, null);
$this->ratio = $ratio;
$this->minimum = null;
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'compound';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create($attestation);
is_array($attestation['attStmt']) || throw AttestationStatementLoadingException::create($attestation);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
$loadedAttestations = [];
foreach ($attStmt as $index => $nestedAttestationObject) {
is_array($nestedAttestationObject) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('Attestation at index %s must be an array.', (string) $index)
);
array_key_exists('fmt', $nestedAttestationObject) || throw InvalidDataException::create(
$nestedAttestationObject,
'Invalid attestation object'
);
/** @var string $fmt */
$fmt = $nestedAttestationObject['fmt'];
$fmt !== 'compound' || throw InvalidDataException::create(
$nestedAttestationObject,
'Compound attestation object in a compound attestation is not allowed.'
);
array_key_exists('attStmt', $nestedAttestationObject) || throw InvalidDataException::create(
$nestedAttestationObject,
'Invalid attestation object'
);
$this->attestationStatementSupportManager->has($fmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('Unsupported attestation format "%s" at index %s.', $fmt, (string) $index)
);
/** @var array<string, mixed> $nestedAttestationObject */
$attestationStatementSupport = $this->attestationStatementSupportManager->get($fmt);
$loadedAttestations[] = $attestationStatementSupport->load($nestedAttestationObject);
}
/** @var string $compoundFmt */
$compoundFmt = $attestation['fmt'];
$attestationType = $this->deriveAttestationType($loadedAttestations);
// Create a compound attestation statement with compound trust path
$attestationStatement = AttestationStatement::create(
$compoundFmt,
$loadedAttestations,
$attestationType,
EmptyTrustPath::create()
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
count($attestationStatement->attStmt) > 1 || throw AttestationStatementVerificationException::create(
'Compound attestation must contain at least two attestations.'
);
// Verify all nested attestations
$countValid = 0;
$total = count($attestationStatement->attStmt);
foreach ($attestationStatement->attStmt as $nestedAttestationObject) {
/** @var AttestationStatement $nestedAttestationObject */
$attestationStatementSupport = $this->attestationStatementSupportManager->get(
$nestedAttestationObject->fmt
);
try {
$isValid = $attestationStatementSupport->isValid(
$clientDataJSONHash,
$nestedAttestationObject,
$authenticatorData
);
if ($isValid) {
$countValid++;
}
} catch (Throwable) {
// Nothing to do
}
}
if ($this->minimum !== null) {
return $countValid >= $this->minimum;
}
return $countValid / $total >= $this->ratio;
}
/**
* Derives the compound attestation type from the nested attestation types
* by selecting the weakest (least trusted) type among them.
*
* @param array<AttestationStatement> $loadedAttestations
*/
private function deriveAttestationType(array $loadedAttestations): string
{
$weakest = 0;
foreach ($loadedAttestations as $stmt) {
$index = array_search($stmt->type, self::ATTESTATION_TYPE_TRUST_ORDER, true);
if ($index === false) {
return AttestationStatement::TYPE_NONE;
}
if ($index > $weakest) {
$weakest = $index;
}
}
return self::ATTESTATION_TYPE_TRUST_ORDER[$weakest];
}
private function checkRules(?float $ratio, ?int $minimum): void
{
if ($ratio !== null && ($ratio <= 0 || $ratio > 1)) {
throw new InvalidArgumentException('The ratio must be greater than 0 and less than or equal to 1.');
}
if ($minimum !== null && $minimum <= 1) {
throw new InvalidArgumentException('The minimum must be greater than 1.');
}
if ($ratio !== null && $minimum !== null) {
throw new InvalidArgumentException('You cannot define both ratio and minimum at the same time.');
}
if ($ratio === null && $minimum === null) {
throw new InvalidArgumentException('You must define either ratio or minimum.');
}
}
}

View file

@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\MapObject;
use Cose\Key\Ec2Key;
use function count;
use function is_array;
use const OPENSSL_ALGO_SHA256;
use function openssl_pkey_get_public;
use function openssl_verify;
use OpenSSLAsymmetricKey;
use Psr\EventDispatcher\EventDispatcherInterface;
use function sprintf;
use Throwable;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class FidoU2FAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'fido-u2f';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
foreach (['sig', 'x5c'] as $key) {
array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('The attestation statement value "%s" is missing.', $key)
);
}
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
is_array($certificates) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with one certificate.'
);
count($certificates) === 1 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with one certificate.'
);
reset($certificates);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
$this->checkCertificate($certificates[0]);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createBasic(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$authenticatorData->attestedCredentialData
?->aaguid
->__toString() === '00000000-0000-0000-0000-000000000000' || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid AAGUID for fido-u2f attestation statement. Shall be "00000000-0000-0000-0000-000000000000"'
);
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid trust path'
);
$dataToVerify = "\0";
$dataToVerify .= $authenticatorData->rpIdHash;
$dataToVerify .= $clientDataJSONHash;
$dataToVerify .= $authenticatorData->attestedCredentialData
->credentialId;
$dataToVerify .= $this->extractPublicKey($authenticatorData->attestedCredentialData->credentialPublicKey);
/** @var string $sig */
$sig = $attestationStatement->get('sig');
return openssl_verify($dataToVerify, $sig, $trustPath->certificates[0], OPENSSL_ALGO_SHA256) === 1;
}
private function extractPublicKey(?string $publicKey): string
{
$publicKey !== null || throw AttestationStatementVerificationException::create(
'The attested credential data does not contain a valid public key.'
);
$publicKeyStream = new StringStream($publicKey);
$coseKey = $this->decoder->decode($publicKeyStream);
$publicKeyStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key. Presence of extra bytes.'
);
$publicKeyStream->close();
$coseKey instanceof MapObject || throw AttestationStatementVerificationException::create(
'The attested credential data does not contain a valid public key.'
);
$coseKey = $coseKey->normalize();
$ec2Key = new Ec2Key($coseKey + [
Ec2Key::TYPE => 2,
Ec2Key::DATA_CURVE => Ec2Key::CURVE_P256,
]);
return "\x04" . $ec2Key->x() . $ec2Key->y();
}
private function checkCertificate(string $publicKey): void
{
try {
$resource = openssl_pkey_get_public($publicKey);
$resource !== false || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
/** @var OpenSSLAsymmetricKey $resource */
$details = openssl_pkey_get_details($resource);
} catch (Throwable $throwable) {
throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain',
$throwable
);
}
is_array($details) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
array_key_exists('ec', $details) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
/** @var array<string, mixed> $ec */
$ec = $details['ec'];
array_key_exists('curve_name', $ec) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
$ec['curve_name'] === 'prime256v1' || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
array_key_exists('curve_oid', $ec) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
$ec['curve_oid'] === '1.2.840.10045.3.1.7' || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
}
}

View file

@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function count;
use function is_array;
use function is_string;
use Psr\EventDispatcher\EventDispatcherInterface;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\TrustPath\EmptyTrustPath;
final class NoneAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'none';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
$format = $attestation['fmt'] ?? null;
$attestationStatement = $attestation['attStmt'] ?? [];
(is_string($format) && $format !== '') || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
(is_array(
$attestationStatement
) && $attestationStatement === []) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
$attestationStatement = AttestationStatement::createNone(
$format,
$attestationStatement,
EmptyTrustPath::create()
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
return count($attestationStatement->attStmt) === 0;
}
}

View file

@ -0,0 +1,305 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\MapObject;
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\Signature;
use Cose\Algorithms;
use Cose\Key\Key;
use function count;
use function is_array;
use function is_string;
use function openssl_verify;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X501\ASN1\AttributeType;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use SpomkyLabs\Pki\X509\Certificate\TBSCertificate;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\Exception\InvalidDataException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
use Webauthn\TrustPath\EmptyTrustPath;
use Webauthn\Util\CoseSignatureFixer;
final class PackedAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_FIDO_GEN_CE_AAGUID = '1.3.6.1.4.1.45724.1.1.4';
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct(
private readonly Manager $algorithmManager
) {
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(Manager $algorithmManager): self
{
return new self($algorithmManager);
}
public function name(): string
{
return 'packed';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
array_key_exists('sig', $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "sig" is missing.'
);
array_key_exists('alg', $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "alg" is missing.'
);
is_string($attStmt['sig']) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "sig" is missing.'
);
return match (true) {
array_key_exists('x5c', $attStmt) => $this->loadBasicType($attestation),
default => $this->loadEmptyType($attestation),
};
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
return match (true) {
$trustPath instanceof CertificateTrustPath => $this->processWithCertificate(
$clientDataJSONHash,
$attestationStatement,
$authenticatorData,
$trustPath
),
$trustPath instanceof EmptyTrustPath => $this->processWithSelfAttestation(
$clientDataJSONHash,
$attestationStatement,
$authenticatorData
),
default => throw InvalidAttestationStatementException::create(
$attestationStatement,
'Unsupported attestation statement'
),
};
}
/**
* @param mixed[] $attestation
*/
private function loadBasicType(array $attestation): AttestationStatement
{
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
is_array($certificates) || throw AttestationStatementVerificationException::create(
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
count($certificates) > 0 || throw AttestationStatementVerificationException::create(
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createBasic(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
/**
* @param mixed[] $attestation
*/
private function loadEmptyType(array $attestation): AttestationStatement
{
/** @var string $fmt */
$fmt = $attestation['fmt'];
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
$attestationStatement = AttestationStatement::createSelf($fmt, $attStmt, EmptyTrustPath::create());
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
// https://www.w3.org/TR/webauthn-3/#sctn-packed-attestation-cert-requirements
private function checkCertificate(string $attestnCert, AuthenticatorData $authenticatorData): void
{
$certificate = Certificate::fromPEM(PEM::fromString($attestnCert));
$tbsCertificate = $certificate->tbsCertificate();
// Check version (X.509 version 3 is encoded as 2)
$tbsCertificate->version() === TBSCertificate::VERSION_3 || throw AttestationStatementVerificationException::create(
'Invalid certificate version'
);
// Check subject field
$subject = $tbsCertificate->subject();
$subject->countOfType(
AttributeType::OID_COUNTRY_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-C must be set');
$subject->countOfType(
AttributeType::OID_ORGANIZATION_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-O must be set');
$subject->countOfType(
AttributeType::OID_ORGANIZATIONAL_UNIT_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-OU must be set');
$subject->countOfType(
AttributeType::OID_COMMON_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-CN must be set');
$ouValue = $subject->firstValueOf('OU')
->stringValue();
$ouValue === 'Authenticator Attestation' || throw AttestationStatementVerificationException::create(
'Invalid certificate name. The Subject Organization Unit must be "Authenticator Attestation"'
);
// Check extensions
$extensions = $tbsCertificate->extensions();
// Check certificate is not a CA cert
$extensions->hasBasicConstraints() || throw AttestationStatementVerificationException::create(
'The Basic Constraints extension must have the CA component set to false'
);
! $extensions->basicConstraints()
->isCA() || throw AttestationStatementVerificationException::create(
'The Basic Constraints extension must have the CA component set to false'
);
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential available'
);
// id-fido-gen-ce-aaguid OID check
if ($extensions->has(self::OID_FIDO_GEN_CE_AAGUID)) {
/** @var UnknownExtension $aaguidExtension */
$aaguidExtension = $extensions->get(self::OID_FIDO_GEN_CE_AAGUID);
! $aaguidExtension->isCritical() || throw AttestationStatementVerificationException::create(
'Extension ' . self::OID_FIDO_GEN_CE_AAGUID . ' must not be marked as critical'
);
$aaguidElement = UnspecifiedType::fromDER($aaguidExtension->extensionValue())->asElement();
$aaguidElement instanceof OctetString || throw AttestationStatementVerificationException::create(
'Invalid ' . self::OID_FIDO_GEN_CE_AAGUID . ' extension format'
);
$aaguidValue = $aaguidElement->string();
hash_equals(
$attestedCredentialData->aaguid
->toBinary(),
$aaguidValue
) || throw AttestationStatementVerificationException::create(
'The value of the "aaguid" does not match with the certificate extension ' . self::OID_FIDO_GEN_CE_AAGUID
);
}
}
private function processWithCertificate(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData,
CertificateTrustPath $trustPath
): bool {
$certificates = $trustPath->certificates;
// Check leaf certificate
$this->checkCertificate($certificates[0], $authenticatorData);
// Get the COSE algorithm identifier and the corresponding OpenSSL one
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$coseAlgorithmIdentifier = (int) $algRaw;
$opensslAlgorithmIdentifier = Algorithms::getOpensslAlgorithmFor($coseAlgorithmIdentifier);
// Verification of the signature
$signedData = $authenticatorData->authData . $clientDataJSONHash;
/** @var string $sig */
$sig = $attestationStatement->get('sig');
$result = openssl_verify($signedData, $sig, $certificates[0], $opensslAlgorithmIdentifier);
return $result === 1;
}
private function processWithSelfAttestation(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential available'
);
$credentialPublicKey = $attestedCredentialData->credentialPublicKey;
$credentialPublicKey !== null || throw AttestationStatementVerificationException::create(
'No credential public key available'
);
$publicKeyStream = new StringStream($credentialPublicKey);
$publicKey = $this->decoder->decode($publicKeyStream);
$publicKeyStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key. Presence of extra bytes.'
);
$publicKeyStream->close();
$publicKey instanceof MapObject || throw AttestationStatementVerificationException::create(
'The attested credential data does not contain a valid public key.'
);
$publicKey = $publicKey->normalize();
$publicKey = new Key($publicKey);
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$alg = (int) $algRaw;
$publicKey->alg() === $alg || throw AttestationStatementVerificationException::create(
'The algorithm of the attestation statement and the key are not identical.'
);
$dataToVerify = $authenticatorData->authData . $clientDataJSONHash;
$algorithm = $this->algorithmManager->get($alg);
if (! $algorithm instanceof Signature) {
throw InvalidDataException::create($algorithm, 'Invalid algorithm');
}
/** @var string $sigForFix */
$sigForFix = $attestationStatement->get('sig');
$signature = CoseSignatureFixer::fix($sigForFix, $algorithm);
return $algorithm->verify($dataToVerify, $publicKey, $signature);
}
}

View file

@ -0,0 +1,461 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\MapObject;
use Cose\Algorithms;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use Cose\Key\OkpKey;
use Cose\Key\RsaKey;
use function count;
use DateTimeImmutable;
use function openssl_verify;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Psr\Clock\ClockInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use SpomkyLabs\Pki\X509\Certificate\TBSCertificate;
use function sprintf;
use Symfony\Component\Clock\NativeClock;
use function unpack;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class TPMAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_FIDO_GEN_CE_AAGUID = '1.3.6.1.4.1.45724.1.1.4';
private const OID_AIK_CERTIFICATE = '2.23.133.8.3';
private EventDispatcherInterface $dispatcher;
private readonly ClockInterface $clock;
public function __construct(null|ClockInterface $clock = null)
{
$this->clock = $clock ?? new NativeClock();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(null|ClockInterface $clock = null): self
{
return new self($clock);
}
public function name(): string
{
return 'tpm';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
foreach (['ver', 'ver', 'sig', 'alg', 'certInfo', 'pubArea'] as $key) {
array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('The attestation statement value "%s" is missing.', $key)
);
}
$attStmt['ver'] === '2.0' || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var string $certInfoData */
$certInfoData = $attStmt['certInfo'];
$certInfo = $this->checkCertInfo($certInfoData);
bin2hex($certInfo['type']) === '8017' || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var string $pubAreaData */
$pubAreaData = $attStmt['pubArea'];
$pubArea = $this->checkPubArea($pubAreaData);
$pubAreaAttestedNameAlg = substr($certInfo['attestedName'], 0, 2);
/** @var string $pubAreaRaw */
$pubAreaRaw = $attStmt['pubArea'];
$pubAreaHash = hash($this->getTPMHash($pubAreaAttestedNameAlg), $pubAreaRaw, true);
$attestedName = $pubAreaAttestedNameAlg . $pubAreaHash;
$attestedName === $certInfo['attestedName'] || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attested name'
);
$attStmt['parsedCertInfo'] = $certInfo;
$attStmt['parsedPubArea'] = $pubArea;
/** @var array<string> $x5c */
$x5c = $attStmt['x5c'];
$certificates = CertificateToolbox::convertAllDERToPEM($x5c);
count($certificates) > 0 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$attestationStatement = AttestationStatement::createAttCA(
$this->name(),
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$attToBeSigned = $authenticatorData->authData . $clientDataJSONHash;
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$alg = (int) $algRaw;
$attToBeSignedHash = hash(Algorithms::getHashAlgorithmFor($alg), $attToBeSigned, true);
/** @var array{extraData: string} $parsedCertInfo */
$parsedCertInfo = $attestationStatement->get('parsedCertInfo');
$parsedCertInfo['extraData'] === $attToBeSignedHash || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid attestation hash'
);
$credentialPublicKey = $authenticatorData->attestedCredentialData?->credentialPublicKey;
$credentialPublicKey !== null || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Not credential public key available in the attested credential data'
);
/** @var array{unique: string} $parsedPubArea */
$parsedPubArea = $attestationStatement->get('parsedPubArea');
$this->checkUniquePublicKey($parsedPubArea['unique'], $credentialPublicKey);
return match (true) {
$attestationStatement->trustPath instanceof CertificateTrustPath => $this->processWithCertificate(
$attestationStatement,
$authenticatorData
),
default => throw InvalidAttestationStatementException::create(
$attestationStatement,
'Unsupported attestation statement'
),
};
}
private function checkUniquePublicKey(string $unique, string $cborPublicKey): void
{
$cborDecoder = Decoder::create();
$publicKey = $cborDecoder->decode(new StringStream($cborPublicKey));
$publicKey instanceof MapObject || throw AttestationStatementVerificationException::create(
'Invalid public key'
);
$key = Key::create($publicKey->normalize());
switch ($key->type()) {
case Key::TYPE_OKP:
$uniqueFromKey = (new OkpKey($key->getData()))->x();
break;
case Key::TYPE_EC2:
$ec2Key = new Ec2Key($key->getData());
$uniqueFromKey = "\x04" . $ec2Key->x() . $ec2Key->y();
break;
case Key::TYPE_RSA:
$uniqueFromKey = (new RsaKey($key->getData()))->n();
break;
default:
throw AttestationStatementVerificationException::create('Invalid or unsupported key type.');
}
$unique === $uniqueFromKey || throw AttestationStatementVerificationException::create(
'Invalid pubArea.unique value'
);
}
/**
* @return mixed[]
*/
/**
* @return array{magic: string, type: string, qualifiedSigner: string, extraData: string, clockInfo: string, firmwareVersion: string, attestedName: string, attestedQualifiedName: string}
*/
private function checkCertInfo(string $data): array
{
$certInfo = new StringStream($data);
$magic = $certInfo->read(4);
bin2hex($magic) === 'ff544347' || throw AttestationStatementVerificationException::create(
'Invalid attestation object'
);
$type = $certInfo->read(2);
/** @var array{1: int} $qualifiedSignerLengthData */
$qualifiedSignerLengthData = unpack('n', $certInfo->read(2));
$qualifiedSigner = $certInfo->read($qualifiedSignerLengthData[1]); // Ignored
/** @var array{1: int} $extraDataLengthData */
$extraDataLengthData = unpack('n', $certInfo->read(2));
$extraData = $certInfo->read($extraDataLengthData[1]);
$clockInfo = $certInfo->read(17); // Ignore
$firmwareVersion = $certInfo->read(8);
/** @var array{1: int} $attestedNameLengthData */
$attestedNameLengthData = unpack('n', $certInfo->read(2));
$attestedName = $certInfo->read($attestedNameLengthData[1]);
/** @var array{1: int} $attestedQualifiedNameLengthData */
$attestedQualifiedNameLengthData = unpack('n', $certInfo->read(2));
$attestedQualifiedName = $certInfo->read($attestedQualifiedNameLengthData[1]); // Ignore
$certInfo->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid certificate information. Presence of extra bytes.'
);
$certInfo->close();
return [
'magic' => $magic,
'type' => $type,
'qualifiedSigner' => $qualifiedSigner,
'extraData' => $extraData,
'clockInfo' => $clockInfo,
'firmwareVersion' => $firmwareVersion,
'attestedName' => $attestedName,
'attestedQualifiedName' => $attestedQualifiedName,
];
}
/**
* @return mixed[]
*/
private function checkPubArea(string $data): array
{
$pubArea = new StringStream($data);
$type = $pubArea->read(2);
$nameAlg = $pubArea->read(2);
$objectAttributes = $pubArea->read(4);
/** @var array{1: int} $authPolicyLengthData */
$authPolicyLengthData = unpack('n', $pubArea->read(2));
$authPolicy = $pubArea->read($authPolicyLengthData[1]);
$parameters = $this->getParameters($type, $pubArea);
$unique = $this->getUnique($type, $pubArea);
$pubArea->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public area. Presence of extra bytes.'
);
$pubArea->close();
return [
'type' => $type,
'nameAlg' => $nameAlg,
'objectAttributes' => $objectAttributes,
'authPolicy' => $authPolicy,
'parameters' => $parameters,
'unique' => $unique,
];
}
/**
* @return mixed[]
*/
private function getParameters(string $type, StringStream $stream): array
{
return match (bin2hex($type)) {
'0001' => $this->getRsaParameters($stream),
'0023' => [
'symmetric' => $stream->read(2),
'scheme' => $stream->read(2),
'curveId' => $stream->read(2),
'kdf' => $stream->read(2),
],
default => throw AttestationStatementVerificationException::create('Unsupported type'),
};
}
private function getUnique(string $type, StringStream $stream): string
{
switch (bin2hex($type)) {
case '0001':
/** @var array{1: int} $uniqueLengthData */
$uniqueLengthData = unpack('n', $stream->read(2));
return $stream->read($uniqueLengthData[1]);
case '0023':
/** @var array{1: int} $xLenData */
$xLenData = unpack('n', $stream->read(2));
$x = $stream->read($xLenData[1]);
/** @var array{1: int} $yLenData */
$yLenData = unpack('n', $stream->read(2));
$y = $stream->read($yLenData[1]);
return "\04" . $x . $y;
default:
throw AttestationStatementVerificationException::create('Unsupported type');
}
}
/**
* @return array{symmetric: string, scheme: string, keyBits: int, exponent: string}
*/
private function getRsaParameters(StringStream $stream): array
{
$symmetric = $stream->read(2);
$scheme = $stream->read(2);
/** @var array{1: int} $keyBitsData */
$keyBitsData = unpack('n', $stream->read(2));
return [
'symmetric' => $symmetric,
'scheme' => $scheme,
'keyBits' => $keyBitsData[1],
'exponent' => $this->getExponent($stream->read(4)),
];
}
private function getExponent(string $exponent): string
{
return bin2hex($exponent) === '00000000' ? Base64UrlSafe::decodeNoPadding('AQAB') : $exponent;
}
private function getTPMHash(string $nameAlg): string
{
return match (bin2hex($nameAlg)) {
'0004' => 'sha1',
'000b' => 'sha256',
'000c' => 'sha384',
'000d' => 'sha512',
default => throw AttestationStatementVerificationException::create('Unsupported hash algorithm'),
};
}
private function processWithCertificate(
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw AttestationStatementVerificationException::create(
'Invalid trust path'
);
$certificates = $trustPath->certificates;
// Check certificate CA chain and returns the Attestation Certificate
$this->checkCertificate($certificates[0], $authenticatorData);
// Get the COSE algorithm identifier and the corresponding OpenSSL one
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$coseAlgorithmIdentifier = (int) $algRaw;
$opensslAlgorithmIdentifier = Algorithms::getOpensslAlgorithmFor($coseAlgorithmIdentifier);
/** @var string $certInfo */
$certInfo = $attestationStatement->get('certInfo');
/** @var string $sig */
$sig = $attestationStatement->get('sig');
$result = openssl_verify($certInfo, $sig, $certificates[0], $opensslAlgorithmIdentifier);
return $result === 1;
}
// https://www.w3.org/TR/webauthn-3/#sctn-tpm-cert-requirements
private function checkCertificate(string $attestnCert, AuthenticatorData $authenticatorData): void
{
$certificate = Certificate::fromPEM(PEM::fromString($attestnCert));
$tbsCertificate = $certificate->tbsCertificate();
// Version MUST be set to 3 (X.509 version 3 is encoded as 2)
$tbsCertificate->version() === TBSCertificate::VERSION_3 || throw AttestationStatementVerificationException::create(
'Invalid certificate version'
);
// Subject field MUST be set to empty
$tbsCertificate->subject()
->count() === 0 || throw AttestationStatementVerificationException::create(
'Invalid certificate name. The Subject should be empty'
);
// Check period of validity
$validity = $tbsCertificate->validity();
$startDate = DateTimeImmutable::createFromInterface($validity->notBefore()->dateTime());
$startDate < $this->clock->now() || throw AttestationStatementVerificationException::create(
'Invalid certificate start date.'
);
$endDate = DateTimeImmutable::createFromInterface($validity->notAfter()->dateTime());
$endDate > $this->clock->now() || throw AttestationStatementVerificationException::create(
'Invalid certificate end date.'
);
// Check extensions
$extensions = $tbsCertificate->extensions();
// Check Subject Alternative Name extension
$extensions->hasSubjectAlternativeName() || throw AttestationStatementVerificationException::create(
'The Subject Alternative Name extension must be set'
);
// Check Extended Key Usage extension MUST contain the OID 2.23.133.8.3
$extensions->hasExtendedKeyUsage() || throw AttestationStatementVerificationException::create(
'The Extended Key Usage extensions must contain ' . self::OID_AIK_CERTIFICATE,
);
$extendedKeyUsage = $extensions->extendedKeyUsage();
$extendedKeyUsage->has(self::OID_AIK_CERTIFICATE) || throw AttestationStatementVerificationException::create(
'The Extended Key Usage extensions must contain ' . self::OID_AIK_CERTIFICATE,
);
// The Basic Constraints extension MUST have the CA component set to false.
$extensions->basicConstraints()
->isCA() === false || throw AttestationStatementVerificationException::create(
'The Basic Constraints extension must have the CA component set to false'
);
// id-fido-gen-ce-aaguid OID check
if ($extensions->has(self::OID_FIDO_GEN_CE_AAGUID)) {
/** @var UnknownExtension $aaguidExtension */
$aaguidExtension = $extensions->get(self::OID_FIDO_GEN_CE_AAGUID);
$aaguidElement = UnspecifiedType::fromDER($aaguidExtension->extensionValue())->asElement();
$aaguidElement instanceof OctetString || throw AttestationStatementVerificationException::create(
'Invalid ' . self::OID_FIDO_GEN_CE_AAGUID . ' extension format'
);
$aaguidValue = $aaguidElement->string();
hash_equals(
$authenticatorData->attestedCredentialData
?->aaguid
->toBinary() ?? '',
$aaguidValue
) || throw AttestationStatementVerificationException::create(
'The value of the "aaguid" does not match with the certificate'
);
}
}
}

View file

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use Symfony\Component\Uid\Uuid;
/**
* @see https://www.w3.org/TR/webauthn/#sec-attested-credential-data
*/
class AttestedCredentialData
{
public function __construct(
public Uuid $aaguid,
public readonly string $credentialId,
public readonly ?string $credentialPublicKey
) {
}
public static function create(Uuid $aaguid, string $credentialId, ?string $credentialPublicKey = null): self
{
return new self($aaguid, $credentialId, $credentialPublicKey);
}
}

View file

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
final class AppIdExcludeInputExtension extends AuthenticationExtension
{
public static function enable(string $value): AuthenticationExtension
{
return self::create('appidExclude', $value);
}
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
final class AppIdInputExtension extends AuthenticationExtension
{
public static function enable(): AuthenticationExtension
{
return self::create('appid', true);
}
public static function disable(): AuthenticationExtension
{
return self::create('appid', false);
}
}

View file

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
class AuthenticationExtension
{
public function __construct(
public readonly string $name,
public readonly mixed $value
) {
}
public static function create(string $name, mixed $value): self
{
return new self($name, $value);
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
use CBOR\CBORObject;
use CBOR\MapObject;
use Webauthn\Exception\AuthenticationExtensionException;
abstract class AuthenticationExtensionLoader
{
public static function load(CBORObject $object): AuthenticationExtensions
{
$object instanceof MapObject || throw AuthenticationExtensionException::create('Invalid extension object');
/** @var array<string, mixed> $data */
$data = $object->normalize();
return AuthenticationExtensions::create(
array_map(
fn (mixed $value, string $key) => AuthenticationExtension::create($key, $value),
$data,
array_keys($data)
)
);
}
}

View file

@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
use function array_key_exists;
use ArrayAccess;
use ArrayIterator;
use function count;
use const COUNT_NORMAL;
use Countable;
use function is_string;
use Iterator;
use IteratorAggregate;
use function sprintf;
use Webauthn\Exception\AuthenticationExtensionException;
/**
* @implements IteratorAggregate<string, AuthenticationExtension>
* @implements ArrayAccess<string, AuthenticationExtension>
*/
final class AuthenticationExtensions implements Countable, IteratorAggregate, ArrayAccess
{
/**
* @var array<string, AuthenticationExtension>
*/
public array $extensions;
/**
* @param array<array-key, mixed|AuthenticationExtension> $extensions
*/
public function __construct(array $extensions = [])
{
$list = [];
foreach ($extensions as $key => $extension) {
if ($extension instanceof AuthenticationExtension) {
$list[$extension->name] = $extension;
continue;
}
if (is_string($key)) {
$list[$key] = AuthenticationExtension::create($key, $extension);
continue;
}
throw new AuthenticationExtensionException('Invalid extension');
}
$this->extensions = $list;
}
/**
* @param array<array-key, AuthenticationExtension> $extensions
*/
public static function create(array $extensions = []): static
{
return new static($extensions);
}
public function has(string $key): bool
{
return array_key_exists($key, $this->extensions);
}
public function get(string $key): AuthenticationExtension
{
$this->has($key) || throw AuthenticationExtensionException::create(sprintf(
'The extension with key "%s" is not available',
$key
));
return $this->extensions[$key];
}
/**
* @return Iterator<string, AuthenticationExtension>
*/
public function getIterator(): Iterator
{
return new ArrayIterator($this->extensions);
}
/**
* @param 0|1 $mode
*/
public function count(int $mode = COUNT_NORMAL): int
{
return count($this->extensions, $mode);
}
public function offsetExists(mixed $offset): bool
{
return array_key_exists($offset, $this->extensions);
}
public function offsetGet(mixed $offset): AuthenticationExtension
{
return $this->extensions[$offset];
}
public function offsetSet(mixed $offset, mixed $value): void
{
if ($value === null) {
return;
}
if ($value instanceof AuthenticationExtension) {
$this->extensions[$value->name] = $value;
return;
}
if (is_string($offset)) {
$this->extensions[$offset] = AuthenticationExtension::create($offset, $value);
return;
}
throw new AuthenticationExtensionException('Invalid extension');
}
public function offsetUnset(mixed $offset): void
{
unset($this->extensions[$offset]);
}
}

Some files were not shown because too many files have changed in this diff Show more