/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { asError, Bytes, Crypto, Diagnostic, EcdsaSignature, ImplementationError, InternalError, MaybePromise, PublicKey, } from "@matter/general"; import { MATTER_EPOCH_OFFSET_S, VendorId } from "@matter/types"; import { TlvAttestation } from "../common/OperationalCredentialsTypes.js"; import { DclCertificateService } from "../dcl/DclCertificateService.js"; import { CommissioningError } from "../peer/CommissioningError.js"; import { Dac, Paa, Pai } from "./kinds/AttestationCertificates.js"; import { mayIssue } from "./kinds/CertificateSignature.js"; import { CertificationDeclaration } from "./kinds/CertificationDeclaration.js"; import { CertificationType } from "./kinds/definitions/certification-declaration.js"; /** Reasons a device attestation validation can fail or produce warnings. */ export enum DeviceAttestationCheck { PaaNotTrusted = "PaaNotTrusted", CertificateChainInvalid = "CertificateChainInvalid", CertificateExpired = "CertificateExpired", VendorIdMismatch = "VendorIdMismatch", AttestationSignatureInvalid = "AttestationSignatureInvalid", AttestationNonceMismatch = "AttestationNonceMismatch", CertificationDeclarationSignatureInvalid = "CertificationDeclarationSignatureInvalid", CertificationDeclarationFieldMismatch = "CertificationDeclarationFieldMismatch", CertificateRevoked = "CertificateRevoked", FirmwareInfoMismatch = "FirmwareInfoMismatch", CertificationTypeProvisional = "CertificationTypeProvisional", CertificationTypeTest = "CertificationTypeTest", CertificateIdNotVerified = "CertificateIdNotVerified", CertificateUnparseable = "CertificateUnparseable", AttestationElementsUnparseable = "AttestationElementsUnparseable", CertificationDeclarationUnparseable = "CertificationDeclarationUnparseable", CdSignerVerificationSkipped = "CdSignerVerificationSkipped", PaaTrustStoreTimeMismatch = "PaaTrustStoreTimeMismatch", DclServiceUnavailable = "DclServiceUnavailable", TrustedAsTestCertificate = "TrustedAsTestCertificate", /** An unexpected error during validation (e.g. an unrecoverably corrupt trust-store certificate). */ ValidationError = "ValidationError", } /** A single finding from the attestation validation process. */ export interface AttestationFinding { /** Severity. "error" aborts validation unless the check is recoverable (collected instead). */ level: "error" | "warning" | "info"; /** The specific check that produced this finding. */ type: DeviceAttestationCheck; /** Human-readable description. */ message: string; } /** Error thrown when device attestation validation encounters a hard failure. */ export class DeviceAttestationError extends CommissioningError { constructor( readonly failure: DeviceAttestationCheck, message: string, options?: ErrorOptions, ) { super(message, options); } } /** * Decode a value the peer supplied, reporting malformed input as an attestation failure rather than letting a decoder * error escape. */ function parsePeerValue(check: DeviceAttestationCheck, description: string, parse: () => T): T { try { return parse(); } catch (cause) { // A defect of ours is not the peer's malformed data and must not be reported as such if (cause instanceof InternalError || cause instanceof ImplementationError) { throw cause; } throw new DeviceAttestationError(check, `${description}: ${asError(cause).message}`, { cause }); } } /** Parse an attestation certificate the peer supplied, rejecting a missing certificate before the decoder sees it. */ function parsePeerCertificate(kind: string, der: Bytes, parse: (der: Bytes) => T): T { if (Bytes.of(der).byteLength === 0) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateUnparseable, `Device returned an empty ${kind} certificate`, ); } return parsePeerValue( DeviceAttestationCheck.CertificateUnparseable, `Device returned a ${kind} certificate that cannot be parsed`, () => parse(der), ); } function idHex(id?: number) { return id === undefined ? "undefined" : `0x${Diagnostic.hex(id, 4).toUpperCase()}`; } export namespace DeviceAttestationValidator { export interface Context { crypto: Crypto; attestationChallenge: Bytes; /** * DclCertificateService for PAA trust store, chain validation, revocation checks, and * CD signer lookup. When absent, DCL-dependent checks are skipped (PAA lookup, chain * verification, revocation, CD signature) but local checks still run (nonce, signature, * VendorID, CD fields). */ dclCertificateService?: DclCertificateService; } export interface DeviceAttestationData { dac: Bytes; pai: Bytes; attestationElements: Bytes; attestationSignature: Bytes; attestationNonce: Bytes; vendorId: VendorId; productId: number; } /** Result of a successful validation, including any non-fatal findings. */ export interface ValidationResult { dacPublicKey: ReturnType; findings: AttestationFinding[]; } /** * Controls behavior when attestation findings occur. * - `true`: always proceed (warnings/info logged) * - `false`: reject on any finding * - `undefined`: backward-compatible accept with logging * - function: receives all findings; may * - return `true` to proceed * - return `false` to reject with the underlying error (the original * {@link DeviceAttestationError} on hard-failure findings, or a fresh * {@link CommissioningError} on collected-finding rejection) * - return a `string` to reject with a new {@link CommissioningError} whose message is * that string and whose `cause` is the underlying error * - throw any error to reject by rethrowing that error verbatim (no wrapping) */ export type OnAttestationFailure = boolean | ((findings: AttestationFinding[]) => MaybePromise); /** * Validates device attestation per Matter spec Section 6.2.3.1. * * Local checks (nonce, signature, VendorID, CD fields) always run. DCL-dependent checks * (PAA trust store, chain verification, revocation) only run when dclCertificateService * is provided. * * Most error-level failures throw immediately via {@link DeviceAttestationError}. A small * set of recoverable error cases (currently {@link DeviceAttestationCheck.TrustedAsTestCertificate}) * are collected in `findings` so the caller can decide via `onFailure` whether to proceed. * Warning and info findings are always collected. */ export async function validate(context: Context, data: DeviceAttestationData): Promise { const { crypto, dclCertificateService } = context; const findings = new Array(); // Step 1: Parse DAC and PAI from DER const dac = parsePeerCertificate("DAC", data.dac, der => Dac.fromAsn1(der)); const pai = parsePeerCertificate("PAI", data.pai, der => Pai.fromAsn1(der)); // === Local checks (always run, no DCL needed) === // Step 4 (local part): VendorID matching — DAC vendorId must match PAI vendorId if (dac.cert.subject.vendorId !== pai.cert.subject.vendorId) { throw new DeviceAttestationError( DeviceAttestationCheck.VendorIdMismatch, `DAC vendorId ${idHex(dac.cert.subject.vendorId)} does not match PAI vendorId ${idHex(pai.cert.subject.vendorId)}`, ); } // Step 6: AttestationNonce match const attestationInfo = parsePeerValue( DeviceAttestationCheck.AttestationElementsUnparseable, "Device returned attestation elements that cannot be decoded", () => TlvAttestation.decode(data.attestationElements), ); if (!Bytes.areEqual(attestationInfo.attestationNonce, data.attestationNonce)) { throw new DeviceAttestationError( DeviceAttestationCheck.AttestationNonceMismatch, "AttestationNonce in response does not match the nonce sent to the device", ); } // Step 7: Attestation Signature verification const dacKey = dac.publicKey; if (dacKey.algorithm !== "ECDSA-P256") { throw new InternalError("A Dac admits only an EC P-256 key"); } const dacPublicKey = dacKey.key; try { await crypto.verifyEcdsa( dacPublicKey, Bytes.concat(data.attestationElements, context.attestationChallenge), new EcdsaSignature(data.attestationSignature), ); } catch { throw new DeviceAttestationError( DeviceAttestationCheck.AttestationSignatureInvalid, "Attestation signature verification failed against DAC public key", ); } // === DCL-dependent checks (only when dclCertificateService is available) === let paa: Paa | undefined; if (dclCertificateService === undefined) { findings.push({ level: "warning", type: DeviceAttestationCheck.DclServiceUnavailable, message: "DclCertificateService not available; skipping PAA trust store, chain, and revocation checks. " + "Register DclCertificateService in the environment for full attestation.", }); } else { // Step 2: PAA Trust Store lookup — probe both production and test scope const paiAkid = pai.cert.extensions.authorityKeyIdentifier; const paaMetadata = dclCertificateService.getCertificate(paiAkid, { considerTestCertificates: true }); if (paaMetadata === undefined) { throw new DeviceAttestationError( DeviceAttestationCheck.PaaNotTrusted, `PAA not found in trust store for authority key identifier ${Bytes.toHex(paiAkid)}`, ); } if (!paaMetadata.isProduction && !dclCertificateService.acceptsTestCertificates) { findings.push({ level: "error", type: DeviceAttestationCheck.TrustedAsTestCertificate, message: `PAA ${Bytes.toHex(paiAkid)} is a test/development certificate; ` + `device presented a valid test attestation but production trust policy is in effect`, }); } // Step 2b: Time-based trust store check (SHOULD per spec 6.2.3.1) if (paaMetadata.fetchedAt !== undefined) { const dacNotBeforeUnixMs = (dac.cert.notBefore + MATTER_EPOCH_OFFSET_S) * 1000; if (paaMetadata.fetchedAt > dacNotBeforeUnixMs) { findings.push({ level: "info", type: DeviceAttestationCheck.PaaTrustStoreTimeMismatch, message: `PAA was fetched at ${new Date(paaMetadata.fetchedAt).toISOString()} ` + `which is after DAC notBefore ${new Date(dacNotBeforeUnixMs).toISOString()}; ` + `cannot confirm PAA was in DCL when DAC was issued`, }); } } // Step 3: Certificate chain signature verification const paaDer = await dclCertificateService.getCertificateAsDer(paiAkid, { considerTestCertificates: true }); paa = Paa.fromAsn1(paaDer); try { await pai.verifySignature(crypto, paa.publicKey); } catch (error) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateChainInvalid, `PAI signature verification failed: ${error}`, ); } // Reading the key inside the try below would relabel its failure as a chain failure const paiPublicKey = parsePeerValue( DeviceAttestationCheck.CertificateUnparseable, "Device returned a PAI whose public key cannot be read", () => pai.publicKey, ); const paaKeyAlgorithm = paa.publicKey.algorithm; if (!mayIssue(paaKeyAlgorithm, paiPublicKey.algorithm)) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateChainInvalid, `PAI key algorithm ${paiPublicKey.algorithm} is stronger than the ${paaKeyAlgorithm} of its PAA`, ); } try { await dac.verifySignature(crypto, paiPublicKey); } catch (error) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateChainInvalid, `DAC signature verification failed: ${error}`, ); } // Step 3b: Certificate validity at DAC's notBefore timestamp const dacNotBefore = dac.cert.notBefore; if (dacNotBefore < pai.cert.notBefore) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateExpired, `DAC notBefore (${dacNotBefore}) is before PAI notBefore (${pai.cert.notBefore})`, ); } if (pai.cert.notAfter !== 0 && dacNotBefore > pai.cert.notAfter) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateExpired, `DAC notBefore (${dacNotBefore}) is after PAI notAfter (${pai.cert.notAfter})`, ); } if (dacNotBefore < paa.cert.notBefore) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateExpired, `DAC notBefore (${dacNotBefore}) is before PAA notBefore (${paa.cert.notBefore})`, ); } if (paa.cert.notAfter !== 0 && dacNotBefore > paa.cert.notAfter) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateExpired, `DAC notBefore (${dacNotBefore}) is after PAA notAfter (${paa.cert.notAfter})`, ); } // Step 4 (DCL part): PAA VendorID matching const paaVendorId = paa.cert.subject.vendorId; if (paaVendorId !== undefined && paaVendorId !== pai.cert.subject.vendorId) { throw new DeviceAttestationError( DeviceAttestationCheck.VendorIdMismatch, `PAA vendorId ${idHex(paaVendorId)} does not match PAI vendorId ${idHex(pai.cert.subject.vendorId)}`, ); } // Step 5: Revocation check — composite key is (AKID, IssuerDN) per spec 6.2.6.2 const dacIssuerDnHex = dac.cert.issuerDer ? Bytes.toHex(dac.cert.issuerDer).toUpperCase() : undefined; if ( await dclCertificateService.isRevoked( dac.cert.extensions.authorityKeyIdentifier, dac.cert.serialNumber, dacIssuerDnHex, ) ) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateRevoked, "Device Attestation Certificate has been revoked", ); } const paiIssuerDnHex = pai.cert.issuerDer ? Bytes.toHex(pai.cert.issuerDer).toUpperCase() : undefined; if (await dclCertificateService.isRevoked(paiAkid, pai.cert.serialNumber, paiIssuerDnHex)) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificateRevoked, "Product Attestation Intermediate certificate has been revoked", ); } } // === Remaining local checks (CD validation) === // Step 8: Certification Declaration signature verification const cd = parsePeerValue( DeviceAttestationCheck.CertificationDeclarationUnparseable, "Device returned a Certification Declaration that cannot be parsed", () => CertificationDeclaration.parse(attestationInfo.declaration), ); const cdSignerSkidHex = Bytes.toHex(cd.signerSubjectKeyId); if (dclCertificateService !== undefined) { const cdSigner = await dclCertificateService.getOrFetchCdSigner(cd.signerSubjectKeyId); if (cdSigner !== undefined) { try { await crypto.verifyEcdsa(PublicKey(cdSigner.publicKey), cd.signedData, cd.signature); } catch { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationSignatureInvalid, "Certification Declaration signature verification failed", ); } } else { findings.push({ level: "warning", type: DeviceAttestationCheck.CdSignerVerificationSkipped, message: `CD signer SKID ${cdSignerSkidHex} not found in trust store or DCL; skipping CD signature verification`, }); } } else { findings.push({ level: "warning", type: DeviceAttestationCheck.CdSignerVerificationSkipped, message: "No DclCertificateService provided; skipping CD signature verification", }); } // Step 9: Certification Declaration field validation (Matter spec Section 6.2.3.1) const cdContent = cd.content; // certification_type check (Matter 1.5.1): log and surface provisional/test CDs const certType = cdContent.certificationType; if (certType === CertificationType.Provisional) { findings.push({ level: "warning", type: DeviceAttestationCheck.CertificationTypeProvisional, message: "Certification Declaration has certification_type=1 (provisional)", }); } else if (certType === CertificationType.Test) { findings.push({ level: "info", type: DeviceAttestationCheck.CertificationTypeTest, message: "Certification Declaration has certification_type=0 (test)", }); } // TODO: certificate_id SHOULD be checked against DCL DeviceSoftwareCompliance (spec 6.2.3.1) // Not yet implemented — will emit CertificateIdNotVerified finding once DCL lookup is available. // vendor_id SHALL match BasicInformation VendorID if (cdContent.vendorId !== data.vendorId) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `CD vendor_id ${idHex(cdContent.vendorId)} does not match BasicInformation VendorID ${idHex(data.vendorId)}`, ); } // product_id_array SHALL contain BasicInformation ProductID if (!cdContent.produceIdArray.includes(data.productId)) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `CD product_id_array [${cdContent.produceIdArray.map(idHex).join(", ")}] does not contain BasicInformation ProductID ${idHex(data.productId)}`, ); } // CD SHALL contain both or neither of dac_origin_vendor_id and dac_origin_product_id const hasDacOriginVid = cdContent.dacOriginVendorId !== undefined; const hasDacOriginPid = cdContent.dacOriginProductId !== undefined; if (hasDacOriginVid !== hasDacOriginPid) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, "CD has only one of dac_origin_vendor_id and dac_origin_product_id", ); } if (hasDacOriginVid && hasDacOriginPid) { // If BOTH dac_origin fields present: validate against dac_origin values if (dac.cert.subject.vendorId !== cdContent.dacOriginVendorId) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `DAC vendorId ${idHex(dac.cert.subject.vendorId)} does not match CD dac_origin_vendor_id ${idHex(cdContent.dacOriginVendorId)}`, ); } if (pai.cert.subject.vendorId !== cdContent.dacOriginVendorId) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `PAI vendorId ${idHex(pai.cert.subject.vendorId)} does not match CD dac_origin_vendor_id ${idHex(cdContent.dacOriginVendorId)}`, ); } const dacProductId = dac.cert.subject.productId; if (dacProductId !== undefined && dacProductId !== cdContent.dacOriginProductId) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `DAC productId ${idHex(dacProductId)} does not match CD dac_origin_product_id ${idHex(cdContent.dacOriginProductId)}`, ); } const paiProductId = pai.cert.subject.productId; if (paiProductId !== undefined && paiProductId !== cdContent.dacOriginProductId) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `PAI productId ${idHex(paiProductId)} does not match CD dac_origin_product_id ${idHex(cdContent.dacOriginProductId)}`, ); } } else { // NEITHER dac_origin fields: validate against vendor_id / product_id_array if (dac.cert.subject.vendorId !== cdContent.vendorId) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `DAC vendorId ${idHex(dac.cert.subject.vendorId)} does not match CD vendor_id ${idHex(cdContent.vendorId)}`, ); } if (pai.cert.subject.vendorId !== cdContent.vendorId) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `PAI vendorId ${idHex(pai.cert.subject.vendorId)} does not match CD vendor_id ${idHex(cdContent.vendorId)}`, ); } const dacProductId = dac.cert.subject.productId; if (dacProductId !== undefined && !cdContent.produceIdArray.includes(dacProductId)) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `DAC productId ${idHex(dacProductId)} not found in CD product_id_array [${cdContent.produceIdArray.map(idHex).join(", ")}]`, ); } const paiProductId = pai.cert.subject.productId; if (paiProductId !== undefined && !cdContent.produceIdArray.includes(paiProductId)) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, `PAI productId ${idHex(paiProductId)} not found in CD product_id_array [${cdContent.produceIdArray.map(idHex).join(", ")}]`, ); } } // authorized_paa_list needs PAA from DCL if (cdContent.authorizedPaaList !== undefined) { if (paa !== undefined) { const paaSki = paa.cert.extensions.subjectKeyIdentifier; const found = cdContent.authorizedPaaList.some(entry => Bytes.areEqual(entry, paaSki)); if (!found) { throw new DeviceAttestationError( DeviceAttestationCheck.CertificationDeclarationFieldMismatch, "PAA subject key identifier not in CD authorized_paa_list", ); } } else { findings.push({ level: "warning", type: DeviceAttestationCheck.DclServiceUnavailable, message: "CD has authorized_paa_list but cannot verify without DCL service", }); } } // Step 10: Firmware information (spec 6.3.2) // Commissioners MAY validate firmware_information against DCL DeviceSoftwareCompliance // to confirm the firmware is authorized and not revoked. The bytes are compared as an // opaque value against the expected firmware info for this CD's certificate_id + version. // TODO: When DCL DeviceSoftwareCompliance API is implemented (same as certificate_id), // compare attestationInfo.firmwareInfo bytes against expected value and emit a // FirmwareInfoMismatch warning finding on mismatch. Validation is MAY per spec. return { dacPublicKey, findings }; } }