diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 28d8f2ad192e10..aed111dc473cdc 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -293,9 +293,7 @@ CHIP_ERROR DeviceController::LoadLocalCredentials(Transport::AdminPairingInfo * MutableByteSpan rootCertSpan(rootCert.Get(), kMaxCHIPDERCertLength); ReturnErrorOnFailure(mOperationalCredentialsDelegate->GetRootCACertificate(0, rootCertSpan)); VerifyOrReturnError(CanCastTo(rootCertSpan.size()), CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorOnFailure(ConvertX509CertToChipCert(rootCertSpan.data(), static_cast(rootCertSpan.size()), - chipCert.Get(), chipCertAllocatedLen, chipCertLen)); - + ReturnErrorOnFailure(ConvertX509CertToChipCert(rootCertSpan, chipCert.Get(), chipCertAllocatedLen, chipCertLen)); ReturnErrorOnFailure(admin->SetRootCert(ByteSpan(chipCert.Get(), chipCertLen))); } diff --git a/src/credentials/CHIPCert.cpp b/src/credentials/CHIPCert.cpp index 46cb3f2ed6425e..3d9283d25fcdd4 100644 --- a/src/credentials/CHIPCert.cpp +++ b/src/credentials/CHIPCert.cpp @@ -336,7 +336,7 @@ const ChipCertificateData * ChipCertificateSet::FindCert(const CertificateKeyId for (uint8_t i = 0; i < mCertCount; i++) { ChipCertificateData & cert = mCerts[i]; - if (cert.mSubjectKeyId.IsEqual(subjectKeyId)) + if (cert.mSubjectKeyId.data_equal(subjectKeyId)) { return &cert; } @@ -392,12 +392,12 @@ CHIP_ERROR ChipCertificateSet::VerifySignature(const ChipCertificateData * cert, P256ECDSASignature signature; uint16_t derSigLen; - ReturnErrorOnFailure(ConvertECDSASignatureRawToDER(cert->mSignature, cert->mSignatureLen, signature, - static_cast(signature.Capacity()), derSigLen)); + ReturnErrorOnFailure( + ConvertECDSASignatureRawToDER(cert->mSignature, signature, static_cast(signature.Capacity()), derSigLen)); ReturnErrorOnFailure(signature.SetLength(derSigLen)); - memcpy(caPublicKey, caCert->mPublicKey, caCert->mPublicKeyLen); + memcpy(caPublicKey, caCert->mPublicKey.data(), caCert->mPublicKey.size()); ReturnErrorOnFailure(caPublicKey.ECDSA_validate_hash_signature(cert->mTBSHash, chip::Crypto::kSHA256_Hash_Length, signature)); @@ -495,7 +495,7 @@ CHIP_ERROR ChipCertificateSet::ValidateCert(const ChipCertificateData * cert, Va // Fail validation if the certificate is self-signed. Since we don't trust this certificate (see the check above) and // it has no path we can follow to a trust anchor, it can't be considered valid. - if (cert->mIssuerDN.IsEqual(cert->mSubjectDN) && cert->mAuthKeyId.IsEqual(cert->mSubjectKeyId)) + if (cert->mIssuerDN.IsEqual(cert->mSubjectDN) && cert->mAuthKeyId.data_equal(cert->mSubjectKeyId)) { ExitNow(err = CHIP_ERROR_CERT_NOT_TRUSTED); } @@ -536,7 +536,7 @@ CHIP_ERROR ChipCertificateSet::FindValidCert(const ChipDN & subjectDN, const Cer err = (depth > 0) ? CHIP_ERROR_CA_CERT_NOT_FOUND : CHIP_ERROR_CERT_NOT_FOUND; // Fail immediately if neither of the input criteria are specified. - if (subjectDN.IsEmpty() && subjectKeyId.IsEmpty()) + if (subjectDN.IsEmpty() && subjectKeyId.empty()) { ExitNow(); } @@ -551,7 +551,7 @@ CHIP_ERROR ChipCertificateSet::FindValidCert(const ChipDN & subjectDN, const Cer { continue; } - if (!subjectKeyId.IsEmpty() && !candidateCert->mSubjectKeyId.IsEqual(subjectKeyId)) + if (!subjectKeyId.empty() && !candidateCert->mSubjectKeyId.data_equal(subjectKeyId)) { continue; } @@ -581,21 +581,20 @@ void ChipCertificateData::Clear() { mSubjectDN.Clear(); mIssuerDN.Clear(); - mSubjectKeyId.Clear(); - mAuthKeyId.Clear(); - mNotBeforeTime = 0; - mNotAfterTime = 0; - mPublicKey = nullptr; - mPublicKeyLen = 0; - mPubKeyCurveOID = 0; - mPubKeyAlgoOID = 0; - mSigAlgoOID = 0; + mSubjectKeyId = CertificateKeyId(); + mAuthKeyId = CertificateKeyId(); + mNotBeforeTime = 0; + mNotAfterTime = 0; + mPublicKey = P256PublicKeySpan(); + mPubKeyCurveOID = 0; + mPubKeyAlgoOID = 0; + mSigAlgoOID = 0; + mPathLenConstraint = 0; mCertFlags.ClearAll(); mKeyUsageFlags.ClearAll(); mKeyPurposeFlags.ClearAll(); - mPathLenConstraint = 0; - mSignature = nullptr; - mSignatureLen = 0; + mSignature = P256ECDSASignatureSpan(); + memset(mTBSHash, 0, sizeof(mTBSHash)); } @@ -603,14 +602,13 @@ bool ChipCertificateData::IsEqual(const ChipCertificateData & other) const { // TODO - Add an operator== on BitFlags class. return mSubjectDN.IsEqual(other.mSubjectDN) && mIssuerDN.IsEqual(other.mIssuerDN) && - mSubjectKeyId.IsEqual(other.mSubjectKeyId) && mAuthKeyId.IsEqual(other.mAuthKeyId) && + mSubjectKeyId.data_equal(other.mSubjectKeyId) && mAuthKeyId.data_equal(other.mAuthKeyId) && (mNotBeforeTime == other.mNotBeforeTime) && (mNotAfterTime == other.mNotAfterTime) && - (mPublicKeyLen == other.mPublicKeyLen) && (memcmp(mPublicKey, other.mPublicKey, mPublicKeyLen) == 0) && - (mPubKeyCurveOID == other.mPubKeyCurveOID) && (mPubKeyAlgoOID == other.mPubKeyAlgoOID) && - (mSigAlgoOID == other.mSigAlgoOID) && (mCertFlags.Raw() == other.mCertFlags.Raw()) && - (mKeyUsageFlags.Raw() == other.mKeyUsageFlags.Raw()) && (mKeyPurposeFlags.Raw() == other.mKeyPurposeFlags.Raw()) && - (mPathLenConstraint == other.mPathLenConstraint) && (mSignatureLen == other.mSignatureLen) && - (memcmp(mSignature, other.mSignature, mSignatureLen) == 0) && (memcmp(mTBSHash, other.mTBSHash, sizeof(mTBSHash)) == 0); + mPublicKey.data_equal(other.mPublicKey) && (mPubKeyCurveOID == other.mPubKeyCurveOID) && + (mPubKeyAlgoOID == other.mPubKeyAlgoOID) && (mSigAlgoOID == other.mSigAlgoOID) && + (mCertFlags.Raw() == other.mCertFlags.Raw()) && (mKeyUsageFlags.Raw() == other.mKeyUsageFlags.Raw()) && + (mKeyPurposeFlags.Raw() == other.mKeyPurposeFlags.Raw()) && (mPathLenConstraint == other.mPathLenConstraint) && + mSignature.data_equal(other.mSignature) && (memcmp(mTBSHash, other.mTBSHash, sizeof(mTBSHash)) == 0); } void ValidationContext::Reset() @@ -633,12 +631,11 @@ bool ChipRDN::IsEqual(const ChipRDN & other) const if (IsChipDNAttr(mAttrOID)) { - return mAttrValue.mChipVal == other.mAttrValue.mChipVal; + return mChipVal == other.mChipVal; } else { - return (mAttrValue.mString.mLen == other.mAttrValue.mString.mLen && - memcmp(mAttrValue.mString.mValue, other.mAttrValue.mString.mValue, mAttrValue.mString.mLen) == 0); + return mString.data_equal(other.mString); } } @@ -671,39 +668,34 @@ uint8_t ChipDN::RDNCount() const CHIP_ERROR ChipDN::AddAttribute(chip::ASN1::OID oid, uint64_t val) { - CHIP_ERROR err = CHIP_NO_ERROR; uint8_t rdnCount = RDNCount(); - VerifyOrExit(rdnCount < CHIP_CONFIG_CERT_MAX_RDN_ATTRIBUTES, err = CHIP_ERROR_NO_MEMORY); - VerifyOrExit(IsChipDNAttr(oid), err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(rdnCount < CHIP_CONFIG_CERT_MAX_RDN_ATTRIBUTES, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(IsChipDNAttr(oid), CHIP_ERROR_INVALID_ARGUMENT); if (IsChip32bitDNAttr(oid)) { - VerifyOrExit(val <= UINT32_MAX, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(val <= UINT32_MAX, CHIP_ERROR_INVALID_ARGUMENT); } - rdn[rdnCount].mAttrOID = oid; - rdn[rdnCount].mAttrValue.mChipVal = val; + rdn[rdnCount].mAttrOID = oid; + rdn[rdnCount].mChipVal = val; -exit: - return err; + return CHIP_NO_ERROR; } -CHIP_ERROR ChipDN::AddAttribute(chip::ASN1::OID oid, const uint8_t * val, uint32_t valLen) +CHIP_ERROR ChipDN::AddAttribute(chip::ASN1::OID oid, ByteSpan val) { - CHIP_ERROR err = CHIP_NO_ERROR; uint8_t rdnCount = RDNCount(); - VerifyOrExit(rdnCount < CHIP_CONFIG_CERT_MAX_RDN_ATTRIBUTES, err = CHIP_ERROR_NO_MEMORY); - VerifyOrExit(!IsChipDNAttr(oid), err = CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrExit(oid != kOID_NotSpecified, err = CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(rdnCount < CHIP_CONFIG_CERT_MAX_RDN_ATTRIBUTES, CHIP_ERROR_NO_MEMORY); + VerifyOrReturnError(!IsChipDNAttr(oid), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(oid != kOID_NotSpecified, CHIP_ERROR_INVALID_ARGUMENT); - rdn[rdnCount].mAttrOID = oid; - rdn[rdnCount].mAttrValue.mString.mValue = val; - rdn[rdnCount].mAttrValue.mString.mLen = valLen; + rdn[rdnCount].mAttrOID = oid; + rdn[rdnCount].mString = val; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR ChipDN::GetCertType(uint8_t & certType) const @@ -777,7 +769,7 @@ CHIP_ERROR ChipDN::GetCertChipId(uint64_t & chipId) const case kOID_AttributeType_ChipFirmwareSigningId: VerifyOrReturnError(chipId == 0, CHIP_ERROR_WRONG_CERT_TYPE); - chipId = rdn[i].mAttrValue.mChipVal; + chipId = rdn[i].mChipVal; break; default: break; @@ -804,11 +796,6 @@ bool ChipDN::IsEqual(const ChipDN & other) const return res; } -bool CertificateKeyId::IsEqual(const CertificateKeyId & other) const -{ - return mId != nullptr && other.mId != nullptr && mLen == other.mLen && memcmp(mId, other.mId, mLen) == 0; -} - DLL_EXPORT CHIP_ERROR ASN1ToChipEpochTime(const chip::ASN1::ASN1UniversalTime & asn1Time, uint32_t & epochTime) { CHIP_ERROR err = CHIP_NO_ERROR; @@ -856,16 +843,18 @@ DLL_EXPORT CHIP_ERROR ChipEpochToASN1Time(uint32_t epochTime, chip::ASN1::ASN1Un return CHIP_NO_ERROR; } -CHIP_ERROR ConvertIntegerDERToRaw(const uint8_t * derInt, uint16_t derIntLen, uint8_t * rawInt, const uint16_t rawIntLen) +CHIP_ERROR ConvertIntegerDERToRaw(ByteSpan derInt, uint8_t * rawInt, const uint16_t rawIntLen) { - VerifyOrReturnError(derInt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(derIntLen > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!derInt.empty(), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(rawInt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + const uint8_t * derIntData = derInt.data(); + size_t derIntLen = derInt.size(); + /* one leading zero is allowed for positive integer in ASN1 DER format */ - if (*derInt == 0) + if (*derIntData == 0) { - derInt++; + derIntData++; derIntLen--; } @@ -873,31 +862,33 @@ CHIP_ERROR ConvertIntegerDERToRaw(const uint8_t * derInt, uint16_t derIntLen, ui if (derIntLen > 0) { - VerifyOrReturnError(*derInt != 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(*derIntData != 0, CHIP_ERROR_INVALID_ARGUMENT); } memset(rawInt, 0, (rawIntLen - derIntLen)); - memcpy(rawInt + (rawIntLen - derIntLen), derInt, derIntLen); + memcpy(rawInt + (rawIntLen - derIntLen), derIntData, derIntLen); return CHIP_NO_ERROR; } -CHIP_ERROR ConvertIntegerRawToDER(const uint8_t * rawInt, uint16_t rawIntLen, uint8_t * derInt, const uint16_t derIntBufSize, - uint16_t & derIntLen) +CHIP_ERROR ConvertIntegerRawToDER(P256IntegerSpan rawInt, uint8_t * derInt, const uint16_t derIntBufSize, uint16_t & derIntLen) { - VerifyOrReturnError(rawInt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(rawIntLen > 0, CHIP_ERROR_INVALID_ARGUMENT); + static_assert(rawInt.size() <= UINT16_MAX - 1, "P256 raw integer doesn't fit in a uint16_t"); + + VerifyOrReturnError(!rawInt.empty(), CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(derInt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - while (*rawInt == 0) + const uint8_t * rawIntData = rawInt.data(); + size_t rawIntLen = rawInt.size(); + + while (*rawIntData == 0) { - rawInt++; + rawIntData++; rawIntLen--; } - if (*rawInt & 0x80) /* Need Leading Zero */ + if (*rawIntData & 0x80) /* Need Leading Zero */ { - VerifyOrReturnError(rawIntLen <= UINT16_MAX - 1, CHIP_ERROR_BUFFER_TOO_SMALL); VerifyOrReturnError(derIntBufSize >= rawIntLen + 1, CHIP_ERROR_BUFFER_TOO_SMALL); *derInt++ = 0; @@ -907,26 +898,24 @@ CHIP_ERROR ConvertIntegerRawToDER(const uint8_t * rawInt, uint16_t rawIntLen, ui { VerifyOrReturnError(derIntBufSize >= rawIntLen, CHIP_ERROR_BUFFER_TOO_SMALL); - derIntLen = rawIntLen; + derIntLen = static_cast(rawIntLen); } - memcpy(derInt, rawInt, rawIntLen); + memcpy(derInt, rawIntData, rawIntLen); return CHIP_NO_ERROR; } -CHIP_ERROR ConvertECDSASignatureRawToDER(const uint8_t * rawSig, uint16_t rawSigLen, uint8_t * derSig, const uint16_t derSigBufSize, +CHIP_ERROR ConvertECDSASignatureRawToDER(P256ECDSASignatureSpan rawSig, uint8_t * derSig, const uint16_t derSigBufSize, uint16_t & derSigLen) { ASN1Writer writer; - VerifyOrReturnError(rawSig != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(rawSigLen > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(derSig != nullptr, CHIP_ERROR_INVALID_ARGUMENT); writer.Init(derSig, derSigBufSize); - ReturnErrorOnFailure(ConvertECDSASignatureRawToDER(rawSig, rawSigLen, writer)); + ReturnErrorOnFailure(ConvertECDSASignatureRawToDER(rawSig, writer)); ReturnErrorOnFailure(writer.Finalize()); @@ -935,24 +924,24 @@ CHIP_ERROR ConvertECDSASignatureRawToDER(const uint8_t * rawSig, uint16_t rawSig return CHIP_NO_ERROR; } -CHIP_ERROR ConvertECDSASignatureRawToDER(const uint8_t * rawSig, uint16_t rawSigLen, ASN1Writer & writer) +CHIP_ERROR ConvertECDSASignatureRawToDER(P256ECDSASignatureSpan rawSig, ASN1Writer & writer) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t derInt[kP256_FE_Length + 1]; uint16_t derIntLen; - VerifyOrReturnError(rawSig != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(rawSigLen == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!rawSig.empty(), CHIP_ERROR_INVALID_ARGUMENT); // Ecdsa-Sig-Value ::= SEQUENCE ASN1_START_SEQUENCE { // r INTEGER - ReturnErrorOnFailure(ConvertIntegerRawToDER(rawSig, kP256_FE_Length, derInt, sizeof(derInt), derIntLen)); + ReturnErrorOnFailure(ConvertIntegerRawToDER(P256IntegerSpan(rawSig.data()), derInt, sizeof(derInt), derIntLen)); ReturnErrorOnFailure(writer.PutValue(kASN1TagClass_Universal, kASN1UniversalTag_Integer, false, derInt, derIntLen)); // s INTEGER - ReturnErrorOnFailure(ConvertIntegerRawToDER(rawSig + kP256_FE_Length, kP256_FE_Length, derInt, sizeof(derInt), derIntLen)); + ReturnErrorOnFailure( + ConvertIntegerRawToDER(P256IntegerSpan(rawSig.data() + kP256_FE_Length), derInt, sizeof(derInt), derIntLen)); ReturnErrorOnFailure(writer.PutValue(kASN1TagClass_Universal, kASN1UniversalTag_Integer, false, derInt, derIntLen)); } ASN1_END_SEQUENCE; diff --git a/src/credentials/CHIPCert.h b/src/credentials/CHIPCert.h index c9161e92368039..6a5d94077cd321 100644 --- a/src/credentials/CHIPCert.h +++ b/src/credentials/CHIPCert.h @@ -44,8 +44,9 @@ static constexpr uint32_t kChip32bitAttrUTF8Length = 8; static constexpr uint32_t kChip64bitAttrUTF8Length = 16; static constexpr uint16_t kX509NoWellDefinedExpirationDateYear = 9999; -// As per specifications (section 6.3.7. Trusted Root CA Certificates) +// As per specifications (6.3.5. Node Operational Credentials Certificates) static constexpr uint32_t kMaxCHIPCertLength = 400; +static constexpr uint32_t kMaxDERCertLength = 600; /** Data Element Tags for the CHIP Certificate */ @@ -189,16 +190,9 @@ enum */ struct ChipRDN { - union - { - uint64_t mChipVal; /**< CHIP specific DN attribute value. */ - struct - { - const uint8_t * mValue; /**< Pointer to the DN attribute value. */ - uint32_t mLen; /**< DN attribute length. */ - } mString; /**< DN attribute structure when encoded as a string. */ - } mAttrValue; /**< DN attribute value union: string or unsigned integer. */ - chip::ASN1::OID mAttrOID; /**< DN attribute CHIP OID. */ + ByteSpan mString; /**< Attribute value when encoded as a string. */ + uint64_t mChipVal; /**< CHIP specific DN attribute value. */ + chip::ASN1::OID mAttrOID; /**< DN attribute CHIP OID. */ bool IsEqual(const ChipRDN & other) const; bool IsEmpty() const { return mAttrOID == chip::ASN1::kOID_NotSpecified; } @@ -231,13 +225,12 @@ class ChipDN * @brief Add string attribute to the DN. * * @param oid String OID for DN attribute. - * @param val Pointer to the DN string attribute. The value in the argument buffer should - * remain valid while the object is in use. - * @param valLen Length of the DN string attribute. + * @param val A ByteSpan object containing a pointer and length of the DN string attribute + * buffer. The value in the buffer should remain valid while the object is in use. * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - CHIP_ERROR AddAttribute(chip::ASN1::OID oid, const uint8_t * val, uint32_t valLen); + CHIP_ERROR AddAttribute(chip::ASN1::OID oid, ByteSpan val); /** * @brief Determine type of a CHIP certificate. @@ -274,21 +267,24 @@ class ChipDN }; /** - * @struct CertificateKeyId - * - * @brief - * A data structure representing a certificate key identifier. + * @brief A data structure for holding a certificate key identifier, without the ownership of it. */ -struct CertificateKeyId -{ - const uint8_t * mId = nullptr; /**< Pointer to the key identifier. Encoded as Octet String and represented as the ASN.1 DER - Integer (X.690 standard). */ - uint8_t mLen = 0; /**< Key identifier length. */ +using CertificateKeyId = FixedByteSpan; - bool IsEqual(const CertificateKeyId & other) const; - bool IsEmpty() const { return mId == nullptr; } - void Clear() { mId = nullptr; } -}; +/** + * @brief A data structure for holding a P256 ECDSA signature, without the ownership of it. + */ +using P256ECDSASignatureSpan = FixedByteSpan; + +/** + * @brief A data structure for holding a P256 Public Key, without the ownership of it. + */ +using P256PublicKeySpan = FixedByteSpan; + +/** + * @brief A data structure for holding a P256 Integer, without the ownership of it. + */ +using P256IntegerSpan = FixedByteSpan; /** * @struct ChipCertificateData @@ -309,7 +305,6 @@ struct ChipCertificateData void Clear(); bool IsEqual(const ChipCertificateData & other) const; - // TODO: Review and consider replacing some data pointer/len pairs with ByteSpan and FixedByteSpan types. ByteSpan mCertificate; /**< Original raw buffer data. */ ChipDN mSubjectDN; /**< Certificate Subject DN. */ ChipDN mIssuerDN; /**< Certificate Issuer DN. */ @@ -317,8 +312,7 @@ struct ChipCertificateData CertificateKeyId mAuthKeyId; /**< Certificate Authority public key identifier. */ uint32_t mNotBeforeTime; /**< Certificate validity: Not Before field. */ uint32_t mNotAfterTime; /**< Certificate validity: Not After field. */ - const uint8_t * mPublicKey; /**< Pointer to the certificate public key. */ - uint8_t mPublicKeyLen; /**< Certificate public key length. */ + P256PublicKeySpan mPublicKey; /**< Certificate public key. */ uint16_t mPubKeyCurveOID; /**< Public key Elliptic Curve CHIP OID. */ uint16_t mPubKeyAlgoOID; /**< Public key algorithm CHIP OID. */ uint16_t mSigAlgoOID; /**< Certificate signature algorithm CHIP OID. */ @@ -326,8 +320,7 @@ struct ChipCertificateData BitFlags mKeyUsageFlags; /**< Certificate key usage extensions flags. */ BitFlags mKeyPurposeFlags; /**< Certificate extended key usage extensions flags. */ uint8_t mPathLenConstraint; /**< Basic constraint: path length. */ - const uint8_t * mSignature; /**< Pointer to the certificate signature. */ - uint8_t mSignatureLen; /**< Certificate signature length. */ + P256ECDSASignatureSpan mSignature; /**< Certificate signature. */ uint8_t mTBSHash[Crypto::kSHA256_Hash_Length]; /**< Certificate TBS hash. */ }; @@ -624,16 +617,15 @@ CHIP_ERROR DecodeChipDN(chip::TLV::TLVReader & reader, ChipDN & dn); /** * @brief Convert standard X.509 certificate to CHIP certificate. * - * @param x509Cert Buffer containing X.509 DER encoded certificate. - * @param x509CertLen The length of the X.509 DER encoded certificate. + * @param x509Cert CHIP X.509 DER encoded certificate. * @param chipCertBuf Buffer to store converted certificate in CHIP format. * @param chipCertBufSize The size of the buffer to store converted certificate. * @param chipCertLen The length of the converted certificate. * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ -CHIP_ERROR ConvertX509CertToChipCert(const uint8_t * x509Cert, uint32_t x509CertLen, uint8_t * chipCertBuf, - uint32_t chipCertBufSize, uint32_t & chipCertLen); +CHIP_ERROR ConvertX509CertToChipCert(const ByteSpan x509Cert, uint8_t * chipCertBuf, uint32_t chipCertBufSize, + uint32_t & chipCertLen); /** * @brief Convert standard X.509 certificates to CHIP certificate array. @@ -672,16 +664,15 @@ CHIP_ERROR ExtractCertsFromCertArray(const ByteSpan & opCertArray, ByteSpan & no /** * @brief Convert CHIP certificate to the standard X.509 DER encoded certificate. * - * @param chipCert Buffer containing CHIP certificate. - * @param chipCertLen The length of the CHIP certificate. + * @param chipCert CHIP certificate in CHIP TLV encoding. * @param x509CertBuf Buffer to store converted certificate in X.509 DER format. * @param x509CertBufSize The size of the buffer to store converted certificate. * @param x509CertLen The length of the converted certificate. * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ -CHIP_ERROR ConvertChipCertToX509Cert(const uint8_t * chipCert, uint32_t chipCertLen, uint8_t * x509CertBuf, - uint32_t x509CertBufSize, uint32_t & x509CertLen); +CHIP_ERROR ConvertChipCertToX509Cert(const ByteSpan chipCert, uint8_t * x509CertBuf, uint32_t x509CertBufSize, + uint32_t & x509CertLen); /** * @brief Generate a standard X.509 DER encoded certificate using provided CHIP certificate and signing key @@ -822,53 +813,48 @@ inline bool IsChipDNAttr(chip::ASN1::OID oid) /** * @brief Convert an ASN.1 DER encoded integer to a raw big-endian integer. * - * @param derInt Buffer that holds ASN.1 DER encoded integer. - * @param derIntLen The length of the ASN.1 DER encoded integer. + * @param derInt P256 integer in ASN.1 DER encoded form. * @param rawInt Buffer to store converted raw integer. * @param rawIntLen The length of the converted raw integer. * * @retval #CHIP_NO_ERROR If the integer value was successfully converted. */ -CHIP_ERROR ConvertIntegerDERToRaw(const uint8_t * derInt, uint16_t derIntLen, uint8_t * rawInt, const uint16_t rawIntLen); +CHIP_ERROR ConvertIntegerDERToRaw(ByteSpan derInt, uint8_t * rawInt, const uint16_t rawIntLen); /** * @brief Convert a raw integer in big-endian form to an ASN.1 DER encoded integer. * - * @param rawInt Buffer that holds raw integer. - * @param rawIntLen The length of the raw integer. + * @param rawInt P256 integer in raw form. * @param derInt Buffer to store converted ASN.1 DER encoded integer. * @param derIntBufSize The size of the buffer to store ASN.1 DER encoded integer. * @param derIntLen The length of the ASN.1 DER encoded integer. * * @retval #CHIP_NO_ERROR If the integer value was successfully converted. */ -CHIP_ERROR ConvertIntegerRawToDER(const uint8_t * rawInt, uint16_t rawIntLen, uint8_t * derInt, const uint16_t derIntBufSize, - uint16_t & derIntLen); +CHIP_ERROR ConvertIntegerRawToDER(P256IntegerSpan rawInt, uint8_t * derInt, const uint16_t derIntBufSize, uint16_t & derIntLen); /** * @brief Convert a raw CHIP signature to an ASN.1 DER encoded signature structure. * - * @param rawSig Buffer that holds raw CHIP signature. - * @param rawSigLen The length of the raw CHIP signature. + * @param rawSig P256 ECDSA signature in raw form. * @param derSig Buffer to store converted ASN.1 DER encoded signature. * @param derSigBufSize The size of the buffer to store ASN.1 DER encoded signature. * @param derSigLen The length of the ASN.1 DER encoded signature. * * @retval #CHIP_NO_ERROR If the signature value was successfully converted. */ -CHIP_ERROR ConvertECDSASignatureRawToDER(const uint8_t * rawSig, uint16_t rawSigLen, uint8_t * derSig, const uint16_t derSigBufSize, +CHIP_ERROR ConvertECDSASignatureRawToDER(P256ECDSASignatureSpan rawSig, uint8_t * derSig, const uint16_t derSigBufSize, uint16_t & derSigLen); /** * @brief Convert a raw CHIP ECDSA signature to an ASN.1 DER encoded signature structure. * - * @param rawSig Buffer that holds raw CHIP signature. - * @param rawSigLen The length of the raw CHIP signature. + * @param rawSig P256 ECDSA signature in raw form. * @param writer A reference to the ASN1Writer to store ASN.1 DER encoded signature. * * @retval #CHIP_NO_ERROR If the signature value was successfully converted. */ -CHIP_ERROR ConvertECDSASignatureRawToDER(const uint8_t * rawSig, uint16_t rawSigLen, ASN1::ASN1Writer & writer); +CHIP_ERROR ConvertECDSASignatureRawToDER(P256ECDSASignatureSpan rawSig, ASN1::ASN1Writer & writer); /** * @brief Convert an ASN.1 DER encoded ECDSA signature to a raw CHIP signature. diff --git a/src/credentials/CHIPCertFromX509.cpp b/src/credentials/CHIPCertFromX509.cpp index 93fe709670cff1..a284412c91d1e5 100644 --- a/src/credentials/CHIPCertFromX509.cpp +++ b/src/credentials/CHIPCertFromX509.cpp @@ -555,15 +555,13 @@ CHIP_ERROR ConvertECDSASignatureDERToRaw(ASN1Reader & reader, TLVWriter & writer { // r INTEGER ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_Integer); - VerifyOrReturnError(reader.GetValueLen() <= UINT16_MAX, CHIP_ERROR_INVALID_ARGUMENT); ReturnErrorOnFailure( - ConvertIntegerDERToRaw(reader.GetValue(), static_cast(reader.GetValueLen()), rawSig, kP256_FE_Length)); + ConvertIntegerDERToRaw(ByteSpan(reader.GetValue(), reader.GetValueLen()), rawSig, kP256_FE_Length)); // s INTEGER ASN1_PARSE_ELEMENT(kASN1TagClass_Universal, kASN1UniversalTag_Integer); - VerifyOrReturnError(reader.GetValueLen() <= UINT16_MAX, CHIP_ERROR_INVALID_ARGUMENT); - ReturnErrorOnFailure(ConvertIntegerDERToRaw(reader.GetValue(), static_cast(reader.GetValueLen()), - rawSig + kP256_FE_Length, kP256_FE_Length)); + ReturnErrorOnFailure(ConvertIntegerDERToRaw(ByteSpan(reader.GetValue(), reader.GetValueLen()), rawSig + kP256_FE_Length, + kP256_FE_Length)); } ASN1_EXIT_SEQUENCE; } @@ -703,37 +701,36 @@ static CHIP_ERROR ConvertCertificate(ASN1Reader & reader, TLVWriter & writer, ui return err; } -DLL_EXPORT CHIP_ERROR ConvertX509CertToChipCert(const uint8_t * x509Cert, uint32_t x509CertLen, uint8_t * chipCertBuf, - uint32_t chipCertBufSize, uint32_t & chipCertLen) +DLL_EXPORT CHIP_ERROR ConvertX509CertToChipCert(const ByteSpan x509Cert, uint8_t * chipCertBuf, uint32_t chipCertBufSize, + uint32_t & chipCertLen) { - CHIP_ERROR err; ASN1Reader reader; TLVWriter writer; uint64_t issuer, subject; Optional fabric; - reader.Init(x509Cert, x509CertLen); + VerifyOrReturnError(!x509Cert.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(CanCastTo(x509Cert.size()), CHIP_ERROR_INVALID_ARGUMENT); + + reader.Init(x509Cert.data(), static_cast(x509Cert.size())); writer.Init(chipCertBuf, chipCertBufSize); - err = ConvertCertificate(reader, writer, ProfileTag(Protocols::OpCredentials::Id.ToTLVProfileId(), kTag_ChipCertificate), - issuer, subject, fabric); - SuccessOrExit(err); + ReturnErrorOnFailure(ConvertCertificate( + reader, writer, ProfileTag(Protocols::OpCredentials::Id.ToTLVProfileId(), kTag_ChipCertificate), issuer, subject, fabric)); - err = writer.Finalize(); - SuccessOrExit(err); + ReturnErrorOnFailure(writer.Finalize()); chipCertLen = writer.GetLengthWritten(); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR ConvertX509CertsToChipCertArray(const ByteSpan & x509NOC, const ByteSpan & x509ICAC, MutableByteSpan & chipCertArray) { // NOC is mandatory - VerifyOrReturnError(x509NOC.size() > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!x509NOC.empty(), CHIP_ERROR_INVALID_ARGUMENT); TLVWriter writer; @@ -754,7 +751,7 @@ CHIP_ERROR ConvertX509CertsToChipCertArray(const ByteSpan & x509NOC, const ByteS VerifyOrReturnError(nocFabric.HasValue(), CHIP_ERROR_INVALID_ARGUMENT); // ICAC is optional - if (x509ICAC.size() > 0) + if (!x509ICAC.empty()) { VerifyOrReturnError(CanCastTo(x509ICAC.size()), CHIP_ERROR_INVALID_ARGUMENT); reader.Init(x509ICAC.data(), static_cast(x509ICAC.size())); diff --git a/src/credentials/CHIPCertToX509.cpp b/src/credentials/CHIPCertToX509.cpp index ac9343626ebcac..f653d1f6e0ecfd 100644 --- a/src/credentials/CHIPCertToX509.cpp +++ b/src/credentials/CHIPCertToX509.cpp @@ -40,6 +40,7 @@ #include #include #include +#include namespace chip { namespace Credentials { @@ -160,7 +161,7 @@ static CHIP_ERROR DecodeConvertDN(TLVReader & reader, ASN1Writer & writer, ChipD } // Save the string value in the caller's DN structure. - err = dn.AddAttribute(attrOID, asn1AttrVal, asn1AttrValLen); + err = dn.AddAttribute(attrOID, ByteSpan(asn1AttrVal, asn1AttrValLen)); SuccessOrExit(err); } @@ -281,19 +282,17 @@ static CHIP_ERROR DecodeConvertSubjectPublicKeyInfo(TLVReader & reader, ASN1Writ } ASN1_END_SEQUENCE; - err = reader.Next(kTLVType_ByteString, ContextTag(kTag_EllipticCurvePublicKey)); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Next(kTLVType_ByteString, ContextTag(kTag_EllipticCurvePublicKey))); + VerifyOrReturnError(reader.GetLength() == certData.mPublicKey.size(), CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - err = reader.GetDataPtr(certData.mPublicKey); - SuccessOrExit(err); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mPublicKey = P256PublicKeySpan(ptr); - uint32_t len = reader.GetLength(); - VerifyOrExit(len == chip::Crypto::kP256_PublicKey_Length, err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - certData.mPublicKeyLen = static_cast(len); + static_assert(P256PublicKeySpan().size() <= UINT16_MAX, "Public key size doesn't fit in a uint16_t"); // For EC certs, the subjectPublicKey BIT STRING contains the X9.62 encoded EC point. - err = writer.PutBitString(0, certData.mPublicKey, certData.mPublicKeyLen); - SuccessOrExit(err); + ReturnErrorOnFailure(writer.PutBitString(0, certData.mPublicKey.data(), static_cast(certData.mPublicKey.size()))); } ASN1_END_SEQUENCE; @@ -305,7 +304,6 @@ static CHIP_ERROR DecodeConvertAuthorityKeyIdentifierExtension(TLVReader & reade ChipCertificateData & certData) { CHIP_ERROR err; - uint32_t len; certData.mCertFlags.Set(CertFlags::kExtPresent_AuthKeyId); @@ -316,19 +314,18 @@ static CHIP_ERROR DecodeConvertAuthorityKeyIdentifierExtension(TLVReader & reade { // keyIdentifier [0] IMPLICIT KeyIdentifier // KeyIdentifier ::= OCTET STRING - VerifyOrExit(reader.GetType() == kTLVType_ByteString, err = CHIP_ERROR_WRONG_TLV_TYPE); - VerifyOrExit(reader.GetTag() == ContextTag(kTag_AuthorityKeyIdentifier), err = CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); + VerifyOrReturnError(reader.GetType() == kTLVType_ByteString, CHIP_ERROR_WRONG_TLV_TYPE); + VerifyOrReturnError(reader.GetTag() == ContextTag(kTag_AuthorityKeyIdentifier), CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); + VerifyOrReturnError(reader.GetLength() == certData.mAuthKeyId.size(), CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - err = reader.GetDataPtr(certData.mAuthKeyId.mId); - SuccessOrExit(err); - - len = reader.GetLength(); - VerifyOrExit(len == kKeyIdentifierLength, err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mAuthKeyId = CertificateKeyId(ptr); - certData.mAuthKeyId.mLen = static_cast(len); + static_assert(CertificateKeyId().size() <= UINT16_MAX, "Authority key id size doesn't fit in a uint16_t"); - err = writer.PutOctetString(kASN1TagClass_ContextSpecific, 0, certData.mAuthKeyId.mId, certData.mAuthKeyId.mLen); - SuccessOrExit(err); + ReturnErrorOnFailure(writer.PutOctetString(kASN1TagClass_ContextSpecific, 0, certData.mAuthKeyId.data(), + static_cast(certData.mAuthKeyId.size()))); } ASN1_END_SEQUENCE; @@ -339,31 +336,26 @@ static CHIP_ERROR DecodeConvertAuthorityKeyIdentifierExtension(TLVReader & reade static CHIP_ERROR DecodeConvertSubjectKeyIdentifierExtension(TLVReader & reader, ASN1Writer & writer, ChipCertificateData & certData) { - CHIP_ERROR err; - uint32_t len; - certData.mCertFlags.Set(CertFlags::kExtPresent_SubjectKeyId); // SubjectKeyIdentifier extension MUST be marked as non-critical (default). // SubjectKeyIdentifier ::= KeyIdentifier // KeyIdentifier ::= OCTET STRING - VerifyOrExit(reader.GetType() == kTLVType_ByteString, err = CHIP_ERROR_WRONG_TLV_TYPE); - VerifyOrExit(reader.GetTag() == ContextTag(kTag_SubjectKeyIdentifier), err = CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); - - len = reader.GetLength(); - VerifyOrExit(len == kKeyIdentifierLength, err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); + VerifyOrReturnError(reader.GetType() == kTLVType_ByteString, CHIP_ERROR_WRONG_TLV_TYPE); + VerifyOrReturnError(reader.GetTag() == ContextTag(kTag_SubjectKeyIdentifier), CHIP_ERROR_UNEXPECTED_TLV_ELEMENT); + VerifyOrReturnError(reader.GetLength() == certData.mSubjectKeyId.size(), CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - certData.mSubjectKeyId.mLen = static_cast(len); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mSubjectKeyId = CertificateKeyId(ptr); - err = reader.GetDataPtr(certData.mSubjectKeyId.mId); - SuccessOrExit(err); + static_assert(CertificateKeyId().size() <= UINT16_MAX, "Subject key id size doesn't fit in a uint16_t"); - err = writer.PutOctetString(certData.mSubjectKeyId.mId, certData.mSubjectKeyId.mLen); - SuccessOrExit(err); + ReturnErrorOnFailure( + writer.PutOctetString(certData.mSubjectKeyId.data(), static_cast(certData.mSubjectKeyId.size()))); -exit: - return err; + return CHIP_NO_ERROR; } static CHIP_ERROR DecodeConvertKeyUsageExtension(TLVReader & reader, ASN1Writer & writer, ChipCertificateData & certData) @@ -677,10 +669,11 @@ CHIP_ERROR DecodeECDSASignature(TLVReader & reader, ChipCertificateData & certDa { ReturnErrorOnFailure(reader.Next(kTLVType_ByteString, ContextTag(kTag_ECDSASignature))); - VerifyOrReturnError(reader.GetLength() == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - certData.mSignatureLen = kP256_ECDSA_Signature_Length_Raw; + VerifyOrReturnError(reader.GetLength() == certData.mSignature.size(), CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - ReturnErrorOnFailure(reader.GetDataPtr(certData.mSignature)); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mSignature = P256ECDSASignatureSpan(ptr); return CHIP_NO_ERROR; } @@ -693,10 +686,7 @@ static CHIP_ERROR DecodeConvertECDSASignature(TLVReader & reader, ASN1Writer & w // signatureValue BIT STRING // Per RFC3279, the ECDSA signature value is encoded in DER encapsulated in the signatureValue BIT STRING. - ASN1_START_BIT_STRING_ENCAPSULATED - { - ReturnErrorOnFailure(ConvertECDSASignatureRawToDER(certData.mSignature, certData.mSignatureLen, writer)); - } + ASN1_START_BIT_STRING_ENCAPSULATED { ReturnErrorOnFailure(ConvertECDSASignatureRawToDER(certData.mSignature, writer)); } ASN1_END_ENCAPSULATED; exit: @@ -840,30 +830,29 @@ static CHIP_ERROR DecodeConvertCert(TLVReader & reader, ASN1Writer & writer, Chi return err; } -DLL_EXPORT CHIP_ERROR ConvertChipCertToX509Cert(const uint8_t * chipCert, uint32_t chipCertLen, uint8_t * x509CertBuf, - uint32_t x509CertBufSize, uint32_t & x509CertLen) +DLL_EXPORT CHIP_ERROR ConvertChipCertToX509Cert(const ByteSpan chipCert, uint8_t * x509CertBuf, uint32_t x509CertBufSize, + uint32_t & x509CertLen) { - CHIP_ERROR err; TLVReader reader; ASN1Writer writer; ChipCertificateData certData; - reader.Init(chipCert, chipCertLen); + VerifyOrReturnError(!chipCert.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(CanCastTo(chipCert.size()), CHIP_ERROR_INVALID_ARGUMENT); + + reader.Init(chipCert.data(), static_cast(chipCert.size())); writer.Init(x509CertBuf, x509CertBufSize); certData.Clear(); - err = DecodeConvertCert(reader, writer, certData); - SuccessOrExit(err); + ReturnErrorOnFailure(DecodeConvertCert(reader, writer, certData)); - err = writer.Finalize(); - SuccessOrExit(err); + ReturnErrorOnFailure(writer.Finalize()); x509CertLen = writer.GetLengthWritten(); -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR DecodeChipCert(const uint8_t * chipCert, uint32_t chipCertLen, ChipCertificateData & certData) diff --git a/src/credentials/CHIPOperationalCredentials.cpp b/src/credentials/CHIPOperationalCredentials.cpp index e19ba10db0f229..faaba5c5152f35 100644 --- a/src/credentials/CHIPOperationalCredentials.cpp +++ b/src/credentials/CHIPOperationalCredentials.cpp @@ -102,14 +102,9 @@ void OperationalCredentialSet::Release() chip::Platform::MemoryFree(mChipDeviceCredentials[i].nodeCredential.mCredential); mChipDeviceCredentials[i].nodeCredential.mCredential = nullptr; mChipDeviceCredentials[i].nodeCredential.mLen = 0; - mChipDeviceCredentials[i].trustedRootId.mId = nullptr; - mChipDeviceCredentials[i].trustedRootId.mLen = 0; - } - if (mDeviceOpCredKeypair[i].trustedRootId.mId != nullptr) - { - mDeviceOpCredKeypair[i].trustedRootId.mId = nullptr; - mDeviceOpCredKeypair[i].trustedRootId.mLen = 0; + mChipDeviceCredentials[i].trustedRootId = CertificateKeyId(); } + mDeviceOpCredKeypair[i].trustedRootId = CertificateKeyId(); } mChipDeviceCredentialsCount = 0; @@ -130,13 +125,11 @@ void OperationalCredentialSet::CleanupMaps() { for (size_t i = 0; i < kOperationalCredentialsMax; ++i) { - mChipDeviceCredentials[i].trustedRootId.mId = nullptr; - mChipDeviceCredentials[i].trustedRootId.mLen = 0; + mChipDeviceCredentials[i].trustedRootId = CertificateKeyId(); mChipDeviceCredentials[i].nodeCredential.mCredential = nullptr; mChipDeviceCredentials[i].nodeCredential.mLen = 0; - mDeviceOpCredKeypair[i].trustedRootId.mId = nullptr; - mDeviceOpCredKeypair[i].trustedRootId.mLen = 0; + mDeviceOpCredKeypair[i].trustedRootId = CertificateKeyId(); } } @@ -149,7 +142,7 @@ ChipCertificateSet * OperationalCredentialSet::FindCertSet(const CertificateKeyI for (uint8_t j = 0; j < certSet->GetCertCount(); j++) { const ChipCertificateData * cert = &certSet->GetCertSet()[j]; - if (cert->mCertFlags.Has(CertFlags::kIsTrustAnchor) && cert->mAuthKeyId.IsEqual(trustedRootId)) + if (cert->mCertFlags.Has(CertFlags::kIsTrustAnchor) && cert->mAuthKeyId.data_equal(trustedRootId)) { return certSet; } @@ -176,8 +169,7 @@ bool OperationalCredentialSet::IsTrustedRootIn(const CertificateKeyId & trustedR { for (uint16_t i = 0; i < mOpCredCount; ++i) { - const CertificateKeyId * trustedRootId = GetTrustedRootId(i); - if (trustedRootId->IsEqual(trustedRoot)) + if (GetTrustedRootId(i).data_equal(trustedRoot)) { return true; } @@ -216,9 +208,9 @@ CHIP_ERROR OperationalCredentialSet::SignMsg(const CertificateKeyId & trustedRoo return GetNodeKeypairAt(trustedRootId)->ECDSA_sign_msg(msg, msg_length, out_signature); } -const CertificateKeyId * OperationalCredentialSet::GetTrustedRootId(uint16_t certSetIndex) const +CertificateKeyId OperationalCredentialSet::GetTrustedRootId(uint16_t certSetIndex) const { - VerifyOrReturnError(certSetIndex <= mOpCredCount, nullptr); + VerifyOrReturnError(certSetIndex <= mOpCredCount, CertificateKeyId()); const ChipCertificateData * chipCertificateData = mOpCreds[certSetIndex].GetCertSet(); uint8_t numberCertificates = mOpCreds[certSetIndex].GetCertCount(); @@ -227,10 +219,10 @@ const CertificateKeyId * OperationalCredentialSet::GetTrustedRootId(uint16_t cer { if (chipCertificateData[i].mCertFlags.Has(CertFlags::kIsTrustAnchor)) { - return &chipCertificateData[i].mAuthKeyId; + return chipCertificateData[i].mAuthKeyId; } } - return nullptr; + return CertificateKeyId(); } CHIP_ERROR OperationalCredentialSet::SetDevOpCred(const CertificateKeyId & trustedRootId, const uint8_t * chipDeviceCredentials, @@ -320,8 +312,7 @@ CHIP_ERROR OperationalCredentialSet::FromSerializable(const OperationalCredentia BitFlags(CertDecodeFlags::kIsTrustAnchor)); SuccessOrExit(err); - trustedRootId.mId = certificateSet.GetLastCert()->mAuthKeyId.mId; - trustedRootId.mLen = certificateSet.GetLastCert()->mAuthKeyId.mLen; + trustedRootId = certificateSet.GetLastCert()->mAuthKeyId; if (serializable.mCACertificateLen != 0) { @@ -351,9 +342,7 @@ const NodeCredential * OperationalCredentialSet::GetNodeCredentialAt(const Certi { for (size_t i = 0; i < kOperationalCredentialsMax && mChipDeviceCredentials[i].nodeCredential.mCredential != nullptr; ++i) { - VerifyOrReturnError(trustedRootId.mLen == mChipDeviceCredentials[i].trustedRootId.mLen, nullptr); - - if (memcmp(trustedRootId.mId, mChipDeviceCredentials[i].trustedRootId.mId, trustedRootId.mLen) == 0) + if (trustedRootId.data_equal(mChipDeviceCredentials[i].trustedRootId)) { return &mChipDeviceCredentials[i].nodeCredential; } @@ -364,11 +353,9 @@ const NodeCredential * OperationalCredentialSet::GetNodeCredentialAt(const Certi P256Keypair * OperationalCredentialSet::GetNodeKeypairAt(const CertificateKeyId & trustedRootId) { - for (size_t i = 0; i < kOperationalCredentialsMax && mDeviceOpCredKeypair[i].trustedRootId.mId != nullptr; ++i) + for (size_t i = 0; i < kOperationalCredentialsMax && !mDeviceOpCredKeypair[i].trustedRootId.empty(); ++i) { - VerifyOrReturnError(trustedRootId.mLen == mChipDeviceCredentials[i].trustedRootId.mLen, nullptr); - - if (memcmp(trustedRootId.mId, mDeviceOpCredKeypair[i].trustedRootId.mId, trustedRootId.mLen) == 0) + if (trustedRootId.data_equal(mDeviceOpCredKeypair[i].trustedRootId)) { return &mDeviceOpCredKeypair[i].keypair; } diff --git a/src/credentials/CHIPOperationalCredentials.h b/src/credentials/CHIPOperationalCredentials.h index 143ed287b0f7e8..f6717781f57ebb 100644 --- a/src/credentials/CHIPOperationalCredentials.h +++ b/src/credentials/CHIPOperationalCredentials.h @@ -35,8 +35,7 @@ namespace chip { namespace Credentials { -static constexpr size_t kOperationalCredentialsMax = 5; -static constexpr size_t kOperationalCertificateMaxSize = 400; +static constexpr size_t kOperationalCredentialsMax = 5; using namespace Crypto; @@ -49,13 +48,13 @@ struct NodeCredential struct OperationalCredentialSerializable { uint16_t mNodeCredentialLen; - uint8_t mNodeCredential[kOperationalCertificateMaxSize]; + uint8_t mNodeCredential[kMaxCHIPCertLength]; uint16_t mNodeKeypairLen; uint8_t mNodeKeypair[kP256_PublicKey_Length + kP256_PrivateKey_Length]; uint16_t mRootCertificateLen; - uint8_t mRootCertificate[kOperationalCertificateMaxSize]; + uint8_t mRootCertificate[kMaxCHIPCertLength]; uint16_t mCACertificateLen; - uint8_t mCACertificate[kOperationalCertificateMaxSize]; + uint8_t mCACertificate[kMaxCHIPCertLength]; }; struct NodeCredentialMap @@ -153,7 +152,7 @@ class DLL_EXPORT OperationalCredentialSet * * @return A pointer to the Trusted Root ID on success. Otherwise, nullptr if no Trust Anchor is found. **/ - const CertificateKeyId * GetTrustedRootId(uint16_t certSetIndex) const; + CertificateKeyId GetTrustedRootId(uint16_t certSetIndex) const; /** * @brief Check whether certificate set is in the operational credential set. diff --git a/src/credentials/tests/CHIPCert_test_vectors.cpp b/src/credentials/tests/CHIPCert_test_vectors.cpp index e8a0e20235d930..a5042d8bd71a16 100644 --- a/src/credentials/tests/CHIPCert_test_vectors.cpp +++ b/src/credentials/tests/CHIPCert_test_vectors.cpp @@ -56,8 +56,7 @@ extern const uint8_t gTestCerts[] = { extern const size_t gNumTestCerts = sizeof(gTestCerts) / sizeof(gTestCerts[0]); -CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, const uint8_t *& certData, - uint32_t & certDataLen) +CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, ByteSpan & cert) { CHIP_ERROR err; bool derForm = certLoadFlags.Has(TestCertLoadFlags::kDERForm); @@ -69,13 +68,11 @@ CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFla { \ if (derForm) \ { \ - certData = sTestCert_##NAME##_DER; \ - certDataLen = sTestCert_##NAME##_DER_Len; \ + cert = ByteSpan(sTestCert_##NAME##_DER, sTestCert_##NAME##_DER_Len); \ } \ else \ { \ - certData = sTestCert_##NAME##_Chip; \ - certDataLen = sTestCert_##NAME##_Chip_Len; \ + cert = ByteSpan(sTestCert_##NAME##_Chip, sTestCert_##NAME##_Chip_Len); \ } \ ExitNow(err = CHIP_NO_ERROR); \ } \ @@ -176,39 +173,38 @@ CHIP_ERROR LoadTestCert(ChipCertificateSet & certSet, uint8_t certType, BitFlags BitFlags decodeFlags) { CHIP_ERROR err; - ChipCertificateData * cert; - const uint8_t * certData; - uint32_t certDataLen; + ChipCertificateData * certData; + ByteSpan cert; // Get the requested certificate data. - err = GetTestCert(certType, certLoadFlags, certData, certDataLen); + err = GetTestCert(certType, certLoadFlags, cert); SuccessOrExit(err); // Load it into the certificate set. - err = certSet.LoadCert(certData, certDataLen, decodeFlags); + err = certSet.LoadCert(cert.data(), static_cast(cert.size()), decodeFlags); SuccessOrExit(err); // Get loaded certificate data. - cert = const_cast(certSet.GetLastCert()); - VerifyOrExit(cert != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); + certData = const_cast(certSet.GetLastCert()); + VerifyOrExit(certData != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT); // Apply load flags. if (certLoadFlags.Has(TestCertLoadFlags::kSuppressIsCA)) { - cert->mCertFlags.Clear(CertFlags::kIsCA); + certData->mCertFlags.Clear(CertFlags::kIsCA); } if (certLoadFlags.Has(TestCertLoadFlags::kSuppressKeyUsage)) { - cert->mCertFlags.Clear(CertFlags::kExtPresent_KeyUsage); + certData->mCertFlags.Clear(CertFlags::kExtPresent_KeyUsage); } if (certLoadFlags.Has(TestCertLoadFlags::kSuppressKeyCertSign)) { - cert->mKeyUsageFlags.Clear(KeyUsageFlags::kKeyCertSign); + certData->mKeyUsageFlags.Clear(KeyUsageFlags::kKeyCertSign); } if (certLoadFlags.Has(TestCertLoadFlags::kSetPathLenConstZero)) { - cert->mCertFlags.Set(CertFlags::kPathLenConstraintPresent); - cert->mPathLenConstraint = 0; + certData->mCertFlags.Set(CertFlags::kPathLenConstraintPresent); + certData->mPathLenConstraint = 0; } exit: diff --git a/src/credentials/tests/CHIPCert_test_vectors.h b/src/credentials/tests/CHIPCert_test_vectors.h index 88b581ce08496c..4da3279546a9d7 100644 --- a/src/credentials/tests/CHIPCert_test_vectors.h +++ b/src/credentials/tests/CHIPCert_test_vectors.h @@ -68,8 +68,7 @@ enum class TestCertLoadFlags : uint8_t kSetAppDefinedCertType = 0x20, }; -extern CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, const uint8_t *& certData, - uint32_t & certDataLen); +extern CHIP_ERROR GetTestCert(uint8_t certType, BitFlags certLoadFlags, ByteSpan & cert); extern const char * GetTestCertName(uint8_t certType); extern CHIP_ERROR GetTestCertPubkey(uint8_t certType, const uint8_t *& certPubkey, uint32_t & certPubkeyLen); extern CHIP_ERROR LoadTestCert(ChipCertificateSet & certSet, uint8_t certType, BitFlags certLoadFlags, diff --git a/src/credentials/tests/TestChipCert.cpp b/src/credentials/tests/TestChipCert.cpp index d1196569c65cf1..90e4a482d2303d 100644 --- a/src/credentials/tests/TestChipCert.cpp +++ b/src/credentials/tests/TestChipCert.cpp @@ -47,17 +47,6 @@ using namespace chip::Crypto; enum { kStandardCertsCount = 3, - - /** - * Maximum buffer size needed to hold any of the test certificates in CHIP TLV encoded form. - */ - kTestCHIPCertBufSize = kOperationalCertificateMaxSize, - - /** - * Maximum buffer size needed to hold any of the test certificates in DER encoded form. - * The same buffer size is also used when the certificate is decoded. - */ - kTestDERCertBufSize = 600, }; static const BitFlags sIgnoreNotBeforeFlag(CertValidateFlags::kIgnoreNotBefore); @@ -148,52 +137,46 @@ static CHIP_ERROR SetEffectiveTime(ValidationContext & validContext, uint16_t ye static void TestChipCert_ChipToX509(nlTestSuite * inSuite, void * inContext) { CHIP_ERROR err; - const uint8_t * inCert; - uint32_t inCertLen; - const uint8_t * expectedOutCert; - uint32_t expectedOutCertLen; - uint8_t outCertBuf[kTestDERCertBufSize]; + ByteSpan inCert; + ByteSpan expectedOutCert; + uint8_t outCertBuf[kMaxDERCertLength]; uint32_t outCertLen; for (size_t i = 0; i < gNumTestCerts; i++) { uint8_t certType = gTestCerts[i]; - err = GetTestCert(certType, sNullLoadFlag, inCert, inCertLen); + err = GetTestCert(certType, sNullLoadFlag, inCert); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = GetTestCert(certType, sDerFormFlag, expectedOutCert, expectedOutCertLen); + err = GetTestCert(certType, sDerFormFlag, expectedOutCert); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = ConvertChipCertToX509Cert(inCert, inCertLen, outCertBuf, sizeof(outCertBuf), outCertLen); + err = ConvertChipCertToX509Cert(inCert, outCertBuf, sizeof(outCertBuf), outCertLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, outCertLen == expectedOutCertLen); - NL_TEST_ASSERT(inSuite, memcmp(outCertBuf, expectedOutCert, outCertLen) == 0); + NL_TEST_ASSERT(inSuite, expectedOutCert.data_equal(ByteSpan(outCertBuf, outCertLen))); } } static void TestChipCert_X509ToChip(nlTestSuite * inSuite, void * inContext) { CHIP_ERROR err; - const uint8_t * inCert; - uint32_t inCertLen; - const uint8_t * expectedOutCert; - uint32_t expectedOutCertLen; - uint8_t outCertBuf[kTestCHIPCertBufSize]; + ByteSpan inCert; + ByteSpan expectedOutCert; + uint8_t outCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; for (size_t i = 0; i < gNumTestCerts; i++) { uint8_t certType = gTestCerts[i]; - err = GetTestCert(certType, sDerFormFlag, inCert, inCertLen); + err = GetTestCert(certType, sDerFormFlag, inCert); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = GetTestCert(certType, sNullLoadFlag, expectedOutCert, expectedOutCertLen); + err = GetTestCert(certType, sNullLoadFlag, expectedOutCert); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = ConvertX509CertToChipCert(inCert, inCertLen, outCertBuf, sizeof(outCertBuf), outCertLen); + err = ConvertX509CertToChipCert(inCert, outCertBuf, sizeof(outCertBuf), outCertLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, outCertLen == expectedOutCertLen); - NL_TEST_ASSERT(inSuite, memcmp(outCertBuf, expectedOutCert, outCertLen) == 0); + NL_TEST_ASSERT(inSuite, expectedOutCert.data_equal(ByteSpan(outCertBuf, outCertLen))); } } @@ -367,7 +350,7 @@ static void TestChipCert_CertValidation(nlTestSuite * inSuite, void * inContext) const ValidationTestCase & testCase = sValidationTestCases[i]; // Initialize the certificate set and load the specified test certificates. - certSet.Init(kMaxCertsPerTestCase, kTestDERCertBufSize); + certSet.Init(kMaxCertsPerTestCase, kMaxDERCertLength); for (size_t i2 = 0; i2 < kMaxCertsPerTestCase; i2++) { if (testCase.InputCerts[i2].Type != TestCert::kNone) @@ -425,7 +408,7 @@ static void TestChipCert_CertValidTime(nlTestSuite * inSuite, void * inContext) ChipCertificateSet certSet; ValidationContext validContext; - certSet.Init(kStandardCertsCount, kTestDERCertBufSize); + certSet.Init(kStandardCertsCount, kMaxDERCertLength); err = LoadTestCertSet01(certSet); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); @@ -585,7 +568,7 @@ static void TestChipCert_CertUsage(nlTestSuite * inSuite, void * inContext) // clang-format on size_t sNumUsageTestCases = sizeof(sUsageTestCases) / sizeof(sUsageTestCases[0]); - certSet.Init(kStandardCertsCount, kTestDERCertBufSize); + certSet.Init(kStandardCertsCount, kMaxDERCertLength); err = LoadTestCertSet01(certSet); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); @@ -641,7 +624,7 @@ static void TestChipCert_CertType(nlTestSuite * inSuite, void * inContext) uint8_t certType; // Initialize the certificate set and load the test certificate. - certSet.Init(1, kTestDERCertBufSize); + certSet.Init(1, kMaxDERCertLength); err = LoadTestCert(certSet, testCase.Cert, sNullLoadFlag, sNullDecodeFlag); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); @@ -688,7 +671,7 @@ static void TestChipCert_CertId(nlTestSuite * inSuite, void * inContext) uint64_t chipId; // Initialize the certificate set and load the test certificate. - certSet.Init(1, kTestDERCertBufSize); + certSet.Init(1, kMaxDERCertLength); err = LoadTestCert(certSet, testCase.Cert, sNullLoadFlag, sNullDecodeFlag); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); @@ -706,7 +689,7 @@ static void TestChipCert_LoadDuplicateCerts(nlTestSuite * inSuite, void * inCont ChipCertificateSet certSet; ValidationContext validContext; - certSet.Init(kStandardCertsCount, kTestDERCertBufSize); + certSet.Init(kStandardCertsCount, kMaxDERCertLength); // Let's load two distinct certificates, and make sure cert count is 2 err = LoadTestCert(certSet, TestCert::kRoot01, sNullLoadFlag, sTrustAnchorFlag); @@ -738,7 +721,7 @@ static void TestChipCert_GenerateRootCert(nlTestSuite * inSuite, void * inContex P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - uint8_t signed_cert[kTestDERCertBufSize]; + uint8_t signed_cert[kMaxDERCertLength]; uint32_t signed_len = 0; ChipCertificateData certData; @@ -747,11 +730,12 @@ static void TestChipCert_GenerateRootCert(nlTestSuite * inSuite, void * inContex NL_TEST_ASSERT(inSuite, NewRootX509Cert(root_params, keypair, signed_cert, sizeof(signed_cert), signed_len) == CHIP_NO_ERROR); - uint8_t outCertBuf[kTestCHIPCertBufSize]; + uint8_t outCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(signed_cert, signed_len, outCertBuf, sizeof(outCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(signed_cert, signed_len), outCertBuf, sizeof(outCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, DecodeChipCert(outCertBuf, outCertLen, certData) == CHIP_NO_ERROR); @@ -775,12 +759,12 @@ static void TestChipCert_GenerateRootFabCert(nlTestSuite * inSuite, void * inCon P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - uint8_t signed_cert[kTestDERCertBufSize]; + uint8_t signed_cert[kMaxDERCertLength]; uint32_t signed_len = 0; ChipCertificateData certData; - uint8_t outCertBuf[kTestCHIPCertBufSize]; + uint8_t outCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; X509CertRequestParams root_params_fabric = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0xabcd, false, 0 }; @@ -789,7 +773,8 @@ static void TestChipCert_GenerateRootFabCert(nlTestSuite * inSuite, void * inCon NewRootX509Cert(root_params_fabric, keypair, signed_cert, sizeof(signed_cert), signed_len) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(signed_cert, signed_len, outCertBuf, sizeof(outCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(signed_cert, signed_len), outCertBuf, sizeof(outCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, DecodeChipCert(outCertBuf, outCertLen, certData) == CHIP_NO_ERROR); } @@ -800,10 +785,10 @@ static void TestChipCert_GenerateICACert(nlTestSuite * inSuite, void * inContext P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - uint8_t signed_cert[kTestDERCertBufSize]; + uint8_t signed_cert[kMaxDERCertLength]; uint32_t signed_len = 0; - uint8_t outCertBuf[kTestCHIPCertBufSize]; + uint8_t outCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; ChipCertificateData certData; @@ -817,7 +802,8 @@ static void TestChipCert_GenerateICACert(nlTestSuite * inSuite, void * inContext CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(signed_cert, signed_len, outCertBuf, sizeof(outCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(signed_cert, signed_len), outCertBuf, sizeof(outCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, DecodeChipCert(outCertBuf, outCertLen, certData) == CHIP_NO_ERROR); @@ -841,10 +827,10 @@ static void TestChipCert_GenerateNOCRoot(nlTestSuite * inSuite, void * inContext P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - uint8_t signed_cert[kTestDERCertBufSize]; + uint8_t signed_cert[kMaxDERCertLength]; uint32_t signed_len = 0; - uint8_t outCertBuf[kTestCHIPCertBufSize]; + uint8_t outCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; ChipCertificateData certData; @@ -858,7 +844,8 @@ static void TestChipCert_GenerateNOCRoot(nlTestSuite * inSuite, void * inContext sizeof(signed_cert), signed_len) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(signed_cert, signed_len, outCertBuf, sizeof(outCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(signed_cert, signed_len), outCertBuf, sizeof(outCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, DecodeChipCert(outCertBuf, outCertLen, certData) == CHIP_NO_ERROR); @@ -890,10 +877,10 @@ static void TestChipCert_GenerateNOCICA(nlTestSuite * inSuite, void * inContext) P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - uint8_t signed_cert[kTestDERCertBufSize]; + uint8_t signed_cert[kMaxDERCertLength]; uint32_t signed_len = 0; - uint8_t outCertBuf[kTestCHIPCertBufSize]; + uint8_t outCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; ChipCertificateData certData; @@ -907,7 +894,8 @@ static void TestChipCert_GenerateNOCICA(nlTestSuite * inSuite, void * inContext) sizeof(signed_cert), signed_len) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(signed_cert, signed_len, outCertBuf, sizeof(outCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(signed_cert, signed_len), outCertBuf, sizeof(outCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, DecodeChipCert(outCertBuf, outCertLen, certData) == CHIP_NO_ERROR); } @@ -918,13 +906,13 @@ static void TestChipCert_VerifyGeneratedCerts(nlTestSuite * inSuite, void * inCo P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - static uint8_t root_cert[kTestDERCertBufSize]; + static uint8_t root_cert[kMaxDERCertLength]; uint32_t root_len = 0; X509CertRequestParams root_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; NL_TEST_ASSERT(inSuite, NewRootX509Cert(root_params, keypair, root_cert, sizeof(root_cert), root_len) == CHIP_NO_ERROR); - static uint8_t ica_cert[kTestDERCertBufSize]; + static uint8_t ica_cert[kMaxDERCertLength]; uint32_t ica_len = 0; X509CertRequestParams ica_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; @@ -935,7 +923,7 @@ static void TestChipCert_VerifyGeneratedCerts(nlTestSuite * inSuite, void * inCo NewICAX509Cert(ica_params, 0xaabbccdd, ica_keypair.Pubkey(), keypair, ica_cert, sizeof(ica_cert), ica_len) == CHIP_NO_ERROR); - static uint8_t noc_cert[kTestDERCertBufSize]; + static uint8_t noc_cert[kMaxDERCertLength]; uint32_t noc_len = 0; X509CertRequestParams noc_params = { 1234, 0xaabbccdd, 631161876, 729942000, true, 0x8888, true, 0x1234 }; @@ -947,15 +935,16 @@ static void TestChipCert_VerifyGeneratedCerts(nlTestSuite * inSuite, void * inCo sizeof(noc_cert), noc_len) == CHIP_NO_ERROR); ChipCertificateSet certSet; - NL_TEST_ASSERT(inSuite, certSet.Init(3, kTestDERCertBufSize) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, certSet.Init(3, kMaxDERCertLength) == CHIP_NO_ERROR); - static uint8_t rootCertBuf[kTestCHIPCertBufSize]; - static uint8_t icaCertBuf[kTestCHIPCertBufSize]; - static uint8_t nocCertBuf[kTestCHIPCertBufSize]; + static uint8_t rootCertBuf[kMaxCHIPCertLength]; + static uint8_t icaCertBuf[kMaxCHIPCertLength]; + static uint8_t nocCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(root_cert, root_len, rootCertBuf, sizeof(rootCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(root_cert, root_len), rootCertBuf, sizeof(rootCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT( inSuite, certSet.LoadCert(rootCertBuf, outCertLen, @@ -963,13 +952,15 @@ static void TestChipCert_VerifyGeneratedCerts(nlTestSuite * inSuite, void * inCo CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(ica_cert, ica_len, icaCertBuf, sizeof(icaCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(ica_cert, ica_len), icaCertBuf, sizeof(icaCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, certSet.LoadCert(icaCertBuf, outCertLen, BitFlags(CertDecodeFlags::kGenerateTBSHash)) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(noc_cert, noc_len, nocCertBuf, sizeof(nocCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(noc_cert, noc_len), nocCertBuf, sizeof(nocCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, certSet.LoadCert(nocCertBuf, outCertLen, BitFlags(CertDecodeFlags::kGenerateTBSHash)) == CHIP_NO_ERROR); @@ -996,13 +987,13 @@ static void TestChipCert_X509ToChipArray(nlTestSuite * inSuite, void * inContext P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - static uint8_t root_cert[kTestDERCertBufSize]; + static uint8_t root_cert[kMaxDERCertLength]; uint32_t root_len = 0; X509CertRequestParams root_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; NL_TEST_ASSERT(inSuite, NewRootX509Cert(root_params, keypair, root_cert, sizeof(root_cert), root_len) == CHIP_NO_ERROR); - static uint8_t ica_cert[kTestDERCertBufSize]; + static uint8_t ica_cert[kMaxDERCertLength]; uint32_t ica_len = 0; X509CertRequestParams ica_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; @@ -1013,7 +1004,7 @@ static void TestChipCert_X509ToChipArray(nlTestSuite * inSuite, void * inContext NewICAX509Cert(ica_params, 0xaabbccdd, ica_keypair.Pubkey(), keypair, ica_cert, sizeof(ica_cert), ica_len) == CHIP_NO_ERROR); - static uint8_t noc_cert[kTestDERCertBufSize]; + static uint8_t noc_cert[kMaxDERCertLength]; uint32_t noc_len = 0; X509CertRequestParams noc_params = { 1234, 0xaabbccdd, 631161876, 729942000, true, 0x8888, true, 0x1234 }; @@ -1024,7 +1015,7 @@ static void TestChipCert_X509ToChipArray(nlTestSuite * inSuite, void * inContext NewNodeOperationalX509Cert(noc_params, kIssuerIsIntermediateCA, noc_keypair.Pubkey(), ica_keypair, noc_cert, sizeof(noc_cert), noc_len) == CHIP_NO_ERROR); - uint8_t outCertBuf[kTestCHIPCertBufSize * 2]; + uint8_t outCertBuf[kMaxCHIPCertLength * 2]; MutableByteSpan outCert(outCertBuf, sizeof(outCertBuf)); NL_TEST_ASSERT(inSuite, ConvertX509CertsToChipCertArray(ByteSpan(noc_cert, noc_len), ByteSpan(ica_cert, ica_len), outCert) == @@ -1032,17 +1023,18 @@ static void TestChipCert_X509ToChipArray(nlTestSuite * inSuite, void * inContext NL_TEST_ASSERT(inSuite, outCert.size() <= sizeof(outCertBuf)); ChipCertificateSet certSet; - NL_TEST_ASSERT(inSuite, certSet.Init(3, kTestDERCertBufSize) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, certSet.Init(3, kMaxDERCertLength) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, certSet.LoadCerts(outCert.data(), static_cast(outCert.size()), BitFlags(CertDecodeFlags::kGenerateTBSHash)) == CHIP_NO_ERROR); - static uint8_t rootCertBuf[kTestCHIPCertBufSize]; + static uint8_t rootCertBuf[kMaxCHIPCertLength]; uint32_t outCertLen; NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(root_cert, root_len, rootCertBuf, sizeof(rootCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(root_cert, root_len), rootCertBuf, sizeof(rootCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT( inSuite, certSet.LoadCert(rootCertBuf, outCertLen, @@ -1071,13 +1063,13 @@ static void TestChipCert_X509ToChipArrayNoICA(nlTestSuite * inSuite, void * inCo P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - static uint8_t root_cert[kTestDERCertBufSize]; + static uint8_t root_cert[kMaxDERCertLength]; uint32_t root_len = 0; X509CertRequestParams root_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; NL_TEST_ASSERT(inSuite, NewRootX509Cert(root_params, keypair, root_cert, sizeof(root_cert), root_len) == CHIP_NO_ERROR); - static uint8_t noc_cert[kTestDERCertBufSize]; + static uint8_t noc_cert[kMaxDERCertLength]; uint32_t noc_len = 0; X509CertRequestParams noc_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, true, 0x1234 }; @@ -1088,7 +1080,7 @@ static void TestChipCert_X509ToChipArrayNoICA(nlTestSuite * inSuite, void * inCo NewNodeOperationalX509Cert(noc_params, kIssuerIsRootCA, noc_keypair.Pubkey(), keypair, noc_cert, sizeof(noc_cert), noc_len) == CHIP_NO_ERROR); - uint8_t outCertBuf[kTestCHIPCertBufSize * 2]; + uint8_t outCertBuf[kMaxCHIPCertLength * 2]; uint32_t outCertLen; MutableByteSpan outCert(outCertBuf, sizeof(outCertBuf)); NL_TEST_ASSERT(inSuite, @@ -1096,16 +1088,17 @@ static void TestChipCert_X509ToChipArrayNoICA(nlTestSuite * inSuite, void * inCo NL_TEST_ASSERT(inSuite, outCert.size() <= sizeof(outCertBuf)); ChipCertificateSet certSet; - NL_TEST_ASSERT(inSuite, certSet.Init(3, kTestDERCertBufSize) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, certSet.Init(3, kMaxDERCertLength) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, certSet.LoadCerts(outCert.data(), static_cast(outCert.size()), BitFlags(CertDecodeFlags::kGenerateTBSHash)) == CHIP_NO_ERROR); - static uint8_t rootCertBuf[kTestCHIPCertBufSize]; + static uint8_t rootCertBuf[kMaxCHIPCertLength]; NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(root_cert, root_len, rootCertBuf, sizeof(rootCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(root_cert, root_len), rootCertBuf, sizeof(rootCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT( inSuite, certSet.LoadCert(rootCertBuf, outCertLen, @@ -1134,13 +1127,13 @@ static void TestChipCert_X509ToChipArrayErrorScenarios(nlTestSuite * inSuite, vo P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - static uint8_t root_cert[kTestDERCertBufSize]; + static uint8_t root_cert[kMaxDERCertLength]; uint32_t root_len = 0; X509CertRequestParams root_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; NL_TEST_ASSERT(inSuite, NewRootX509Cert(root_params, keypair, root_cert, sizeof(root_cert), root_len) == CHIP_NO_ERROR); - static uint8_t ica_cert[kTestDERCertBufSize]; + static uint8_t ica_cert[kMaxDERCertLength]; uint32_t ica_len = 0; X509CertRequestParams ica_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; @@ -1151,7 +1144,7 @@ static void TestChipCert_X509ToChipArrayErrorScenarios(nlTestSuite * inSuite, vo NewICAX509Cert(ica_params, 0xaabbccdd, ica_keypair.Pubkey(), keypair, ica_cert, sizeof(ica_cert), ica_len) == CHIP_NO_ERROR); - static uint8_t noc_cert[kTestDERCertBufSize]; + static uint8_t noc_cert[kMaxDERCertLength]; uint32_t noc_len = 0; X509CertRequestParams noc_params = { 1234, 0xaabbccdd, 631161876, 729942000, true, 0x8888, true, 0x1234 }; @@ -1162,7 +1155,7 @@ static void TestChipCert_X509ToChipArrayErrorScenarios(nlTestSuite * inSuite, vo NewNodeOperationalX509Cert(noc_params, kIssuerIsIntermediateCA, noc_keypair.Pubkey(), ica_keypair, noc_cert, sizeof(noc_cert), noc_len) == CHIP_NO_ERROR); - uint8_t outCertBuf[kTestCHIPCertBufSize * 2]; + uint8_t outCertBuf[kMaxCHIPCertLength * 2]; MutableByteSpan outCert(outCertBuf, sizeof(outCertBuf)); // Test that NOC is mandatory NL_TEST_ASSERT(inSuite, @@ -1191,13 +1184,13 @@ static void TestChipCert_ChipArrayToChipCerts(nlTestSuite * inSuite, void * inCo P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - static uint8_t root_cert[kTestDERCertBufSize]; + static uint8_t root_cert[kMaxDERCertLength]; uint32_t root_len = 0; X509CertRequestParams root_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; NL_TEST_ASSERT(inSuite, NewRootX509Cert(root_params, keypair, root_cert, sizeof(root_cert), root_len) == CHIP_NO_ERROR); - static uint8_t ica_cert[kTestDERCertBufSize]; + static uint8_t ica_cert[kMaxDERCertLength]; uint32_t ica_len = 0; X509CertRequestParams ica_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; @@ -1208,7 +1201,7 @@ static void TestChipCert_ChipArrayToChipCerts(nlTestSuite * inSuite, void * inCo NewICAX509Cert(ica_params, 0xaabbccdd, ica_keypair.Pubkey(), keypair, ica_cert, sizeof(ica_cert), ica_len) == CHIP_NO_ERROR); - static uint8_t noc_cert[kTestDERCertBufSize]; + static uint8_t noc_cert[kMaxDERCertLength]; uint32_t noc_len = 0; X509CertRequestParams noc_params = { 1234, 0xaabbccdd, 631161876, 729942000, true, 0x8888, true, 0x1234 }; @@ -1219,7 +1212,7 @@ static void TestChipCert_ChipArrayToChipCerts(nlTestSuite * inSuite, void * inCo NewNodeOperationalX509Cert(noc_params, kIssuerIsIntermediateCA, noc_keypair.Pubkey(), ica_keypair, noc_cert, sizeof(noc_cert), noc_len) == CHIP_NO_ERROR); - uint8_t outCertBuf[kTestCHIPCertBufSize * 2]; + uint8_t outCertBuf[kMaxCHIPCertLength * 2]; uint32_t outCertLen; MutableByteSpan outCert(outCertBuf, sizeof(outCertBuf)); NL_TEST_ASSERT(inSuite, @@ -1231,7 +1224,7 @@ static void TestChipCert_ChipArrayToChipCerts(nlTestSuite * inSuite, void * inCo NL_TEST_ASSERT(inSuite, ExtractCertsFromCertArray(outCert, noc_chip_cert, ica_chip_cert) == CHIP_NO_ERROR); ChipCertificateSet certSet; - NL_TEST_ASSERT(inSuite, certSet.Init(3, kTestCHIPCertBufSize * 3) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, certSet.Init(3, kMaxDERCertLength) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, certSet.LoadCert(noc_chip_cert.data(), static_cast(noc_chip_cert.size()), @@ -1241,10 +1234,11 @@ static void TestChipCert_ChipArrayToChipCerts(nlTestSuite * inSuite, void * inCo certSet.LoadCert(ica_chip_cert.data(), static_cast(ica_chip_cert.size()), BitFlags(CertDecodeFlags::kGenerateTBSHash)) == CHIP_NO_ERROR); - static uint8_t rootCertBuf[kTestCHIPCertBufSize]; + static uint8_t rootCertBuf[kMaxDERCertLength]; NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(root_cert, root_len, rootCertBuf, sizeof(rootCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(root_cert, root_len), rootCertBuf, sizeof(rootCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT( inSuite, certSet.LoadCert(rootCertBuf, outCertLen, @@ -1272,13 +1266,13 @@ static void TestChipCert_ChipArrayToChipCertsNoICA(nlTestSuite * inSuite, void * P256Keypair keypair; NL_TEST_ASSERT(inSuite, keypair.Initialize() == CHIP_NO_ERROR); - static uint8_t root_cert[kTestDERCertBufSize]; + static uint8_t root_cert[kMaxDERCertLength]; uint32_t root_len = 0; X509CertRequestParams root_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, false, 0 }; NL_TEST_ASSERT(inSuite, NewRootX509Cert(root_params, keypair, root_cert, sizeof(root_cert), root_len) == CHIP_NO_ERROR); - static uint8_t noc_cert[kTestDERCertBufSize]; + static uint8_t noc_cert[kMaxDERCertLength]; uint32_t noc_len = 0; X509CertRequestParams noc_params = { 1234, 0xabcdabcd, 631161876, 729942000, true, 0x8888, true, 0x1234 }; @@ -1289,7 +1283,7 @@ static void TestChipCert_ChipArrayToChipCertsNoICA(nlTestSuite * inSuite, void * NewNodeOperationalX509Cert(noc_params, kIssuerIsRootCA, noc_keypair.Pubkey(), keypair, noc_cert, sizeof(noc_cert), noc_len) == CHIP_NO_ERROR); - uint8_t outCertBuf[kTestCHIPCertBufSize * 2]; + uint8_t outCertBuf[kMaxCHIPCertLength * 2]; uint32_t outCertLen; MutableByteSpan outCert(outCertBuf, sizeof(outCertBuf)); NL_TEST_ASSERT(inSuite, @@ -1302,16 +1296,17 @@ static void TestChipCert_ChipArrayToChipCertsNoICA(nlTestSuite * inSuite, void * NL_TEST_ASSERT(inSuite, ica_chip_cert.data() == nullptr && ica_chip_cert.size() == 0); ChipCertificateSet certSet; - NL_TEST_ASSERT(inSuite, certSet.Init(3, kTestCHIPCertBufSize * 3) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, certSet.Init(3, kMaxDERCertLength) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, certSet.LoadCert(noc_chip_cert.data(), static_cast(noc_chip_cert.size()), BitFlags(CertDecodeFlags::kGenerateTBSHash)) == CHIP_NO_ERROR); - static uint8_t rootCertBuf[kTestCHIPCertBufSize]; + static uint8_t rootCertBuf[kMaxDERCertLength]; NL_TEST_ASSERT(inSuite, - ConvertX509CertToChipCert(root_cert, root_len, rootCertBuf, sizeof(rootCertBuf), outCertLen) == CHIP_NO_ERROR); + ConvertX509CertToChipCert(ByteSpan(root_cert, root_len), rootCertBuf, sizeof(rootCertBuf), outCertLen) == + CHIP_NO_ERROR); NL_TEST_ASSERT( inSuite, certSet.LoadCert(rootCertBuf, outCertLen, diff --git a/src/credentials/tests/TestChipOperationalCredentials.cpp b/src/credentials/tests/TestChipOperationalCredentials.cpp index 4664286ad7c53a..569312200a8a9b 100644 --- a/src/credentials/tests/TestChipOperationalCredentials.cpp +++ b/src/credentials/tests/TestChipOperationalCredentials.cpp @@ -209,8 +209,8 @@ static void TestChipOperationalCredentials_Serialization(nlTestSuite * inSuite, NL_TEST_ASSERT(inSuite, opCredSet.Init(&certSet, 1) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, opCredSet2.Init(1) == CHIP_NO_ERROR); - const CertificateKeyId * trustedRootId = opCredSet.GetTrustedRootId(static_cast(opCredSet.GetCertCount() - 1)); - NL_TEST_ASSERT(inSuite, trustedRootId != nullptr); + CertificateKeyId trustedRootId = opCredSet.GetTrustedRootId(static_cast(opCredSet.GetCertCount() - 1)); + NL_TEST_ASSERT(inSuite, !trustedRootId.empty()); NL_TEST_ASSERT(inSuite, serializedKeypair.SetLength(sTestCert_Node01_01_PublicKey_Len + sTestCert_Node01_01_PrivateKey_Len) == @@ -222,19 +222,19 @@ static void TestChipOperationalCredentials_Serialization(nlTestSuite * inSuite, NL_TEST_ASSERT(inSuite, keypair.Deserialize(serializedKeypair) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opCredSet.SetDevOpCredKeypair(*trustedRootId, &keypair) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, opCredSet.SetDevOpCredKeypair(trustedRootId, &keypair) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, - opCredSet.SetDevOpCred(*trustedRootId, sTestCert_Node01_01_Chip, + opCredSet.SetDevOpCred(trustedRootId, sTestCert_Node01_01_Chip, static_cast(sTestCert_Node01_01_Chip_Len)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opCredSet.ToSerializable(*trustedRootId, sSerialized) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, opCredSet.ToSerializable(trustedRootId, sSerialized) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, opCredSet2.FromSerializable(sSerialized) == CHIP_NO_ERROR); - const CertificateKeyId * trustedRootId2 = opCredSet2.GetTrustedRootId(static_cast(opCredSet2.GetCertCount() - 1)); - NL_TEST_ASSERT(inSuite, trustedRootId2->IsEqual(*trustedRootId)); + CertificateKeyId trustedRootId2 = opCredSet2.GetTrustedRootId(static_cast(opCredSet2.GetCertCount() - 1)); + NL_TEST_ASSERT(inSuite, trustedRootId2.data_equal(trustedRootId)); - NL_TEST_ASSERT(inSuite, opCredSet2.ToSerializable(*trustedRootId2, sSerialized2) == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, opCredSet2.ToSerializable(trustedRootId2, sSerialized2) == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, strncmp(reinterpret_cast(&sSerialized), reinterpret_cast(&sSerialized2), diff --git a/src/crypto/tests/CHIPCryptoPALTest.cpp b/src/crypto/tests/CHIPCryptoPALTest.cpp index 5ccfdb909886ff..d2204db3687220 100644 --- a/src/crypto/tests/CHIPCryptoPALTest.cpp +++ b/src/crypto/tests/CHIPCryptoPALTest.cpp @@ -1463,8 +1463,7 @@ static void TestPubkey_x509Extraction(nlTestSuite * inSuite, void * inContext) CHIP_ERROR err = CHIP_NO_ERROR; P256PublicKey publicKey; - const uint8_t * cert; - uint32_t certLen; + ByteSpan cert; const uint8_t * certPubkey; uint32_t certPubkeyLen; @@ -1472,12 +1471,12 @@ static void TestPubkey_x509Extraction(nlTestSuite * inSuite, void * inContext) { uint8_t certType = TestCerts::gTestCerts[i]; - err = GetTestCert(certType, TestCertLoadFlags::kDERForm, cert, certLen); + err = GetTestCert(certType, TestCertLoadFlags::kDERForm, cert); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = GetTestCertPubkey(certType, certPubkey, certPubkeyLen); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - err = ExtractPubkeyFromX509Cert(ByteSpan(cert, certLen), publicKey); + err = ExtractPubkeyFromX509Cert(cert, publicKey); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, memcmp(publicKey, certPubkey, certPubkeyLen) == 0); } diff --git a/src/lib/support/Span.h b/src/lib/support/Span.h index b6c5213bf5fe06..83f669189976ab 100644 --- a/src/lib/support/Span.h +++ b/src/lib/support/Span.h @@ -43,8 +43,8 @@ class Span {} constexpr pointer data() const { return mDataBuf; } - size_t size() const { return mDataLen; } - bool empty() const { return size() == 0; } + constexpr size_t size() const { return mDataLen; } + constexpr bool empty() const { return size() == 0; } // Allow data_equal for spans that are over the same type up to const-ness. template , std::remove_const_t>::value>> @@ -89,8 +89,8 @@ class FixedSpan constexpr explicit FixedSpan(pointer databuf) : mDataBuf(databuf) {} constexpr pointer data() const { return mDataBuf; } - size_t size() const { return N; } - bool empty() const { return data() == nullptr; } + constexpr size_t size() const { return N; } + constexpr bool empty() const { return data() == nullptr; } // Allow data_equal for spans that are over the same type up to const-ness. template , std::remove_const_t>::value>> diff --git a/src/protocols/secure_channel/CASESession.cpp b/src/protocols/secure_channel/CASESession.cpp index 6a99d92a94cc58..8169061d2a7ad0 100644 --- a/src/protocols/secure_channel/CASESession.cpp +++ b/src/protocols/secure_channel/CASESession.cpp @@ -72,7 +72,7 @@ static constexpr ExchangeContext::Timeout kSigma_Response_Timeout = 10000; CASESession::CASESession() { - mTrustedRootId.mId = nullptr; + mTrustedRootId = CertificateKeyId(); // dummy initialization REMOVE LATER for (size_t i = 0; i < mFabricSecret.Capacity(); i++) { @@ -95,10 +95,10 @@ void CASESession::Clear() mCommissioningHash.Clear(); mPairingComplete = false; mConnectionState.Reset(); - if (mTrustedRootId.mId != nullptr) + if (!mTrustedRootId.empty()) { - chip::Platform::MemoryFree(const_cast(mTrustedRootId.mId)); - mTrustedRootId.mId = nullptr; + chip::Platform::MemoryFree(const_cast(mTrustedRootId.data())); + mTrustedRootId = CertificateKeyId(); } CloseExchange(); @@ -332,9 +332,10 @@ CHIP_ERROR CASESession::SendSigmaR1() bbuf.Put16(n_trusted_roots); for (uint16_t i = 0; i < n_trusted_roots; ++i) { - if (mOpCredSet->GetTrustedRootId(i) != nullptr && mOpCredSet->GetTrustedRootId(i)->mId != nullptr) + CertificateKeyId trustedRootId = mOpCredSet->GetTrustedRootId(i); + if (!trustedRootId.empty()) { - bbuf.Put(mOpCredSet->GetTrustedRootId(i)->mId, kTrustedRootIdSize); + bbuf.Put(trustedRootId.data(), trustedRootId.size()); } } bbuf.Put(mEphemeralKey.Pubkey(), mEphemeralKey.Pubkey().Length()); @@ -530,7 +531,7 @@ CHIP_ERROR CASESession::SendSigmaR2() // Responder's session ID bbuf.Put16(mConnectionState.GetLocalKeyID()); // Step 2 - bbuf.Put(mTrustedRootId.mId, mTrustedRootId.mLen); + bbuf.Put(mTrustedRootId.data(), mTrustedRootId.size()); bbuf.Put(mEphemeralKey.Pubkey(), mEphemeralKey.Pubkey().Length()); bbuf.Put(msg_R2_Encrypted.Get(), msg_r2_signed_enc_len); bbuf.Put(tag, sizeof(tag)); @@ -948,27 +949,25 @@ CHIP_ERROR CASESession::FindValidTrustedRoot(const uint8_t ** msgIterator, uint3 for (uint32_t i = 0; i < nTrustedRoots; ++i) { - trustedRoot[i].mId = *msgIterator; - trustedRoot[i].mLen = kTrustedRootIdSize; + trustedRoot[i] = CertificateKeyId(*msgIterator); *msgIterator += kTrustedRootIdSize; if (mOpCredSet->IsTrustedRootIn(trustedRoot[i])) { - if (mTrustedRootId.mId != nullptr) + if (!mTrustedRootId.empty()) { - chip::Platform::MemoryFree(const_cast(mTrustedRootId.mId)); - mTrustedRootId.mId = nullptr; + chip::Platform::MemoryFree(const_cast(mTrustedRootId.data())); + mTrustedRootId = CertificateKeyId(); } - mTrustedRootId.mId = reinterpret_cast(chip::Platform::MemoryAlloc(kTrustedRootIdSize)); - VerifyOrReturnError(mTrustedRootId.mId != nullptr, CHIP_ERROR_NO_MEMORY); + mTrustedRootId = CertificateKeyId(reinterpret_cast(chip::Platform::MemoryAlloc(kTrustedRootIdSize))); + VerifyOrReturnError(!mTrustedRootId.empty(), CHIP_ERROR_NO_MEMORY); - memcpy(const_cast(mTrustedRootId.mId), trustedRoot[i].mId, trustedRoot[i].mLen); - mTrustedRootId.mLen = trustedRoot[i].mLen; + memcpy(const_cast(mTrustedRootId.data()), trustedRoot[i].data(), trustedRoot[i].size()); break; } } - VerifyOrReturnError(mTrustedRootId.mId != nullptr, CHIP_ERROR_CERT_NOT_TRUSTED); + VerifyOrReturnError(!mTrustedRootId.empty(), CHIP_ERROR_CERT_NOT_TRUSTED); return CHIP_NO_ERROR; } @@ -1015,7 +1014,7 @@ CHIP_ERROR CASESession::Validate_and_RetrieveResponderID(const uint8_t ** msgIte ChipCertificateSet certSet; // Certificate set can contain up to 3 certs (NOC, ICA cert, and Root CA cert) - ReturnErrorOnFailure(certSet.Init(3, kMaxCHIPCertLength * 3)); + ReturnErrorOnFailure(certSet.Init(3, kMaxDERCertLength)); responderOpCertLen = chip::Encoding::LittleEndian::Read16(*msgIterator); *responderOpCert = *msgIterator; @@ -1025,7 +1024,7 @@ CHIP_ERROR CASESession::Validate_and_RetrieveResponderID(const uint8_t ** msgIte ReturnErrorOnFailure( certSet.LoadCerts(*responderOpCert, responderOpCertLen, BitFlags(CertDecodeFlags::kGenerateTBSHash))); - bbuf.Put(certSet.GetCertSet()[0].mPublicKey, certSet.GetCertSet()[0].mPublicKeyLen); + bbuf.Put(certSet.GetCertSet()[0].mPublicKey.data(), certSet.GetCertSet()[0].mPublicKey.size()); VerifyOrReturnError(bbuf.Fit(), CHIP_ERROR_NO_MEMORY); diff --git a/src/protocols/secure_channel/CASESession.h b/src/protocols/secure_channel/CASESession.h index eee94a9496d0d9..72b44d6a6cd9bd 100644 --- a/src/protocols/secure_channel/CASESession.h +++ b/src/protocols/secure_channel/CASESession.h @@ -49,7 +49,7 @@ namespace chip { constexpr uint16_t kAEADKeySize = 16; constexpr uint16_t kSigmaParamRandomNumberSize = 32; -constexpr uint16_t kTrustedRootIdSize = 20; +constexpr uint16_t kTrustedRootIdSize = Credentials::kKeyIdentifierLength; constexpr uint16_t kMaxTrustedRootIds = 5; constexpr uint16_t kIPKSize = 16; diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 9458c12de004ac..b7b4e3843898cf 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -108,7 +108,7 @@ class TestCASESecurePairingDelegate : public SessionEstablishmentDelegate static CHIP_ERROR InitCredentialSets() { - CertificateKeyId trustedRootId = { .mId = sTestCert_Root01_SubjectKeyId, .mLen = sTestCert_Root01_SubjectKeyId_Len }; + CertificateKeyId trustedRootId = CertificateKeyId(sTestCert_Root01_SubjectKeyId); commissionerDevOpCred.Release(); accessoryDevOpCred.Release(); diff --git a/src/tools/chip-cert/CertUtils.cpp b/src/tools/chip-cert/CertUtils.cpp index eb80e9fb6df95c..fdcff62c110e13 100644 --- a/src/tools/chip-cert/CertUtils.cpp +++ b/src/tools/chip-cert/CertUtils.cpp @@ -77,12 +77,12 @@ bool ToolChipDN::SetCertSubjectDN(X509 * cert) const if (IsChip64bitDNAttr(rdn[i].mAttrOID)) { - snprintf(chipAttrStr, sizeof(chipAttrStr), "%016" PRIX64 "", rdn[i].mAttrValue.mChipVal); + snprintf(chipAttrStr, sizeof(chipAttrStr), "%016" PRIX64 "", rdn[i].mChipVal); chipAttrLen = 16; } else { - snprintf(chipAttrStr, sizeof(chipAttrStr), "%08" PRIX32 "", static_cast(rdn[i].mAttrValue.mChipVal)); + snprintf(chipAttrStr, sizeof(chipAttrStr), "%08" PRIX32 "", static_cast(rdn[i].mChipVal)); chipAttrLen = 8; } @@ -95,8 +95,8 @@ bool ToolChipDN::SetCertSubjectDN(X509 * cert) const else { if (!X509_NAME_add_entry_by_NID(X509_get_subject_name(cert), attrNID, MBSTRING_UTF8, - (unsigned char *) rdn[i].mAttrValue.mString.mValue, - (int) rdn[i].mAttrValue.mString.mLen, -1, 0)) + const_cast(rdn[i].mString.data()), static_cast(rdn[i].mString.size()), + -1, 0)) { ReportOpenSSLErrorAndExit("X509_NAME_add_entry_by_NID", res = false); } @@ -134,20 +134,20 @@ void ToolChipDN::PrintDN(FILE * file, const char * name) const { if (IsChip64bitDNAttr(rdn[i].mAttrOID)) { - snprintf(valueStr, sizeof(valueStr), "%016" PRIX64, rdn[i].mAttrValue.mChipVal); + snprintf(valueStr, sizeof(valueStr), "%016" PRIX64, rdn[i].mChipVal); } else if (IsChip32bitDNAttr(rdn[i].mAttrOID)) { - snprintf(valueStr, sizeof(valueStr), "%08" PRIX32, static_cast(rdn[i].mAttrValue.mChipVal)); + snprintf(valueStr, sizeof(valueStr), "%08" PRIX32, static_cast(rdn[i].mChipVal)); } else { - uint32_t len = rdn[i].mAttrValue.mString.mLen; + size_t len = rdn[i].mString.size(); if (len > sizeof(valueStr) - 1) { len = sizeof(valueStr) - 1; } - memcpy(valueStr, rdn[i].mAttrValue.mString.mValue, len); + memcpy(valueStr, rdn[i].mString.data(), len); valueStr[len] = 0; } @@ -383,7 +383,7 @@ bool ReadCert(const char * fileName, X509 * cert, CertFormat & certFmt) CHIP_ERROR err = CHIP_NO_ERROR; const uint8_t * p = nullptr; uint32_t certLen = 0; - std::unique_ptr x509CertBuf(new uint8_t[kMaxX509CertBufSize]); + std::unique_ptr x509CertBuf(new uint8_t[kMaxDERCertLength]); std::unique_ptr certBuf; res = ReadFileIntoMem(fileName, nullptr, certLen); @@ -411,7 +411,7 @@ bool ReadCert(const char * fileName, X509 * cert, CertFormat & certFmt) if (certFmt == kCertFormat_Chip_Base64 || certFmt == kCertFormat_Chip_Raw) { - err = ConvertChipCertToX509Cert(certBuf.get(), certLen, x509CertBuf.get(), kMaxX509CertBufSize, certLen); + err = ConvertChipCertToX509Cert(ByteSpan(certBuf.get(), certLen), x509CertBuf.get(), kMaxDERCertLength, certLen); if (err != CHIP_NO_ERROR) { fprintf(stderr, "Error converting certificate: %s\n", chip::ErrorStr(err)); @@ -448,7 +448,9 @@ bool X509ToChipCert(X509 * cert, uint8_t * certBuf, uint32_t certBufSize, uint32 ReportOpenSSLErrorAndExit("i2d_X509", res = false); } - err = ConvertX509CertToChipCert(derCert, static_cast(derCertLen), certBuf, certBufSize, certLen); + VerifyOrReturnError(chip::CanCastTo(derCertLen), false); + + err = ConvertX509CertToChipCert(ByteSpan(derCert, static_cast(derCertLen)), certBuf, certBufSize, certLen); if (err != CHIP_NO_ERROR) { fprintf(stderr, "ConvertX509CertToChipCert() failed\n%s\n", chip::ErrorStr(err)); @@ -521,7 +523,7 @@ bool WriteCert(const char * fileName, X509 * cert, CertFormat certFmt) { uint8_t * certToWrite = nullptr; uint32_t certToWriteLen = 0; - uint32_t chipCertLen = kMaxChipCertBufSize; + uint32_t chipCertLen = kMaxCHIPCertLength; uint32_t chipCertBase64Len = BASE64_ENCODED_LEN(chipCertLen); std::unique_ptr chipCert(new uint8_t[chipCertLen]); std::unique_ptr chipCertBase64(new uint8_t[chipCertBase64Len]); diff --git a/src/tools/chip-cert/Cmd_GenCert.cpp b/src/tools/chip-cert/Cmd_GenCert.cpp index 6f50fe65e8d4eb..c0a3b40b35cdca 100644 --- a/src/tools/chip-cert/Cmd_GenCert.cpp +++ b/src/tools/chip-cert/Cmd_GenCert.cpp @@ -295,8 +295,8 @@ bool HandleOption(const char * progName, OptionSet * optSet, int id, const char break; case 'c': - err = gSubjectDN.AddAttribute(kOID_AttributeType_CommonName, reinterpret_cast(arg), - static_cast(strlen(arg))); + err = gSubjectDN.AddAttribute(kOID_AttributeType_CommonName, + chip::ByteSpan(reinterpret_cast(arg), strlen(arg))); if (err != CHIP_NO_ERROR) { fprintf(stderr, "Failed to add Common Name attribute to the subject DN: %s\n", chip::ErrorStr(err)); diff --git a/src/tools/chip-cert/Cmd_PrintCert.cpp b/src/tools/chip-cert/Cmd_PrintCert.cpp index c815f3a30e6d9c..143fa2ac55791a 100644 --- a/src/tools/chip-cert/Cmd_PrintCert.cpp +++ b/src/tools/chip-cert/Cmd_PrintCert.cpp @@ -127,7 +127,7 @@ void Indent(FILE * file, int count) } } -void PrintHexField(FILE * file, const char * name, int indent, uint16_t count, const uint8_t * data, int countPerRow = 16) +void PrintHexField(FILE * file, const char * name, int indent, size_t count, const uint8_t * data, size_t countPerRow = 16) { Indent(file, indent); indent += fprintf(file, "%s: ", name); @@ -171,20 +171,20 @@ void PrintDN(FILE * file, const char * name, int indent, const ChipDN * dn) { if (IsChip64bitDNAttr(dn->rdn[i].mAttrOID)) { - snprintf(valueStr, sizeof(valueStr), "%016" PRIX64, dn->rdn[i].mAttrValue.mChipVal); + snprintf(valueStr, sizeof(valueStr), "%016" PRIX64, dn->rdn[i].mChipVal); } else if (IsChip32bitDNAttr(dn->rdn[i].mAttrOID)) { - snprintf(valueStr, sizeof(valueStr), "%08" PRIX32, static_cast(dn->rdn[i].mAttrValue.mChipVal)); + snprintf(valueStr, sizeof(valueStr), "%08" PRIX32, static_cast(dn->rdn[i].mChipVal)); } else { - uint32_t len = dn->rdn[i].mAttrValue.mString.mLen; + size_t len = dn->rdn[i].mString.size(); if (len > sizeof(valueStr) - 1) { len = sizeof(valueStr) - 1; } - memcpy(valueStr, dn->rdn[i].mAttrValue.mString.mValue, len); + memcpy(valueStr, dn->rdn[i].mString.data(), len); valueStr[len] = 0; } @@ -209,7 +209,7 @@ bool PrintCert(const char * fileName, X509 * cert) ChipCertificateSet certSet; const ChipCertificateData * certData; chip::BitFlags decodeFlags; - std::unique_ptr certBuf(new uint8_t[kMaxChipCertBufSize]); + std::unique_ptr certBuf(new uint8_t[kMaxCHIPCertLength]); uint32_t certLen; int indent = 4; @@ -218,7 +218,7 @@ bool PrintCert(const char * fileName, X509 * cert) res = OpenFile(fileName, file, true); VerifyTrueOrExit(res); - res = X509ToChipCert(cert, certBuf.get(), kMaxChipCertBufSize, certLen); + res = X509ToChipCert(cert, certBuf.get(), kMaxCHIPCertLength, certLen); VerifyTrueOrExit(res); err = certSet.Init(1, 1024); @@ -256,7 +256,7 @@ bool PrintCert(const char * fileName, X509 * cert) Indent(file, indent); fprintf(file, "Curve Id : %s\n", GetOIDName(certData->mPubKeyCurveOID)); - PrintHexField(file, "Public Key ", indent, certData->mPublicKeyLen, certData->mPublicKey); + PrintHexField(file, "Public Key ", indent, certData->mPublicKey.size(), certData->mPublicKey.data()); Indent(file, indent); fprintf(file, "Extensions:\n"); @@ -350,18 +350,18 @@ bool PrintCert(const char * fileName, X509 * cert) if (certData->mCertFlags.Has(CertFlags::kExtPresent_SubjectKeyId)) { - PrintHexField(file, "Subject Key Id ", indent, certData->mSubjectKeyId.mLen, certData->mSubjectKeyId.mId, - certData->mSubjectKeyId.mLen); + PrintHexField(file, "Subject Key Id ", indent, certData->mSubjectKeyId.size(), certData->mSubjectKeyId.data(), + certData->mSubjectKeyId.size()); } if (certData->mCertFlags.Has(CertFlags::kExtPresent_AuthKeyId)) { - PrintHexField(file, "Authority Key Id ", indent, certData->mAuthKeyId.mLen, certData->mAuthKeyId.mId, - certData->mAuthKeyId.mLen); + PrintHexField(file, "Authority Key Id ", indent, certData->mAuthKeyId.size(), certData->mAuthKeyId.data(), + certData->mAuthKeyId.size()); } indent -= 4; - PrintHexField(file, "Signature ", indent, certData->mSignatureLen, certData->mSignature); + PrintHexField(file, "Signature ", indent, certData->mSignature.size(), certData->mSignature.data()); exit: CloseFile(file); diff --git a/src/tools/chip-cert/Cmd_ValidateCert.cpp b/src/tools/chip-cert/Cmd_ValidateCert.cpp index d08e5e2396f457..9d691f20f72ae8 100644 --- a/src/tools/chip-cert/Cmd_ValidateCert.cpp +++ b/src/tools/chip-cert/Cmd_ValidateCert.cpp @@ -92,9 +92,7 @@ OptionSet * gCmdOptionSets[] = enum { - kMaxCerts = 16, - kTestCertBufSize = 1024, // Size of buffer needed to hold any of the test certificates - // (in either CHIP or DER form), or to decode the certificates. + kMaxCerts = 16, }; const char * gTargetCertFileName = nullptr; @@ -148,7 +146,7 @@ bool Cmd_ValidateCert(int argc, char * argv[]) const ChipCertificateData * certToBeValidated; ChipCertificateData * validatedCert; ValidationContext context; - uint8_t certsBuf[kMaxCerts * kMaxChipCertBufSize]; + uint8_t certsBuf[kMaxCerts * kMaxCHIPCertLength]; context.Reset(); @@ -161,7 +159,7 @@ bool Cmd_ValidateCert(int argc, char * argv[]) res = ParseArgs(CMD_NAME, argc, argv, gCmdOptionSets, HandleNonOptionArgs); VerifyTrueOrExit(res); - err = certSet.Init(kMaxCerts, kTestCertBufSize); + err = certSet.Init(kMaxCerts, kMaxDERCertLength); if (err != CHIP_NO_ERROR) { fprintf(stderr, "Failed to initialize certificate set: %s\n", chip::ErrorStr(err)); @@ -170,13 +168,12 @@ bool Cmd_ValidateCert(int argc, char * argv[]) for (size_t i = 0; i < gNumCertFileNames; i++) { - res = LoadChipCert(gCACertFileNames[i], gCACertIsTrusted[i], certSet, &certsBuf[i * kMaxChipCertBufSize], - kMaxChipCertBufSize); + res = + LoadChipCert(gCACertFileNames[i], gCACertIsTrusted[i], certSet, &certsBuf[i * kMaxCHIPCertLength], kMaxCHIPCertLength); VerifyTrueOrExit(res); } - res = - LoadChipCert(gTargetCertFileName, false, certSet, &certsBuf[gNumCertFileNames * kMaxChipCertBufSize], kMaxChipCertBufSize); + res = LoadChipCert(gTargetCertFileName, false, certSet, &certsBuf[gNumCertFileNames * kMaxCHIPCertLength], kMaxCHIPCertLength); VerifyTrueOrExit(res); certToBeValidated = certSet.GetLastCert(); diff --git a/src/tools/chip-cert/chip-cert.h b/src/tools/chip-cert/chip-cert.h index 115f59645e2437..124d878ed15de3 100644 --- a/src/tools/chip-cert/chip-cert.h +++ b/src/tools/chip-cert/chip-cert.h @@ -61,6 +61,7 @@ #include #include #include +#include #include using chip::ASN1::OID; @@ -88,12 +89,6 @@ enum KeyFormat kKeyFormat_Chip_Base64 }; -enum -{ - kMaxChipCertBufSize = 400, // Maximum size of a buffer needed to hold CHIP TLV encoded certificates. - kMaxX509CertBufSize = 600, // Maximum size of a buffer needed to hold/encode X.509 certificates in DER form. -}; - struct FutureExtension { int nid; diff --git a/src/transport/AdminPairingTable.cpp b/src/transport/AdminPairingTable.cpp index e6d21855d64962..3a598580d87819 100644 --- a/src/transport/AdminPairingTable.cpp +++ b/src/transport/AdminPairingTable.cpp @@ -362,9 +362,7 @@ CHIP_ERROR AdminPairingInfo::GetCredentials(OperationalCredentialSet & credentia credentials.Release(); ReturnErrorOnFailure(credentials.Init(&certificates, 1)); - const CertificateKeyId * id = credentials.GetTrustedRootId(0); - rootKeyId.mId = id->mId; - rootKeyId.mLen = id->mLen; + rootKeyId = credentials.GetTrustedRootId(0); ReturnErrorOnFailure(credentials.SetDevOpCred(rootKeyId, mNOCCert, mNOCCertLen)); ReturnErrorOnFailure(credentials.SetDevOpCredKeypair(rootKeyId, mOperationalKey));