Skip to content

Commit

Permalink
[nrf fromtree] [crypto] Migrate Operational Keys from mbedTLS to PSA ITS
Browse files Browse the repository at this point in the history
- Extended the OperationalKeystore API by mechanism for migration of
operational keys stored in one Operational Keystore implementation
to another.

- Extended the OperationalKeystore API by exporting keypair for Fabric.

- Added Unit tests to PersistentStorageOpKeyStore and PSAOpKeystore regarding
the new OperationalKeystore for migration and exporting OpKeys.

Added first unit tests, created export method
  • Loading branch information
ArekBalysNordic committed Jan 15, 2024
1 parent e54423d commit 35f1c18
Show file tree
Hide file tree
Showing 10 changed files with 302 additions and 4 deletions.
21 changes: 21 additions & 0 deletions src/app/server/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,27 @@ CHIP_ERROR Server::Init(const ServerInitParams & initParams)
SuccessOrExit(err);
}

#ifdef CHIP_CRYPTO_PSA
{
PersistentStorageOperationalKeystore persistentStorageOperationalKeystore;
if (CHIP_NO_ERROR == persistentStorageOperationalKeystore.Init(mDeviceStorage))
{
for (const FabricInfo & fabric : mFabrics)
{
if (CHIP_NO_ERROR !=
mOperationalKeystore->MigrateOpKeypairForFabric(fabric.GetFabricIndex(), persistentStorageOperationalKeystore))
{
ChipDeviceEvent event;
event.Type = DeviceEventType::kOperationalKeystoreMigrationFailed;
event.OperationalKeystoreMigrationFailed.fabricIndex = fabric.GetFabricIndex();
// Post event and ignore the result to not block server Init flow
err = PlatformMgr().PostEvent(&event);
}
}
}
}
#endif

SuccessOrExit(err = mAccessControl.Init(initParams.accessDelegate, sDeviceTypeResolver));
Access::SetAccessControl(mAccessControl);

Expand Down
3 changes: 1 addition & 2 deletions src/app/server/Server.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,8 @@
#include <crypto/OperationalKeystore.h>
#if CHIP_CRYPTO_PSA
#include <crypto/PSAOperationalKeystore.h>
#else
#include <crypto/PersistentStorageOperationalKeystore.h>
#endif
#include <crypto/PersistentStorageOperationalKeystore.h>
#include <inet/InetConfig.h>
#include <lib/core/CHIPConfig.h>
#include <lib/support/SafeInt.h>
Expand Down
29 changes: 29 additions & 0 deletions src/crypto/OperationalKeystore.h
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,35 @@ class OperationalKeystore
*/
virtual CHIP_ERROR CommitOpKeypairForFabric(FabricIndex fabricIndex) = 0;

/**
* @brief Try to read out the permanently commited operational keypair and save it to the buffer.
*
* @param fabricIndex - FabricIndex from which the keypair will be exported
* @param outKeypair - a reference to P256SerializedKeypair object to store the exported key.
* @retval CHIP_ERROR on success.
* @retval CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE if the key cannot be exported due to security restrictions.
* @retval CHIP_ERROR_NOT_IMPLEMENTED if the exporting is not implemented for the crypto engine.
* @retval CHIP_ERROR_INVALID_FABRIC_INDEX if there is no keypair found for `fabricIndex`.
* @retval CHIP_ERROR_BUFFER_TOO_SMALL if `keyPair` buffer is too small to store the read out keypair.
* @retval other CHIP_ERROR value on internal storage or crypto engine errors.
*/
virtual CHIP_ERROR ExportOpKeypairForFabric(FabricIndex fabricIndex, Crypto::P256SerializedKeypair & outKeypair) = 0;

/**
* @brief Migrate the operational keypair from the extern Operational keystore to this one.
*
* @param fabricIndex - FabricIndex for which to migrate the operational key
* @param operationalKeystore - a reference to the operationalKeystore implementation that may contain saved operational key
* for Fabric
* @retval CHIP_ERROR on success
* @retval CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE if the key cannot be exported due to security restrictions.
* @retval CHIP_ERROR_NOT_IMPLEMENTED if the exporting is not implemented for the crypto engine.
* @retval CHIP_ERROR_INVALID_FABRIC_INDEX if there is no keypair found for `fabricIndex`.
* @retval CHIP_ERROR_BUFFER_TOO_SMALL if `keyPair` buffer is too small to store the read out keypair.
* @retval other CHIP_ERROR value on internal storage or crypto engine errors.
*/
virtual CHIP_ERROR MigrateOpKeypairForFabric(FabricIndex fabricIndex, OperationalKeystore & operationalKeystore) const = 0;

/**
* @brief Permanently remove the keypair associated with a fabric
*
Expand Down
76 changes: 76 additions & 0 deletions src/crypto/PSAOperationalKeystore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

#include "PSAOperationalKeystore.h"
#include "PersistentStorageOperationalKeystore.h"

#include <lib/support/CHIPMem.h>

Expand Down Expand Up @@ -135,6 +136,35 @@ CHIP_ERROR PSAOperationalKeystore::NewOpKeypairForFabric(FabricIndex fabricIndex
return CHIP_NO_ERROR;
}

CHIP_ERROR PSAOperationalKeystore::PersistentP256Keypair::Deserialize(P256SerializedKeypair & input)
{
CHIP_ERROR error = CHIP_NO_ERROR;
psa_status_t status = PSA_SUCCESS;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t keyId = 0;
VerifyOrReturnError(input.Length() == mPublicKey.Length() + kP256_PrivateKey_Length, CHIP_ERROR_INVALID_ARGUMENT);

Destroy();

// Type based on ECC with the elliptic curve SECP256r1 -> PSA_ECC_FAMILY_SECP_R1
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&attributes, kP256_PrivateKey_Length * 8);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_SHA_256));
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
psa_set_key_lifetime(&attributes, PSA_KEY_LIFETIME_PERSISTENT);
psa_set_key_id(&attributes, GetKeyId());

status = psa_import_key(&attributes, input.ConstBytes() + mPublicKey.Length(), kP256_PrivateKey_Length, &keyId);
VerifyOrExit(status == PSA_SUCCESS, error = CHIP_ERROR_INTERNAL);

memcpy(mPublicKey.Bytes(), input.ConstBytes(), mPublicKey.Length());

exit:
psa_reset_key_attributes(&attributes);

return error;
}

CHIP_ERROR PSAOperationalKeystore::ActivateOpKeypairForFabric(FabricIndex fabricIndex, const Crypto::P256PublicKey & nocPublicKey)
{
VerifyOrReturnError(IsValidFabricIndex(fabricIndex) && mPendingFabricIndex == fabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX);
Expand All @@ -154,6 +184,33 @@ CHIP_ERROR PSAOperationalKeystore::CommitOpKeypairForFabric(FabricIndex fabricIn
return CHIP_NO_ERROR;
}

CHIP_ERROR PSAOperationalKeystore::ExportOpKeypairForFabric(FabricIndex fabricIndex, Crypto::P256SerializedKeypair & outKeypair)
{
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
VerifyOrReturnError(HasOpKeypairForFabric(fabricIndex), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);

size_t outSize = 0;
psa_status_t status =
psa_export_key(PersistentP256Keypair(fabricIndex).GetKeyId(), outKeypair.Bytes(), outKeypair.Capacity(), &outSize);

if (status == PSA_ERROR_BUFFER_TOO_SMALL)
{
return CHIP_ERROR_BUFFER_TOO_SMALL;
}
else if (status == PSA_ERROR_NOT_PERMITTED)
{
return CHIP_ERROR_NOT_IMPLEMENTED;
}
else if (status != PSA_SUCCESS)
{
return CHIP_ERROR_INTERNAL;
}

outKeypair.SetLength(outSize);

return CHIP_NO_ERROR;
}

CHIP_ERROR PSAOperationalKeystore::RemoveOpKeypairForFabric(FabricIndex fabricIndex)
{
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
Expand Down Expand Up @@ -209,5 +266,24 @@ void PSAOperationalKeystore::ReleasePendingKeypair()
mIsPendingKeypairActive = false;
}

CHIP_ERROR PSAOperationalKeystore::MigrateOpKeypairForFabric(FabricIndex fabricIndex,
OperationalKeystore & operationalKeystore) const
{
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
VerifyOrReturnError(fabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX);

// Do not allow overwriting the existing key and just remove it from KVS
if (!HasOpKeypairForFabric(fabricIndex))
{
PersistentP256Keypair keypair(fabricIndex);
P256SerializedKeypair serializedKeypair;
ReturnErrorOnFailure(operationalKeystore.ExportOpKeypairForFabric(fabricIndex, serializedKeypair));
ReturnErrorOnFailure(keypair.Deserialize(serializedKeypair));
ReturnErrorOnFailure(operationalKeystore.RemoveOpKeypairForFabric(fabricIndex));
}

return CHIP_NO_ERROR;
}

} // namespace Crypto
} // namespace chip
5 changes: 5 additions & 0 deletions src/crypto/PSAOperationalKeystore.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

#include <crypto/CHIPCryptoPALPSA.h>
#include <crypto/OperationalKeystore.h>
#include <lib/core/CHIPPersistentStorageDelegate.h>

namespace chip {
namespace Crypto {
Expand All @@ -31,7 +32,9 @@ class PSAOperationalKeystore final : public OperationalKeystore
CHIP_ERROR NewOpKeypairForFabric(FabricIndex fabricIndex, MutableByteSpan & outCertificateSigningRequest) override;
CHIP_ERROR ActivateOpKeypairForFabric(FabricIndex fabricIndex, const Crypto::P256PublicKey & nocPublicKey) override;
CHIP_ERROR CommitOpKeypairForFabric(FabricIndex fabricIndex) override;
CHIP_ERROR ExportOpKeypairForFabric(FabricIndex fabricIndex, Crypto::P256SerializedKeypair & outKeypair) override;
CHIP_ERROR RemoveOpKeypairForFabric(FabricIndex fabricIndex) override;
CHIP_ERROR MigrateOpKeypairForFabric(FabricIndex fabricIndex, OperationalKeystore & operationalKeystore) const;
void RevertPendingKeypair() override;
CHIP_ERROR SignWithOpKeypair(FabricIndex fabricIndex, const ByteSpan & message,
Crypto::P256ECDSASignature & outSignature) const override;
Expand All @@ -53,13 +56,15 @@ class PSAOperationalKeystore final : public OperationalKeystore
bool Exists() const;
CHIP_ERROR Generate();
CHIP_ERROR Destroy();
CHIP_ERROR Deserialize(P256SerializedKeypair & input);
};

void ReleasePendingKeypair();

PersistentP256Keypair * mPendingKeypair = nullptr;
FabricIndex mPendingFabricIndex = kUndefinedFabricIndex;
bool mIsPendingKeypairActive = false;
PersistentStorageDelegate * mStorage = nullptr;
};

} // namespace Crypto
Expand Down
66 changes: 66 additions & 0 deletions src/crypto/PersistentStorageOperationalKeystore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,51 @@ CHIP_ERROR PersistentStorageOperationalKeystore::CommitOpKeypairForFabric(Fabric
return CHIP_NO_ERROR;
}

CHIP_ERROR PersistentStorageOperationalKeystore::ExportOpKeypairForFabric(FabricIndex fabricIndex,
Crypto::P256SerializedKeypair & outKeypair)
{
VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);

// Use a SensitiveDataBuffer to get RAII secret data clearing on scope exit.
Crypto::SensitiveDataBuffer<OpKeyTLVMaxSize()> buf;
uint16_t size = static_cast<uint16_t>(buf.Capacity());
ReturnErrorOnFailure(
mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex).KeyName(), buf.Bytes(), size));
buf.SetLength(static_cast<size_t>(size));
// Read-out the operational key TLV entry.
TLV::ContiguousBufferTLVReader reader;
reader.Init(buf.Bytes(), buf.Length());

ReturnErrorOnFailure(reader.Next(TLV::kTLVType_Structure, TLV::AnonymousTag()));
TLV::TLVType containerType;
ReturnErrorOnFailure(reader.EnterContainer(containerType));

ReturnErrorOnFailure(reader.Next(kOpKeyVersionTag));
uint16_t opKeyVersion;
ReturnErrorOnFailure(reader.Get(opKeyVersion));
VerifyOrReturnError(opKeyVersion == kOpKeyVersion, CHIP_ERROR_VERSION_MISMATCH);

ReturnErrorOnFailure(reader.Next(kOpKeyDataTag));
{
ByteSpan keyData;
ReturnErrorOnFailure(reader.GetByteView(keyData));

// Unfortunately, we have to copy the data into a P256SerializedKeypair.
VerifyOrReturnError(keyData.size() <= outKeypair.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL);

// Before doing anything with the key, validate format further.
ReturnErrorOnFailure(reader.ExitContainer(containerType));
ReturnErrorOnFailure(reader.VerifyEndOfContainer());

// Save the key keypair material
memcpy(outKeypair.Bytes(), keyData.data(), keyData.size());
outKeypair.SetLength(keyData.size());
}

return CHIP_NO_ERROR;
}

CHIP_ERROR PersistentStorageOperationalKeystore::RemoveOpKeypairForFabric(FabricIndex fabricIndex)
{
VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE);
Expand Down Expand Up @@ -310,4 +355,25 @@ void PersistentStorageOperationalKeystore::ReleaseEphemeralKeypair(Crypto::P256K
Platform::Delete<Crypto::P256Keypair>(keypair);
}

CHIP_ERROR PersistentStorageOperationalKeystore::MigrateOpKeypairForFabric(FabricIndex fabricIndex,
OperationalKeystore & operationalKeystore) const
{
VerifyOrReturnError(mStorage, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
VerifyOrReturnError(fabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX);

// Do not allow overwriting the existing key and just remove it from KVS
if (!HasOpKeypairForFabric(fabricIndex))
{
P256SerializedKeypair serializedKeypair;
P256Keypair keypair;
ReturnErrorOnFailure(operationalKeystore.ExportOpKeypairForFabric(fabricIndex, serializedKeypair));
ReturnErrorOnFailure(keypair.Deserialize(serializedKeypair));
ReturnErrorOnFailure(StoreOperationalKey(fabricIndex, mStorage, &keypair));
ReturnErrorOnFailure(operationalKeystore.RemoveOpKeypairForFabric(fabricIndex));
}

return CHIP_NO_ERROR;
}

} // namespace chip
2 changes: 2 additions & 0 deletions src/crypto/PersistentStorageOperationalKeystore.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,14 @@ class PersistentStorageOperationalKeystore : public Crypto::OperationalKeystore
CHIP_ERROR NewOpKeypairForFabric(FabricIndex fabricIndex, MutableByteSpan & outCertificateSigningRequest) override;
CHIP_ERROR ActivateOpKeypairForFabric(FabricIndex fabricIndex, const Crypto::P256PublicKey & nocPublicKey) override;
CHIP_ERROR CommitOpKeypairForFabric(FabricIndex fabricIndex) override;
CHIP_ERROR ExportOpKeypairForFabric(FabricIndex fabricIndex, Crypto::P256SerializedKeypair & outKeypair) override;
CHIP_ERROR RemoveOpKeypairForFabric(FabricIndex fabricIndex) override;
void RevertPendingKeypair() override;
CHIP_ERROR SignWithOpKeypair(FabricIndex fabricIndex, const ByteSpan & message,
Crypto::P256ECDSASignature & outSignature) const override;
Crypto::P256Keypair * AllocateEphemeralKeypairForCASE() override;
void ReleaseEphemeralKeypair(Crypto::P256Keypair * keypair) override;
CHIP_ERROR MigrateOpKeypairForFabric(FabricIndex fabricIndex, OperationalKeystore & operationalKeystore) const override;

protected:
void ResetPendingKey()
Expand Down
Loading

0 comments on commit 35f1c18

Please sign in to comment.