diff --git a/src/controller/CHIPDeviceController.cpp b/src/controller/CHIPDeviceController.cpp index 64b4a7fb214663..1b870ed7836141 100644 --- a/src/controller/CHIPDeviceController.cpp +++ b/src/controller/CHIPDeviceController.cpp @@ -241,7 +241,7 @@ CHIP_ERROR DeviceController::LoadLocalCredentials(Transport::AdminPairingInfo * uint8_t * chipCert = buffer1.Get(); uint32_t chipCertLen = 0; - ReturnErrorOnFailure(ConvertX509CertToChipCert(cert, certLen, chipCert, kMaxCHIPOpCertLength, chipCertLen)); + ReturnErrorOnFailure(ConvertX509CertToChipCert(ByteSpan(cert, certLen), chipCert, kMaxCHIPOpCertLength, chipCertLen)); ReturnErrorOnFailure(admin->SetOperationalCert(ByteSpan(chipCert, chipCertLen))); @@ -249,7 +249,7 @@ CHIP_ERROR DeviceController::LoadLocalCredentials(Transport::AdminPairingInfo * ReturnErrorOnFailure(mOperationalCredentialsDelegate->GetRootCACertificate(0, cert, kMaxCHIPOpCertLength, certLen)); chipCertLen = 0; - ReturnErrorOnFailure(ConvertX509CertToChipCert(cert, certLen, chipCert, kMaxCHIPOpCertLength, chipCertLen)); + ReturnErrorOnFailure(ConvertX509CertToChipCert(ByteSpan(cert, certLen), chipCert, kMaxCHIPOpCertLength, chipCertLen)); ReturnErrorOnFailure(admin->SetRootCert(ByteSpan(chipCert, chipCertLen))); diff --git a/src/credentials/CHIPCert.cpp b/src/credentials/CHIPCert.cpp index af52cc49d27ed9..738a13099c6174 100644 --- a/src/credentials/CHIPCert.cpp +++ b/src/credentials/CHIPCert.cpp @@ -324,7 +324,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; } @@ -380,12 +380,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)); @@ -483,7 +483,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); } @@ -524,7 +524,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(); } @@ -539,7 +539,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; } @@ -569,21 +569,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)); } @@ -591,14 +590,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() @@ -625,8 +623,7 @@ bool ChipRDN::IsEqual(const ChipRDN & other) const } else { - return (mAttrValue.mString.mLen == other.mAttrValue.mString.mLen && - memcmp(mAttrValue.mString.mValue, other.mAttrValue.mString.mValue, mAttrValue.mString.mLen) == 0); + return mAttrValue.mString.data_equal(other.mAttrValue.mString); } } @@ -659,39 +656,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; -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].mAttrValue.mString = val; -exit: - return err; + return CHIP_NO_ERROR; } CHIP_ERROR ChipDN::GetCertType(uint8_t & certType) const @@ -792,11 +784,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; @@ -844,16 +831,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--; } @@ -861,31 +850,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; @@ -895,15 +886,15 @@ 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) { static constexpr size_t kMaxBytesForDeferredLenList = sizeof(uint8_t *) + // size of a single pointer in the deferred list @@ -913,13 +904,11 @@ CHIP_ERROR ConvertECDSASignatureRawToDER(const uint8_t * rawSig, uint16_t rawSig uint8_t localDERSigBuf[kMax_ECDSA_Signature_Length + kMaxBytesForDeferredLenList]; 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(localDERSigBuf, sizeof(localDERSigBuf)); - ReturnErrorOnFailure(ConvertECDSASignatureRawToDER(rawSig, rawSigLen, writer)); + ReturnErrorOnFailure(ConvertECDSASignatureRawToDER(rawSig, writer)); ReturnErrorOnFailure(writer.Finalize()); @@ -932,24 +921,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 old mode 100755 new mode 100644 index 0dfaa4e3d6d73f..dd5d15ca253b4d --- a/src/credentials/CHIPCert.h +++ b/src/credentials/CHIPCert.h @@ -186,16 +186,14 @@ enum */ struct ChipRDN { - union + union mAttrValue { - 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. */ + mAttrValue(){}; + ~mAttrValue(){}; + uint64_t mChipVal; /**< CHIP specific DN attribute value. */ + ByteSpan mString; /**< Attribute value when encoded as a string. */ + } mAttrValue; /**< DN attribute value union: string or unsigned integer. */ + chip::ASN1::OID mAttrOID; /**< DN attribute CHIP OID. */ bool IsEqual(const ChipRDN & other) const; bool IsEmpty() const { return mAttrOID == chip::ASN1::kOID_NotSpecified; } @@ -228,13 +226,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. @@ -271,21 +268,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. */ +typedef FixedByteSpan CertificateKeyId; - 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. + */ +typedef FixedByteSpan P256ECDSASignatureSpan; + +/** + * @brief A data structure for holding a P256 Public Key, without the ownership of it. + */ +typedef FixedByteSpan P256PublicKeySpan; + +/** + * @brief A data structure for holding a P256 Integer, without the ownership of it. + */ +typedef FixedByteSpan P256IntegerSpan; /** * @struct ChipCertificateData @@ -306,7 +306,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. */ @@ -314,8 +313,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. */ @@ -323,8 +321,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. */ }; @@ -621,16 +618,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. @@ -656,16 +652,15 @@ CHIP_ERROR ConvertX509CertsToChipCertArray(const ByteSpan & x509NOC, const ByteS /** * @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 @@ -806,53 +801,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 6cd0e6e3b7dc49..ba11b75c0a4af0 100644 --- a/src/credentials/CHIPCertFromX509.cpp +++ b/src/credentials/CHIPCertFromX509.cpp @@ -554,15 +554,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; } @@ -702,37 +700,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, 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, uint8_t * chipCertArrayBuf, uint32_t chipCertArrayBufSize, uint32_t & chipCertBufLen) { // NOC is mandatory - VerifyOrReturnError(x509NOC.size() > 0, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!x509NOC.empty(), CHIP_ERROR_INVALID_ARGUMENT); TLVWriter writer; writer.Init(chipCertArrayBuf, chipCertArrayBufSize); @@ -747,7 +744,7 @@ CHIP_ERROR ConvertX509CertsToChipCertArray(const ByteSpan & x509NOC, const ByteS ReturnErrorOnFailure(ConvertCertificate(reader, writer, AnonymousTag, nocIssuer, nocSubject, nocFabric)); // 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..6268c4b70bc324 100644 --- a/src/credentials/CHIPOperationalCredentials.h +++ b/src/credentials/CHIPOperationalCredentials.h @@ -153,7 +153,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 43dbb7eae55554..3f6c0f958bc1a8 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 a404afafffc8ab..90b28cc0746c7c 100644 --- a/src/credentials/tests/TestChipCert.cpp +++ b/src/credentials/tests/TestChipCert.cpp @@ -138,10 +138,8 @@ 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; + ByteSpan inCert; + ByteSpan expectedOutCert; uint8_t outCertBuf[kTestCertBufSize]; uint32_t outCertLen; @@ -149,25 +147,22 @@ static void TestChipCert_ChipToX509(nlTestSuite * inSuite, void * inContext) { 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; + ByteSpan inCert; + ByteSpan expectedOutCert; uint8_t outCertBuf[kTestCertBufSize]; uint32_t outCertLen; @@ -175,15 +170,14 @@ static void TestChipCert_X509ToChip(nlTestSuite * inSuite, void * inContext) { 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))); } } @@ -736,7 +730,8 @@ static void TestChipCert_GenerateRootCert(nlTestSuite * inSuite, void * inContex 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); @@ -774,7 +769,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); } @@ -802,7 +798,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); @@ -843,7 +840,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); @@ -892,7 +890,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); } @@ -940,7 +939,8 @@ static void TestChipCert_VerifyGeneratedCerts(nlTestSuite * inSuite, void * inCo 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, @@ -948,13 +948,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); @@ -1024,7 +1026,8 @@ static void TestChipCert_X509ToChipArray(nlTestSuite * inSuite, void * inContext static uint8_t rootCertBuf[kTestCertBufSize]; 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, @@ -1085,7 +1088,8 @@ static void TestChipCert_X509ToChipArrayNoICA(nlTestSuite * inSuite, void * inCo static uint8_t rootCertBuf[kTestCertBufSize]; 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 2a8aec586bcebc..69316505c3f8c0 100644 --- a/src/crypto/tests/CHIPCryptoPALTest.cpp +++ b/src/crypto/tests/CHIPCryptoPALTest.cpp @@ -1462,8 +1462,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; @@ -1471,12 +1470,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 99c38f19418dde..225250a41a451d 100644 --- a/src/protocols/secure_channel/CASESession.cpp +++ b/src/protocols/secure_channel/CASESession.cpp @@ -74,7 +74,7 @@ static constexpr ExchangeContext::Timeout kSigma_Response_Timeout = 30000; CASESession::CASESession() { - mTrustedRootId.mId = nullptr; + mTrustedRootId = CertificateKeyId(); // dummy initialization REMOVE LATER for (size_t i = 0; i < fabricSecret.Capacity(); i++) { @@ -97,10 +97,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(); @@ -336,9 +336,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()); @@ -543,7 +544,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->Start(), msg_r2_signed_enc_len); bbuf.Put(tag, sizeof(tag)); @@ -963,22 +964,20 @@ 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])) { - 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; } @@ -1031,7 +1030,7 @@ CHIP_ERROR CASESession::Validate_and_RetrieveResponderID(const uint8_t ** msgIte Encoding::LittleEndian::BufferWriter bbuf(responderID, responderID.Length()); ReturnErrorOnFailure(DecodeChipCert(*responderOpCert, responderOpCertLen, chipCertData)); - bbuf.Put(chipCertData.mPublicKey, chipCertData.mPublicKeyLen); + bbuf.Put(chipCertData.mPublicKey.data(), chipCertData.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 41b38e6d9ab190..2ed8679374bcf2 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 = 32; diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 93d5469fc7a35d..a0d2c130da7ca8 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -286,7 +286,7 @@ int CASE_TestSecurePairing_Setup(void * inContext) { TestContext & ctx = *reinterpret_cast(inContext); - CertificateKeyId trustedRootId = { .mId = sTestCert_Root01_SubjectKeyId, .mLen = sTestCert_Root01_SubjectKeyId_Len }; + CertificateKeyId trustedRootId = CertificateKeyId(sTestCert_Root01_SubjectKeyId); ReturnErrorOnFailure(chip::Platform::MemoryInit()); diff --git a/src/tools/chip-cert/CertUtils.cpp b/src/tools/chip-cert/CertUtils.cpp index 6b70629a8fc31a..ac539bbc3b507c 100644 --- a/src/tools/chip-cert/CertUtils.cpp +++ b/src/tools/chip-cert/CertUtils.cpp @@ -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].mAttrValue.mString.data()), + static_cast(rdn[i].mAttrValue.mString.size()), -1, 0)) { ReportOpenSSLErrorAndExit("X509_NAME_add_entry_by_NID", res = false); } @@ -142,12 +142,12 @@ void ToolChipDN::PrintDN(FILE * file, const char * name) const } else { - uint32_t len = rdn[i].mAttrValue.mString.mLen; + size_t len = rdn[i].mAttrValue.mString.size(); if (len > sizeof(valueStr) - 1) { len = sizeof(valueStr) - 1; } - memcpy(valueStr, rdn[i].mAttrValue.mString.mValue, len); + memcpy(valueStr, rdn[i].mAttrValue.mString.data(), len); valueStr[len] = 0; } @@ -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(), kMaxX509CertBufSize, 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)); diff --git a/src/tools/chip-cert/Cmd_GenCert.cpp b/src/tools/chip-cert/Cmd_GenCert.cpp index 6f50fe65e8d4eb..c0a3b40b35cdca 100755 --- 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..5f7adc6c939459 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); @@ -179,12 +179,12 @@ void PrintDN(FILE * file, const char * name, int indent, const ChipDN * dn) } else { - uint32_t len = dn->rdn[i].mAttrValue.mString.mLen; + size_t len = dn->rdn[i].mAttrValue.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].mAttrValue.mString.data(), len); valueStr[len] = 0; } @@ -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/chip-cert.h b/src/tools/chip-cert/chip-cert.h index 6d4dd82e66dabc..0bbf342a78aae9 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; diff --git a/src/transport/AdminPairingTable.cpp b/src/transport/AdminPairingTable.cpp index 3ff3946c536bdf..9fa20a9c3e23d6 100644 --- a/src/transport/AdminPairingTable.cpp +++ b/src/transport/AdminPairingTable.cpp @@ -284,9 +284,7 @@ CHIP_ERROR AdminPairingInfo::GetCredentials(OperationalCredentialSet & credentia credentials.Release(); ReturnErrorOnFailure(credentials.Init(&certificates, certificates.GetCertCount())); - const CertificateKeyId * id = credentials.GetTrustedRootId(0); - rootKeyId.mId = id->mId; - rootKeyId.mLen = id->mLen; + rootKeyId = credentials.GetTrustedRootId(0); ReturnErrorOnFailure(credentials.SetDevOpCred(rootKeyId, mOperationalCert, mOpCertLen)); ReturnErrorOnFailure(credentials.SetDevOpCredKeypair(rootKeyId, mOperationalKey));