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
Implemented a mechanism to detect all existing mbedTLS-related
operational keys stored in settings (mt/f/%d/o) and move them to
the PSA ITS secure storage.

After the migration all keys will be removed from settings space.
  • Loading branch information
ArekBalysNordic committed Jan 10, 2024
1 parent 496275a commit 93d9f1d
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/app/server/Server.h
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ struct CommonCaseDeviceServerInitParams : public ServerInitParams
if (this->operationalKeystore == nullptr)
{
#if CHIP_CRYPTO_PSA
ReturnErrorOnFailure(sPSAOperationalKeystore.Init(this->persistentStorageDelegate));
this->operationalKeystore = &sPSAOperationalKeystore;
#else
// WARNING: PersistentStorageOperationalKeystore::Finish() is never called. It's fine for
Expand Down
93 changes: 93 additions & 0 deletions src/crypto/PSAOperationalKeystore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,24 @@

#include "PSAOperationalKeystore.h"

#include <lib/core/TLV.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/DefaultStorageKeyAllocator.h>

#include <psa/crypto.h>

namespace chip {
namespace Crypto {

namespace {
// Tags and version of operational keypair storage copied from PersistentStorageOperationalKeystore.cpp
// These values must be compatible with values in the PersistentStorageOperationalKeystore.cpp file to perform a proper keys
// migration.
constexpr TLV::Tag kOpKeyVersionTag = TLV::ContextTag(0);
constexpr TLV::Tag kOpKeyDataTag = TLV::ContextTag(1);
constexpr uint16_t kOpKeyVersion = 1;
} // namespace

PSAOperationalKeystore::PersistentP256Keypair::PersistentP256Keypair(FabricIndex fabricIndex)
{
ToPsaContext(mKeypair).key_id = MakeOperationalKeyId(fabricIndex);
Expand Down Expand Up @@ -102,6 +113,9 @@ bool PSAOperationalKeystore::HasOpKeypairForFabric(FabricIndex fabricIndex) cons
{
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), false);

// check if the key exists in the PersistentStorageOperationalKeystore exist, and if so move it to the PSA ITS secure storage.
VerifyOrReturnError(CHIP_NO_ERROR == MoveOpKeysFromKVSToITS(fabricIndex), false);

if (mPendingFabricIndex == fabricIndex)
{
return mIsPendingKeypairActive;
Expand Down Expand Up @@ -135,6 +149,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 Down Expand Up @@ -178,6 +221,8 @@ CHIP_ERROR PSAOperationalKeystore::SignWithOpKeypair(FabricIndex fabricIndex, co
Crypto::P256ECDSASignature & outSignature) const
{
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
// Check if the key already exists and need to be migrated to PSA ITS
VerifyOrReturnError(HasOpKeypairForFabric(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);

if (mPendingFabricIndex == fabricIndex)
{
Expand Down Expand Up @@ -209,5 +254,53 @@ void PSAOperationalKeystore::ReleasePendingKeypair()
mIsPendingKeypairActive = false;
}

CHIP_ERROR PSAOperationalKeystore::MoveOpKeysFromKVSToITS(FabricIndex fabricIndex) const
{
Crypto::SensitiveDataBuffer<TLV::EstimateStructOverhead(sizeof(uint16_t), P256SerializedKeypair::Capacity())> buf;
uint16_t keySize = static_cast<uint16_t>(buf.Capacity());

if (CHIP_NO_ERROR ==
mStorage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex).KeyName(), buf.Bytes(), keySize))
{
PersistentP256Keypair keypair(fabricIndex);
// Do not allow overwriting the existing key and just remove it from KVS
if (!keypair.Exists())
{
// Read the operational private and public keys from the TLV entry
buf.SetLength(static_cast<size_t>(keySize));
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));
ReturnErrorOnFailure(reader.ExitContainer(containerType));
ReturnErrorOnFailure(reader.VerifyEndOfContainer());

VerifyOrReturnError(keyData.size() == (kP256_PrivateKey_Length + kP256_PublicKey_Length), CHIP_ERROR_BUFFER_TOO_SMALL);

// Migrate the operational keys
P256SerializedKeypair serializedKeypair;
ReturnErrorOnFailure(serializedKeypair.SetLength(kP256_PrivateKey_Length + kP256_PublicKey_Length));
memcpy(serializedKeypair.Bytes(), keyData.data(), kP256_PrivateKey_Length + kP256_PublicKey_Length);
ReturnErrorOnFailure(keypair.Deserialize(serializedKeypair));
ReturnErrorOnFailure(mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex).KeyName()));
}
else
{
ReturnErrorOnFailure(mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricOpKey(fabricIndex).KeyName()));
}
}

return CHIP_NO_ERROR;
}

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

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

namespace chip {
namespace Crypto {

class PSAOperationalKeystore final : public OperationalKeystore
{
public:
/**
* @brief Initialize the PSA Operational Keystore to save the persistent storage delegate.
*
* The PersistentStorageDelegate object will be needed to perform operational keys migration from the Persistent Storage
* Operational Keystore database to PSA ITS secure storage.
*
* NOTE: The migration of the operational keys will occur on each HasOpKeypairForFabric method call for specific fabric index.
*
* @param storage Pointer to persistent storage delegate to use. Must outlive this instance.
* @retval CHIP_NO_ERROR on success.
* @retval CHIP_ERROR_INCORRECT_STATE if already initialized.
*/
CHIP_ERROR Init(PersistentStorageDelegate * storage)
{
VerifyOrReturnError(mStorage == nullptr, CHIP_ERROR_INCORRECT_STATE);
mStorage = storage;
return CHIP_NO_ERROR;
}

bool HasPendingOpKeypair() const override;
bool HasOpKeypairForFabric(FabricIndex fabricIndex) const override;
CHIP_ERROR NewOpKeypairForFabric(FabricIndex fabricIndex, MutableByteSpan & outCertificateSigningRequest) override;
Expand Down Expand Up @@ -53,13 +73,18 @@ 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;

private:
CHIP_ERROR MoveOpKeysFromKVSToITS(FabricIndex fabricIndex) const;
};

} // namespace Crypto
Expand Down
4 changes: 4 additions & 0 deletions src/crypto/PersistentStorageOperationalKeystore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,15 @@ using namespace chip::Crypto;
namespace {

// Tags for our operational keypair storage.
// If the tags changes, change also the copy in the PSAOperationalKeystore.cpp to keep migration of the operational keys to
// PSA ITS properly
constexpr TLV::Tag kOpKeyVersionTag = TLV::ContextTag(0);
constexpr TLV::Tag kOpKeyDataTag = TLV::ContextTag(1);

// If this version grows beyond UINT16_MAX, adjust OpKeypairTLVMaxSize
// accordingly.
// If this version changes, change also the copy in the PSAOperationalKeystore.cpp to keep migration of the operational keys to
// PSA ITS properly
constexpr uint16_t kOpKeyVersion = 1;

constexpr size_t OpKeyTLVMaxSize()
Expand Down

0 comments on commit 93d9f1d

Please sign in to comment.