diff --git a/src/credentials/CHIPCert.cpp b/src/credentials/CHIPCert.cpp index af52cc49d27ed9..a55385c993e132 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.data(), static_cast(cert->mSignature.size()), + 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; diff --git a/src/credentials/CHIPCert.h b/src/credentials/CHIPCert.h index 449c2733808773..e2cc5ddbe8b1ee 100755 --- 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,19 @@ 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; /** * @struct ChipCertificateData @@ -306,7 +301,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 +308,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 +316,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. */ }; diff --git a/src/credentials/CHIPCertToX509.cpp b/src/credentials/CHIPCertToX509.cpp index ac9343626ebcac..0833d8834f69ca 100644 --- a/src/credentials/CHIPCertToX509.cpp +++ b/src/credentials/CHIPCertToX509.cpp @@ -160,7 +160,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 +281,15 @@ static CHIP_ERROR DecodeConvertSubjectPublicKeyInfo(TLVReader & reader, ASN1Writ } ASN1_END_SEQUENCE; - err = reader.Next(kTLVType_ByteString, ContextTag(kTag_EllipticCurvePublicKey)); - SuccessOrExit(err); - - err = reader.GetDataPtr(certData.mPublicKey); - SuccessOrExit(err); + ReturnErrorOnFailure(reader.Next(kTLVType_ByteString, ContextTag(kTag_EllipticCurvePublicKey))); + VerifyOrReturnError(reader.GetLength() == chip::Crypto::kP256_PublicKey_Length, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - uint32_t len = reader.GetLength(); - VerifyOrExit(len == chip::Crypto::kP256_PublicKey_Length, err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - certData.mPublicKeyLen = static_cast(len); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mPublicKey = P256PublicKeySpan(ptr); // 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 +301,6 @@ static CHIP_ERROR DecodeConvertAuthorityKeyIdentifierExtension(TLVReader & reade ChipCertificateData & certData) { CHIP_ERROR err; - uint32_t len; certData.mCertFlags.Set(CertFlags::kExtPresent_AuthKeyId); @@ -316,19 +311,16 @@ 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() == kKeyIdentifierLength, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - err = reader.GetDataPtr(certData.mAuthKeyId.mId); - SuccessOrExit(err); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mAuthKeyId = CertificateKeyId(ptr); - len = reader.GetLength(); - VerifyOrExit(len == kKeyIdentifierLength, err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - - certData.mAuthKeyId.mLen = static_cast(len); - - 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 +331,24 @@ 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() == kKeyIdentifierLength, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); - certData.mSubjectKeyId.mLen = static_cast(len); - - err = reader.GetDataPtr(certData.mSubjectKeyId.mId); - SuccessOrExit(err); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mSubjectKeyId = CertificateKeyId(ptr); - 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) @@ -678,9 +663,10 @@ 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; - ReturnErrorOnFailure(reader.GetDataPtr(certData.mSignature)); + const uint8_t * ptr; + ReturnErrorOnFailure(reader.GetDataPtr(ptr)); + certData.mSignature = P256ECDSASignatureSpan(ptr); return CHIP_NO_ERROR; } @@ -695,7 +681,8 @@ static CHIP_ERROR DecodeConvertECDSASignature(TLVReader & reader, ASN1Writer & w // 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)); + ReturnErrorOnFailure( + ConvertECDSASignatureRawToDER(certData.mSignature.data(), static_cast(certData.mSignature.size()), writer)); } ASN1_END_ENCAPSULATED; 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/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/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 57d5b6f41a4b48..6bfd947a1c17d1 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -287,7 +287,7 @@ int CASE_TestSecurePairing_Setup(void * inContext) TestContext & ctx = *reinterpret_cast(inContext); CHIP_ERROR error; - CertificateKeyId trustedRootId = { .mId = sTestCert_Root01_SubjectKeyId, .mLen = sTestCert_Root01_SubjectKeyId_Len }; + CertificateKeyId trustedRootId = CertificateKeyId(sTestCert_Root01_SubjectKeyId); error = chip::Platform::MemoryInit(); SuccessOrExit(error); diff --git a/src/tools/chip-cert/CertUtils.cpp b/src/tools/chip-cert/CertUtils.cpp index 6b70629a8fc31a..3a4f5d0d166617 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; + uint32_t len = static_cast(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; } 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/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));