From 70ebbb31e5a3bdc9319324971a546bf12827894a Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Wed, 21 Jun 2023 17:16:19 +0200 Subject: [PATCH 01/16] Fix typo in ckmc-manager.h Change-Id: I76c95dcf4c32f3fc70abea680f757edd45676c07 --- src/include/ckmc/ckmc-manager.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/include/ckmc/ckmc-manager.h b/src/include/ckmc/ckmc-manager.h index 3c04778..3dc6d9f 100644 --- a/src/include/ckmc/ckmc-manager.h +++ b/src/include/ckmc/ckmc-manager.h @@ -1189,7 +1189,7 @@ int ckmc_import_wrapped_key(const ckmc_param_list_h params, * * @return @c 0 on success, otherwise a negative error value * @retval #CKMC_ERROR_NONE Successful - * @retval #CKMC_ERROR_PERMISSION_DENIED Insuffucient permissions to access key manager, the + * @retval #CKMC_ERROR_PERMISSION_DENIED Insufficient permissions to access key manager, the * wrapping key or the key being wrapped * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid (missing or invalid mandatory * algorithm parameter, GCM tag authentication failed, -- 2.7.4 From 915cfa9216d2daaee021d42c4690c0f67b06c3db Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Wed, 21 Jun 2023 20:50:26 +0200 Subject: [PATCH 02/16] Fix wrong fuction name in the documentation Change-Id: Ib83d88de1d17bd32b86cd7c99b5dd12247d0aaf8 --- src/include/ckmc/ckmc-manager.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/include/ckmc/ckmc-manager.h b/src/include/ckmc/ckmc-manager.h index 3dc6d9f..5e7a755 100644 --- a/src/include/ckmc/ckmc-manager.h +++ b/src/include/ckmc/ckmc-manager.h @@ -869,8 +869,8 @@ int ckmc_get_cert_chain_with_trustedcert(const ckmc_cert_s *cert, * @retval #CKMC_ERROR_PERMISSION_DENIED Failed to access key manager * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid * @pre User is already logged in and the user key is already loaded into memory in plain text form. - * @pre @a pcert_chain_list is created with ckmc_get_certificate_chain() or - * ckmc_get_certificate_chain_with_alias(). + * @pre @a pcert_chain_list is created with ckmc_get_cert_chain() or + * ckmc_get_cert_chain_with_alias(). * @see ckmc_get_cert_chain()) * @see ckmc_cert_list_all_free() */ -- 2.7.4 From 45cf0c035909249b49b20242a863ae5f9162436a Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 13 Jun 2023 16:47:07 +0200 Subject: [PATCH 03/16] Simplify serialization calls Remove unnecessary casts and use type deduction. Change-Id: I88d8ae4b8060a509984a6883289c4bb05a9c1015 --- .../client-async/client-manager-async-impl.cpp | 7 +++---- .../client-async/client-manager-async-impl.h | 2 +- src/manager/client/client-control.cpp | 20 ++++++++---------- src/manager/client/client-manager-impl.cpp | 7 +++---- src/manager/common/message-buffer.cpp | 2 +- src/manager/common/protocols.cpp | 24 +++++++++------------- src/manager/service/ckm-service.cpp | 15 ++++++-------- 7 files changed, 33 insertions(+), 44 deletions(-) diff --git a/src/manager/client-async/client-manager-async-impl.cpp b/src/manager/client-async/client-manager-async-impl.cpp index f5082ec..92a18e4 100644 --- a/src/manager/client-async/client-manager-async-impl.cpp +++ b/src/manager/client-async/client-manager-async-impl.cpp @@ -314,7 +314,7 @@ void ManagerAsync::Impl::createKeyAES(const ObserverPtr &observer, AliasSupport aliasHelper(keyAlias); sendToStorage(LogicCommand::CREATE_KEY_AES, observer, - static_cast(size), PolicySerializable(policyKey), + size, PolicySerializable(policyKey), aliasHelper.getName(), aliasHelper.getOwner()); }); } @@ -341,13 +341,12 @@ void ManagerAsync::Impl::crypt( CryptoAlgorithmSerializable cas(algo); m_counter++; - auto command = static_cast(encryption ? - EncryptionCommand::ENCRYPT : EncryptionCommand::DECRYPT); + auto command = encryption ? EncryptionCommand::ENCRYPT : EncryptionCommand::DECRYPT; auto send = SerializeMessage(command, m_counter, cas, helper.getName(), helper.getOwner(), password, input); thread()->sendMessage(AsyncRequest(observer, SERVICE_SOCKET_ENCRYPTION, - std::move(send), m_counter, command)); + std::move(send), m_counter, static_cast(command))); }); } diff --git a/src/manager/client-async/client-manager-async-impl.h b/src/manager/client-async/client-manager-async-impl.h index eb354ef..3caf47c 100644 --- a/src/manager/client-async/client-manager-async-impl.h +++ b/src/manager/client-async/client-manager-async-impl.h @@ -155,7 +155,7 @@ private: void sendToStorage(LogicCommand command, const ObserverPtr &observer, Args &&... args) { m_counter++; - auto send = SerializeMessage(static_cast(command), m_counter, std::forward(args)...); + auto send = SerializeMessage(command, m_counter, std::forward(args)...); thread()->sendMessage(AsyncRequest(observer, SERVICE_SOCKET_CKM_STORAGE, std::move(send), m_counter, static_cast(command))); } diff --git a/src/manager/client/client-control.cpp b/src/manager/client/client-control.cpp index d0a4d18..50c1870 100644 --- a/src/manager/client/client-control.cpp +++ b/src/manager/client/client-control.cpp @@ -46,9 +46,7 @@ public: return CKM_API_ERROR_INPUT_PARAM; MessageBuffer recv; - auto send = SerializeMessage(static_cast(ControlCommand::UNLOCK_USER_KEY), - user, - password); + auto send = SerializeMessage(ControlCommand::UNLOCK_USER_KEY, user, password); int retCode = m_controlConnection.processRequest(send, recv); @@ -70,7 +68,7 @@ public: return CKM_API_ERROR_INPUT_PARAM; MessageBuffer recv; - auto send = SerializeMessage(static_cast(ControlCommand::LOCK_USER_KEY), user); + auto send = SerializeMessage(ControlCommand::LOCK_USER_KEY, user); int retCode = m_controlConnection.processRequest(send, recv); @@ -92,7 +90,7 @@ public: return CKM_API_ERROR_INPUT_PARAM; MessageBuffer recv; - auto send = SerializeMessage(static_cast(ControlCommand::REMOVE_USER_DATA), user); + auto send = SerializeMessage(ControlCommand::REMOVE_USER_DATA, user); int retCode = m_controlConnection.processRequest(send, recv); @@ -115,7 +113,7 @@ public: return CKM_API_ERROR_INPUT_PARAM; MessageBuffer recv; - auto send = SerializeMessage(static_cast(ControlCommand::CHANGE_USER_PASSWORD), + auto send = SerializeMessage(ControlCommand::CHANGE_USER_PASSWORD, user, oldPassword, newPassword); @@ -140,7 +138,7 @@ public: return CKM_API_ERROR_INPUT_PARAM; MessageBuffer recv; - auto send = SerializeMessage(static_cast(ControlCommand::RESET_USER_PASSWORD), + auto send = SerializeMessage(ControlCommand::RESET_USER_PASSWORD, user, newPassword); @@ -164,7 +162,7 @@ public: return CKM_API_ERROR_INPUT_PARAM; MessageBuffer recv; - auto send = SerializeMessage(static_cast(ControlCommand::REMOVE_APP_DATA), owner); + auto send = SerializeMessage(ControlCommand::REMOVE_APP_DATA, owner); int retCode = m_controlConnection.processRequest(send, recv); @@ -183,7 +181,7 @@ public: EXCEPTION_GUARD_START_CPPAPI MessageBuffer recv; - auto send = SerializeMessage(static_cast(ControlCommand::UPDATE_CC_MODE)); + auto send = SerializeMessage(ControlCommand::UPDATE_CC_MODE); int retCode = m_controlConnection.processRequest(send, recv); @@ -206,8 +204,8 @@ public: MessageBuffer recv; AliasSupport helper(alias); - auto send = SerializeMessage(static_cast(ControlCommand::SET_PERMISSION), - static_cast(user), + auto send = SerializeMessage(ControlCommand::SET_PERMISSION, + user, helper.getName(), helper.getOwner(), accessor, diff --git a/src/manager/client/client-manager-impl.cpp b/src/manager/client/client-manager-impl.cpp index 4d6e59e..0204028 100644 --- a/src/manager/client/client-manager-impl.cpp +++ b/src/manager/client/client-manager-impl.cpp @@ -101,7 +101,7 @@ Manager::Impl::Request::Request(Manager::Impl &impl, Cmd cmd, CKM::ServiceConnec { static_assert(sizeof cmd <= sizeof(int)); const auto msgId = m_msgId = ++impl.m_counter; - m_retCode = doRequest(m_recv, conn, static_cast(cmd), msgId, std::forward(t)...); + m_retCode = doRequest(m_recv, conn, cmd, msgId, std::forward(t)...); } Manager::Impl::Request::operator bool() const { @@ -216,8 +216,7 @@ int Manager::Impl::getPKCS12(const Alias &alias, const Password &keyPass, int msgId = ++m_counter; MessageBuffer recv; - int retCode = doRequest(recv, m_storageConnection, - static_cast(LogicCommand::GET_PKCS12), msgId, + int retCode = doRequest(recv, m_storageConnection, LogicCommand::GET_PKCS12, msgId, helper.getName(), helper.getOwner(), keyPass, certPass); if (CKM_API_SUCCESS != retCode) @@ -476,7 +475,7 @@ int Manager::Impl::createKeyAES( AliasSupport aliasHelper(keyAlias); return Request(*this, LogicCommand::CREATE_KEY_AES, m_storageConnection, - static_cast(size), PolicySerializable(policyKey), + size, PolicySerializable(policyKey), aliasHelper.getName(), aliasHelper.getOwner() ).maybeDeserialize(); diff --git a/src/manager/common/message-buffer.cpp b/src/manager/common/message-buffer.cpp index 237f716..4dc5c16 100644 --- a/src/manager/common/message-buffer.cpp +++ b/src/manager/common/message-buffer.cpp @@ -80,7 +80,7 @@ void MessageSerializer::Sizer::Write(size_t num, const void*) MessageSerializer::Writer::Writer(size_t size) { m_buffer.reserve(sizeof(size_t) + size); - Serializer::Serialize(*this, size); + Serialization::Serialize(*this, size); } void MessageSerializer::Writer::Read(size_t, void*) diff --git a/src/manager/common/protocols.cpp b/src/manager/common/protocols.cpp index d402548..d270f0c 100644 --- a/src/manager/common/protocols.cpp +++ b/src/manager/common/protocols.cpp @@ -51,16 +51,14 @@ void PolicySerializable::Serialize(IStream &stream) const { Serialization::Serialize(stream, password); Serialization::Serialize(stream, extractable); - Serialization::Serialize(stream, static_cast(backend)); + Serialization::Serialize(stream, backend); } void PolicySerializable::Deserialize(IStream &stream) { - int policyBackend; Deserialization::Deserialize(stream, password); Deserialization::Deserialize(stream, extractable); - Deserialization::Deserialize(stream, policyBackend); - backend = static_cast(policyBackend); + Deserialization::Deserialize(stream, backend); } PKCS12Serializable::PKCS12Serializable() @@ -212,15 +210,13 @@ CryptoAlgorithmSerializable::CryptoAlgorithmSerializable(IStream &stream) void CryptoAlgorithmSerializable::Deserialize(IStream &stream) { size_t plen = 0; - Deserializer::Deserialize(stream, plen); + Deserialization::Deserialize(stream, plen); while (plen) { ParamName name; uint64_t integer; RawBuffer buffer; - int tmpName; - Deserializer::Deserialize(stream, tmpName); - name = static_cast(tmpName); + Deserialization::Deserialize(stream, name); switch (name) { case ParamName::ED_IV: @@ -230,7 +226,7 @@ void CryptoAlgorithmSerializable::Deserialize(IStream &stream) case ParamName::KBKDF_CONTEXT: case ParamName::KBKDF_FIXED_INPUT: case ParamName::ECDH_PUBKEY: - Deserializer::Deserialize(stream, buffer); + Deserialization::Deserialize(stream, buffer); setParam(name, buffer); break; @@ -248,7 +244,7 @@ void CryptoAlgorithmSerializable::Deserialize(IStream &stream) case ParamName::KBKDF_LLEN: case ParamName::KBKDF_COUNTER_LOCATION: case ParamName::KBKDF_NO_SEPARATOR: - Deserializer::Deserialize(stream, integer); + Deserialization::Deserialize(stream, integer); setParam(name, integer); break; @@ -262,17 +258,17 @@ void CryptoAlgorithmSerializable::Deserialize(IStream &stream) void CryptoAlgorithmSerializable::Serialize(IStream &stream) const { - Serializer::Serialize(stream, m_params.size()); + Serialization::Serialize(stream, m_params.size()); for (const auto &it : m_params) { - Serializer::Serialize(stream, static_cast(it.first)); + Serialization::Serialize(stream, it.first); uint64_t integer; RawBuffer buffer; if (it.second->getInt(integer)) - Serializer::Serialize(stream, integer); + Serialization::Serialize(stream, integer); else if (it.second->getBuffer(buffer)) - Serializer::Serialize(stream, buffer); + Serialization::Serialize(stream, buffer); else ThrowMsg(UnsupportedParam, "Unsupported param type"); } diff --git a/src/manager/service/ckm-service.cpp b/src/manager/service/ckm-service.cpp index 7bfebbe..1803635 100644 --- a/src/manager/service/ckm-service.cpp +++ b/src/manager/service/ckm-service.cpp @@ -116,21 +116,18 @@ bool CKMService::ProcessOne( RawBuffer CKMService::ProcessControl(MessageBuffer &buffer, bool allowed) { - int command = 0; uid_t user = 0; - ControlCommand cc; + ControlCommand command; Password newPass, oldPass; ClientId explicitOwner; buffer.Deserialize(command); - LogDebug("Process control. Command: " << command); + LogDebug("Process control. Command: " << static_cast(command)); std::function logicFunc; - cc = static_cast(command); - - switch (cc) { + switch (command) { case ControlCommand::UNLOCK_USER_KEY: buffer.Deserialize(user, newPass); logicFunc = [&]() { @@ -213,7 +210,7 @@ RawBuffer CKMService::ProcessControl(MessageBuffer &buffer, bool allowed) RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) { - int command = 0; + LogicCommand command; int msgId = 0; DataType tmpDataType; Name name; @@ -230,9 +227,9 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) Password nullPassword(""); m_logic->unlockUserKey(cred.clientUid, nullPassword); - LogDebug("Process storage. Command: " << command); + LogDebug("Process storage. Command: " << static_cast(command)); - switch (static_cast(command)) { + switch (command) { case LogicCommand::SAVE: { RawBuffer rawData; PolicySerializable policy; -- 2.7.4 From 036a1bfaf01bb99777fbbe17ab247a86e64334cc Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Thu, 22 Jun 2023 11:04:18 +0200 Subject: [PATCH 04/16] Add missing exception guard to C++ API Change-Id: Ie9164be51dbea8cf8b6f1524808fbb8841c2f2bf --- src/manager/client/client-manager-impl.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/manager/client/client-manager-impl.cpp b/src/manager/client/client-manager-impl.cpp index 0204028..d78f0c1 100644 --- a/src/manager/client/client-manager-impl.cpp +++ b/src/manager/client/client-manager-impl.cpp @@ -403,7 +403,9 @@ int Manager::Impl::getDataAliasVector(AliasVector &aliasVector) int Manager::Impl::getKeyAliasInfoVector(AliasInfoVector &aliasInfoVector) { + EXCEPTION_GUARD_START_CPPAPI return getAliasInfoVectorHelper(DataType::DB_KEY_LAST, aliasInfoVector); + EXCEPTION_GUARD_END } int Manager::Impl::getKeyEncryptionStatus(const Alias &alias, bool &status) @@ -413,7 +415,9 @@ int Manager::Impl::getKeyEncryptionStatus(const Alias &alias, bool &status) int Manager::Impl::getCertificateAliasInfoVector(AliasInfoVector &aliasInfoVector) { + EXCEPTION_GUARD_START_CPPAPI return getAliasInfoVectorHelper(DataType::CERTIFICATE, aliasInfoVector); + EXCEPTION_GUARD_END } int Manager::Impl::getCertificateEncryptionStatus(const Alias &alias, bool &status) @@ -423,7 +427,9 @@ int Manager::Impl::getCertificateEncryptionStatus(const Alias &alias, bool &stat int Manager::Impl::getDataAliasInfoVector(AliasInfoVector &aliasInfoVector) { + EXCEPTION_GUARD_START_CPPAPI return getAliasInfoVectorHelper(DataType::BINARY_DATA, aliasInfoVector); + EXCEPTION_GUARD_END } int Manager::Impl::getDataEncryptionStatus(const Alias &alias, bool &status) -- 2.7.4 From f6eac5fb2855cdc7adb40f001f3187844d68775a Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 27 Jun 2023 13:39:48 +0200 Subject: [PATCH 05/16] Update ckmc_import_wrapped_key description The remark allows passing a wrapped key without any type letting the backend autodetect it. Current implementation in SW backend does not support it. In case of TZ backend such autodetection would unnecessarily complicate the code. Since the feature is not actually needed, the value CKMC_KEY_NONE option will be forbidden from now on. Change-Id: I2396d03bd28b0eeef0a1e922029808061beb71c8 --- src/include/ckmc/ckmc-manager.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/include/ckmc/ckmc-manager.h b/src/include/ckmc/ckmc-manager.h index 5e7a755..f4db37f 100644 --- a/src/include/ckmc/ckmc-manager.h +++ b/src/include/ckmc/ckmc-manager.h @@ -1108,8 +1108,7 @@ int ckmc_decrypt_data(ckmc_param_list_h params, * * @remarks The wrapping key must be either symmetric (#CKMC_KEY_AES) or private RSA * (#CKMC_KEY_RSA_PRIVATE). - * @remarks key_type in @a wrapped_key may be set to #CKMC_KEY_NONE as an input. In such case the - * key type is determined inside key manager during storing keys. + * @remarks key_type in @a wrapped_key must not be set to #CKMC_KEY_NONE. * @remarks password in @a wrapped_key must be set to NULL. There's no need to additionally encrypt * a wrapped key. * @remarks If password in @a policy is provided, the stored key is additionally encrypted with it. -- 2.7.4 From 68bd681ac61299383a8a481497c94877fdf15a2d Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 27 Jun 2023 17:00:29 +0200 Subject: [PATCH 06/16] Return proper error for wrong wrapped key type Change-Id: I72e888e9808865c9ac3178ec8821dbf79aad9fd5 --- src/manager/client/client-manager-impl.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/manager/client/client-manager-impl.cpp b/src/manager/client/client-manager-impl.cpp index d78f0c1..961f31d 100644 --- a/src/manager/client/client-manager-impl.cpp +++ b/src/manager/client/client-manager-impl.cpp @@ -748,6 +748,9 @@ int Manager::Impl::importWrappedKey(const CryptoAlgorithm ¶ms, { EXCEPTION_GUARD_START_CPPAPI + if (keyType == KeyType::KEY_NONE) + return CKM_API_ERROR_INPUT_PARAM; + AliasSupport wrapping_helper(wrappingKeyAlias); AliasSupport helper(alias); -- 2.7.4 From 5b48826f33df8236f8aa37dda4c055b662adafc2 Mon Sep 17 00:00:00 2001 From: Dongsun Lee Date: Thu, 29 Jun 2023 16:42:00 +0900 Subject: [PATCH 07/16] add ALGO_ECDSA_SV to MAX_KEY_SIZE in tz_backend Change-Id: I484312a778a8587d3197132e5182af8b842646ce --- src/manager/crypto/tz-backend/tz-context.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index e8c500b..cc9a78c 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -66,7 +66,8 @@ static std::string rawToHexString(const RawBuffer &raw) const std::unordered_map MAX_KEY_SIZE = { { ALGO_RSA, 4096 / 8 }, { ALGO_RSA_SV, 4096 / 8 }, - { ALGO_DSA_SV, 4096 / 8 } + { ALGO_DSA_SV, 4096 / 8 }, + { ALGO_ECDSA_SV, 1024 / 8 } // 384*2 + additional space for DERR encoding }; struct EncPwd { -- 2.7.4 From 127f0a0e5983dbf2642e0badcb1a3aab3e450079 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Wed, 28 Jun 2023 10:21:21 +0200 Subject: [PATCH 08/16] Implement public key extraction in TZ backend Public keys are not secrets and there are scenarios like ECDH when they have to be extracted in raw form. Exportability logic still applies. * Separate the object id and the raw data in TZ backend objects. * Rename function arguments to make their meaning more adequate. * Use object id when making operations using given key or binary data. * Return raw data only to CKMLogic via getBinary() method. * Make getBinary() return an empty buffer for private and symmetric keys. * Move m_type to AKey where it's used. Change-Id: Idf6db51387d98f6560f0da18e2fc1d9bbc3abc4f --- src/manager/crypto/tz-backend/internals.cpp | 68 +++++++++++++------------- src/manager/crypto/tz-backend/internals.h | 28 +++++------ src/manager/crypto/tz-backend/obj.cpp | 22 ++++----- src/manager/crypto/tz-backend/obj.h | 73 +++++++++++++++++----------- src/manager/crypto/tz-backend/store.cpp | 18 ++++--- src/manager/crypto/tz-backend/tz-context.cpp | 12 ++--- src/manager/crypto/tz-backend/tz-context.h | 6 +-- 7 files changed, 123 insertions(+), 104 deletions(-) diff --git a/src/manager/crypto/tz-backend/internals.cpp b/src/manager/crypto/tz-backend/internals.cpp index aca0124..2cbdf23 100644 --- a/src/manager/crypto/tz-backend/internals.cpp +++ b/src/manager/crypto/tz-backend/internals.cpp @@ -337,9 +337,9 @@ AlgoType generateAKey(const CryptoAlgorithm &alg, return keyType; } -void destroyKey(const RawBuffer &key) +void destroyKey(const RawBuffer &keyId) { - TrustZoneContext::Instance().executeDestroy(key); + TrustZoneContext::Instance().executeDestroy(keyId); } void importData(const Data &data, @@ -364,7 +364,7 @@ void importData(const Data &data, hash); } -void importWrappedKey(const RawBuffer &wrappingKey, +void importWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, const CryptoAlgorithm &alg, const Data &encryptedKey, @@ -382,7 +382,7 @@ void importWrappedKey(const RawBuffer &wrappingKey, decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad); // TODO it is awful! - TrustZoneContext::Instance().importWrappedKey(wrappingKey, + TrustZoneContext::Instance().importWrappedKey(wrappingKeyId, wrappingKeyPwd, getAlgType(algo), iv, @@ -396,7 +396,7 @@ void importWrappedKey(const RawBuffer &wrappingKey, encryptedKeyId); } -RawBuffer exportWrappedKey(const RawBuffer &wrappingKey, +RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, const CryptoAlgorithm &alg, const RawBuffer &keyToWrapId, @@ -409,7 +409,7 @@ RawBuffer exportWrappedKey(const RawBuffer &wrappingKey, decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad); // TODO it is awful! - return TrustZoneContext::Instance().exportWrappedKey(wrappingKey, + return TrustZoneContext::Instance().exportWrappedKey(wrappingKeyId, wrappingKeyPwd, getAlgType(algo), iv, @@ -434,7 +434,7 @@ void destroyData(const RawBuffer &dataId) TrustZoneContext::Instance().destroyData(dataId); } -BufferPair encryptDataAesGcm(const RawBuffer &key, +BufferPair encryptDataAesGcm(const RawBuffer &keyId, const Pwd &pwd, const RawBuffer &iv, int tagSize, @@ -444,26 +444,26 @@ BufferPair encryptDataAesGcm(const RawBuffer &key, RawBuffer result; RawBuffer tag; - TrustZoneContext::Instance().executeEncryptAE(key, pwd, iv, tagSize, + TrustZoneContext::Instance().executeEncryptAE(keyId, pwd, iv, tagSize, aad, data, result, tag); return std::make_pair(result, tag); } -RawBuffer encryptDataAesGcmPacked(const RawBuffer &key, +RawBuffer encryptDataAesGcmPacked(const RawBuffer &keyId, const Pwd &pwd, const RawBuffer &iv, int tagSize, const RawBuffer &data, const RawBuffer &aad) { - auto pair = encryptDataAesGcm(key, pwd, iv, tagSize, data, aad); + auto pair = encryptDataAesGcm(keyId, pwd, iv, tagSize, data, aad); std::copy(pair.second.begin(), pair.second.end(), std::back_inserter(pair.first)); return pair.first; } -RawBuffer decryptDataAesGcm(const RawBuffer &key, +RawBuffer decryptDataAesGcm(const RawBuffer &keyId, const Pwd &pwd, const RawBuffer &iv, int tagSizeBits, @@ -473,13 +473,13 @@ RawBuffer decryptDataAesGcm(const RawBuffer &key, { RawBuffer result; - TrustZoneContext::Instance().executeDecryptAE(key, pwd, iv, tagSizeBits, + TrustZoneContext::Instance().executeDecryptAE(keyId, pwd, iv, tagSizeBits, tag, aad, data, result); return result; } -RawBuffer decryptDataAesGcmPacked(const RawBuffer &key, +RawBuffer decryptDataAesGcmPacked(const RawBuffer &keyId, const Pwd &pwd, const RawBuffer &iv, int tagSizeBits, @@ -491,7 +491,7 @@ RawBuffer decryptDataAesGcmPacked(const RawBuffer &key, ThrowErr(Exc::Crypto::InputParam, "Wrong size of tag"); auto tagPos = data.data() + data.size() - tagSizeBytes; - return decryptDataAesGcm(key, + return decryptDataAesGcm(keyId, pwd, iv, tagSizeBits, @@ -501,7 +501,7 @@ RawBuffer decryptDataAesGcmPacked(const RawBuffer &key, } -RawBuffer symmetricEncrypt(const RawBuffer &key, +RawBuffer symmetricEncrypt(const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &data) @@ -525,7 +525,7 @@ RawBuffer symmetricEncrypt(const RawBuffer &key, RawBuffer result; TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT, getAlgType(algo), - key, + keyId, pwd, unpack(alg, ParamName::ED_IV), data, @@ -537,7 +537,7 @@ RawBuffer symmetricEncrypt(const RawBuffer &key, alg.getParam(ParamName::ED_TAG_LEN, tagLenBits); RawBuffer aad; alg.getParam(ParamName::ED_AAD, aad); - return encryptDataAesGcmPacked(key, + return encryptDataAesGcmPacked(keyId, pwd, unpack(alg, ParamName::ED_IV), tagLenBits, @@ -552,7 +552,7 @@ RawBuffer symmetricEncrypt(const RawBuffer &key, "Incorrect algorithm provided for symmetric crypto operation"); } -RawBuffer symmetricDecrypt(const RawBuffer &key, +RawBuffer symmetricDecrypt(const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &data) @@ -576,7 +576,7 @@ RawBuffer symmetricDecrypt(const RawBuffer &key, RawBuffer result; TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT, getAlgType(algo), - key, + keyId, pwd, unpack(alg, ParamName::ED_IV), data, @@ -588,7 +588,7 @@ RawBuffer symmetricDecrypt(const RawBuffer &key, alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits); RawBuffer aad; alg.getParam(ParamName::ED_AAD, aad); - return decryptDataAesGcmPacked(key, + return decryptDataAesGcmPacked(keyId, pwd, unpack(alg, ParamName::ED_IV), tagSizeBits, @@ -603,7 +603,7 @@ RawBuffer symmetricDecrypt(const RawBuffer &key, "Incorrect algorithm provided for symmetric crypto operation"); } -RawBuffer asymmetricEncrypt(const RawBuffer &key, +RawBuffer asymmetricEncrypt(const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &data) @@ -616,7 +616,7 @@ RawBuffer asymmetricEncrypt(const RawBuffer &key, case AlgoType::RSA_OAEP: { TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT, getAlgType(algo), - key, + keyId, pwd, result, // unused dummy data, @@ -631,7 +631,7 @@ RawBuffer asymmetricEncrypt(const RawBuffer &key, "Incorrect algorithm provided for asymmetric crypto operation"); } -RawBuffer asymmetricDecrypt(const RawBuffer &key, +RawBuffer asymmetricDecrypt(const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &cipher) @@ -644,7 +644,7 @@ RawBuffer asymmetricDecrypt(const RawBuffer &key, case AlgoType::RSA_OAEP: { TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT, getAlgType(algo), - key, + keyId, pwd, result, // unused dummy cipher, @@ -659,7 +659,7 @@ RawBuffer asymmetricDecrypt(const RawBuffer &key, "Incorrect algorithm provided for asymmetric crypto operation"); } -uint32_t initCipher(const RawBuffer &key, +uint32_t initCipher(const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, bool encrypt) @@ -674,7 +674,7 @@ uint32_t initCipher(const RawBuffer &key, RawBuffer aad; alg.getParam(ParamName::ED_AAD, aad); return TrustZoneContext::Instance().initGcmCipher(encrypt ? CIPHER_ENCRYPT : CIPHER_DECRYPT, - key, + keyId, pwd, unpack(alg, ParamName::ED_IV), tagSizeBits, @@ -710,7 +710,7 @@ RawBuffer finalizeCipher(uint32_t opId, return TrustZoneContext::Instance().finalizeGcmCipher(opId, data); } -RawBuffer sign(const RawBuffer &pkey, +RawBuffer sign(const RawBuffer &pkeyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &message) @@ -723,14 +723,14 @@ RawBuffer sign(const RawBuffer &pkey, RawBuffer signature; TrustZoneContext::Instance().executeSign(getAlgType(algo), getHashType(hash), - pkey, + pkeyId, pwd, message, signature); return signature; } -int verify(const RawBuffer &pkey, +int verify(const RawBuffer &pkeyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &message, @@ -743,13 +743,13 @@ int verify(const RawBuffer &pkey, return TrustZoneContext::Instance().executeVerify(getAlgType(algo), getHashType(hash), - pkey, + pkeyId, pwd, message, signature); } -void deriveECDH(const RawBuffer &prvKey, +void deriveECDH(const RawBuffer &prvKeyId, const Pwd &prvKeyPwd, const RawBuffer &pubKey, const Password &secretPwd, @@ -789,7 +789,7 @@ void deriveECDH(const RawBuffer &prvKey, RawBuffer secretPwdBuf(secretPwd.begin(), secretPwd.end()); - TrustZoneContext::Instance().executeEcdh(prvKey, + TrustZoneContext::Instance().executeEcdh(prvKeyId, prvKeyPwd, xBuf, yBuf, @@ -799,7 +799,7 @@ void deriveECDH(const RawBuffer &prvKey, secretHash); } -void deriveKBKDF(const RawBuffer &secret, +void deriveKBKDF(const RawBuffer &secretId, const CryptoAlgorithm &alg, const Password &keyPwd, const RawBuffer &keyPwdIV, @@ -821,7 +821,7 @@ void deriveKBKDF(const RawBuffer &secret, RawBuffer keyPwdBuf(keyPwd.begin(), keyPwd.end()); - TrustZoneContext::Instance().executeKbkdf(secret, + TrustZoneContext::Instance().executeKbkdf(secretId, label, context, fixed, diff --git a/src/manager/crypto/tz-backend/internals.h b/src/manager/crypto/tz-backend/internals.h index cb6b814..bb8e444 100644 --- a/src/manager/crypto/tz-backend/internals.h +++ b/src/manager/crypto/tz-backend/internals.h @@ -62,7 +62,7 @@ void importData(const Data &key, RawBuffer &tag, const RawBuffer &hash); -void importWrappedKey(const RawBuffer &wrappingKey, +void importWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, const CryptoAlgorithm &alg, const Data &encryptedKey, @@ -71,7 +71,7 @@ void importWrappedKey(const RawBuffer &wrappingKey, RawBuffer &encryptedKeyTag, const RawBuffer &encryptedKeyId); -RawBuffer exportWrappedKey(const RawBuffer &wrappingKey, +RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, const CryptoAlgorithm &alg, const RawBuffer &keyToWrapId, @@ -82,47 +82,47 @@ RawBuffer getData(const RawBuffer &dataId, void destroyData(const RawBuffer &dataId); -void destroyKey(const RawBuffer &key); +void destroyKey(const RawBuffer &keyId); RawBuffer symmetricEncrypt( - const RawBuffer &key, + const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &data); RawBuffer symmetricDecrypt( - const RawBuffer &key, + const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &cipher); RawBuffer asymmetricEncrypt( - const RawBuffer &key, + const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &data); RawBuffer asymmetricDecrypt( - const RawBuffer &key, + const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &cipher); -BufferPair encryptDataAesGcm(const RawBuffer &key, +BufferPair encryptDataAesGcm(const RawBuffer &keyId, const Pwd &pwd, const RawBuffer &iv, int tagSize, const RawBuffer &data, const RawBuffer &aad = RawBuffer()); -RawBuffer decryptDataAesGcm(const RawBuffer &key, +RawBuffer decryptDataAesGcm(const RawBuffer &keyId, const Pwd &pwd, const RawBuffer &iv, const RawBuffer &tag, const RawBuffer &data, const RawBuffer &aad = RawBuffer()); -uint32_t initCipher(const RawBuffer &key, +uint32_t initCipher(const RawBuffer &keyId, const Pwd &pwd, const CryptoAlgorithm &alg, bool encrypt); @@ -136,18 +136,18 @@ RawBuffer updateCipher(uint32_t opId, RawBuffer finalizeCipher(uint32_t opId, const RawBuffer &data); -RawBuffer sign(const RawBuffer &pkey, +RawBuffer sign(const RawBuffer &pkeyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &message); -int verify(const RawBuffer &pkey, +int verify(const RawBuffer &pkeyId, const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &message, const RawBuffer &signature); -void deriveECDH(const RawBuffer &prvKey, +void deriveECDH(const RawBuffer &prvKeyId, const Pwd &prvKeyPwd, const RawBuffer &pubKey, const Password &secretPwd, @@ -155,7 +155,7 @@ void deriveECDH(const RawBuffer &prvKey, RawBuffer &secretTag, const RawBuffer &secretHash); -void deriveKBKDF(const RawBuffer &secret, +void deriveKBKDF(const RawBuffer &secretId, const CryptoAlgorithm &alg, const Password &keyPwd, const RawBuffer &keyPwdIV, diff --git a/src/manager/crypto/tz-backend/obj.cpp b/src/manager/crypto/tz-backend/obj.cpp index d743753..fa464f1 100644 --- a/src/manager/crypto/tz-backend/obj.cpp +++ b/src/manager/crypto/tz-backend/obj.cpp @@ -66,7 +66,7 @@ Token BData::derive(const CryptoAlgorithm &alg, const Password &pass, const RawB iv = Internals::generateIV(); } - Internals::deriveKBKDF(getBinary(), alg, pass, iv, tag, hash); + Internals::deriveKBKDF(getId(), alg, pass, iv, tag, hash); return Token(backendId(), DataType(KeyType::KEY_AES), Store::pack(hash, pass, iv, tag)); } @@ -88,7 +88,7 @@ Token Key::unwrap(const CryptoAlgorithm ¶ms, passIV = Internals::generateIV(); } - Internals::importWrappedKey(getBinary(), + Internals::importWrappedKey(getId(), getPassword(), params, encryptedKey, @@ -115,7 +115,7 @@ RawBuffer Key::wrap(const CryptoAlgorithm &alg, keyToWrapIV, keyToWrapTag); - return Internals::exportWrappedKey(getBinary(), + return Internals::exportWrappedKey(getId(), getPassword(), alg, keyToWrapId, @@ -124,29 +124,29 @@ RawBuffer Key::wrap(const CryptoAlgorithm &alg, RawBuffer SKey::encrypt(const CryptoAlgorithm &alg, const RawBuffer &data) { - return Internals::symmetricEncrypt(getBinary(), getPassword(), alg, data); + return Internals::symmetricEncrypt(getId(), getPassword(), alg, data); } RawBuffer SKey::decrypt(const CryptoAlgorithm &alg, const RawBuffer &cipher) { - return Internals::symmetricDecrypt(getBinary(), getPassword(), alg, cipher); + return Internals::symmetricDecrypt(getId(), getPassword(), alg, cipher); } GCtxShPtr SKey::initContext(const CryptoAlgorithm &alg, bool onward) { - auto opId = Internals::initCipher(getBinary(), getPassword(), alg, onward); + auto opId = Internals::initCipher(getId(), getPassword(), alg, onward); return std::make_shared(opId); } RawBuffer AKey::encrypt(const CryptoAlgorithm &alg, const RawBuffer &data) { - return Internals::asymmetricEncrypt(getBinary(), getPassword(), alg, data); + return Internals::asymmetricEncrypt(getId(), getPassword(), alg, data); } RawBuffer AKey::decrypt(const CryptoAlgorithm &alg, const RawBuffer &cipher) { - return Internals::asymmetricDecrypt(getBinary(), getPassword(), alg, cipher); + return Internals::asymmetricDecrypt(getId(), getPassword(), alg, cipher); } Token AKey::derive(const CryptoAlgorithm &alg, const Password &pass, const RawBuffer &hash) @@ -167,7 +167,7 @@ Token AKey::derive(const CryptoAlgorithm &alg, const Password &pass, const RawBu iv = Internals::generateIV(); } - Internals::deriveECDH(getBinary(), getPassword(), pubKey, pass, iv, tag, hash); + Internals::deriveECDH(getId(), getPassword(), pubKey, pass, iv, tag, hash); return Token(backendId(), DataType::BINARY_DATA, Store::pack(hash, pass, iv, tag)); } @@ -183,7 +183,7 @@ RawBuffer AKey::sign( { CryptoAlgorithm algWithType(alg); algWithType.setParam(ParamName::ALGO_TYPE, key2algo(m_type)); - return Internals::sign(getBinary(), getPassword(), algWithType, message); + return Internals::sign(getId(), getPassword(), algWithType, message); } int AKey::verify(const CryptoAlgorithm &alg, const RawBuffer &message, @@ -197,7 +197,7 @@ int AKey::verify(const CryptoAlgorithm &alg, const RawBuffer &message, algWithType.setParam(ParamName::ALGO_TYPE, key2algo(m_type)); } - return Internals::verify(getBinary(), getPassword(), algWithType, message, sign); + return Internals::verify(getId(), getPassword(), algWithType, message, sign); } Token Cert::unwrap(const CryptoAlgorithm &, diff --git a/src/manager/crypto/tz-backend/obj.h b/src/manager/crypto/tz-backend/obj.h index dd35a8e..2b0fff3 100644 --- a/src/manager/crypto/tz-backend/obj.h +++ b/src/manager/crypto/tz-backend/obj.h @@ -52,7 +52,6 @@ public: return m_tag; } - private: RawBuffer m_password; RawBuffer m_iv; @@ -61,36 +60,46 @@ private: class BData : public GObj { public: - explicit BData(CryptoBackend backendId, RawBuffer buffer) : - GObj(backendId), m_raw(std::move(buffer)) {} + BData(CryptoBackend backendId, + int scheme, + RawBuffer id, + Pwd pwd, + RawBuffer buffer = RawBuffer()) : + GObj(backendId), + m_scheme(scheme), + m_password(std::move(pwd)), + m_id(std::move(id)), + m_raw(std::move(buffer)) {} RawBuffer getBinary() const override { return m_raw; } + virtual const RawBuffer& getId() const + { + return m_id; + } + virtual int getScheme() const + { + return m_scheme; + } + virtual const Pwd& getPassword() const + { + return m_password; + } Token derive(const CryptoAlgorithm &, const Password &, const RawBuffer &) override; protected: + int m_scheme; + Pwd m_password; + RawBuffer m_id; RawBuffer m_raw; }; class Key : public BData { public: - Key(CryptoBackend backendId, int scheme, RawBuffer buffer, Pwd pwd, DataType dataType) : - BData(backendId, std::move(buffer)), - m_scheme(scheme), - m_password(std::move(pwd)), - m_type(dataType) {} - - virtual int getScheme() const - { - return m_scheme; - } - - virtual Pwd getPassword() const - { - return m_password; - } + Key(CryptoBackend backendId, int scheme, RawBuffer id, Pwd pwd) : + BData(backendId, scheme, std::move(id), std::move(pwd)) {} Token unwrap(const CryptoAlgorithm ¶ms, const Data &encryptedKey, @@ -100,17 +109,12 @@ public: RawBuffer wrap(const CryptoAlgorithm ¶ms, const Token &keyToWrap, const Password &keyToWrapPass) override; - -protected: - int m_scheme; - Pwd m_password; - DataType m_type; }; class SKey : public Key { public: - SKey(CryptoBackend backendId, int scheme, RawBuffer buffer, Pwd pwd, DataType dataType) : - Key(backendId, scheme, std::move(buffer), std::move(pwd), dataType) {} + SKey(CryptoBackend backendId, int scheme, RawBuffer id, Pwd pwd) : + Key(backendId, scheme, std::move(id), std::move(pwd)) {} RawBuffer encrypt(const CryptoAlgorithm &, const RawBuffer &) override; RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &) override; @@ -119,8 +123,16 @@ public: class AKey : public Key { public: - AKey(CryptoBackend backendId, int scheme, RawBuffer buffer, Pwd pwd, DataType dataType) : - Key(backendId, scheme, std::move(buffer), std::move(pwd), dataType) {} + AKey(CryptoBackend backendId, + int scheme, + RawBuffer id, + Pwd pwd, + DataType dataType, + RawBuffer raw = RawBuffer()) : + Key(backendId, scheme, std::move(id), std::move(pwd)), m_type(dataType) + { + m_raw = std::move(raw); + } RawBuffer sign(const CryptoAlgorithm &alg, const RawBuffer &message) override; int verify(const CryptoAlgorithm &alg, const RawBuffer &message, @@ -129,12 +141,15 @@ public: RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &) override; Token derive(const CryptoAlgorithm &, const Password &, const RawBuffer &) override; GCtxShPtr initContext(const CryptoAlgorithm &, bool) override; + +protected: + DataType m_type; }; class Cert : public AKey { public: - Cert(CryptoBackend backendId, int scheme, RawBuffer buffer, Pwd pwd, DataType dataType) : - AKey(backendId, scheme, std::move(buffer), std::move(pwd), dataType) {} + Cert(CryptoBackend backendId, int scheme, RawBuffer id, Pwd pwd, DataType dataType) : + AKey(backendId, scheme, std::move(id), std::move(pwd), dataType) {} Token unwrap(const CryptoAlgorithm &, const Data &, diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index 302fd2a..ff06b77 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -68,19 +68,23 @@ GObjUPtr Store::getObject(const Token &token, const Password &pass) RawBuffer tag; unpack(token.data, pass, scheme, id, iv, tag); - if (token.dataType.isKeyPrivate() || token.dataType.isKeyPublic()) + if (token.dataType.isKeyPrivate()) return make(scheme, std::move(id), Pwd(pass, iv, tag), token.dataType); if (token.dataType.isSymmetricKey()) - return make(scheme, std::move(id), Pwd(pass, iv, tag), token.dataType); + return make(scheme, std::move(id), Pwd(pass, iv, tag)); if (token.dataType.isCertificate() || token.dataType.isChainCert()) return make(scheme, std::move(id), Pwd(pass, iv, tag), token.dataType); - if (token.dataType.isBinaryData()) { - RawBuffer exported_data = Internals::getData(std::move(id), Pwd(pass, iv, tag)); - return make(std::move(exported_data)); - } + auto pwd = Pwd(pass, iv, tag); + RawBuffer raw = Internals::getData(id, pwd); + + if (token.dataType.isKeyPublic()) + return make(scheme, std::move(id), std::move(pwd), token.dataType, std::move(raw)); + + if (token.dataType.isBinaryData()) + return make(scheme, std::move(id), std::move(pwd), std::move(raw)); ThrowErr(Exc::Crypto::DataTypeNotSupported, "This type of data is not supported by trustzone backend: ", token.dataType); @@ -198,7 +202,7 @@ void Store::unpack(const RawBuffer &packed, buffer.Deserialize(data); } - if (scheme & EncryptionScheme::PASSWORD && password.empty()) { + if ((scheme & EncryptionScheme::PASSWORD) && password.empty()) { ThrowErr(Exc::Crypto::AuthenticationFailed, "This token is protected with password and none passed"); } else if (!(scheme & EncryptionScheme::PASSWORD) && !password.empty()) { diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index cc9a78c..f33897b 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -685,7 +685,7 @@ void TrustZoneContext::importData( LogDebug("Imported object ID is (hex): " << rawToHexString(hash)); } -void TrustZoneContext::importWrappedKey(const RawBuffer &wrappingKey, +void TrustZoneContext::importWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, tz_algo_type algo, const RawBuffer &iv, @@ -701,7 +701,7 @@ void TrustZoneContext::importWrappedKey(const RawBuffer &wrappingKey, // command ID = CMD_IMPORT_WRAPPED_KEY LogDebug("TrustZoneContext::importWrappedKey encryptedKey size = [" << encryptedKey.size() << "]"); - auto sIn = makeSerializer(wrappingKey, + auto sIn = makeSerializer(wrappingKeyId, wrappingKeyPwd, algo, iv, @@ -736,7 +736,7 @@ void TrustZoneContext::importWrappedKey(const RawBuffer &wrappingKey, LogDebug("Imported object ID is (hex): " << rawToHexString(encryptedKeyId)); } -RawBuffer TrustZoneContext::exportWrappedKey(const RawBuffer &wrappingKey, +RawBuffer TrustZoneContext::exportWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, tz_algo_type algo, const RawBuffer &iv, @@ -748,7 +748,7 @@ RawBuffer TrustZoneContext::exportWrappedKey(const RawBuffer &wrappingKey, // command ID = CMD_EXPORT_WRAPPED_KEY LogDebug("TrustZoneContext::exportWrappedKey"); - auto sIn = makeSerializer(wrappingKey, + auto sIn = makeSerializer(wrappingKeyId, wrappingKeyPwd, algo, iv, @@ -886,7 +886,7 @@ void TrustZoneContext::executeEcdh(const RawBuffer &prvKeyId, LogDebug("Derived object ID is (hex): " << rawToHexString(secretHash)); } -void TrustZoneContext::executeKbkdf(const RawBuffer& secret, +void TrustZoneContext::executeKbkdf(const RawBuffer& secretId, const RawBuffer& label, const RawBuffer& context, const RawBuffer& fixed, @@ -904,7 +904,7 @@ void TrustZoneContext::executeKbkdf(const RawBuffer& secret, // command ID = CMD_DERIVE LogDebug("TrustZoneContext::executeKbkdf"); - auto sIn = makeSerializer(secret, + auto sIn = makeSerializer(secretId, label, context, fixed, diff --git a/src/manager/crypto/tz-backend/tz-context.h b/src/manager/crypto/tz-backend/tz-context.h index da27aa2..7233ef7 100644 --- a/src/manager/crypto/tz-backend/tz-context.h +++ b/src/manager/crypto/tz-backend/tz-context.h @@ -89,7 +89,7 @@ public: RawBuffer &pwdTag, const RawBuffer &hash); - void importWrappedKey(const RawBuffer &wrappingKey, + void importWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, tz_algo_type algo, const RawBuffer &iv, @@ -102,7 +102,7 @@ public: RawBuffer &encryptedKeyTag, const RawBuffer &encryptedKeyHash); - RawBuffer exportWrappedKey(const RawBuffer &wrappingKey, + RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId, const Pwd &wrappingKeyPwd, tz_algo_type algo, const RawBuffer &iv, @@ -182,7 +182,7 @@ public: RawBuffer &secretTag, const RawBuffer &secretHash); - void executeKbkdf(const RawBuffer& secret, + void executeKbkdf(const RawBuffer& secretId, const RawBuffer& label, const RawBuffer& context, const RawBuffer& fixed, -- 2.7.4 From 16d4ba44f9e140f077de4864f2d7477d5af64a7c Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Thu, 29 Jun 2023 10:32:17 +0200 Subject: [PATCH 09/16] Release 0.1.54 * Implement public key extraction in TZ backend * add ALGO_ECDSA_SV to MAX_KEY_SIZE in tz_backend * Return proper error for wrong wrapped key type * Update ckmc_import_wrapped_key description * Add missing exception guard to C++ API * Simplify serialization calls * Fix wrong fuction name in the documentation * Fix typo in ckmc-manager.h * Enable -Wshadow and fix warnings Change-Id: I1009a607df537d843cc59fa8148f4912262480cc --- packaging/key-manager.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/key-manager.spec b/packaging/key-manager.spec index 6db5f60..2231921 100644 --- a/packaging/key-manager.spec +++ b/packaging/key-manager.spec @@ -12,7 +12,7 @@ Name: key-manager Summary: Central Key Manager and utilities -Version: 0.1.53 +Version: 0.1.54 Release: 1 Group: Security/Secure Storage License: Apache-2.0 and BSD-3-Clause -- 2.7.4 From 4252bcf8916799a4b1c914d7f137001e5c06f1ea Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Mon, 3 Jul 2023 14:32:23 +0200 Subject: [PATCH 10/16] Allow EC keys to be imported to TZ backend Change-Id: I54ab75a7d30817aea1054fd13b81f2519d0bdc13 --- src/manager/crypto/tz-backend/internals.cpp | 2 ++ src/manager/crypto/tz-backend/obj.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/manager/crypto/tz-backend/internals.cpp b/src/manager/crypto/tz-backend/internals.cpp index 2cbdf23..ae8f9f8 100644 --- a/src/manager/crypto/tz-backend/internals.cpp +++ b/src/manager/crypto/tz-backend/internals.cpp @@ -95,8 +95,10 @@ tz_data_type toTzDataType(const CKM::DataType dataType) { case CKM::DataType::KEY_AES: return TYPE_SKEY; case CKM::DataType::KEY_DSA_PRIVATE: return TYPE_AKEY_PRIVATE_DSA; case CKM::DataType::KEY_RSA_PRIVATE: return TYPE_AKEY_PRIVATE_RSA; + case CKM::DataType::KEY_ECDSA_PRIVATE: return TYPE_AKEY_PRIVATE_EC; case CKM::DataType::KEY_DSA_PUBLIC: return TYPE_AKEY_PUBLIC_DSA; case CKM::DataType::KEY_RSA_PUBLIC: return TYPE_AKEY_PUBLIC_RSA; + case CKM::DataType::KEY_ECDSA_PUBLIC: return TYPE_AKEY_PUBLIC_EC; default: ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "Data type could not be imported by tz-backend"); diff --git a/src/manager/crypto/tz-backend/obj.cpp b/src/manager/crypto/tz-backend/obj.cpp index fa464f1..55a4164 100644 --- a/src/manager/crypto/tz-backend/obj.cpp +++ b/src/manager/crypto/tz-backend/obj.cpp @@ -77,7 +77,7 @@ Token Key::unwrap(const CryptoAlgorithm ¶ms, const RawBuffer &hash) { - if (!encryptedKey.type.isKey() || encryptedKey.type.isEllipticCurve()) + if (!encryptedKey.type.isKey()) ThrowErr(Exc::Crypto::DataTypeNotSupported, "Invalid data provided for import"); RawBuffer passIV; -- 2.7.4 From 30c356c26c7bdebadd82f7d9c130bfd45438be37 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Mon, 3 Jul 2023 13:59:21 +0200 Subject: [PATCH 11/16] Modify decider logic Allow importing of all types of asymmetric keys to TZ backend. Add unit-test Change-Id: Iebbd0d5f37b4568b8c2473cdfe178d1ddad85a86 --- src/manager/crypto/platform/decider.cpp | 38 +++++--- src/manager/crypto/platform/decider.h | 6 +- unit-tests/CMakeLists.txt | 1 + unit-tests/test_decider.cpp | 156 ++++++++++++++++++++++++++++++++ 4 files changed, 185 insertions(+), 16 deletions(-) create mode 100644 unit-tests/test_decider.cpp diff --git a/src/manager/crypto/platform/decider.cpp b/src/manager/crypto/platform/decider.cpp index bdb976e..a1409d8 100644 --- a/src/manager/crypto/platform/decider.cpp +++ b/src/manager/crypto/platform/decider.cpp @@ -91,22 +91,26 @@ GStore* Decider::tryBackend(CryptoBackend backend) /* * operation encrypted type extractable backend * ---------------------------------------------- - * import FALSE binary - TZ/SW + * import FALSE binary * TZ/SW * skey FALSE TZ/SW * skey TRUE SW - * akey - SW - * cert - SW - * TRUE binary - TZ + * akey FALSE TZ/SW + * akey TRUE SW + * cert * SW + * ---------------------------------------------- + * import TRUE binary * TZ * skey FALSE TZ * skey TRUE NONE - * akey - NONE - * cert - NONE - * generate - binary - TZ/SW - * - cert - NONE - * - skey FALSE TZ/SW - * - skey TRUE SW - * - akey FALSE TZ/SW - * - akey TRUE SW + * akey FALSE TZ + * akey TRUE NONE + * cert * NONE + * ---------------------------------------------- + * generate N/A binary * TZ/SW + * skey FALSE TZ/SW + * skey TRUE SW + * akey FALSE TZ/SW + * akey TRUE SW + * cert * NONE */ std::deque Decider::getCompatibleBackends(DataType data, const Policy &policy, @@ -131,7 +135,7 @@ std::deque Decider::getCompatibleBackends(DataType data, if (!encrypted) addSW(); - if (data.isBinaryData() || (data.isSymmetricKey() && !policy.extractable)) + if (data.isBinaryData() || (data.isKey() && !policy.extractable)) addTZ(); } else { // generate/derive assert(!encrypted); @@ -160,9 +164,13 @@ GStore &Decider::getStore(DataType data, const Policy &policy, bool import, bool ThrowErr(Exc::Crypto::InternalError, "Failed to connect to a compatible backend."); } -bool Decider::checkStore(CryptoBackend requestedBackend, DataType data, const Policy &policy, bool import) +bool Decider::checkStore(CryptoBackend requestedBackend, + DataType data, + const Policy &policy, + bool import, + bool encrypted) { - auto backends = getCompatibleBackends(data, policy, import); + auto backends = getCompatibleBackends(data, policy, import, encrypted); for (auto id : backends) { if (id == requestedBackend) return true; diff --git a/src/manager/crypto/platform/decider.h b/src/manager/crypto/platform/decider.h index 47fb08d..e4c24fe 100644 --- a/src/manager/crypto/platform/decider.h +++ b/src/manager/crypto/platform/decider.h @@ -47,7 +47,11 @@ public: const Policy &policy, bool import = true, bool encrypted = false); - bool checkStore(CryptoBackend id, DataType data, const Policy &policy, bool import); + bool checkStore(CryptoBackend id, + DataType data, + const Policy &policy, + bool import, + bool encrypted = false); private: GStore* tryBackend(CryptoBackend backend); diff --git a/unit-tests/CMakeLists.txt b/unit-tests/CMakeLists.txt index 139836d..3f7ad2e 100644 --- a/unit-tests/CMakeLists.txt +++ b/unit-tests/CMakeLists.txt @@ -74,6 +74,7 @@ SET(UNIT_TESTS_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/test_crypto-logic.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_data-type.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_db_crypto.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test_decider.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_descriptor-set.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_dpl-db.cpp ${CMAKE_CURRENT_SOURCE_DIR}/test_dpl-exception.cpp diff --git a/unit-tests/test_decider.cpp b/unit-tests/test_decider.cpp new file mode 100644 index 0000000..6328977 --- /dev/null +++ b/unit-tests/test_decider.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2023 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License + */ + +#include + +#include + +#include + +using namespace CKM; +using namespace CKM::Crypto; + +namespace { + +struct Mapping { + bool import; // true - import, false - generate + bool encrypted; + DataType type; + bool extractable; + bool swBackend; + bool tzBackend; +}; + +std::vector MAPPING { +// imp., enc., type, ext., SW, TZ + {true, false, DataType::BINARY_DATA, false, true, true }, + {true, false, DataType::BINARY_DATA, true, true, true }, + + {true, false, DataType::KEY_AES, false, true, true }, + {true, false, DataType::KEY_AES, true, true, false }, + + {true, false, DataType::KEY_RSA_PRIVATE, false, true, true }, + {true, false, DataType::KEY_RSA_PRIVATE, true, true, false }, + {true, false, DataType::KEY_RSA_PUBLIC, false, true, true }, + {true, false, DataType::KEY_RSA_PUBLIC, true, true, false }, + + {true, false, DataType::KEY_DSA_PRIVATE, false, true, true }, + {true, false, DataType::KEY_DSA_PRIVATE, true, true, false }, + {true, false, DataType::KEY_DSA_PUBLIC, false, true, true }, + {true, false, DataType::KEY_DSA_PUBLIC, true, true, false }, + + {true, false, DataType::KEY_ECDSA_PRIVATE, false, true, true }, + {true, false, DataType::KEY_ECDSA_PRIVATE, true, true, false }, + {true, false, DataType::KEY_ECDSA_PUBLIC, false, true, true }, + {true, false, DataType::KEY_ECDSA_PUBLIC, true, true, false }, + + {true, false, DataType::CERTIFICATE, false, true, false }, + {true, false, DataType::CERTIFICATE, true, true, false }, + + {true, false, DataType::CHAIN_CERT_0, false, true, false }, + {true, false, DataType::CHAIN_CERT_0, true, true, false }, + + + {true, true, DataType::BINARY_DATA, false, false, true }, + {true, true, DataType::BINARY_DATA, true, false, true }, + + {true, true, DataType::KEY_AES, false, false, true }, + {true, true, DataType::KEY_AES, true, false, false }, + + {true, true, DataType::KEY_RSA_PRIVATE, false, false, true }, + {true, true, DataType::KEY_RSA_PRIVATE, true, false, false }, + {true, true, DataType::KEY_RSA_PUBLIC, false, false, true }, + {true, true, DataType::KEY_RSA_PUBLIC, true, false, false }, + + {true, true, DataType::KEY_DSA_PRIVATE, false, false, true }, + {true, true, DataType::KEY_DSA_PRIVATE, true, false, false }, + {true, true, DataType::KEY_DSA_PUBLIC, false, false, true }, + {true, true, DataType::KEY_DSA_PUBLIC, true, false, false }, + + {true, true, DataType::KEY_ECDSA_PRIVATE, false, false, true }, + {true, true, DataType::KEY_ECDSA_PRIVATE, true, false, false }, + {true, true, DataType::KEY_ECDSA_PUBLIC, false, false, true }, + {true, true, DataType::KEY_ECDSA_PUBLIC, true, false, false }, + + {true, true, DataType::CERTIFICATE, false, false, false }, + {true, true, DataType::CERTIFICATE, true, false, false }, + + {true, true, DataType::CHAIN_CERT_0, false, false, false }, + {true, true, DataType::CHAIN_CERT_0, true, false, false }, + + + {false, false, DataType::BINARY_DATA, false, true, true }, + {false, false, DataType::BINARY_DATA, true, true, true }, + + {false, false, DataType::KEY_AES, false, true, true }, + {false, false, DataType::KEY_AES, true, true, false }, + + {false, false, DataType::KEY_RSA_PRIVATE, false, true, true }, + {false, false, DataType::KEY_RSA_PRIVATE, true, true, false }, + {false, false, DataType::KEY_RSA_PUBLIC, false, true, true }, + {false, false, DataType::KEY_RSA_PUBLIC, true, true, false }, + + {false, false, DataType::KEY_DSA_PRIVATE, false, true, true }, + {false, false, DataType::KEY_DSA_PRIVATE, true, true, false }, + {false, false, DataType::KEY_DSA_PUBLIC, false, true, true }, + {false, false, DataType::KEY_DSA_PUBLIC, true, true, false }, + + {false, false, DataType::KEY_ECDSA_PRIVATE, false, true, true }, + {false, false, DataType::KEY_ECDSA_PRIVATE, true, true, false }, + {false, false, DataType::KEY_ECDSA_PUBLIC, false, true, true }, + {false, false, DataType::KEY_ECDSA_PUBLIC, true, true, false }, + + {false, false, DataType::CERTIFICATE, false, false, false }, + {false, false, DataType::CERTIFICATE, true, false, false }, + + {false, false, DataType::CHAIN_CERT_0, false, false, false }, + {false, false, DataType::CHAIN_CERT_0, true, false, false }, +}; + +} // namespace + +BOOST_AUTO_TEST_SUITE(DECIDER_TEST) + +POSITIVE_TEST_CASE(MappingTest) +{ + Decider d; + bool ret; + for (const auto& row : MAPPING) { + Policy policy("", row.extractable); + + ret = d.checkStore(CryptoBackend::OpenSSL, row.type, policy, row.import, row.encrypted); + BOOST_REQUIRE(ret == row.swBackend); + + ret = d.checkStore(CryptoBackend::TrustZone, row.type, policy, row.import, row.encrypted); +#ifdef TZ_BACKEND_ENABLED + BOOST_REQUIRE(ret == row.tzBackend); +#else + BOOST_REQUIRE(ret == false); +#endif + + ret = d.checkStore(CryptoBackend::None, row.type, policy, row.import, row.encrypted); + BOOST_REQUIRE(ret == false); + + ret = d.checkStore(CryptoBackend::SecureElement, + row.type, + policy, + row.import, + row.encrypted); + BOOST_REQUIRE(ret == false); + } +} + +BOOST_AUTO_TEST_SUITE_END() -- 2.7.4 From 1a5aff3586e14aabe3326c06a74e212701fbe3c9 Mon Sep 17 00:00:00 2001 From: wchang kim Date: Tue, 4 Jul 2023 08:06:34 +0900 Subject: [PATCH 12/16] Fixed the build error using gcc 13 Change-Id: I716b3be00e9e2015591af34b33031726fa1b5969 --- common/DBFixture.cpp | 2 +- misc/ckm_db_tool/CMakeLists.txt | 2 ++ misc/encryption_perf/main.cpp | 2 +- src/manager/common/stringify.h | 6 +++++- src/manager/initial-values/NoCharactersHandler.cpp | 1 + src/manager/service/ckm-logic.cpp | 2 +- src/manager/service/for-each-file.h | 1 + src/manager/sqlcipher/sqlcipher.c | 3 ++- unit-tests/CMakeLists.txt | 2 ++ 9 files changed, 16 insertions(+), 5 deletions(-) diff --git a/common/DBFixture.cpp b/common/DBFixture.cpp index ee85abc..b310521 100644 --- a/common/DBFixture.cpp +++ b/common/DBFixture.cpp @@ -233,7 +233,7 @@ void DBFixture::insert_row(const Name &name, const ClientId &owner) void DBFixture::delete_row(const Name &name, const ClientId &owner) { - bool exit_flag; + bool exit_flag=0; BOOST_REQUIRE_NO_THROW(exit_flag = m_db.deleteRow(name, owner)); BOOST_REQUIRE_MESSAGE(true == exit_flag, "remove name failed: no rows removed"); } diff --git a/misc/ckm_db_tool/CMakeLists.txt b/misc/ckm_db_tool/CMakeLists.txt index 00b800e..a061da9 100644 --- a/misc/ckm_db_tool/CMakeLists.txt +++ b/misc/ckm_db_tool/CMakeLists.txt @@ -2,6 +2,8 @@ SET(CKM_DB_TOOL "ckm_db_tool") SET(CKM_DB_MERGE "ckm_db_merge") SET(KEY_MANAGER_PATH ${PROJECT_SOURCE_DIR}/src/manager) +ADD_DEFINITIONS("-Wno-alloc-size-larger-than") + FIND_PACKAGE(Threads REQUIRED) INCLUDE_DIRECTORIES( diff --git a/misc/encryption_perf/main.cpp b/misc/encryption_perf/main.cpp index 1a2409f..0dd6ab9 100644 --- a/misc/encryption_perf/main.cpp +++ b/misc/encryption_perf/main.cpp @@ -9,6 +9,7 @@ const char* const ALIAS = "enc_perf_test"; int main(int argc, char* argv[]) { + std::chrono::duration duration{}; int ret; ckmc_policy_s policy {nullptr, false}; ckmc_raw_buffer_s* input = nullptr; @@ -57,7 +58,6 @@ int main(int argc, char* argv[]) goto finish; } - std::chrono::duration duration; for(;;) { size_t chunkSize = std::min(size, maxSize); diff --git a/src/manager/common/stringify.h b/src/manager/common/stringify.h index 300b1ea..fc919fd 100644 --- a/src/manager/common/stringify.h +++ b/src/manager/common/stringify.h @@ -66,6 +66,10 @@ #define STRINGIFY_15(msg, ...) << msg STRINGIFY_14(__VA_ARGS__) #define STRINGIFY_(N, ...) CONCAT(STRINGIFY_, N)(__VA_ARGS__) +/* + * flush() is needed to work around a bug described here: + * https://bugs.llvm.org/show_bug.cgi?id=20596 + */ #define Stringify(...) \ - (static_cast(std::ostringstream() \ + (static_cast(std::ostringstream().flush() \ STRINGIFY_(PP_NARG(__VA_ARGS__), __VA_ARGS__))).str() diff --git a/src/manager/initial-values/NoCharactersHandler.cpp b/src/manager/initial-values/NoCharactersHandler.cpp index e43c130..a23c9d5 100644 --- a/src/manager/initial-values/NoCharactersHandler.cpp +++ b/src/manager/initial-values/NoCharactersHandler.cpp @@ -23,6 +23,7 @@ #include #include +#include #include namespace CKM { diff --git a/src/manager/service/ckm-logic.cpp b/src/manager/service/ckm-logic.cpp index f57f920..ea59099 100644 --- a/src/manager/service/ckm-logic.cpp +++ b/src/manager/service/ckm-logic.cpp @@ -1601,7 +1601,7 @@ RawBuffer CKMLogic::importWrappedKey( } Token token = wrappingKey->unwrap(params, - Crypto::Data(keyType, std::move(wrappedKey)), + Crypto::Data(keyType, wrappedKey), policy.password, digest); diff --git a/src/manager/service/for-each-file.h b/src/manager/service/for-each-file.h index 0c03234..7b35ade 100644 --- a/src/manager/service/for-each-file.h +++ b/src/manager/service/for-each-file.h @@ -23,6 +23,7 @@ #include #include +#include namespace CKM { diff --git a/src/manager/sqlcipher/sqlcipher.c b/src/manager/sqlcipher/sqlcipher.c index 97059a2..eadacc5 100644 --- a/src/manager/sqlcipher/sqlcipher.c +++ b/src/manager/sqlcipher/sqlcipher.c @@ -119238,7 +119238,8 @@ SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){ if( x<99 ){ pIdx->pTable->nRowLogEst = x = 99; } - if( pIdx->pPartIdxWhere!=0 ) x -= 10; assert( 10==sqlite3LogEst(2) ); + if( pIdx->pPartIdxWhere!=0 ) x -= 10; + assert( 10==sqlite3LogEst(2) ); a[0] = x; /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is diff --git a/unit-tests/CMakeLists.txt b/unit-tests/CMakeLists.txt index 3f7ad2e..1dfb7be 100644 --- a/unit-tests/CMakeLists.txt +++ b/unit-tests/CMakeLists.txt @@ -34,6 +34,8 @@ ADD_DEFINITIONS("-DPKCS12_TEST_DIR=\"${PKCS12_TEST_DIR}\"") ADD_DEFINITIONS("-DBOOST_TEST_DYN_LINK") ADD_DEFINITIONS("-DOVERRIDE_SOCKET_TIMEOUT=10") +ADD_DEFINITIONS("-Wno-self-move") +ADD_DEFINITIONS("-Wno-stringop-truncation") SET(MANAGER_PATH ${PROJECT_SOURCE_DIR}/src/manager) -- 2.7.4 From 3d3465f96895b5a6eab2b211cc8742a5902bdd76 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Mon, 10 Jul 2023 17:31:33 +0200 Subject: [PATCH 13/16] Fix TZ backend issues * Add missing namespaces * Include ctx.cpp in TZ source list * Add missing operation id to internal TZ calls Change-Id: I59e71b7af5a1c418f797e7d915b8a9d1fc456edf --- CMakeLists.txt | 1 + src/manager/crypto/sw-backend/ctx.cpp | 2 ++ src/manager/crypto/sw-backend/ctx.h | 2 ++ src/manager/crypto/tz-backend/ctx.cpp | 6 ++++-- src/manager/crypto/tz-backend/ctx.h | 2 ++ 5 files changed, 11 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6af5d8c..2ad368e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -84,6 +84,7 @@ IF (TZ_BACKEND_ENABLED) SET(TZ_BACKEND_SOURCES ${KEY_MANAGER_PATH}/crypto/tz-backend/internals.cpp ${KEY_MANAGER_PATH}/crypto/tz-backend/obj.cpp + ${KEY_MANAGER_PATH}/crypto/tz-backend/ctx.cpp ${KEY_MANAGER_PATH}/crypto/tz-backend/store.cpp ${KEY_MANAGER_PATH}/crypto/tz-backend/tz-context.cpp ${KEY_MANAGER_PATH}/crypto/tz-backend/tz-memory.cpp diff --git a/src/manager/crypto/sw-backend/ctx.cpp b/src/manager/crypto/sw-backend/ctx.cpp index cffd4f4..1dcf0f7 100644 --- a/src/manager/crypto/sw-backend/ctx.cpp +++ b/src/manager/crypto/sw-backend/ctx.cpp @@ -20,6 +20,7 @@ namespace CKM { namespace Crypto { +namespace SW { namespace { constexpr uint8_t STATE_INITIALIZED = 1; @@ -109,5 +110,6 @@ RawBuffer CipherCtx::finalize(const RawBuffer& input) return tag; } +} // namespace SW } // namespace Crypto } // namespace CKM diff --git a/src/manager/crypto/sw-backend/ctx.h b/src/manager/crypto/sw-backend/ctx.h index 04f65a3..428997f 100644 --- a/src/manager/crypto/sw-backend/ctx.h +++ b/src/manager/crypto/sw-backend/ctx.h @@ -23,6 +23,7 @@ namespace CKM { namespace Crypto { +namespace SW { class CipherCtx : public GCtx { public: @@ -38,5 +39,6 @@ private: uint8_t m_state; }; +} // namespace SW } // namespace Crypto } // namespace CKM diff --git a/src/manager/crypto/tz-backend/ctx.cpp b/src/manager/crypto/tz-backend/ctx.cpp index 1fcc80b..db877d8 100644 --- a/src/manager/crypto/tz-backend/ctx.cpp +++ b/src/manager/crypto/tz-backend/ctx.cpp @@ -20,6 +20,7 @@ namespace CKM { namespace Crypto { +namespace TZ { void CipherCtx::customize(const CryptoAlgorithm& algo) { @@ -32,7 +33,7 @@ void CipherCtx::customize(const CryptoAlgorithm& algo) RawBuffer CipherCtx::update(const RawBuffer& input) { - return Internals::updateCipher(input); + return Internals::updateCipher(m_opId, input); } RawBuffer CipherCtx::finalize(const RawBuffer& input) @@ -41,8 +42,9 @@ RawBuffer CipherCtx::finalize(const RawBuffer& input) * It is assumed that finalize for GCM encryption will return the GCM tag only. * In case of GCM decryption the tag will be passed as finalizeCipher argument. */ - return Internals::finalizeCipher(input); + return Internals::finalizeCipher(m_opId, input); } +} // namespace TZ } // namespace Crypto } // namespace CKM diff --git a/src/manager/crypto/tz-backend/ctx.h b/src/manager/crypto/tz-backend/ctx.h index d12b5ce..32eba26 100644 --- a/src/manager/crypto/tz-backend/ctx.h +++ b/src/manager/crypto/tz-backend/ctx.h @@ -20,6 +20,7 @@ namespace CKM { namespace Crypto { +namespace TZ { class CipherCtx : public GCtx { public: @@ -33,5 +34,6 @@ private: uint32_t m_opId; }; +} // namespace TZ } // namespace Crypto } // namespace CKM -- 2.7.4 From dec40f83bd7cfde6f5483caad663f3820ac1bc96 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 11 Jul 2023 12:07:18 +0200 Subject: [PATCH 14/16] Release 0.1.55 * Fix TZ backend issues * Fixed the build error using gcc 13 * Modify decider logic * Allow EC keys to be imported to TZ backend Change-Id: I409287a6d1b9f14deb34041dcce904bcbb43f7ba --- packaging/key-manager.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/key-manager.spec b/packaging/key-manager.spec index 2231921..ea86c3d 100644 --- a/packaging/key-manager.spec +++ b/packaging/key-manager.spec @@ -12,7 +12,7 @@ Name: key-manager Summary: Central Key Manager and utilities -Version: 0.1.54 +Version: 0.1.55 Release: 1 Group: Security/Secure Storage License: Apache-2.0 and BSD-3-Clause -- 2.7.4 From b43f739a1f13d98004ffa73f5f151f772ca9dce2 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 11 Jul 2023 13:05:27 +0200 Subject: [PATCH 15/16] Use proper memory type in TZ backend's addGcmAAD() We need TEEC_VALUE_INOUT to properly read the return code from op.params[0].value.a. Change-Id: I95eb5fd757f9e3235bb855269dd0a804ac7bb135 --- src/manager/crypto/tz-backend/tz-context.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index f33897b..1359258 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -510,7 +510,7 @@ void TrustZoneContext::addGcmAAD(uint32_t opId, TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT); sIn.Serialize(inMemory); - TEEC_Operation op = makeOp(TEEC_VALUE_INPUT, inMemory); + TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory); op.params[0].value.a = opId; Execute(CMD_CIPHER_INIT_AAD, &op); -- 2.7.4 From f746ffb6c1aba2d28630466ed014278cf4c946e2 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Wed, 12 Jul 2023 08:58:38 +0200 Subject: [PATCH 16/16] Reserve enough space for GCM tag in TZ backend Change-Id: I36f9718cfdc37f7fdac1e47fc056aeaabdeee242 --- src/manager/crypto/tz-backend/tz-context.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index 1359258..3cf5702 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -50,6 +50,9 @@ namespace { // whatever TA will return us. const uint32_t CIPHER_EXTRA_PADDING_SIZE = 16; +// Maximum size of GCM tag in bytes. +const size_t MAX_GCM_TAG_SIZE = 16; + // Identifier of our TA const TEEC_UUID KEY_MANAGER_TA_UUID = KM_TA_UUID; @@ -547,7 +550,7 @@ RawBuffer TrustZoneContext::finalizeGcmCipher(uint32_t opId, sIn.Serialize(inMemory); TZSerializer sOut; - sOut.Push(new TZSerializableBinary(data.size())); + sOut.Push(new TZSerializableBinary(MAX_GCM_TAG_SIZE, false)); TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT); TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory); -- 2.7.4