From eab56821b4051e51b69d9492df4b47d9aecd9a9f Mon Sep 17 00:00:00 2001 From: Tomasz Swierczek Date: Tue, 17 Jul 2018 14:14:18 +0200 Subject: [PATCH 01/16] Add protection against memory leaking during deserialization Change-Id: I1fbcd7daf1674dd1ad6b9eaffdba76263bda370b --- src/manager/dpl/core/include/dpl/serialization.h | 60 ++++++++++++++---------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/src/manager/dpl/core/include/dpl/serialization.h b/src/manager/dpl/core/include/dpl/serialization.h index 5d4ed2b..4448923 100644 --- a/src/manager/dpl/core/include/dpl/serialization.h +++ b/src/manager/dpl/core/include/dpl/serialization.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2011 - 2018 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. @@ -260,6 +260,17 @@ struct Deserialization { object = new T(stream); } + // *& deserialization template to simplify rest of the code + template + static inline void DeserializePtr(IStream &stream, T *&value) + { + T *tmp = new T; + std::unique_ptr ptr(tmp); + Deserialize(stream, *tmp); + ptr.release(); + value = tmp; + } + // char static void Deserialize(IStream &stream, char &value) { @@ -267,8 +278,7 @@ struct Deserialization { } static void Deserialize(IStream &stream, char *&value) { - value = new char; - stream.Read(sizeof(*value), value); + DeserializePtr(stream, value); } // unsigned char @@ -278,8 +288,7 @@ struct Deserialization { } static void Deserialize(IStream &stream, unsigned char *&value) { - value = new unsigned char; - stream.Read(sizeof(*value), value); + DeserializePtr(stream, value); } // unsigned int32 @@ -289,8 +298,7 @@ struct Deserialization { } static void Deserialize(IStream &stream, uint32_t *&value) { - value = new uint32_t; - stream.Read(sizeof(*value), value); + DeserializePtr(stream, value); } // int32 @@ -300,8 +308,7 @@ struct Deserialization { } static void Deserialize(IStream &stream, int32_t *&value) { - value = new int32_t; - stream.Read(sizeof(*value), value); + DeserializePtr(stream, value); } // unsigned int64 @@ -311,8 +318,7 @@ struct Deserialization { } static void Deserialize(IStream &stream, uint64_t *&value) { - value = new uint64_t; - stream.Read(sizeof(*value), value); + DeserializePtr(stream, value); } // int64 @@ -322,8 +328,7 @@ struct Deserialization { } static void Deserialize(IStream &stream, int64_t *&value) { - value = new int64_t; - stream.Read(sizeof(*value), value); + DeserializePtr(stream, value); } // bool @@ -333,8 +338,7 @@ struct Deserialization { } static void Deserialize(IStream &stream, bool *&value) { - value = new bool; - stream.Read(sizeof(*value), value); + DeserializePtr(stream, value); } template @@ -375,8 +379,7 @@ struct Deserialization { template static void Deserialize(IStream &stream, std::list *&list) { - list = new std::list; - Deserialize(stream, *list); + DeserializePtr(stream, list); } // RawBuffer @@ -392,8 +395,7 @@ struct Deserialization { template static void Deserialize(IStream &stream, std::vector *&vec) { - vec = new std::vector; - Deserialize(stream, *vec); + DeserializePtr>(stream, vec); } // std::vector @@ -412,8 +414,7 @@ struct Deserialization { template static void Deserialize(IStream &stream, std::vector *&vec) { - vec = new std::vector; - Deserialize(stream, *vec); + DeserializePtr(stream, vec); } // std::pair @@ -426,8 +427,7 @@ struct Deserialization { template static void Deserialize(IStream &stream, std::pair *&p) { - p = new std::pair; - Deserialize(stream, *p); + DeserializePtr(stream, p); } // std::map @@ -448,8 +448,7 @@ struct Deserialization { template static void Deserialize(IStream &stream, std::map *&map) { - map = new std::map; - Deserialize(stream, *map); + DeserializePtr(stream, map); } }; // struct Deserialization @@ -486,6 +485,17 @@ struct Deserializer : public Deserializer { Deserialization::Deserialize(stream, f); Deserializer::Deserialize(stream, args...); } + + static void Deserialize(IStream &stream, First *&f, Args &... args) + { + First *tmp = NULL; + Deserialization::Deserialize(stream, tmp); + std::unique_ptr ptr(tmp); + Deserializer::Deserialize(stream, args...); + ptr.release(); + f = tmp; + } + }; // end of recursion -- 2.7.4 From 2d9d8282745322c2abe083ebe5511ff92cdd45ff Mon Sep 17 00:00:00 2001 From: Konrad Lipinski Date: Thu, 2 Aug 2018 12:44:44 +0200 Subject: [PATCH 02/16] Make spec compliant with gbs --incremental According to [1], %prep section of the spec file should contain a single %setup macro, nothing else. According to [2], manifest %files are best copied to %{buildroot}%{_datadir} in the %install section. Moved manifest copy operations from %prep to %install accordingly. References [1] https://source.tizen.org/documentation/reference/git-build-system/usage/gbs-build [2] https://wiki.tizen.org/Security/Application_installation_and_Manifest Change-Id: Iacf755558636f939a540482f849e810780c19a51 --- packaging/key-manager.spec | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/packaging/key-manager.spec b/packaging/key-manager.spec index aead73a..1a3dd0b 100644 --- a/packaging/key-manager.spec +++ b/packaging/key-manager.spec @@ -128,10 +128,6 @@ and password change events from PAM %prep %setup -q -cp -a %{SOURCE1001} . -cp -a %{SOURCE1002} . -cp -a %{SOURCE1003} . -cp -a %{SOURCE1004} . %build %if 0%{?sec_build_binary_debug_enable} @@ -182,6 +178,7 @@ make %{?jobs:-j%jobs} %install_service sockets.target.wants central-key-manager-api-storage.socket %install_service sockets.target.wants central-key-manager-api-ocsp.socket %install_service sockets.target.wants central-key-manager-api-encryption.socket +cp -a %{SOURCE1001} %{SOURCE1002} %{SOURCE1003} %{SOURCE1004} %{buildroot}%{_datadir}/ %pre # tzplatform-get sync breaked because of on-development situation. comment out just for temporary @@ -278,23 +275,23 @@ fi %{bin_dir}/ckm_tool %files -n key-manager-pam-plugin -%manifest key-manager-pam-plugin.manifest +%manifest %{_datadir}/key-manager-pam-plugin.manifest %license LICENSE %{_libdir}/security/pam_key_manager_plugin.so* %files -n libkey-manager-common -%manifest libkey-manager-common.manifest +%manifest %{_datadir}/libkey-manager-common.manifest %license LICENSE %{_libdir}/libkey-manager-common.so.* %files -n libkey-manager-client -%manifest libkey-manager-client.manifest +%manifest %{_datadir}/libkey-manager-client.manifest %license LICENSE %{_libdir}/libkey-manager-client.so.* %{_libdir}/libkey-manager-control-client.so.* %files -n libkey-manager-client-devel -%manifest libkey-manager-client-devel.manifest +%manifest %{_datadir}/libkey-manager-client-devel.manifest %license LICENSE %{_libdir}/libkey-manager-client.so %{_libdir}/libkey-manager-control-client.so -- 2.7.4 From b61e8105c2dbdf36b33cc870624ec4ce2efbcadd Mon Sep 17 00:00:00 2001 From: Dongsun Lee Date: Tue, 28 Aug 2018 13:51:14 +0900 Subject: [PATCH 03/16] Fix TYPO in key-manager_doc.h Change-Id: I11dbc3468e8277f0cef978f722ecbe275e1048f6 Signed-off-by: Dongsun Lee --- doc/key-manager_doc.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/key-manager_doc.h b/doc/key-manager_doc.h index f553f7a..62b5fce 100644 --- a/doc/key-manager_doc.h +++ b/doc/key-manager_doc.h @@ -66,7 +66,7 @@ * - A client should specify the package id of the owner in the alias to retrieve a a key, certificate, or data shared by other applications. * - Aliases are returned as the format of "package_id name" from the key-manager. * Supported features - * Since Tizen 5.0 on chosen images, the realization of module functionality can be implemened using ARM TrustZone technology. + * Since Tizen 5.0 on chosen images, the realization of module functionality can be implemented using ARM TrustZone technology. * Differences in standards governing TrustZone implementation and previous software-based implementation cause following differences in module operation: * - When using TrustZone-based backend, GCM modes with 32 and 64 bit tag lengths are not supported. * Global Platform TEE specification treats these configurations as unsafe and not supported. -- 2.7.4 From 31a373a9389e65b242ac1890771bfee06f5cfb51 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Thu, 19 Jul 2018 16:31:27 +0200 Subject: [PATCH 04/16] Unify alias naming Get rid of all references to smack labels except database scheme. alias = owner_id + name Simplify db permissions processing Change-Id: I36c3dbb3ee605fb00e5e4e6bcbada6400a0cbcab --- src/CMakeLists.txt | 1 + src/include/ckm/ckm-control.h | 6 +- src/include/ckm/ckm-manager-async.h | 2 +- src/include/ckm/ckm-manager.h | 2 +- src/include/ckm/ckm-type.h | 12 +- src/include/ckmc/ckmc-control.h | 17 +- .../client-async/client-manager-async-impl.cpp | 26 +- .../client-async/client-manager-async-impl.h | 2 +- src/manager/client-async/client-manager-async.cpp | 14 +- src/manager/client-async/storage-receiver.cpp | 6 +- src/manager/client-capi/ckmc-control.cpp | 8 +- src/manager/client-capi/ckmc-type.cpp | 6 +- src/manager/client/client-common.cpp | 22 +- src/manager/client/client-common.h | 8 +- src/manager/client/client-control.cpp | 10 +- src/manager/client/client-manager-impl.cpp | 40 +- src/manager/client/client-manager-impl.h | 2 +- src/manager/client/client-manager.cpp | 2 +- src/manager/common/protocols.cpp | 6 +- src/manager/common/protocols.h | 10 +- src/manager/initial-values/InitialValueHandler.cpp | 4 +- src/manager/initial-values/PermissionHandler.cpp | 4 +- src/manager/initial-values/PermissionHandler.h | 4 +- src/manager/main/credentials.h | 6 +- src/manager/main/service-messages.h | 11 +- src/manager/main/socket-2-id.cpp | 14 +- src/manager/main/socket-2-id.h | 2 +- src/manager/main/socket-manager.cpp | 6 +- src/manager/service/access-control.cpp | 22 +- src/manager/service/access-control.h | 14 +- src/manager/service/ckm-logic.cpp | 407 ++++++++++----------- src/manager/service/ckm-logic.h | 91 +++-- src/manager/service/ckm-service.cpp | 79 ++-- src/manager/service/crypto-logic.cpp | 38 +- src/manager/service/crypto-logic.h | 8 +- src/manager/service/crypto-request.h | 2 +- src/manager/service/db-crypto.cpp | 148 ++++---- src/manager/service/db-crypto.h | 54 +-- src/manager/service/db-row.h | 6 +- src/manager/service/encryption-service.cpp | 6 +- src/manager/service/file-system.cpp | 8 +- src/manager/service/file-system.h | 6 +- src/manager/service/key-provider.cpp | 42 +-- src/manager/service/key-provider.h | 13 +- src/manager/service/permission.cpp | 31 ++ src/manager/service/permission.h | 20 +- tests/DBFixture.cpp | 66 ++-- tests/DBFixture.h | 20 +- tests/encryption-scheme/scheme-test.cpp | 6 +- tests/secure-storage-old-data/README | 4 +- tests/test_crypto-logic.cpp | 46 +-- tests/test_db_crypto.cpp | 156 ++++---- tests/test_key-provider.cpp | 18 +- tools/ckm_db_tool/CMakeLists.txt | 1 + 54 files changed, 798 insertions(+), 767 deletions(-) create mode 100644 src/manager/service/permission.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a4943c8..c24850a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -61,6 +61,7 @@ SET(KEY_MANAGER_SOURCES ${KEY_MANAGER_PATH}/service/ocsp-service.cpp ${KEY_MANAGER_PATH}/service/ss-migrate.cpp ${KEY_MANAGER_PATH}/service/ss-crypto.cpp + ${KEY_MANAGER_PATH}/service/permission.cpp ${KEY_MANAGER_PATH}/initial-values/parser.cpp ${KEY_MANAGER_PATH}/initial-values/BufferHandler.cpp ${KEY_MANAGER_PATH}/initial-values/CertHandler.cpp diff --git a/src/include/ckm/ckm-control.h b/src/include/ckm/ckm-control.h index dd36f9d..51b8256 100644 --- a/src/include/ckm/ckm-control.h +++ b/src/include/ckm/ckm-control.h @@ -57,15 +57,15 @@ public: // Required for tizen 2.3. // It will remove all application data owned by application identified - // by smackLabel. This function will remove application data from unlocked + // by owner. This function will remove application data from unlocked // database only. This function may be used during application uninstallation. - virtual int removeApplicationData(const std::string &smackLabel) = 0; + virtual int removeApplicationData(const ClientId &owner) = 0; virtual int updateCCMode() = 0; virtual int setPermission(uid_t user, const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask) = 0; virtual ~Control() {} diff --git a/src/include/ckm/ckm-manager-async.h b/src/include/ckm/ckm-manager-async.h index f812aea..e8fabaa 100644 --- a/src/include/ckm/ckm-manager-async.h +++ b/src/include/ckm/ckm-manager-async.h @@ -193,7 +193,7 @@ public: void setPermission( const ObserverPtr &observer, const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask); // This function will encrypt data. diff --git a/src/include/ckm/ckm-manager.h b/src/include/ckm/ckm-manager.h index 8f67384..22ec9a5 100644 --- a/src/include/ckm/ckm-manager.h +++ b/src/include/ckm/ckm-manager.h @@ -143,7 +143,7 @@ public: int ocspCheck(const CertificateShPtrVector &certificateChainVector, int &ocspStatus); - int setPermission(const Alias &alias, const Label &accessor, + int setPermission(const Alias &alias, const ClientId &accessor, PermissionMask permissionMask); // This function will encrypt data. diff --git a/src/include/ckm/ckm-type.h b/src/include/ckm/ckm-type.h index 5a07a3d..5021f26 100644 --- a/src/include/ckm/ckm-type.h +++ b/src/include/ckm/ckm-type.h @@ -38,8 +38,18 @@ namespace CKM { // used to pass password and raw key data typedef std::vector RawBufferVector; +/* + * Alias = ClientId + ' ' + Name + * ClientId is optional + */ typedef std::string Alias; -typedef std::string Label; +/* + * ClientId is an identifier of the API caller returned by security-manager(pkgid). + * It can be an application or a system component. + * Depending on the context the ClientId may indicate a data owner, data accessor + * or just a client in general. + */ +typedef std::string ClientId; typedef std::vector AliasVector; enum class KeyType : int { diff --git a/src/include/ckmc/ckmc-control.h b/src/include/ckmc/ckmc-control.h index 687deb1..459c480 100644 --- a/src/include/ckmc/ckmc-control.h +++ b/src/include/ckmc/ckmc-control.h @@ -218,14 +218,15 @@ TIZEN_DEPRECATED_API; * @privilege %http://tizen.org/privilege/keymanager.admin * * @remarks Data identified by @a alias should exist - * @remarks @a alias must contain owner label () - * - * @param[in] user User ID of a user whose data will be affected - * @param[in] alias Data alias for which access will be granted - * @param[in] accessor Package id of the application that will gain access rights - * @param[in] permissions Mask of permissions granted for @a accessor application - * (@a ckmc_permission_e) - * (previous permission mask will be replaced with the new mask value) + * @remarks @a alias must contain owner id and name + * () + * + * @param[in] user User ID of a user whose data will be affected + * @param[in] alias Data alias for which access will be granted + * @param[in] accessor Package id of the application that will gain access rights + * @param[in] mask Mask of permissions granted for @a accessor application + * (@a ckmc_permission_e) + * (previous permission mask will be replaced with the new mask value) * * @return @c 0 on success, otherwise a negative error value * diff --git a/src/manager/client-async/client-manager-async-impl.cpp b/src/manager/client-async/client-manager-async-impl.cpp index 3837771..74f14f9 100644 --- a/src/manager/client-async/client-manager-async-impl.cpp +++ b/src/manager/client-async/client-manager-async-impl.cpp @@ -96,7 +96,7 @@ void ManagerAsync::Impl::saveBinaryData(const ManagerAsync::ObserverPtr AliasSupport helper(alias); sendToStorage(observer, static_cast(LogicCommand::SAVE), m_counter, - static_cast(dataType), helper.getName(), helper.getLabel(), rawData, + static_cast(dataType), helper.getName(), helper.getOwner(), rawData, PolicySerializable(policy)); }, [&observer](int error) { observer->ReceivedError(error); @@ -112,7 +112,7 @@ void ManagerAsync::Impl::savePKCS12(const ManagerAsync::ObserverPtr &observer, try_catch_async([&]() { AliasSupport helper(alias); sendToStorage(observer, static_cast(LogicCommand::SAVE_PKCS12), - m_counter, helper.getName(), helper.getLabel(), PKCS12Serializable(*pkcs.get()), + m_counter, helper.getName(), helper.getOwner(), PKCS12Serializable(*pkcs.get()), PolicySerializable(keyPolicy), PolicySerializable(certPolicy)); }, [&observer](int error) { observer->ReceivedError(error); @@ -132,7 +132,7 @@ void ManagerAsync::Impl::removeAlias(const ManagerAsync::ObserverPtr &observer, try_catch_async([&]() { AliasSupport helper(alias); sendToStorage(observer, static_cast(LogicCommand::REMOVE), m_counter, - helper.getName(), helper.getLabel()); + helper.getName(), helper.getOwner()); }, [&observer](int error) { observer->ReceivedError(error); }); @@ -155,7 +155,7 @@ void ManagerAsync::Impl::getBinaryData(const ManagerAsync::ObserverPtr AliasSupport helper(alias); sendToStorage(observer, static_cast(LogicCommand::GET), m_counter, - static_cast(sendDataType), helper.getName(), helper.getLabel(), password); + static_cast(sendDataType), helper.getName(), helper.getOwner(), password); }, [&observer](int error) { observer->ReceivedError(error); }); @@ -177,7 +177,7 @@ void ManagerAsync::Impl::getPKCS12(const ManagerAsync::ObserverPtr &observer, AliasSupport helper(alias); sendToStorage(observer, static_cast(LogicCommand::GET_PKCS12), m_counter, - helper.getName(), helper.getLabel(), passwordKey, passwordCert); + helper.getName(), helper.getOwner(), passwordKey, passwordCert); }, [&observer](int error) { observer->ReceivedError(error); }); @@ -199,7 +199,7 @@ void ManagerAsync::Impl::createSignature(const ObserverPtr &observer, try_catch_async([&]() { AliasSupport helper(privateKeyAlias); sendToStorage(observer, static_cast(LogicCommand::CREATE_SIGNATURE), - m_counter, helper.getName(), helper.getLabel(), password, message, + m_counter, helper.getName(), helper.getOwner(), password, message, CryptoAlgorithmSerializable(cAlg)); }, [&observer](int error) { observer->ReceivedError(error); @@ -224,7 +224,7 @@ void ManagerAsync::Impl::verifySignature(const ObserverPtr &observer, AliasSupport helper(publicKeyOrCertAlias); sendToStorage(observer, static_cast(LogicCommand::VERIFY_SIGNATURE), - m_counter, helper.getName(), helper.getLabel(), password, + m_counter, helper.getName(), helper.getOwner(), password, message, signature, CryptoAlgorithmSerializable(cAlg)); }, [&observer](int error) { observer->ReceivedError(error); @@ -263,7 +263,7 @@ void ManagerAsync::Impl::ocspCheck(const ObserverPtr &observer, void ManagerAsync::Impl::setPermission(const ObserverPtr &observer, const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask) { observerCheck(observer); @@ -277,7 +277,7 @@ void ManagerAsync::Impl::setPermission(const ObserverPtr &observer, AliasSupport helper(alias); sendToStorage(observer, static_cast(LogicCommand::SET_PERMISSION), - m_counter, helper.getName(), helper.getLabel(), accessor, permissionMask); + m_counter, helper.getName(), helper.getOwner(), accessor, permissionMask); }, [&observer](int error) { observer->ReceivedError(error); }); @@ -346,8 +346,8 @@ void ManagerAsync::Impl::createKeyPair(const ManagerAsync::ObserverPtr sendToStorage(observer, static_cast(LogicCommand::CREATE_KEY_PAIR), m_counter, CryptoAlgorithmSerializable(keyGenAlgorithm), PolicySerializable(policyPrivateKey), PolicySerializable(policyPublicKey), - prvHelper.getName(), prvHelper.getLabel(), pubHelper.getName(), - pubHelper.getLabel()); + prvHelper.getName(), prvHelper.getOwner(), pubHelper.getName(), + pubHelper.getOwner()); }, [&observer](int error) { observer->ReceivedError(error); }); @@ -370,7 +370,7 @@ void ManagerAsync::Impl::createKeyAES(const ManagerAsync::ObserverPtr &observer, sendToStorage(observer, static_cast(LogicCommand::CREATE_KEY_AES), m_counter, static_cast(size), PolicySerializable(policyKey), - aliasHelper.getName(), aliasHelper.getLabel()); + aliasHelper.getName(), aliasHelper.getOwner()); }, [&observer](int error) { observer->ReceivedError(error); }); @@ -403,7 +403,7 @@ void ManagerAsync::Impl::crypt( auto send = MessageBuffer::Serialize(static_cast(encryption ? EncryptionCommand::ENCRYPT : EncryptionCommand::DECRYPT), m_counter, cas, - helper.getName(), helper.getLabel(), password, input); + helper.getName(), helper.getOwner(), password, input); thread()->sendMessage(AsyncRequest(observer, SERVICE_SOCKET_ENCRYPTION, send.Pop(), m_counter)); diff --git a/src/manager/client-async/client-manager-async-impl.h b/src/manager/client-async/client-manager-async-impl.h index 65f4970..96c1051 100644 --- a/src/manager/client-async/client-manager-async-impl.h +++ b/src/manager/client-async/client-manager-async-impl.h @@ -80,7 +80,7 @@ public: void setPermission( const ObserverPtr &observer, const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask); // generic methods diff --git a/src/manager/client-async/client-manager-async.cpp b/src/manager/client-async/client-manager-async.cpp index 471c848..6227b8d 100644 --- a/src/manager/client-async/client-manager-async.cpp +++ b/src/manager/client-async/client-manager-async.cpp @@ -39,16 +39,16 @@ RawBufferVector toRawBufferVector(const CertificateShPtrVector &certificates) return rawBufferVector; } -LabelNameVector toLabelNameVector(const AliasVector &aliases) +OwnerNameVector toOwnerNameVector(const AliasVector &aliases) { - LabelNameVector labelNames; + OwnerNameVector ownerNameVector; for (auto &e : aliases) { AliasSupport helper(e); - labelNames.push_back(std::make_pair(helper.getLabel(), helper.getName())); + ownerNameVector.push_back(std::make_pair(helper.getOwner(), helper.getName())); } - return labelNames; + return ownerNameVector; } } // namespace anonymous @@ -235,8 +235,8 @@ void ManagerAsync::getCertificateChain(const ObserverPtr &observer, m_impl->getCertChain(observer, LogicCommand::GET_CHAIN_ALIAS, certificate, - toLabelNameVector(untrustedCertificates), - toLabelNameVector(trustedCertificates), + toOwnerNameVector(untrustedCertificates), + toOwnerNameVector(trustedCertificates), useSystemTrustedCertificates); }, [&observer](int error) { observer->ReceivedError(error); @@ -279,7 +279,7 @@ void ManagerAsync::ocspCheck(const ObserverPtr &observer, void ManagerAsync::setPermission(const ObserverPtr &observer, const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask) { m_impl->setPermission(observer, alias, accessor, permissionMask); diff --git a/src/manager/client-async/storage-receiver.cpp b/src/manager/client-async/storage-receiver.cpp index ad25917..e282dfa 100644 --- a/src/manager/client-async/storage-receiver.cpp +++ b/src/manager/client-async/storage-receiver.cpp @@ -153,8 +153,8 @@ void StorageReceiver::parseGetPKCS12Command() void StorageReceiver::parseGetListCommand() { int dataType = 0, retCode = 0; - LabelNameVector labelNameVector; - m_buffer.Deserialize(retCode, dataType, labelNameVector); + OwnerNameVector ownerNameVector; + m_buffer.Deserialize(retCode, dataType, ownerNameVector); // check error code if (retCode != CKM_API_SUCCESS) { @@ -164,7 +164,7 @@ void StorageReceiver::parseGetListCommand() AliasVector aliasVector; - for (const auto &it : labelNameVector) + for (const auto &it : ownerNameVector) aliasVector.push_back(AliasSupport::merge(it.first, it.second)); DataType type(dataType); diff --git a/src/manager/client-capi/ckmc-control.cpp b/src/manager/client-capi/ckmc-control.cpp index ff3d603..2ee1438 100644 --- a/src/manager/client-capi/ckmc-control.cpp +++ b/src/manager/client-capi/ckmc-control.cpp @@ -95,9 +95,9 @@ int ckmc_allow_access_by_adm(uid_t user, const char *owner, const char *alias, if (ec != CKMC_ERROR_NONE) return ec; - // if label given twice, service will return an error + // if owner given twice, service will return an error return ckmc_set_permission_by_adm(user, - CKM::AliasSupport::merge(CKM::Label(owner), CKM::Name(alias)).c_str(), accessor, + CKM::AliasSupport::merge(CKM::ClientId(owner), CKM::Name(alias)).c_str(), accessor, permissionMask); } @@ -123,11 +123,11 @@ int ckmc_deny_access_by_adm(uid_t user, const char *owner, const char *alias, if (!owner || !alias) return CKMC_ERROR_INVALID_PARAMETER; - // if label given twice, service will return an error + // if owner given twice, service will return an error auto control = CKM::Control::create(); return to_ckmc_error(control->setPermission( user, - CKM::AliasSupport::merge(CKM::Label(owner), CKM::Name(alias)).c_str(), + CKM::AliasSupport::merge(CKM::ClientId(owner), CKM::Name(alias)).c_str(), accessor, CKM::Permission::NONE)); } diff --git a/src/manager/client-capi/ckmc-type.cpp b/src/manager/client-capi/ckmc-type.cpp index 926cbd4..a613d8d 100644 --- a/src/manager/client-capi/ckmc-type.cpp +++ b/src/manager/client-capi/ckmc-type.cpp @@ -68,9 +68,9 @@ int _ckmc_load_cert_from_x509(X509 *xCert, ckmc_cert_s **cert) } // namespace anonymous -const char *const ckmc_label_name_separator = CKM::LABEL_NAME_SEPARATOR; -const char *const ckmc_owner_id_separator = CKM::LABEL_NAME_SEPARATOR; -const char *const ckmc_owner_id_system = CKM::OWNER_ID_SYSTEM; +const char *const ckmc_label_name_separator = CKM::ALIAS_SEPARATOR; +const char *const ckmc_owner_id_separator = CKM::ALIAS_SEPARATOR; +const char *const ckmc_owner_id_system = CKM::CLIENT_ID_SYSTEM; KEY_MANAGER_CAPI int ckmc_alias_new(const char *owner_id, const char *alias, char **full_alias) diff --git a/src/manager/client/client-common.cpp b/src/manager/client/client-common.cpp index 312f334..bb9ad4d 100644 --- a/src/manager/client/client-common.cpp +++ b/src/manager/client/client-common.cpp @@ -173,24 +173,24 @@ int SockRAII::get() const AliasSupport::AliasSupport(const Alias &alias) { - std::size_t separator_pos = alias.rfind(CKM::LABEL_NAME_SEPARATOR); + std::size_t separator_pos = alias.rfind(CKM::ALIAS_SEPARATOR); if (separator_pos == Alias::npos) { - m_label.clear(); + m_owner.clear(); m_name = alias; } else { - m_label = alias.substr(0, separator_pos); - m_name = alias.substr(separator_pos + strlen(CKM::LABEL_NAME_SEPARATOR)); + m_owner = alias.substr(0, separator_pos); + m_name = alias.substr(separator_pos + strlen(CKM::ALIAS_SEPARATOR)); } } -Alias AliasSupport::merge(const Label &label, const Name &name) +Alias AliasSupport::merge(const ClientId &owner, const Name &name) { - if (label.empty()) + if (owner.empty()) return name; std::stringstream output; - output << label << std::string(CKM::LABEL_NAME_SEPARATOR) << name; + output << owner << std::string(CKM::ALIAS_SEPARATOR) << name; return output.str(); } @@ -199,14 +199,14 @@ const Name &AliasSupport::getName() const return m_name; } -const Label &AliasSupport::getLabel() const +const ClientId &AliasSupport::getOwner() const { - return m_label; + return m_owner; } -bool AliasSupport::isLabelEmpty() const +bool AliasSupport::isOwnerEmpty() const { - return m_label.empty(); + return m_owner.empty(); } ServiceConnection::ServiceConnection(const char *service_interface) diff --git a/src/manager/client/client-common.h b/src/manager/client/client-common.h index 442da37..cedb50e 100644 --- a/src/manager/client/client-common.h +++ b/src/manager/client/client-common.h @@ -51,15 +51,15 @@ class AliasSupport { public: AliasSupport(const Alias &alias); - const Label &getLabel() const; + const ClientId &getOwner() const; const Name &getName() const; - bool isLabelEmpty() const; + bool isOwnerEmpty() const; - static Alias merge(const Label &label, const Name &alias); + static Alias merge(const ClientId &owner, const Name &alias); private: Name m_name; - Label m_label; + ClientId m_owner; }; class SockRAII { diff --git a/src/manager/client/client-control.cpp b/src/manager/client/client-control.cpp index 9a90cad..e92c4d4 100644 --- a/src/manager/client/client-control.cpp +++ b/src/manager/client/client-control.cpp @@ -161,16 +161,16 @@ public: EXCEPTION_GUARD_END } - virtual int removeApplicationData(const Label &smackLabel) + virtual int removeApplicationData(const ClientId &owner) { EXCEPTION_GUARD_START_CPPAPI - if (smackLabel.empty()) + if (owner.empty()) return CKM_API_ERROR_INPUT_PARAM; MessageBuffer recv; auto send = MessageBuffer::Serialize(static_cast - (ControlCommand::REMOVE_APP_DATA), smackLabel); + (ControlCommand::REMOVE_APP_DATA), owner); int retCode = m_controlConnection.processRequest(send.Pop(), recv); @@ -206,7 +206,7 @@ public: virtual int setPermission(uid_t user, const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask) { EXCEPTION_GUARD_START_CPPAPI @@ -217,7 +217,7 @@ public: (ControlCommand::SET_PERMISSION), static_cast(user), helper.getName(), - helper.getLabel(), + helper.getOwner(), accessor, permissionMask); diff --git a/src/manager/client/client-manager-impl.cpp b/src/manager/client/client-manager-impl.cpp index fa4f5a9..7a81943 100644 --- a/src/manager/client/client-manager-impl.cpp +++ b/src/manager/client/client-manager-impl.cpp @@ -118,7 +118,7 @@ int Manager::Impl::saveBinaryData( my_counter, static_cast(dataType), helper.getName(), - helper.getLabel(), + helper.getOwner(), rawData, PolicySerializable(policy)); @@ -194,7 +194,7 @@ int Manager::Impl::savePKCS12( (LogicCommand::SAVE_PKCS12), my_counter, helper.getName(), - helper.getLabel(), + helper.getOwner(), PKCS12Serializable(*pkcs.get()), PolicySerializable(keyPolicy), PolicySerializable(certPolicy)); @@ -236,7 +236,7 @@ int Manager::Impl::getPKCS12(const Alias &alias, const Password &keyPass, auto send = MessageBuffer::Serialize(static_cast(LogicCommand::GET_PKCS12), my_counter, helper.getName(), - helper.getLabel(), + helper.getOwner(), keyPass, certPass); @@ -275,7 +275,7 @@ int Manager::Impl::removeAlias(const Alias &alias) auto send = MessageBuffer::Serialize(static_cast(LogicCommand::REMOVE), my_counter, helper.getName(), - helper.getLabel()); + helper.getOwner()); int retCode = m_storageConnection.processRequest(send.Pop(), recv); @@ -314,7 +314,7 @@ int Manager::Impl::getBinaryData( my_counter, static_cast(sendDataType), helper.getName(), - helper.getLabel(), + helper.getOwner(), password); int retCode = m_storageConnection.processRequest(send.Pop(), recv); @@ -439,14 +439,14 @@ int Manager::Impl::getBinaryDataAliasVector(DataType dataType, int command; int counter; int tmpDataType; - LabelNameVector labelNameVector; - recv.Deserialize(command, counter, retCode, tmpDataType, labelNameVector); + OwnerNameVector ownerNameVector; + recv.Deserialize(command, counter, retCode, tmpDataType, ownerNameVector); if ((command != static_cast(LogicCommand::GET_LIST)) || (counter != my_counter)) return CKM_API_ERROR_UNKNOWN; - for (const auto &it : labelNameVector) + for (const auto &it : ownerNameVector) aliasVector.push_back(AliasSupport::merge(it.first, it.second)); return retCode; @@ -523,7 +523,7 @@ int Manager::Impl::createKeyAES( static_cast(size), PolicySerializable(policyKey), aliasHelper.getName(), - aliasHelper.getLabel()); + aliasHelper.getOwner()); int retCode = m_storageConnection.processRequest(send.Pop(), recv); @@ -592,9 +592,9 @@ int Manager::Impl::createKeyPair( PolicySerializable(policyPrivateKey), PolicySerializable(policyPublicKey), privateHelper.getName(), - privateHelper.getLabel(), + privateHelper.getOwner(), publicHelper.getName(), - publicHelper.getLabel()); + publicHelper.getOwner()); int retCode = m_storageConnection.processRequest(send.Pop(), recv); @@ -656,20 +656,20 @@ int Manager::Impl::getCertificateChain( bool useTrustedSystemCertificates, CertificateShPtrVector &certificateChainVector) { - LabelNameVector untrustedVector; - LabelNameVector trustedVector; + OwnerNameVector untrustedVector; + OwnerNameVector trustedVector; if (!certificate || certificate->empty()) return CKM_API_ERROR_INPUT_PARAM; for (auto &e : untrustedCertificates) { AliasSupport helper(e); - untrustedVector.push_back(std::make_pair(helper.getLabel(), helper.getName())); + untrustedVector.push_back(std::make_pair(helper.getOwner(), helper.getName())); } for (auto &e : trustedCertificates) { AliasSupport helper(e); - trustedVector.push_back(std::make_pair(helper.getLabel(), helper.getName())); + trustedVector.push_back(std::make_pair(helper.getOwner(), helper.getName())); } return getCertChain( @@ -700,7 +700,7 @@ int Manager::Impl::createSignature( (LogicCommand::CREATE_SIGNATURE), my_counter, helper.getName(), - helper.getLabel(), + helper.getOwner(), password, message, CryptoAlgorithmSerializable(cAlgorithm)); @@ -740,7 +740,7 @@ int Manager::Impl::verifySignature( (LogicCommand::VERIFY_SIGNATURE), my_counter, helper.getName(), - helper.getLabel(), + helper.getOwner(), password, message, signature, @@ -802,7 +802,7 @@ int Manager::Impl::ocspCheck(const CertificateShPtrVector &certChain, } int Manager::Impl::setPermission(const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask) { int my_counter = ++m_counter; @@ -815,7 +815,7 @@ int Manager::Impl::setPermission(const Alias &alias, (LogicCommand::SET_PERMISSION), my_counter, helper.getName(), - helper.getLabel(), + helper.getOwner(), accessor, permissionMask); @@ -854,7 +854,7 @@ int Manager::Impl::crypt(EncryptionCommand command, my_counter, cas, helper.getName(), - helper.getLabel(), + helper.getOwner(), password, input); diff --git a/src/manager/client/client-manager-impl.h b/src/manager/client/client-manager-impl.h index ca8a617..caaf669 100644 --- a/src/manager/client/client-manager-impl.h +++ b/src/manager/client/client-manager-impl.h @@ -115,7 +115,7 @@ public: int ocspCheck(const CertificateShPtrVector &certificateChain, int &ocspCheck); - int setPermission(const Alias &alias, const Label &accessor, + int setPermission(const Alias &alias, const ClientId &accessor, PermissionMask permissionMask); int encrypt(const CryptoAlgorithm &algo, diff --git a/src/manager/client/client-manager.cpp b/src/manager/client/client-manager.cpp index c7f1319..073f829 100644 --- a/src/manager/client/client-manager.cpp +++ b/src/manager/client/client-manager.cpp @@ -229,7 +229,7 @@ int Manager::ocspCheck(const CertificateShPtrVector &certificateChainVector, int Manager::setPermission( const Alias &alias, - const Label &accessor, + const ClientId &accessor, PermissionMask permissionMask) { return m_impl->setPermission(alias, accessor, permissionMask); diff --git a/src/manager/common/protocols.cpp b/src/manager/common/protocols.cpp index 8cf6572..d846ca4 100644 --- a/src/manager/common/protocols.cpp +++ b/src/manager/common/protocols.cpp @@ -38,9 +38,9 @@ char const *const SERVICE_SOCKET_OCSP = "/tmp/.central-key-manager-api-ocsp.sock"; char const *const SERVICE_SOCKET_ENCRYPTION = "/tmp/.central-key-manager-api-encryption.sock"; -char const *const LABEL_NAME_SEPARATOR = " "; -char const *const OWNER_ID_SYSTEM = "/System"; -char const *const OWNER_ID_ADMIN_USER = "/User"; +char const *const ALIAS_SEPARATOR = " "; +char const *const CLIENT_ID_SYSTEM = "/System"; +char const *const CLIENT_ID_ADMIN_USER = "/User"; PKCS12Serializable::PKCS12Serializable() { diff --git a/src/manager/common/protocols.h b/src/manager/common/protocols.h index e8be62b..8f7ec0e 100644 --- a/src/manager/common/protocols.h +++ b/src/manager/common/protocols.h @@ -73,13 +73,13 @@ enum class EncryptionCommand : int { DECRYPT }; -// (client side) Alias = (service side) Label::Name -COMMON_API extern char const *const LABEL_NAME_SEPARATOR; -COMMON_API extern char const *const OWNER_ID_SYSTEM; -COMMON_API extern char const *const OWNER_ID_ADMIN_USER; +// (client side) Alias = (service side) Owner::Name +COMMON_API extern char const *const ALIAS_SEPARATOR; +COMMON_API extern char const *const CLIENT_ID_SYSTEM; +COMMON_API extern char const *const CLIENT_ID_ADMIN_USER; typedef std::string Name; -typedef std::vector> LabelNameVector; +typedef std::vector> OwnerNameVector; class IStream; diff --git a/src/manager/initial-values/InitialValueHandler.cpp b/src/manager/initial-values/InitialValueHandler.cpp index c4bcd92..cd92dd6 100644 --- a/src/manager/initial-values/InitialValueHandler.cpp +++ b/src/manager/initial-values/InitialValueHandler.cpp @@ -87,9 +87,9 @@ void InitialValueHandler::End() // save permissions for (const auto &permission : m_permissions) { ec = m_db_logic.setPermissionHelper( - Credentials(CKMLogic::SYSTEM_DB_UID, OWNER_ID_SYSTEM), + Credentials(CKMLogic::SYSTEM_DB_UID, CLIENT_ID_SYSTEM), m_name, - OWNER_ID_SYSTEM, + CLIENT_ID_SYSTEM, permission->getAccessor(), Permission::READ); diff --git a/src/manager/initial-values/PermissionHandler.cpp b/src/manager/initial-values/PermissionHandler.cpp index 0a7f523..7efc3e9 100644 --- a/src/manager/initial-values/PermissionHandler.cpp +++ b/src/manager/initial-values/PermissionHandler.cpp @@ -34,9 +34,9 @@ PermissionHandler::~PermissionHandler() {} void PermissionHandler::Start(const XML::Parser::Attributes &attr) { - // get accessor label + // get accessor id if (attr.find(XML_ATTR_ACCESSOR) != attr.end()) - m_accessor = Label(attr.at(XML_ATTR_ACCESSOR)); + m_accessor = ClientId(attr.at(XML_ATTR_ACCESSOR)); } void PermissionHandler::End() diff --git a/src/manager/initial-values/PermissionHandler.h b/src/manager/initial-values/PermissionHandler.h index d84ecb2..acef23c 100644 --- a/src/manager/initial-values/PermissionHandler.h +++ b/src/manager/initial-values/PermissionHandler.h @@ -39,13 +39,13 @@ public: virtual void Start(const XML::Parser::Attributes &); virtual void End(); - const Label &getAccessor() const + const ClientId &getAccessor() const { return m_accessor; } private: - Label m_accessor; + ClientId m_accessor; }; } diff --git a/src/manager/main/credentials.h b/src/manager/main/credentials.h index bae9c85..916e4eb 100644 --- a/src/manager/main/credentials.h +++ b/src/manager/main/credentials.h @@ -28,10 +28,10 @@ namespace CKM { struct Credentials { Credentials() : clientUid(0) {} - Credentials(uid_t socketUid, const Label &socketLabel) - : clientUid(socketUid), smackLabel(socketLabel) {} + Credentials(uid_t socketUid, const ClientId &client) + : clientUid(socketUid), client(client) {} uid_t clientUid; - Label smackLabel; + ClientId client; }; } // namespace CKM diff --git a/src/manager/main/service-messages.h b/src/manager/main/service-messages.h index 0815f6d..dbe7648 100644 --- a/src/manager/main/service-messages.h +++ b/src/manager/main/service-messages.h @@ -44,12 +44,17 @@ struct MsgBase { // key request struct MsgKeyRequest : public MsgBase { MsgKeyRequest(int id, const Credentials &cred, const Name &name, - const Label &label, const Password &password) : - MsgBase(id), cred(cred), name(name), label(label), password(password) {} + const ClientId &explicitOwner, const Password &password) : + MsgBase(id), + cred(cred), + name(name), + explicitOwner(explicitOwner), + password(password) + {} Credentials cred; Name name; - Label label; + ClientId explicitOwner; Password password; }; diff --git a/src/manager/main/socket-2-id.cpp b/src/manager/main/socket-2-id.cpp index ea0b50a..8d4f712 100644 --- a/src/manager/main/socket-2-id.cpp +++ b/src/manager/main/socket-2-id.cpp @@ -96,15 +96,15 @@ int Socket2Id::getCredentialsFromSocket(int sock, std::string &res) return assignToString(result, length, res); } -void Socket2Id::mapToDomainLabel(std::string &label) +void Socket2Id::mapToDomainClient(std::string &pkgId) { static const std::string subdomainSep = "::"; - static const auto systemLabelLen = strlen(OWNER_ID_SYSTEM); + static const auto systemClientLen = strlen(CLIENT_ID_SYSTEM); - if (label.length() > systemLabelLen + subdomainSep.length() && - label.compare(0, systemLabelLen, OWNER_ID_SYSTEM) == 0 && - label.compare(systemLabelLen, subdomainSep.length(), subdomainSep) == 0) { - label = OWNER_ID_SYSTEM; + if (pkgId.length() > systemClientLen + subdomainSep.length() && + pkgId.compare(0, systemClientLen, CLIENT_ID_SYSTEM) == 0 && + pkgId.compare(systemClientLen, subdomainSep.length(), subdomainSep) == 0) { + pkgId = CLIENT_ID_SYSTEM; } } @@ -138,7 +138,7 @@ int Socket2Id::translate(int sock, std::string &result) pkgId = "/" + smack; } - mapToDomainLabel(pkgId); + mapToDomainClient(pkgId); result = pkgId; m_stringMap.emplace(std::move(smack), std::move(pkgId)); diff --git a/src/manager/main/socket-2-id.h b/src/manager/main/socket-2-id.h index 3e970c2..754683d 100644 --- a/src/manager/main/socket-2-id.h +++ b/src/manager/main/socket-2-id.h @@ -36,7 +36,7 @@ public: private: int getCredentialsFromSocket(int sock, std::string &res); - void mapToDomainLabel(std::string &label); + void mapToDomainClient(std::string &label); typedef std::map StringMap; StringMap m_stringMap; diff --git a/src/manager/main/socket-manager.cpp b/src/manager/main/socket-manager.cpp index ee5a0bf..db3f2a6 100644 --- a/src/manager/main/socket-manager.cpp +++ b/src/manager/main/socket-manager.cpp @@ -51,9 +51,9 @@ const time_t SOCKET_TIMEOUT = 1000; int getCredentialsFromSocket(int sock, CKM::Credentials &cred) { static CKM::Socket2Id sock2id; - std::string ownerId; + CKM::ClientId client; - if (0 > sock2id.translate(sock, ownerId)) + if (0 > sock2id.translate(sock, client)) return -1; ucred peerCred; @@ -64,7 +64,7 @@ int getCredentialsFromSocket(int sock, CKM::Credentials &cred) return -1; } - cred = CKM::Credentials(peerCred.uid, std::move(ownerId)); + cred = CKM::Credentials(peerCred.uid, std::move(client)); return 0; } diff --git a/src/manager/service/access-control.cpp b/src/manager/service/access-control.cpp index 95cd3a3..0704147 100644 --- a/src/manager/service/access-control.cpp +++ b/src/manager/service/access-control.cpp @@ -65,12 +65,12 @@ bool AccessControl::isSystemService(const CKM::Credentials &cred) const int AccessControl::canSave( const CKM::Credentials &accessorCred, - const Label &ownerLabel) const + const ClientId &owner) const { if (isSystemService(accessorCred)) return CKM_API_SUCCESS; - if (ownerLabel != accessorCred.smackLabel) + if (owner != accessorCred.client) return CKM_API_ERROR_ACCESS_DENIED; return CKM_API_SUCCESS; @@ -78,19 +78,19 @@ int AccessControl::canSave( int AccessControl::canModify( const CKM::Credentials &accessorCred, - const Label &ownerLabel) const + const ClientId &owner) const { - return canSave(accessorCred, ownerLabel); + return canSave(accessorCred, owner); } int AccessControl::canRead( const CKM::Credentials &accessorCred, - const PermissionForLabel &permissionLabel) const + const PermissionMask &existingPermission) const { if (isSystemService(accessorCred)) return CKM_API_SUCCESS; - if (permissionLabel & Permission::READ) + if (existingPermission & Permission::READ) return CKM_API_SUCCESS; return CKM_API_ERROR_DB_ALIAS_UNKNOWN; @@ -99,11 +99,11 @@ int AccessControl::canRead( int AccessControl::canExport( const CKM::Credentials &accessorCred, const DB::Row &row, - const PermissionForLabel &permissionLabel) const + const PermissionMask &existingPermission) const { int ec; - if (CKM_API_SUCCESS != (ec = canRead(accessorCred, permissionLabel))) + if (CKM_API_SUCCESS != (ec = canRead(accessorCred, existingPermission))) return ec; // check if can export @@ -119,15 +119,15 @@ int AccessControl::canExport( int AccessControl::canDelete( const CKM::Credentials &accessorCred, - const PermissionForLabel &permissionLabel) const + const PermissionMask &existingPermission) const { if (isSystemService(accessorCred)) return CKM_API_SUCCESS; - if (permissionLabel & Permission::REMOVE) + if (existingPermission & Permission::REMOVE) return CKM_API_SUCCESS; - if (permissionLabel & Permission::READ) + if (existingPermission & Permission::READ) return CKM_API_ERROR_ACCESS_DENIED; return CKM_API_ERROR_DB_ALIAS_UNKNOWN; diff --git a/src/manager/service/access-control.h b/src/manager/service/access-control.h index f5c2fea..4488b92 100644 --- a/src/manager/service/access-control.h +++ b/src/manager/service/access-control.h @@ -43,21 +43,21 @@ public: * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code */ int canSave(const CKM::Credentials &accessorCred, - const Label &ownerLabel) const; + const ClientId &owner) const; /** - * check if given label can be modified by accessor + * check if given data can be modified by accessor * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code */ int canModify(const CKM::Credentials &accessorCred, - const Label &ownerLabel) const; + const ClientId &owner) const; /** * check if given row can be read (for internal use) * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code */ int canRead(const CKM::Credentials &accessorCred, - const PermissionForLabel &permissionLabel) const; + const PermissionMask &existingPermission) const; /** * check if given row can be exported (data provided to the client) @@ -65,14 +65,14 @@ public: */ int canExport(const CKM::Credentials &accessorCred, const DB::Row &row, - const PermissionForLabel &permissionLabel) const; + const PermissionMask &existingPermission) const; /** - * check if given accessor can delete ownerLabel's items. + * check if given accessor can delete owner's items. * @return CKM_API_SUCCESS if access is allowed, otherwise negative error code */ int canDelete(const CKM::Credentials &accessorCred, - const PermissionForLabel &permissionLabel) const; + const PermissionMask &existingPermission) const; void updateCCMode(); bool isCCMode() const; diff --git a/src/manager/service/ckm-logic.cpp b/src/manager/service/ckm-logic.cpp index 7d976a9..635f8b9 100644 --- a/src/manager/service/ckm-logic.cpp +++ b/src/manager/service/ckm-logic.cpp @@ -39,10 +39,9 @@ namespace { const char *const CERT_SYSTEM_DIR = CA_CERTS_DIR; const char *const SYSTEM_DB_PASSWD = "cAtRugU7"; -bool isLabelValid(const CKM::Label &label) +bool isClientValid(const CKM::ClientId &client) { - // TODO: copy code from libprivilege control (for check smack label) - if (label.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Label::npos) + if (client.find(CKM::ALIAS_SEPARATOR) != CKM::ClientId::npos) return false; return true; @@ -50,7 +49,7 @@ bool isLabelValid(const CKM::Label &label) bool isNameValid(const CKM::Name &name) { - if (name.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Name::npos) + if (name.find(CKM::ALIAS_SEPARATOR) != CKM::Name::npos) return false; return true; @@ -102,7 +101,7 @@ void CKMLogic::migrateSecureStorageData(bool isAdminUser) const Crypto::Data &data, bool adminUserFlag) { LogInfo("Migrate data called with name: " << name); - auto ownerId = adminUserFlag ? OWNER_ID_ADMIN_USER : OWNER_ID_SYSTEM; + auto ownerId = adminUserFlag ? CLIENT_ID_ADMIN_USER : CLIENT_ID_SYSTEM; auto uid = adminUserFlag ? ADMIN_USER_DB_UID : SYSTEM_DB_UID; int ret = verifyAndSaveDataHelper(Credentials(uid, ownerId), name, ownerId, data, @@ -144,11 +143,11 @@ int CKMLogic::unlockDatabase(uid_t user, const Password &password) if (!m_accessControl.isSystemService(user)) { // remove data of removed apps during locked state - AppLabelVector removedApps = fs.clearRemovedsApps(); + ClientIdVector removedApps = fs.clearRemovedsApps(); - for (auto &appSmackLabel : removedApps) { - handle.crypto.removeKey(appSmackLabel); - handle.database.deleteKey(appSmackLabel); + for (auto &app : removedApps) { + handle.crypto.removeKey(app); + handle.database.deleteKey(app); } } @@ -175,21 +174,21 @@ int CKMLogic::unlockSystemDB() } UserData &CKMLogic::selectDatabase(const Credentials &cred, - const Label &incoming_label) + const ClientId &explicitOwner) { // if user trying to access system service - check: // * if user database is unlocked [mandatory] // * if not - proceed with regular user database - // * if explicit system database label given -> switch to system DB + // * if explicit system database owner given -> switch to system DB if (!m_accessControl.isSystemService(cred)) { if (0 == m_userDataMap.count(cred.clientUid)) ThrowErr(Exc::DatabaseLocked, "database with UID: ", cred.clientUid, " locked"); - if (0 != incoming_label.compare(OWNER_ID_SYSTEM)) + if (0 != explicitOwner.compare(CLIENT_ID_SYSTEM)) return m_userDataMap[cred.clientUid]; } - // system database selected, modify the label + // system database selected, modify the owner id if (CKM_API_SUCCESS != unlockSystemDB()) ThrowErr(Exc::DatabaseLocked, "can not unlock system database"); @@ -316,12 +315,12 @@ RawBuffer CKMLogic::resetUserPassword( return MessageBuffer::Serialize(retCode).Pop(); } -RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) +RawBuffer CKMLogic::removeApplicationData(const ClientId &owner) { int retCode = CKM_API_SUCCESS; try { - if (smackLabel.empty()) { + if (owner.empty()) { retCode = CKM_API_ERROR_INPUT_PARAM; } else { UidVector uids = FileSystem::getUIDsFromDBFile(); @@ -329,11 +328,11 @@ RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) for (auto userId : uids) { if (0 == m_userDataMap.count(userId)) { FileSystem fs(userId); - fs.addRemovedApp(smackLabel); + fs.addRemovedApp(owner); } else { auto &handle = m_userDataMap[userId]; - handle.crypto.removeKey(smackLabel); - handle.database.deleteKey(smackLabel); + handle.crypto.removeKey(owner); + handle.database.deleteKey(owner); } } } @@ -348,47 +347,47 @@ RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) } int CKMLogic::checkSaveConditions( - const Credentials &cred, + const Credentials &accessorCred, UserData &handler, const Name &name, - const Label &ownerLabel) + const ClientId &owner) { - // verify name and label are correct - if (!isNameValid(name) || !isLabelValid(ownerLabel)) { + // verify name and client are correct + if (!isNameValid(name) || !isClientValid(owner)) { LogDebug("Invalid parameter passed to key-manager"); return CKM_API_ERROR_INPUT_PARAM; } - // check if allowed to save using ownerLabel - int access_ec = m_accessControl.canSave(cred, ownerLabel); + // check if accessor is allowed to save owner's items + int access_ec = m_accessControl.canSave(accessorCred, owner); if (access_ec != CKM_API_SUCCESS) { - LogDebug("label " << cred.smackLabel << " can not save rows using label " << - ownerLabel); + LogDebug("accessor " << accessorCred.client << " can not save rows owned by " << + owner); return access_ec; } // check if not a duplicate - if (handler.database.isNameLabelPresent(name, ownerLabel)) + if (handler.database.isNameOwnerPresent(name, owner)) return CKM_API_ERROR_DB_ALIAS_EXISTS; // encryption section - if (!handler.crypto.haveKey(ownerLabel)) { + if (!handler.crypto.haveKey(owner)) { RawBuffer got_key; - auto key_optional = handler.database.getKey(ownerLabel); + auto key_optional = handler.database.getKey(owner); if (!key_optional) { - LogDebug("No Key in database found. Generating new one for label: " << - ownerLabel); - got_key = handler.keyProvider.generateDEK(ownerLabel); - handler.database.saveKey(ownerLabel, got_key); + LogDebug("No Key in database found. Generating new one for client: " << + owner); + got_key = handler.keyProvider.generateDEK(owner); + handler.database.saveKey(owner, got_key); } else { LogDebug("Key from DB"); got_key = *key_optional; } got_key = handler.keyProvider.getPureDEK(got_key); - handler.crypto.pushKey(ownerLabel, got_key); + handler.crypto.pushKey(owner, got_key); } return CKM_API_SUCCESS; @@ -397,7 +396,7 @@ int CKMLogic::checkSaveConditions( DB::Row CKMLogic::createEncryptedRow( CryptoLogic &crypto, const Name &name, - const Label &label, + const ClientId &owner, const Crypto::Data &data, const Policy &policy) const { @@ -406,7 +405,7 @@ DB::Row CKMLogic::createEncryptedRow( // do not encrypt data with password during cc_mode on Token token = store.import(data, m_accessControl.isCCMode() ? "" : policy.password); - DB::Row row(std::move(token), name, label, + DB::Row row(std::move(token), name, owner, static_cast(policy.extractable)); crypto.encryptRow(row); return row; @@ -457,7 +456,7 @@ int CKMLogic::toBinaryData(const Crypto::Data &input, int CKMLogic::verifyAndSaveDataHelper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Crypto::Data &data, const PolicySerializable &policy) { @@ -471,7 +470,7 @@ int CKMLogic::verifyAndSaveDataHelper( if (retCode != CKM_API_SUCCESS) return retCode; else - return saveDataHelper(cred, name, label, binaryData, policy); + return saveDataHelper(cred, name, explicitOwner, binaryData, policy); } catch (const Exc::Exception &e) { return e.error(); } catch (const CKM::Exception &e) { @@ -483,14 +482,14 @@ int CKMLogic::verifyAndSaveDataHelper( int CKMLogic::getKeyForService( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &pass, Crypto::GObjShPtr &key) { try { // Key is for internal service use. It won't be exported to the client Crypto::GObjUPtr obj; - int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, label, + int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, explicitOwner, pass, obj); if (retCode == CKM_API_SUCCESS) @@ -509,11 +508,11 @@ RawBuffer CKMLogic::saveData( const Credentials &cred, int commandId, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Crypto::Data &data, const PolicySerializable &policy) { - int retCode = verifyAndSaveDataHelper(cred, name, label, data, policy); + int retCode = verifyAndSaveDataHelper(cred, name, explicitOwner, data, policy); auto response = MessageBuffer::Serialize(static_cast(LogicCommand::SAVE), commandId, retCode, @@ -524,7 +523,7 @@ RawBuffer CKMLogic::saveData( int CKMLogic::extractPKCS12Data( CryptoLogic &crypto, const Name &name, - const Label &ownerLabel, + const ClientId &owner, const PKCS12Serializable &pkcs, const PolicySerializable &keyPolicy, const PolicySerializable &certPolicy, @@ -544,7 +543,7 @@ int CKMLogic::extractPKCS12Data( if (retCode != CKM_API_SUCCESS) return retCode; - output.push_back(createEncryptedRow(crypto, name, ownerLabel, keyData, + output.push_back(createEncryptedRow(crypto, name, owner, keyData, keyPolicy)); // certificate is mandatory @@ -561,7 +560,7 @@ int CKMLogic::extractPKCS12Data( if (retCode != CKM_API_SUCCESS) return retCode; - output.push_back(createEncryptedRow(crypto, name, ownerLabel, certData, + output.push_back(createEncryptedRow(crypto, name, owner, certData, certPolicy)); // CA cert chain @@ -575,7 +574,7 @@ int CKMLogic::extractPKCS12Data( if (retCode != CKM_API_SUCCESS) return retCode; - output.push_back(createEncryptedRow(crypto, name, ownerLabel, caCertData, + output.push_back(createEncryptedRow(crypto, name, owner, caCertData, certPolicy)); } @@ -586,7 +585,7 @@ RawBuffer CKMLogic::savePKCS12( const Credentials &cred, int commandId, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PKCS12Serializable &pkcs, const PolicySerializable &keyPolicy, const PolicySerializable &certPolicy) @@ -594,7 +593,7 @@ RawBuffer CKMLogic::savePKCS12( int retCode = CKM_API_ERROR_UNKNOWN; try { - retCode = saveDataHelper(cred, name, label, pkcs, keyPolicy, certPolicy); + retCode = saveDataHelper(cred, name, explicitOwner, pkcs, keyPolicy, certPolicy); } catch (const Exc::Exception &e) { retCode = e.error(); } catch (const CKM::Exception &e) { @@ -613,15 +612,15 @@ RawBuffer CKMLogic::savePKCS12( int CKMLogic::removeDataHelper( const Credentials &cred, const Name &name, - const Label &label) + const ClientId &explicitOwner) { - auto &handler = selectDatabase(cred, label); + auto &handler = selectDatabase(cred, explicitOwner); - // use client label if not explicitly provided - const Label &ownerLabel = label.empty() ? cred.smackLabel : label; + // use client id if not explicitly provided + const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; - if (!isNameValid(name) || !isLabelValid(ownerLabel)) { - LogDebug("Invalid label or name format"); + if (!isNameValid(name) || !isClientValid(owner)) { + LogDebug("Invalid owner or name format"); return CKM_API_ERROR_INPUT_PARAM; } @@ -629,9 +628,9 @@ int CKMLogic::removeDataHelper( // read and check permissions PermissionMaskOptional permissionRowOpt = - handler.database.getPermissionRow(name, ownerLabel, cred.smackLabel); + handler.database.getPermissionRow(name, owner, cred.client); int retCode = m_accessControl.canDelete(cred, - PermissionForLabel(cred.smackLabel, permissionRowOpt)); + toPermissionMask(permissionRowOpt)); if (retCode != CKM_API_SUCCESS) { LogWarning("access control check result: " << retCode); @@ -640,16 +639,16 @@ int CKMLogic::removeDataHelper( // get all matching rows DB::RowVector rows; - handler.database.getRows(name, ownerLabel, DataType::DB_FIRST, + handler.database.getRows(name, owner, DataType::DB_FIRST, DataType::DB_LAST, rows); if (rows.empty()) { - LogDebug("No row for given name and label"); + LogDebug("No row for given name and owner"); return CKM_API_ERROR_DB_ALIAS_UNKNOWN; } // load app key if needed - retCode = loadAppKey(handler, rows.front().ownerLabel); + retCode = loadAppKey(handler, rows.front().owner); if (CKM_API_SUCCESS != retCode) return retCode; @@ -665,7 +664,7 @@ int CKMLogic::removeDataHelper( } // delete row in db - handler.database.deleteRow(name, ownerLabel); + handler.database.deleteRow(name, owner); transaction.commit(); return CKM_API_SUCCESS; @@ -675,12 +674,12 @@ RawBuffer CKMLogic::removeData( const Credentials &cred, int commandId, const Name &name, - const Label &label) + const ClientId &explicitOwner) { int retCode = CKM_API_ERROR_UNKNOWN; try { - retCode = removeDataHelper(cred, name, label); + retCode = removeDataHelper(cred, name, explicitOwner); } catch (const Exc::Exception &e) { retCode = e.error(); } catch (const CKM::Exception &e) { @@ -695,7 +694,7 @@ RawBuffer CKMLogic::removeData( } int CKMLogic::readSingleRow(const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType dataType, DB::Crypto &database, DB::Row &row) @@ -705,18 +704,18 @@ int CKMLogic::readSingleRow(const Name &name, if (dataType.isKey()) { // read all key types row_optional = database.getRow(name, - ownerLabel, + owner, DataType::DB_KEY_FIRST, DataType::DB_KEY_LAST); } else { // read anything else row_optional = database.getRow(name, - ownerLabel, + owner, dataType); } if (!row_optional) { - LogDebug("No row for given name, label and type"); + LogDebug("No row for given name, owner and type"); return CKM_API_ERROR_DB_ALIAS_UNKNOWN; } else { row = *row_optional; @@ -727,7 +726,7 @@ int CKMLogic::readSingleRow(const Name &name, int CKMLogic::readMultiRow(const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType dataType, DB::Crypto &database, DB::RowVector &output) @@ -735,49 +734,49 @@ int CKMLogic::readMultiRow(const Name &name, if (dataType.isKey()) // read all key types database.getRows(name, - ownerLabel, + owner, DataType::DB_KEY_FIRST, DataType::DB_KEY_LAST, output); else if (dataType.isChainCert()) // read all key types database.getRows(name, - ownerLabel, + owner, DataType::DB_CHAIN_FIRST, DataType::DB_CHAIN_LAST, output); else // read anything else database.getRows(name, - ownerLabel, + owner, dataType, output); if (!output.size()) { - LogDebug("No row for given name, label and type"); + LogDebug("No row for given name, owner and type"); return CKM_API_ERROR_DB_ALIAS_UNKNOWN; } return CKM_API_SUCCESS; } -int CKMLogic::checkDataPermissionsHelper(const Credentials &cred, +int CKMLogic::checkDataPermissionsHelper(const Credentials &accessorCred, const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, + const ClientId &owner, const DB::Row &row, bool exportFlag, DB::Crypto &database) { PermissionMaskOptional permissionRowOpt = - database.getPermissionRow(name, ownerLabel, accessorLabel); + database.getPermissionRow(name, owner, accessorCred.client); if (exportFlag) - return m_accessControl.canExport(cred, row, PermissionForLabel(accessorLabel, - permissionRowOpt)); + return m_accessControl.canExport(accessorCred, + row, + toPermissionMask(permissionRowOpt)); - return m_accessControl.canRead(cred, PermissionForLabel(accessorLabel, - permissionRowOpt)); + return m_accessControl.canRead(accessorCred, + toPermissionMask(permissionRowOpt)); } Crypto::GObjUPtr CKMLogic::rowToObject( @@ -827,22 +826,22 @@ int CKMLogic::readDataHelper( const Credentials &cred, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password, Crypto::GObjUPtrVector &objs) { - auto &handler = selectDatabase(cred, label); + auto &handler = selectDatabase(cred, explicitOwner); - // use client label if not explicitly provided - const Label &ownerLabel = label.empty() ? cred.smackLabel : label; + // use client id if not explicitly provided + const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; - if (!isNameValid(name) || !isLabelValid(ownerLabel)) + if (!isNameValid(name) || !isClientValid(owner)) return CKM_API_ERROR_INPUT_PARAM; // read rows DB::Crypto::Transaction transaction(&handler.database); DB::RowVector rows; - int retCode = readMultiRow(name, ownerLabel, dataType, handler.database, rows); + int retCode = readMultiRow(name, owner, dataType, handler.database, rows); if (CKM_API_SUCCESS != retCode) return retCode; @@ -851,14 +850,14 @@ int CKMLogic::readDataHelper( DB::Row &firstRow = rows.at(0); // check access rights - retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel, - firstRow, exportFlag, handler.database); + retCode = checkDataPermissionsHelper(cred, name, owner, firstRow, + exportFlag, handler.database); if (CKM_API_SUCCESS != retCode) return retCode; // load app key if needed - retCode = loadAppKey(handler, firstRow.ownerLabel); + retCode = loadAppKey(handler, firstRow.owner); if (CKM_API_SUCCESS != retCode) return retCode; @@ -878,13 +877,13 @@ int CKMLogic::readDataHelper( const Credentials &cred, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password, Crypto::GObjUPtr &obj) { DataType objDataType; - return readDataHelper(exportFlag, cred, dataType, name, label, password, obj, - objDataType); + return readDataHelper(exportFlag, cred, dataType, name, explicitOwner, + password, obj, objDataType); } int CKMLogic::readDataHelper( @@ -892,23 +891,23 @@ int CKMLogic::readDataHelper( const Credentials &cred, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password, Crypto::GObjUPtr &obj, DataType &objDataType) { - auto &handler = selectDatabase(cred, label); + auto &handler = selectDatabase(cred, explicitOwner); - // use client label if not explicitly provided - const Label &ownerLabel = label.empty() ? cred.smackLabel : label; + // use client id if not explicitly provided + const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; - if (!isNameValid(name) || !isLabelValid(ownerLabel)) + if (!isNameValid(name) || !isClientValid(owner)) return CKM_API_ERROR_INPUT_PARAM; // read row DB::Crypto::Transaction transaction(&handler.database); DB::Row row; - int retCode = readSingleRow(name, ownerLabel, dataType, handler.database, row); + int retCode = readSingleRow(name, owner, dataType, handler.database, row); if (CKM_API_SUCCESS != retCode) return retCode; @@ -916,14 +915,14 @@ int CKMLogic::readDataHelper( objDataType = row.dataType; // check access rights - retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel, - row, exportFlag, handler.database); + retCode = checkDataPermissionsHelper(cred, name, owner, row, exportFlag, + handler.database); if (CKM_API_SUCCESS != retCode) return retCode; // load app key if needed - retCode = loadAppKey(handler, row.ownerLabel); + retCode = loadAppKey(handler, row.owner); if (CKM_API_SUCCESS != retCode) return retCode; @@ -940,7 +939,7 @@ RawBuffer CKMLogic::getData( int commandId, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password) { int retCode = CKM_API_SUCCESS; @@ -949,8 +948,8 @@ RawBuffer CKMLogic::getData( try { Crypto::GObjUPtr obj; - retCode = readDataHelper(true, cred, dataType, name, label, password, obj, - objDataType); + retCode = readDataHelper(true, cred, dataType, name, explicitOwner, + password, obj, objDataType); if (retCode == CKM_API_SUCCESS) rowData = obj->getBinary(); @@ -975,7 +974,7 @@ RawBuffer CKMLogic::getData( int CKMLogic::getPKCS12Helper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &keyPassword, const Password &certPassword, KeyShPtr &privKey, @@ -986,7 +985,7 @@ int CKMLogic::getPKCS12Helper( // read private key (mandatory) Crypto::GObjUPtr keyObj; - retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, label, + retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, explicitOwner, keyPassword, keyObj); if (retCode != CKM_API_SUCCESS) { @@ -998,7 +997,7 @@ int CKMLogic::getPKCS12Helper( // read certificate (mandatory) Crypto::GObjUPtr certObj; - retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, label, + retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, explicitOwner, certPassword, certObj); if (retCode != CKM_API_SUCCESS) { @@ -1010,7 +1009,7 @@ int CKMLogic::getPKCS12Helper( // read CA cert chain (optional) Crypto::GObjUPtrVector caChainObjs; - retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, label, + retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, explicitOwner, certPassword, caChainObjs); if (retCode != CKM_API_SUCCESS && retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN) { @@ -1033,7 +1032,7 @@ RawBuffer CKMLogic::getPKCS12( const Credentials &cred, int commandId, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &keyPassword, const Password &certPassword) { @@ -1045,8 +1044,8 @@ RawBuffer CKMLogic::getPKCS12( KeyShPtr privKey; CertificateShPtr cert; CertificateShPtrVector caChain; - retCode = getPKCS12Helper(cred, name, label, keyPassword, certPassword, privKey, - cert, caChain); + retCode = getPKCS12Helper(cred, name, explicitOwner, keyPassword, + certPassword, privKey, cert, caChain); // prepare response if (retCode == CKM_API_SUCCESS) @@ -1069,7 +1068,7 @@ RawBuffer CKMLogic::getPKCS12( int CKMLogic::getDataListHelper(const Credentials &cred, const DataType dataType, - LabelNameVector &labelNameVector) + OwnerNameVector &ownerNameVector) { int retCode = CKM_API_ERROR_DB_LOCKED; @@ -1077,22 +1076,22 @@ int CKMLogic::getDataListHelper(const Credentials &cred, auto &database = m_userDataMap[cred.clientUid].database; try { - LabelNameVector tmpVector; + OwnerNameVector tmpVector; if (dataType.isKey()) { // list all key types - database.listNames(cred.smackLabel, + database.listNames(cred.client, tmpVector, DataType::DB_KEY_FIRST, DataType::DB_KEY_LAST); } else { // list anything else - database.listNames(cred.smackLabel, + database.listNames(cred.client, tmpVector, dataType); } - labelNameVector.insert(labelNameVector.end(), tmpVector.begin(), + ownerNameVector.insert(ownerNameVector.end(), tmpVector.begin(), tmpVector.end()); retCode = CKM_API_SUCCESS; } catch (const CKM::Exception &e) { @@ -1111,9 +1110,9 @@ RawBuffer CKMLogic::getDataList( int commandId, DataType dataType) { - LabelNameVector systemVector; - LabelNameVector userVector; - LabelNameVector labelNameVector; + OwnerNameVector systemVector; + OwnerNameVector userVector; + OwnerNameVector ownerNameVector; int retCode = unlockSystemDB(); @@ -1122,13 +1121,13 @@ RawBuffer CKMLogic::getDataList( if (m_accessControl.isSystemService(cred)) { // lookup system DB retCode = getDataListHelper(Credentials(SYSTEM_DB_UID, - OWNER_ID_SYSTEM), + CLIENT_ID_SYSTEM), dataType, systemVector); } else { // user - lookup system, then client DB retCode = getDataListHelper(Credentials(SYSTEM_DB_UID, - cred.smackLabel), + cred.client), dataType, systemVector); @@ -1142,9 +1141,9 @@ RawBuffer CKMLogic::getDataList( } if (retCode == CKM_API_SUCCESS) { - labelNameVector.insert(labelNameVector.end(), systemVector.begin(), + ownerNameVector.insert(ownerNameVector.end(), systemVector.begin(), systemVector.end()); - labelNameVector.insert(labelNameVector.end(), userVector.begin(), + ownerNameVector.insert(ownerNameVector.end(), userVector.begin(), userVector.end()); } @@ -1153,7 +1152,7 @@ RawBuffer CKMLogic::getDataList( commandId, retCode, static_cast(dataType), - labelNameVector); + ownerNameVector); return response.Pop(); } @@ -1164,14 +1163,14 @@ int CKMLogic::importInitialData( const Policy &policy) { try { - // Inital values are always imported with root credentials. Label is not important. + // Inital values are always imported with root credentials. Client id is not important. Credentials rootCred(0, ""); - auto &handler = selectDatabase(rootCred, OWNER_ID_SYSTEM); + auto &handler = selectDatabase(rootCred, CLIENT_ID_SYSTEM); // check if save is possible DB::Crypto::Transaction transaction(&handler.database); - int retCode = checkSaveConditions(rootCred, handler, name, OWNER_ID_SYSTEM); + int retCode = checkSaveConditions(rootCred, handler, name, CLIENT_ID_SYSTEM); if (retCode != CKM_API_SUCCESS) return retCode; @@ -1193,7 +1192,7 @@ int CKMLogic::importInitialData( m_accessControl.isCCMode() ? "" : policy.password, enc); } - DB::Row row(std::move(token), name, OWNER_ID_SYSTEM, + DB::Row row(std::move(token), name, CLIENT_ID_SYSTEM, static_cast(policy.extractable)); handler.crypto.encryptRow(row); @@ -1215,28 +1214,28 @@ int CKMLogic::importInitialData( int CKMLogic::saveDataHelper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Crypto::Data &data, const PolicySerializable &policy) { - auto &handler = selectDatabase(cred, label); + auto &handler = selectDatabase(cred, explicitOwner); - // use client label if not explicitly provided - const Label &ownerLabel = label.empty() ? cred.smackLabel : label; + // use client id if not explicitly provided + const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; if (m_accessControl.isSystemService(cred) && - ownerLabel.compare(OWNER_ID_SYSTEM) != 0) + owner.compare(CLIENT_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; // check if save is possible DB::Crypto::Transaction transaction(&handler.database); - int retCode = checkSaveConditions(cred, handler, name, ownerLabel); + int retCode = checkSaveConditions(cred, handler, name, owner); if (retCode != CKM_API_SUCCESS) return retCode; // save the data - DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, ownerLabel, + DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, owner, data, policy); handler.database.saveRow(encryptedRow); @@ -1247,37 +1246,37 @@ int CKMLogic::saveDataHelper( int CKMLogic::saveDataHelper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PKCS12Serializable &pkcs, const PolicySerializable &keyPolicy, const PolicySerializable &certPolicy) { - auto &handler = selectDatabase(cred, label); + auto &handler = selectDatabase(cred, explicitOwner); - // use client label if not explicitly provided - const Label &ownerLabel = label.empty() ? cred.smackLabel : label; + // use client id if not explicitly provided + const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; if (m_accessControl.isSystemService(cred) && - ownerLabel.compare(OWNER_ID_SYSTEM) != 0) + owner.compare(CLIENT_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; // check if save is possible DB::Crypto::Transaction transaction(&handler.database); - int retCode = checkSaveConditions(cred, handler, name, ownerLabel); + int retCode = checkSaveConditions(cred, handler, name, owner); if (retCode != CKM_API_SUCCESS) return retCode; // extract and encrypt the data DB::RowVector encryptedRows; - retCode = extractPKCS12Data(handler.crypto, name, ownerLabel, pkcs, keyPolicy, + retCode = extractPKCS12Data(handler.crypto, name, owner, pkcs, keyPolicy, certPolicy, encryptedRows); if (retCode != CKM_API_SUCCESS) return retCode; // save the data - handler.database.saveRows(name, ownerLabel, encryptedRows); + handler.database.saveRows(name, owner, encryptedRows); transaction.commit(); return CKM_API_SUCCESS; @@ -1288,21 +1287,21 @@ int CKMLogic::createKeyAESHelper( const Credentials &cred, const int size, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PolicySerializable &policy) { - auto &handler = selectDatabase(cred, label); + auto &handler = selectDatabase(cred, explicitOwner); - // use client label if not explicitly provided - const Label &ownerLabel = label.empty() ? cred.smackLabel : label; + // use client id if not explicitly provided + const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; if (m_accessControl.isSystemService(cred) && - ownerLabel.compare(OWNER_ID_SYSTEM) != 0) + owner.compare(CLIENT_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; // check if save is possible DB::Crypto::Transaction transaction(&handler.database); - int retCode = checkSaveConditions(cred, handler, name, ownerLabel); + int retCode = checkSaveConditions(cred, handler, name, owner); if (retCode != CKM_API_SUCCESS) return retCode; @@ -1315,7 +1314,7 @@ int CKMLogic::createKeyAESHelper( policy).generateSKey(keyGenAlgorithm, policy.password); // save the data - DB::Row row(std::move(key), name, ownerLabel, + DB::Row row(std::move(key), name, owner, static_cast(policy.extractable)); handler.crypto.encryptRow(row); @@ -1329,14 +1328,14 @@ int CKMLogic::createKeyPairHelper( const Credentials &cred, const CryptoAlgorithmSerializable &keyGenParams, const Name &namePrivate, - const Label &labelPrivate, + const ClientId &explicitOwnerPrivate, const Name &namePublic, - const Label &labelPublic, + const ClientId &explicitOwnerPublic, const PolicySerializable &policyPrivate, const PolicySerializable &policyPublic) { - auto &handlerPriv = selectDatabase(cred, labelPrivate); - auto &handlerPub = selectDatabase(cred, labelPublic); + auto &handlerPriv = selectDatabase(cred, explicitOwnerPrivate); + auto &handlerPub = selectDatabase(cred, explicitOwnerPublic); AlgoType keyType = AlgoType::RSA_GEN; @@ -1351,19 +1350,19 @@ int CKMLogic::createKeyPairHelper( if (policyPrivate.backend != policyPublic.backend) ThrowErr(Exc::InputParam, "Error, key pair must be supported with the same backend."); - // use client label if not explicitly provided - const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel : - labelPrivate; + // use client id if not explicitly provided + const ClientId &ownerPrv = explicitOwnerPrivate.empty() ? cred.client : + explicitOwnerPrivate; if (m_accessControl.isSystemService(cred) && - ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0) + ownerPrv.compare(CLIENT_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; - const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel : - labelPublic; + const ClientId &ownerPub = explicitOwnerPublic.empty() ? cred.client : + explicitOwnerPublic; if (m_accessControl.isSystemService(cred) && - ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0) + ownerPub.compare(CLIENT_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; bool exportable = policyPrivate.extractable || policyPublic.extractable; @@ -1379,23 +1378,23 @@ int CKMLogic::createKeyPairHelper( DB::Crypto::Transaction transactionPub(&handlerPub.database); int retCode; - retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerLabelPrv); + retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerPrv); if (CKM_API_SUCCESS != retCode) return retCode; - retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerLabelPub); + retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerPub); if (CKM_API_SUCCESS != retCode) return retCode; // save the data - DB::Row rowPrv(std::move(keys.first), namePrivate, ownerLabelPrv, + DB::Row rowPrv(std::move(keys.first), namePrivate, ownerPrv, static_cast(policyPrivate.extractable)); handlerPriv.crypto.encryptRow(rowPrv); handlerPriv.database.saveRow(rowPrv); - DB::Row rowPub(std::move(keys.second), namePublic, ownerLabelPub, + DB::Row rowPub(std::move(keys.second), namePublic, ownerPub, static_cast(policyPublic.extractable)); handlerPub.crypto.encryptRow(rowPub); handlerPub.database.saveRow(rowPub); @@ -1410,9 +1409,9 @@ RawBuffer CKMLogic::createKeyPair( int commandId, const CryptoAlgorithmSerializable &keyGenParams, const Name &namePrivate, - const Label &labelPrivate, + const ClientId &explicitOwnerPrivate, const Name &namePublic, - const Label &labelPublic, + const ClientId &explicitOwnerPublic, const PolicySerializable &policyPrivate, const PolicySerializable &policyPublic) { @@ -1423,9 +1422,9 @@ RawBuffer CKMLogic::createKeyPair( cred, keyGenParams, namePrivate, - labelPrivate, + explicitOwnerPrivate, namePublic, - labelPublic, + explicitOwnerPublic, policyPrivate, policyPublic); } catch (const Exc::Exception &e) { @@ -1444,13 +1443,13 @@ RawBuffer CKMLogic::createKeyAES( int commandId, const int size, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PolicySerializable &policy) { int retCode = CKM_API_SUCCESS; try { - retCode = createKeyAESHelper(cred, size, name, label, policy); + retCode = createKeyAESHelper(cred, size, name, explicitOwner, policy); } catch (const Exc::Exception &e) { retCode = e.error(); } catch (std::invalid_argument &e) { @@ -1467,10 +1466,10 @@ RawBuffer CKMLogic::createKeyAES( int CKMLogic::readCertificateHelper( const Credentials &cred, - const LabelNameVector &labelNameVector, + const OwnerNameVector &ownerNameVector, CertificateImplVector &certVector) { - for (auto &i : labelNameVector) { + for (auto &i : ownerNameVector) { // certificates can't be protected with custom user password Crypto::GObjUPtr obj; int ec; @@ -1559,8 +1558,8 @@ int CKMLogic::getCertificateChainHelper( int CKMLogic::getCertificateChainHelper( const Credentials &cred, const CertificateImpl &cert, - const LabelNameVector &untrusted, - const LabelNameVector &trusted, + const OwnerNameVector &untrusted, + const OwnerNameVector &trusted, bool useTrustedSystemCertificates, RawBufferVector &chainRawVector) { @@ -1637,8 +1636,8 @@ RawBuffer CKMLogic::getCertificateChain( const Credentials &cred, int commandId, const RawBuffer &certificate, - const LabelNameVector &untrustedCertificates, - const LabelNameVector &trustedCertificates, + const OwnerNameVector &untrustedCertificates, + const OwnerNameVector &trustedCertificates, bool useTrustedSystemCertificates) { int retCode = CKM_API_ERROR_UNKNOWN; @@ -1673,7 +1672,7 @@ RawBuffer CKMLogic::createSignature( const Credentials &cred, int commandId, const Name &privateKeyName, - const Label &ownerLabel, + const ClientId &explicitOwner, const Password &password, // password for private_key const RawBuffer &message, const CryptoAlgorithm &cryptoAlg) @@ -1685,7 +1684,7 @@ RawBuffer CKMLogic::createSignature( try { Crypto::GObjUPtr obj; retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName, - ownerLabel, password, obj); + explicitOwner, password, obj); if (retCode == CKM_API_SUCCESS) signature = obj->sign(cryptoAlg, message); @@ -1711,7 +1710,7 @@ RawBuffer CKMLogic::verifySignature( const Credentials &cred, int commandId, const Name &publicKeyOrCertName, - const Label &ownerLabel, + const ClientId &explicitOwner, const Password &password, // password for public_key (optional) const RawBuffer &message, const RawBuffer &signature, @@ -1725,11 +1724,11 @@ RawBuffer CKMLogic::verifySignature( // rather than private key from the same PKCS. Crypto::GObjUPtr obj; retCode = readDataHelper(false, cred, DataType::CERTIFICATE, - publicKeyOrCertName, ownerLabel, password, obj); + publicKeyOrCertName, explicitOwner, password, obj); if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN) retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, - publicKeyOrCertName, ownerLabel, password, obj); + publicKeyOrCertName, explicitOwner, password, obj); if (retCode == CKM_API_SUCCESS) retCode = obj->verify(params, message, signature); @@ -1750,46 +1749,46 @@ RawBuffer CKMLogic::verifySignature( int CKMLogic::setPermissionHelper( const Credentials &cred, // who's the client const Name &name, - const Label &label, // who's the owner - const Label &accessorLabel, // who will get the access + const ClientId &explicitOwner, // who's the owner + const ClientId &accessor, // who will get the access const PermissionMask permissionMask) { - auto &handler = selectDatabase(cred, label); + auto &handler = selectDatabase(cred, explicitOwner); // we don't know the client - if (cred.smackLabel.empty() || !isLabelValid(cred.smackLabel)) + if (cred.client.empty() || !isClientValid(cred.client)) return CKM_API_ERROR_INPUT_PARAM; - // use client label if not explicitly provided - const Label &ownerLabel = label.empty() ? cred.smackLabel : label; + // use client id if not explicitly provided + const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; - // verify name and label are correct - if (!isNameValid(name) || !isLabelValid(ownerLabel) || - !isLabelValid(accessorLabel)) + // verify name and owner are correct + if (!isNameValid(name) || !isClientValid(owner) || + !isClientValid(accessor)) return CKM_API_ERROR_INPUT_PARAM; // currently we don't support modification of owner's permissions to his own rows - if (ownerLabel == accessorLabel) + if (owner == accessor) return CKM_API_ERROR_INPUT_PARAM; // system database does not support write/remove permissions - if ((0 == ownerLabel.compare(OWNER_ID_SYSTEM)) && + if ((0 == owner.compare(CLIENT_ID_SYSTEM)) && (permissionMask & Permission::REMOVE)) return CKM_API_ERROR_INPUT_PARAM; // can the client modify permissions to owner's row? - int retCode = m_accessControl.canModify(cred, ownerLabel); + int retCode = m_accessControl.canModify(cred, owner); if (retCode != CKM_API_SUCCESS) return retCode; DB::Crypto::Transaction transaction(&handler.database); - if (!handler.database.isNameLabelPresent(name, ownerLabel)) + if (!handler.database.isNameOwnerPresent(name, owner)) return CKM_API_ERROR_DB_ALIAS_UNKNOWN; - // set permissions to the row owned by ownerLabel for accessorLabel - handler.database.setPermission(name, ownerLabel, accessorLabel, permissionMask); + // set permissions to the row owned by owner for accessor + handler.database.setPermission(name, owner, accessor, permissionMask); transaction.commit(); return CKM_API_SUCCESS; @@ -1800,14 +1799,14 @@ RawBuffer CKMLogic::setPermission( const int command, const int msgID, const Name &name, - const Label &label, - const Label &accessorLabel, + const ClientId &explicitOwner, + const ClientId &accessor, const PermissionMask permissionMask) { int retCode; try { - retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask); + retCode = setPermissionHelper(cred, name, explicitOwner, accessor, permissionMask); } catch (const Exc::Exception &e) { retCode = e.error(); } catch (const CKM::Exception &e) { @@ -1818,20 +1817,20 @@ RawBuffer CKMLogic::setPermission( return MessageBuffer::Serialize(command, msgID, retCode).Pop(); } -int CKMLogic::loadAppKey(UserData &handle, const Label &appLabel) +int CKMLogic::loadAppKey(UserData &handle, const ClientId &owner) { - if (!handle.crypto.haveKey(appLabel)) { + if (!handle.crypto.haveKey(owner)) { RawBuffer key; - auto key_optional = handle.database.getKey(appLabel); + auto key_optional = handle.database.getKey(owner); if (!key_optional) { - LogError("No key for given label in database"); + LogError("No key for given owner in database"); return CKM_API_ERROR_DB_ERROR; } key = *key_optional; key = handle.keyProvider.getPureDEK(key); - handle.crypto.pushKey(appLabel, key); + handle.crypto.pushKey(owner, key); } return CKM_API_SUCCESS; diff --git a/src/manager/service/ckm-logic.h b/src/manager/service/ckm-logic.h index b1ab091..95048cb 100644 --- a/src/manager/service/ckm-logic.h +++ b/src/manager/service/ckm-logic.h @@ -74,13 +74,13 @@ public: const Password &newPassword); RawBuffer removeApplicationData( - const Label &smackLabel); + const ClientId &owner); RawBuffer saveData( const Credentials &cred, int commandId, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Crypto::Data &data, const PolicySerializable &policy); @@ -88,7 +88,7 @@ public: const Credentials &cred, int commandId, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PKCS12Serializable &pkcs, const PolicySerializable &keyPolicy, const PolicySerializable &certPolicy); @@ -97,21 +97,21 @@ public: const Credentials &cred, int commandId, const Name &name, - const Label &label); + const ClientId &explicitOwner); RawBuffer getData( const Credentials &cred, int commandId, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password); RawBuffer getPKCS12( const Credentials &cred, int commandId, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &keyPassword, const Password &certPassword); @@ -125,9 +125,9 @@ public: int commandId, const CryptoAlgorithmSerializable &keyGenParams, const Name &namePrivate, - const Label &labelPrivate, + const ClientId &explicitOwnerPrivate, const Name &namePublic, - const Label &labelPublic, + const ClientId &explicitOwnerPublic, const PolicySerializable &policyPrivate, const PolicySerializable &policyPublic); @@ -136,7 +136,7 @@ public: int commandId, const int size, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PolicySerializable &policy); RawBuffer getCertificateChain( @@ -151,15 +151,15 @@ public: const Credentials &cred, int commandId, const RawBuffer &certificate, - const LabelNameVector &untrustedCertificates, - const LabelNameVector &trustedCertificates, + const OwnerNameVector &untrustedCertificates, + const OwnerNameVector &trustedCertificates, bool useTrustedSystemCertificates); RawBuffer createSignature( const Credentials &cred, int commandId, const Name &privateKeyName, - const Label &ownerLabel, + const ClientId &explicitOwner, const Password &password, // password for private_key const RawBuffer &message, const CryptoAlgorithm &cryptoAlgorithm); @@ -168,7 +168,7 @@ public: const Credentials &cred, int commandId, const Name &publicKeyOrCertName, - const Label &label, + const ClientId &explicitOwner, const Password &password, // password for public_key (optional) const RawBuffer &message, const RawBuffer &signature, @@ -181,28 +181,28 @@ public: const int command, const int msgID, const Name &name, - const Label &label, - const Label &accessor_label, + const ClientId &explicitOwner, + const ClientId &accessor, const PermissionMask permissionMask); int setPermissionHelper( const Credentials &cred, const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, + const ClientId &explicitOwner, + const ClientId &accessor, const PermissionMask permissionMask); int verifyAndSaveDataHelper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Crypto::Data &data, const PolicySerializable &policy); int getKeyForService( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &pass, Crypto::GObjShPtr &key); @@ -215,10 +215,10 @@ public: int unlockSystemDB(); private: - // select private/system database depending on asking uid and owner label. - // output: database handler and effective label - UserData &selectDatabase(const Credentials &incoming_cred, - const Label &incoming_label); + // select private/system database depending on asking uid and owner id. + // output: database handler for effective owner + UserData &selectDatabase(const Credentials &cred, + const ClientId &explicitOwner); int unlockDatabase(uid_t user, const Password &password); @@ -241,19 +241,19 @@ private: const Credentials &cred, UserData &handler, const Name &name, - const Label &label); + const ClientId &owner); int saveDataHelper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Crypto::Data &data, const PolicySerializable &policy); int saveDataHelper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PKCS12Serializable &pkcs, const PolicySerializable &keyPolicy, const PolicySerializable &certPolicy); @@ -261,14 +261,14 @@ private: DB::Row createEncryptedRow( CryptoLogic &crypto, const Name &name, - const Label &label, + const ClientId &owner, const Crypto::Data &data, const Policy &policy) const; int getPKCS12Helper( const Credentials &cred, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &keyPassword, const Password &certPassword, KeyShPtr &privKey, @@ -278,7 +278,7 @@ private: int extractPKCS12Data( CryptoLogic &crypto, const Name &name, - const Label &ownerLabel, + const ClientId &owner, const PKCS12Serializable &pkcs, const PolicySerializable &keyPolicy, const PolicySerializable &certPolicy, @@ -287,26 +287,25 @@ private: int removeDataHelper( const Credentials &cred, const Name &name, - const Label &ownerLabel); + const ClientId &explicitOwner); int readSingleRow( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType dataType, DB::Crypto &database, DB::Row &row); int readMultiRow(const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType dataType, DB::Crypto &database, DB::RowVector &output); int checkDataPermissionsHelper( - const Credentials &cred, + const Credentials &accessorCred, const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, + const ClientId &owner, const DB::Row &row, bool exportFlag, DB::Crypto &database); @@ -321,7 +320,7 @@ private: const Credentials &cred, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password, Crypto::GObjUPtr &obj); @@ -330,7 +329,7 @@ private: const Credentials &cred, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password, Crypto::GObjUPtr &obj, DataType &objDataType); @@ -340,7 +339,7 @@ private: const Credentials &cred, DataType dataType, const Name &name, - const Label &label, + const ClientId &explicitOwner, const Password &password, Crypto::GObjUPtrVector &objs); @@ -348,22 +347,22 @@ private: const Credentials &cred, const int size, const Name &name, - const Label &label, + const ClientId &explicitOwner, const PolicySerializable &policy); int createKeyPairHelper( const Credentials &cred, const CryptoAlgorithmSerializable &keyGenParams, const Name &namePrivate, - const Label &labelPrivate, + const ClientId &explicitOwnerPrivate, const Name &namePublic, - const Label &labelPublic, + const ClientId &explicitOwnerPublic, const PolicySerializable &policyPrivate, const PolicySerializable &policyPublic); int readCertificateHelper( const Credentials &cred, - const LabelNameVector &labelNameVector, + const OwnerNameVector &ownerNameVector, CertificateImplVector &certVector); int getCertificateChainHelper( @@ -376,15 +375,15 @@ private: int getCertificateChainHelper( const Credentials &cred, const CertificateImpl &cert, - const LabelNameVector &untrusted, - const LabelNameVector &trusted, + const OwnerNameVector &untrusted, + const OwnerNameVector &trusted, bool useTrustedSystemCertificates, RawBufferVector &chainRawVector); int getDataListHelper( const Credentials &cred, const DataType dataType, - LabelNameVector &labelNameVector); + OwnerNameVector &ownerNameVector); int changeUserPasswordHelper(uid_t user, const Password &oldPassword, @@ -392,7 +391,7 @@ private: int resetUserPasswordHelper(uid_t user, const Password &newPassword); - int loadAppKey(UserData &handle, const Label &appLabel); + int loadAppKey(UserData &handle, const ClientId &owner); void migrateSecureStorageData(bool isAdminUser); diff --git a/src/manager/service/ckm-service.cpp b/src/manager/service/ckm-service.cpp index 2fd0e2e..127e0a8 100644 --- a/src/manager/service/ckm-service.cpp +++ b/src/manager/service/ckm-service.cpp @@ -120,7 +120,7 @@ RawBuffer CKMService::ProcessControl(MessageBuffer &buffer, bool allowed) uid_t user = 0; ControlCommand cc; Password newPass, oldPass; - Label smackLabel; + ClientId explicitOwner; buffer.Deserialize(command); @@ -167,9 +167,9 @@ RawBuffer CKMService::ProcessControl(MessageBuffer &buffer, bool allowed) break; case ControlCommand::REMOVE_APP_DATA: - buffer.Deserialize(smackLabel); + buffer.Deserialize(explicitOwner); logicFunc = [&]() { - return m_logic->removeApplicationData(smackLabel); + return m_logic->removeApplicationData(explicitOwner); }; break; @@ -181,21 +181,20 @@ RawBuffer CKMService::ProcessControl(MessageBuffer &buffer, bool allowed) case ControlCommand::SET_PERMISSION: { Name name; - Label label; - Label accessorLabel; + ClientId accessor; PermissionMask permissionMask = 0; - buffer.Deserialize(user, name, label, accessorLabel, permissionMask); + buffer.Deserialize(user, name, explicitOwner, accessor, permissionMask); - Credentials cred(user, label); - logicFunc = [&, name, label, accessorLabel, permissionMask, cred]() { + Credentials cred(user, explicitOwner); + logicFunc = [&, name, explicitOwner, accessor, permissionMask, cred]() { return m_logic->setPermission( cred, command, 0, // dummy name, - label, - accessorLabel, + explicitOwner, + accessor, permissionMask); }; break; @@ -219,7 +218,7 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) int msgID = 0; int tmpDataType = 0; Name name; - Label label, accessorLabel; + ClientId explicitOwner, accessor; buffer.Deserialize(command); buffer.Deserialize(msgID); @@ -238,12 +237,12 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) case LogicCommand::SAVE: { RawBuffer rawData; PolicySerializable policy; - buffer.Deserialize(tmpDataType, name, label, rawData, policy); + buffer.Deserialize(tmpDataType, name, explicitOwner, rawData, policy); return m_logic->saveData( cred, msgID, name, - label, + explicitOwner, Crypto::Data(DataType(tmpDataType), std::move(rawData)), policy); } @@ -252,35 +251,35 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) RawBuffer rawData; PKCS12Serializable pkcs; PolicySerializable keyPolicy, certPolicy; - buffer.Deserialize(name, label, pkcs, keyPolicy, certPolicy); + buffer.Deserialize(name, explicitOwner, pkcs, keyPolicy, certPolicy); return m_logic->savePKCS12( cred, msgID, name, - label, + explicitOwner, pkcs, keyPolicy, certPolicy); } case LogicCommand::REMOVE: { - buffer.Deserialize(name, label); + buffer.Deserialize(name, explicitOwner); return m_logic->removeData( cred, msgID, name, - label); + explicitOwner); } case LogicCommand::GET: { Password password; - buffer.Deserialize(tmpDataType, name, label, password); + buffer.Deserialize(tmpDataType, name, explicitOwner, password); return m_logic->getData( cred, msgID, DataType(tmpDataType), name, - label, + explicitOwner, password); } @@ -289,14 +288,14 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) Password passCert; buffer.Deserialize( name, - label, + explicitOwner, passKey, passCert); return m_logic->getPKCS12( cred, msgID, name, - label, + explicitOwner, passKey, passCert); } @@ -312,45 +311,45 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) case LogicCommand::CREATE_KEY_AES: { int size = 0; Name keyName; - Label keyLabel; + ClientId keyExplicitOwner; PolicySerializable policyKey; buffer.Deserialize( size, policyKey, keyName, - keyLabel); + keyExplicitOwner); return m_logic->createKeyAES( cred, msgID, size, keyName, - keyLabel, + keyExplicitOwner, policyKey); } case LogicCommand::CREATE_KEY_PAIR: { CryptoAlgorithmSerializable keyGenAlgorithm; Name privateKeyName; - Label privateKeyLabel; + ClientId explicitOwnerPrivate; Name publicKeyName; - Label publicKeyLabel; + ClientId explicitOwnerPublic; PolicySerializable policyPrivateKey; PolicySerializable policyPublicKey; buffer.Deserialize(keyGenAlgorithm, policyPrivateKey, policyPublicKey, privateKeyName, - privateKeyLabel, + explicitOwnerPrivate, publicKeyName, - publicKeyLabel); + explicitOwnerPublic); return m_logic->createKeyPair( cred, msgID, keyGenAlgorithm, privateKeyName, - privateKeyLabel, + explicitOwnerPrivate, publicKeyName, - publicKeyLabel, + explicitOwnerPublic, policyPrivateKey, policyPublicKey); } @@ -372,8 +371,8 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) case LogicCommand::GET_CHAIN_ALIAS: { RawBuffer certificate; - LabelNameVector untrustedVector; - LabelNameVector trustedVector; + OwnerNameVector untrustedVector; + OwnerNameVector trustedVector; bool systemCerts = false; buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts); return m_logic->getCertificateChain( @@ -390,13 +389,13 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) RawBuffer message; CryptoAlgorithmSerializable cAlgorithm; - buffer.Deserialize(name, label, password, message, cAlgorithm); + buffer.Deserialize(name, explicitOwner, password, message, cAlgorithm); return m_logic->createSignature( cred, msgID, name, - label, + explicitOwner, password, // password for private_key message, cAlgorithm); @@ -409,7 +408,7 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) CryptoAlgorithmSerializable cAlg; buffer.Deserialize(name, - label, + explicitOwner, password, message, signature, @@ -419,7 +418,7 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) cred, msgID, name, - label, + explicitOwner, password, // password for public_key (optional) message, signature, @@ -428,14 +427,14 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) case LogicCommand::SET_PERMISSION: { PermissionMask permissionMask = 0; - buffer.Deserialize(name, label, accessorLabel, permissionMask); + buffer.Deserialize(name, explicitOwner, accessor, permissionMask); return m_logic->setPermission( cred, command, msgID, name, - label, - accessorLabel, + explicitOwner, + accessor, permissionMask); } @@ -449,7 +448,7 @@ void CKMService::ProcessMessage(MsgKeyRequest msg) Crypto::GObjShPtr key; int ret = m_logic->getKeyForService(msg.cred, msg.name, - msg.label, + msg.explicitOwner, msg.password, key); MsgKeyResponse kResp(msg.id, key, ret); diff --git a/src/manager/service/crypto-logic.cpp b/src/manager/service/crypto-logic.cpp index 3cbfedb..d15a37c 100644 --- a/src/manager/service/crypto-logic.cpp +++ b/src/manager/service/crypto-logic.cpp @@ -67,30 +67,30 @@ CryptoLogic &CryptoLogic::operator=(CryptoLogic &&second) return *this; } -bool CryptoLogic::haveKey(const Label &smackLabel) +bool CryptoLogic::haveKey(const ClientId &client) { - return (m_keyMap.count(smackLabel) > 0); + return (m_keyMap.count(client) > 0); } -void CryptoLogic::pushKey(const Label &smackLabel, +void CryptoLogic::pushKey(const ClientId &client, const RawBuffer &applicationKey) { - if (smackLabel.length() == 0) - ThrowErr(Exc::InternalError, "Empty smack label."); + if (client.empty()) + ThrowErr(Exc::InternalError, "Empty client id."); if (applicationKey.size() == 0) ThrowErr(Exc::InternalError, "Empty application key."); - if (haveKey(smackLabel)) - ThrowErr(Exc::InternalError, "Application key for ", smackLabel, - "label already exists."); + if (haveKey(client)) + ThrowErr(Exc::InternalError, "Application key for ", client, + " already exists."); - m_keyMap[smackLabel] = applicationKey; + m_keyMap[client] = applicationKey; } -void CryptoLogic::removeKey(const Label &smackLabel) +void CryptoLogic::removeKey(const ClientId &client) { - m_keyMap.erase(smackLabel); + m_keyMap.erase(client); } RawBuffer CryptoLogic::passwordToKey( @@ -134,14 +134,14 @@ void CryptoLogic::encryptRow(DB::Row &row) if (crow.dataSize <= 0) ThrowErr(Exc::InternalError, "Invalid dataSize."); - if (!haveKey(row.ownerLabel)) + if (!haveKey(row.owner)) ThrowErr(Exc::InternalError, "Missing application key for ", - row.ownerLabel, " label."); + row.owner, " client."); if (crow.iv.empty()) crow.iv = generateRandIV(); - key = m_keyMap[row.ownerLabel]; + key = m_keyMap[row.owner]; CLEAR_FLAGS(crow.encryptionScheme); SET_FLAG(ENCR_APPKEY, crow.encryptionScheme); @@ -186,11 +186,11 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row) ThrowErr(Exc::AuthenticationFailed, "DB row is not password protected, but given password is not empty."); - if (GET_FLAG(ENCR_APPKEY, row.encryptionScheme) && !haveKey(row.ownerLabel)) + if (GET_FLAG(ENCR_APPKEY, row.encryptionScheme) && !haveKey(row.owner)) ThrowErr(Exc::AuthenticationFailed, "Missing application key for ", - row.ownerLabel, - " label."); + row.owner, + " client."); decBase64(crow.iv); @@ -200,7 +200,7 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row) try { if (GET_ENCRYPTION_VERSION(crow.encryptionScheme) == ENCRYPTION_V2) { if (GET_FLAG(ENCR_APPKEY, crow.encryptionScheme)) { - key = m_keyMap[crow.ownerLabel]; + key = m_keyMap[crow.owner]; crow.data = Crypto::SW::Internals::decryptDataAesGcm(key, crow.data, crow.iv, crow.tag); } @@ -212,7 +212,7 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row) } if (GET_FLAG(ENCR_APPKEY, crow.encryptionScheme)) { - key = m_keyMap[crow.ownerLabel]; + key = m_keyMap[crow.owner]; crow.data = Crypto::SW::Internals::decryptDataAesGcm(key, crow.data, crow.iv, crow.tag); } diff --git a/src/manager/service/crypto-logic.h b/src/manager/service/crypto-logic.h index fab4cf9..154b1b2 100644 --- a/src/manager/service/crypto-logic.h +++ b/src/manager/service/crypto-logic.h @@ -43,10 +43,10 @@ public: static int getSchemeVersion(int encryptionScheme); - bool haveKey(const Label &smackLabel); - void pushKey(const Label &smackLabel, + bool haveKey(const ClientId &client); + void pushKey(const ClientId &client, const RawBuffer &applicationKey); - void removeKey(const Label &smackLabel); + void removeKey(const ClientId &client); /* * v1 encryption. @@ -101,7 +101,7 @@ private: return encryptionScheme >> ENCR_ORDER_OFFSET; } - std::map m_keyMap; + std::map m_keyMap; RawBuffer generateRandIV() const; RawBuffer passwordToKey(const Password &password, diff --git a/src/manager/service/crypto-request.h b/src/manager/service/crypto-request.h index 83ccab5..467c9c7 100644 --- a/src/manager/service/crypto-request.h +++ b/src/manager/service/crypto-request.h @@ -34,7 +34,7 @@ struct CryptoRequest { int msgId; CryptoAlgorithmSerializable cas; Name name; - Label label; + ClientId explicitOwner; Password password; RawBuffer input; }; diff --git a/src/manager/service/db-crypto.cpp b/src/manager/service/db-crypto.cpp index 9395386..2bc2a92 100644 --- a/src/manager/service/db-crypto.cpp +++ b/src/manager/service/db-crypto.cpp @@ -81,7 +81,7 @@ const char *DB_CMD_NAME_COUNT_ROWS = const char *DB_CMD_NAME_DELETE = "DELETE FROM NAMES WHERE name=?101 AND label=?102;"; -const char *DB_CMD_NAME_DELETE_BY_LABEL = +const char *DB_CMD_NAME_DELETE_BY_OWNER = "DELETE FROM NAMES WHERE label=?102;"; @@ -107,7 +107,7 @@ const char *DB_CMD_OBJECT_UPDATE = " WHERE idx IN (SELECT idx FROM NAMES WHERE name=?101 and label=?102)" " AND dataType = ?002;"; -const char *DB_CMD_OBJECT_SELECT_BY_NAME_AND_LABEL = +const char *DB_CMD_OBJECT_SELECT_BY_NAME_AND_OWNER = "SELECT * FROM [join_name_object_tables] " " WHERE (dataType BETWEEN ?001 AND ?002) " " AND name=?101 and label=?102;"; @@ -338,7 +338,7 @@ void Crypto::resetDB() transaction.commit(); } -bool Crypto::isNameLabelPresent(const Name &name, const Label &owner) const +bool Crypto::isNameOwnerPresent(const Name &name, const ClientId &owner) const { try { NameTable nameTable(this->m_connection); @@ -350,10 +350,10 @@ bool Crypto::isNameLabelPresent(const Name &name, const Label &owner) const } ThrowErr(Exc::DatabaseFailed, - "Couldn't check if name and label pair is present"); + "Couldn't check if name and owner pair is present"); } -void Crypto::saveRows(const Name &name, const Label &owner, +void Crypto::saveRows(const Name &name, const ClientId &owner, const RowVector &rows) { try { @@ -389,11 +389,11 @@ void Crypto::saveRow(const Row &row) NameTable nameTable(this->m_connection); ObjectTable objectTable(this->m_connection); PermissionTable permissionTable(this->m_connection); - nameTable.addRow(row.name, row.ownerLabel); + nameTable.addRow(row.name, row.owner); objectTable.addRow(row); permissionTable.setPermission(row.name, - row.ownerLabel, - row.ownerLabel, + row.owner, + row.owner, static_cast(DEFAULT_PERMISSIONS)); return; } catch (const SqlConnection::Exception::SyntaxError &) { @@ -423,14 +423,14 @@ void Crypto::updateRow(const Row &row) bool Crypto::deleteRow( const Name &name, - const Label &ownerLabel) + const ClientId &owner) { try { // transaction is present in the layer above NameTable nameTable(this->m_connection); - if (nameTable.isPresent(name, ownerLabel)) { - nameTable.deleteRow(name, ownerLabel); + if (nameTable.isPresent(name, owner)) { + nameTable.deleteRow(name, owner); return true; } @@ -442,7 +442,7 @@ bool Crypto::deleteRow( } ThrowErr(Exc::DatabaseFailed, - "Couldn't delete Row for name ", name, " using ownerLabel ", ownerLabel); + "Couldn't delete Row for name ", name, " using owner id ", owner); } Row Crypto::getRow( @@ -450,7 +450,7 @@ Row Crypto::getRow( { Row row; row.name = selectCommand->GetColumnString(0); - row.ownerLabel = selectCommand->GetColumnString(1); + row.owner = selectCommand->GetColumnString(1); row.exportable = selectCommand->GetColumnInteger(2); row.dataType = DataType(selectCommand->GetColumnInteger(3)); row.algorithmType = @@ -466,12 +466,12 @@ Row Crypto::getRow( PermissionMaskOptional Crypto::getPermissionRow( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel) const + const ClientId &owner, + const ClientId &accessor) const { try { PermissionTable permissionTable(this->m_connection); - return permissionTable.getPermissionRow(name, ownerLabel, accessorLabel); + return permissionTable.getPermissionRow(name, owner, accessor); } catch (const SqlConnection::Exception::InvalidColumn &) { LogError("Select statement invalid column error"); } catch (const SqlConnection::Exception::SyntaxError &) { @@ -485,27 +485,27 @@ PermissionMaskOptional Crypto::getPermissionRow( Crypto::RowOptional Crypto::getRow( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType type) { - return getRow(name, ownerLabel, type, type); + return getRow(name, owner, type, type); } Crypto::RowOptional Crypto::getRow( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType typeRangeStart, DataType typeRangeStop) { try { SqlConnection::DataCommandUniquePtr selectCommand = - m_connection->PrepareDataCommand(DB_CMD_OBJECT_SELECT_BY_NAME_AND_LABEL); + m_connection->PrepareDataCommand(DB_CMD_OBJECT_SELECT_BY_NAME_AND_OWNER); selectCommand->BindInteger(1, typeRangeStart); selectCommand->BindInteger(2, typeRangeStop); // name table reference selectCommand->BindString(101, name.c_str()); - selectCommand->BindString(102, ownerLabel.c_str()); + selectCommand->BindString(102, owner.c_str()); if (selectCommand->Step()) { // extract data @@ -528,34 +528,34 @@ Crypto::RowOptional Crypto::getRow( "Couldn't get row of type <", static_cast(typeRangeStart), ",", static_cast(typeRangeStop), ">", - " name ", name, " with owner label ", ownerLabel); + " name ", name, " with owner ", owner); } void Crypto::getRows( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType type, RowVector &output) { - getRows(name, ownerLabel, type, type, output); + getRows(name, owner, type, type, output); } void Crypto::getRows( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType typeRangeStart, DataType typeRangeStop, RowVector &output) { try { SqlConnection::DataCommandUniquePtr selectCommand = - m_connection->PrepareDataCommand(DB_CMD_OBJECT_SELECT_BY_NAME_AND_LABEL); + m_connection->PrepareDataCommand(DB_CMD_OBJECT_SELECT_BY_NAME_AND_OWNER); selectCommand->BindInteger(1, typeRangeStart); selectCommand->BindInteger(2, typeRangeStop); // name table reference selectCommand->BindString(101, name.c_str()); - selectCommand->BindString(102, ownerLabel.c_str()); + selectCommand->BindString(102, owner.c_str()); while (selectCommand->Step()) { // extract data @@ -575,20 +575,20 @@ void Crypto::getRows( "Couldn't get row of type <", static_cast(typeRangeStart), ",", static_cast(typeRangeStop), ">", - " name ", name, " with owner label ", ownerLabel); + " name ", name, " with owner label ", owner); } void Crypto::listNames( - const Label &smackLabel, - LabelNameVector &labelNameVector, + const ClientId &owner, + OwnerNameVector &ownerNameVector, DataType type) { - listNames(smackLabel, labelNameVector, type, type); + listNames(owner, ownerNameVector, type, type); } void Crypto::listNames( - const Label &smackLabel, - LabelNameVector &labelNameVector, + const ClientId &owner, + OwnerNameVector &ownerNameVector, DataType typeRangeStart, DataType typeRangeStop) { @@ -598,14 +598,14 @@ void Crypto::listNames( m_connection->PrepareDataCommand(DB_CMD_NAME_SELECT_BY_TYPE_AND_PERMISSION); selectCommand->BindInteger(1, static_cast(typeRangeStart)); selectCommand->BindInteger(2, static_cast(typeRangeStop)); - selectCommand->BindString(104, smackLabel.c_str()); + selectCommand->BindString(104, owner.c_str()); selectCommand->BindInteger(4, static_cast(Permission::READ | Permission::REMOVE)); while (selectCommand->Step()) { - Label ownerLabel = selectCommand->GetColumnString(0); - Name name = selectCommand->GetColumnString(1); - labelNameVector.push_back(std::make_pair(ownerLabel, name)); + ClientId itemOwner = selectCommand->GetColumnString(0); + Name itemName = selectCommand->GetColumnString(1); + ownerNameVector.push_back(std::make_pair(itemOwner, itemName)); } return; @@ -621,17 +621,17 @@ void Crypto::listNames( "Couldn't list names of type <", static_cast(typeRangeStart), ",", static_cast(typeRangeStop), ">", - " accessible to client label ", smackLabel); + " accessible to client ", owner); } void Crypto::saveKey( - const Label &label, + const ClientId &owner, const RawBuffer &key) { try { SqlConnection::DataCommandUniquePtr insertCommand = m_connection->PrepareDataCommand(DB_CMD_KEY_INSERT); - insertCommand->BindString(1, label.c_str()); + insertCommand->BindString(1, owner.c_str()); insertCommand->BindBlob(2, key); insertCommand->Step(); return; @@ -641,15 +641,15 @@ void Crypto::saveKey( LogError("Couldn't execute insert statement"); } - ThrowErr(Exc::DatabaseFailed, "Couldn't save key for label ", label); + ThrowErr(Exc::DatabaseFailed, "Couldn't save key for owner ", owner); } -Crypto::RawBufferOptional Crypto::getKey(const Label &label) +Crypto::RawBufferOptional Crypto::getKey(const ClientId &owner) { try { SqlConnection::DataCommandUniquePtr selectCommand = m_connection->PrepareDataCommand(DB_CMD_KEY_SELECT); - selectCommand->BindString(1, label.c_str()); + selectCommand->BindString(1, owner.c_str()); if (selectCommand->Step()) return RawBufferOptional(selectCommand->GetColumnBlob(0)); @@ -663,21 +663,21 @@ Crypto::RawBufferOptional Crypto::getKey(const Label &label) LogError("Couldn't execute insert statement"); } - ThrowErr(Exc::DatabaseFailed, "Couldn't get key for label ", label); + ThrowErr(Exc::DatabaseFailed, "Couldn't get key for owner ", owner); } -void Crypto::deleteKey(const Label &label) +void Crypto::deleteKey(const ClientId &owner) { try { Transaction transaction(this); SqlConnection::DataCommandUniquePtr deleteCommand = m_connection->PrepareDataCommand(DB_CMD_KEY_DELETE); - deleteCommand->BindString(1, label.c_str()); + deleteCommand->BindString(1, owner.c_str()); deleteCommand->Step(); NameTable nameTable(this->m_connection); - nameTable.deleteAllRows(label); + nameTable.deleteAllRows(owner); transaction.commit(); return; @@ -687,18 +687,18 @@ void Crypto::deleteKey(const Label &label) LogError("Couldn't execute insert statement"); } - ThrowErr(Exc::DatabaseFailed, "Couldn't delete key for label ", label); + ThrowErr(Exc::DatabaseFailed, "Couldn't delete key for owner ", owner); } void Crypto::setPermission( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, + const ClientId &owner, + const ClientId &accessor, const PermissionMask permissionMask) { try { PermissionTable permissionTable(this->m_connection); - permissionTable.setPermission(name, ownerLabel, accessorLabel, permissionMask); + permissionTable.setPermission(name, owner, accessor, permissionMask); return; } catch (const SqlConnection::Exception::SyntaxError &) { LogError("Couldn't prepare set statement"); @@ -745,45 +745,45 @@ bool Crypto::SchemaInfo::getVersionInfo(int &version) const void Crypto::PermissionTable::setPermission( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, + const ClientId &owner, + const ClientId &accessor, const PermissionMask permissionMask) { if (permissionMask == Permission::NONE) { // clear permissions SqlConnection::DataCommandUniquePtr deletePermissionCommand = m_connection->PrepareDataCommand(DB_CMD_PERMISSION_DELETE); - deletePermissionCommand->BindString(104, accessorLabel.c_str()); + deletePermissionCommand->BindString(104, accessor.c_str()); deletePermissionCommand->BindString(101, name.c_str()); - deletePermissionCommand->BindString(102, ownerLabel.c_str()); + deletePermissionCommand->BindString(102, owner.c_str()); deletePermissionCommand->Step(); } else { // add new permissions SqlConnection::DataCommandUniquePtr setPermissionCommand = m_connection->PrepareDataCommand(DB_CMD_PERMISSION_SET); - setPermissionCommand->BindString(104, accessorLabel.c_str()); + setPermissionCommand->BindString(104, accessor.c_str()); setPermissionCommand->BindInteger(105, static_cast(permissionMask)); setPermissionCommand->BindString(101, name.c_str()); - setPermissionCommand->BindString(102, ownerLabel.c_str()); + setPermissionCommand->BindString(102, owner.c_str()); setPermissionCommand->Step(); } } PermissionMaskOptional Crypto::PermissionTable::getPermissionRow( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel) const + const ClientId &owner, + const ClientId &accessor) const { SqlConnection::DataCommandUniquePtr selectCommand = m_connection->PrepareDataCommand(DB_CMD_PERMISSION_SELECT); - selectCommand->BindString(104, accessorLabel.c_str()); + selectCommand->BindString(104, accessor.c_str()); // name table reference selectCommand->BindString(101, name.c_str()); - selectCommand->BindString(102, ownerLabel.c_str()); + selectCommand->BindString(102, owner.c_str()); if (selectCommand->Step()) { - // there is entry for the pair + // there is entry for the pair return PermissionMaskOptional(PermissionMask(selectCommand->GetColumnInteger( 0))); } @@ -793,35 +793,35 @@ PermissionMaskOptional Crypto::PermissionTable::getPermissionRow( void Crypto::NameTable::addRow( const Name &name, - const Label &ownerLabel) + const ClientId &owner) { // insert NAMES item SqlConnection::DataCommandUniquePtr insertNameCommand = m_connection->PrepareDataCommand(DB_CMD_NAME_INSERT); insertNameCommand->BindString(101, name.c_str()); - insertNameCommand->BindString(102, ownerLabel.c_str()); + insertNameCommand->BindString(102, owner.c_str()); insertNameCommand->Step(); } void Crypto::NameTable::deleteRow( const Name &name, - const Label &ownerLabel) + const ClientId &ownerOwner) { SqlConnection::DataCommandUniquePtr deleteCommand = m_connection->PrepareDataCommand(DB_CMD_NAME_DELETE); deleteCommand->BindString(101, name.c_str()); - deleteCommand->BindString(102, ownerLabel.c_str()); + deleteCommand->BindString(102, ownerOwner.c_str()); // Step() result code does not provide information whether // anything was removed. deleteCommand->Step(); } -void Crypto::NameTable::deleteAllRows(const Label &ownerLabel) +void Crypto::NameTable::deleteAllRows(const ClientId &owner) { SqlConnection::DataCommandUniquePtr deleteData = - m_connection->PrepareDataCommand(DB_CMD_NAME_DELETE_BY_LABEL); - deleteData->BindString(102, ownerLabel.c_str()); + m_connection->PrepareDataCommand(DB_CMD_NAME_DELETE_BY_OWNER); + deleteData->BindString(102, owner.c_str()); // Step() result code does not provide information whether // anything was removed. @@ -829,16 +829,16 @@ void Crypto::NameTable::deleteAllRows(const Label &ownerLabel) } bool Crypto::NameTable::isPresent(const Name &name, - const Label &ownerLabel) const + const ClientId &owner) const { SqlConnection::DataCommandUniquePtr checkCmd = m_connection->PrepareDataCommand(DB_CMD_NAME_COUNT_ROWS); checkCmd->BindString(101, name.c_str()); - checkCmd->BindString(102, ownerLabel.c_str()); + checkCmd->BindString(102, owner.c_str()); if (checkCmd->Step()) { int element_count = checkCmd->GetColumnInteger(0); - LogDebug("Item name: " << name << " ownerLabel: " << ownerLabel << + LogDebug("Item name: " << name << " owner: " << owner << " hit count: " << element_count); if (element_count > 0) @@ -864,7 +864,7 @@ void Crypto::ObjectTable::addRow(const Row &row) // name table reference insertObjectCommand->BindString(101, row.name.c_str()); - insertObjectCommand->BindString(102, row.ownerLabel.c_str()); + insertObjectCommand->BindString(102, row.owner.c_str()); insertObjectCommand->Step(); } @@ -883,7 +883,7 @@ void Crypto::ObjectTable::updateRow(const Row &row) // name table reference updateObjectCommand->BindString(101, row.name.c_str()); - updateObjectCommand->BindString(102, row.ownerLabel.c_str()); + updateObjectCommand->BindString(102, row.owner.c_str()); updateObjectCommand->Step(); } diff --git a/src/manager/service/db-crypto.h b/src/manager/service/db-crypto.h index f4021c3..65ef3a3 100644 --- a/src/manager/service/db-crypto.h +++ b/src/manager/service/db-crypto.h @@ -60,71 +60,71 @@ public: void saveRows( const Name &name, - const Label &owner, + const ClientId &owner, const RowVector &rows); void updateRow( const Row &row); - bool isNameLabelPresent( + bool isNameOwnerPresent( const Name &name, - const Label &owner) const; + const ClientId &owner) const; RowOptional getRow( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType type); RowOptional getRow( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType typeRangeStart, DataType typeRangeStop); void getRows( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType type, RowVector &output); void getRows( const Name &name, - const Label &ownerLabel, + const ClientId &owner, DataType typeRangeStart, DataType typeRangeStop, RowVector &output); void listNames( - const Label &smackLabel, - LabelNameVector &labelNameVector, + const ClientId &owner, + OwnerNameVector &ownerNameVector, DataType type); void listNames( - const Label &smackLabel, - LabelNameVector &labelNameVector, + const ClientId &owner, + OwnerNameVector &ownerNameVector, DataType typeRangeStart, DataType typeRangeStop); bool deleteRow( const Name &name, - const Label &ownerLabel); + const ClientId &owner); // keys - void saveKey(const Label &label, const RawBuffer &key); - RawBufferOptional getKey(const Label &label); - void deleteKey(const Label &label); + void saveKey(const ClientId &owner, const RawBuffer &key); + RawBufferOptional getKey(const ClientId &owner); + void deleteKey(const ClientId &owner); // permissions void setPermission( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, + const ClientId &owner, + const ClientId &accessor, const PermissionMask permissionMask); PermissionMaskOptional getPermissionRow( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel) const; + const ClientId &owner, + const ClientId &accessor) const; // transactions int beginTransaction(); @@ -247,18 +247,18 @@ public: void addRow( const Name &name, - const Label &ownerLabel); + const ClientId &owner); void deleteRow( const Name &name, - const Label &ownerLabel); + const ClientId &owner); void deleteAllRows( - const Label &ownerLabel); + const ClientId &owner); bool isPresent( const Name &name, - const Label &ownerLabel) const; + const ClientId &owner) const; private: SqlConnection *m_connection; @@ -284,14 +284,14 @@ public: void setPermission( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, + const ClientId &owner, + const ClientId &accessor, const PermissionMask permissionMask); PermissionMaskOptional getPermissionRow( const Name &name, - const Label &ownerLabel, - const Label &accessorLabel) const; + const ClientId &owner, + const ClientId &accessor) const; private: SqlConnection *m_connection; diff --git a/src/manager/service/db-row.h b/src/manager/service/db-row.h index 0f171ba..c709ed2 100644 --- a/src/manager/service/db-row.h +++ b/src/manager/service/db-row.h @@ -37,17 +37,17 @@ struct Row : public Token { encryptionScheme(0), dataSize(0) {} - Row(Token token, const Name &pName, const Label &pLabel, int pExportable) : + Row(Token token, const Name &pName, const ClientId &pOwner, int pExportable) : Token(std::move(token)), name(pName), - ownerLabel(pLabel), + owner(pOwner), exportable(pExportable), algorithmType(DBCMAlgType::NONE), encryptionScheme(0), dataSize(data.size()) {} Name name; - Label ownerLabel; + ClientId owner; int exportable; DBCMAlgType algorithmType; // Algorithm type used for row data encryption int encryptionScheme; // for example: (ENCR_BASE64 | ENCR_PASSWORD) diff --git a/src/manager/service/encryption-service.cpp b/src/manager/service/encryption-service.cpp index e403584..5289f83 100644 --- a/src/manager/service/encryption-service.cpp +++ b/src/manager/service/encryption-service.cpp @@ -57,8 +57,8 @@ void EncryptionService::RespondToClient(const CryptoRequest &request, void EncryptionService::RequestKey(const CryptoRequest &request) { - MsgKeyRequest kReq(request.msgId, request.cred, request.name, request.label, - request.password); + MsgKeyRequest kReq(request.msgId, request.cred, request.name, + request.explicitOwner, request.password); if (!m_commMgr->SendMessage(kReq)) throw std::runtime_error("No listener found");// TODO @@ -127,7 +127,7 @@ void EncryptionService::ProcessEncryption(const ConnectionID &conn, int tmpCmd = 0; CryptoRequest req; - buffer.Deserialize(tmpCmd, req.msgId, req.cas, req.name, req.label, + buffer.Deserialize(tmpCmd, req.msgId, req.cas, req.name, req.explicitOwner, req.password, req.input); req.command = static_cast(tmpCmd); diff --git a/src/manager/service/file-system.cpp b/src/manager/service/file-system.cpp index 2da7703..79f8081 100644 --- a/src/manager/service/file-system.cpp +++ b/src/manager/service/file-system.cpp @@ -143,11 +143,11 @@ void FileSystem::saveDBDEK(const RawBuffer &buffer) const saveFile(getDBDEKPath(), buffer); } -void FileSystem::addRemovedApp(const std::string &smackLabel) const +void FileSystem::addRemovedApp(const ClientId &app) const { std::ofstream outfile; outfile.open(getRemovedAppsPath(), std::ios_base::app); - outfile << smackLabel << std::endl; + outfile << app << std::endl; outfile.close(); if (outfile.fail()) { @@ -157,10 +157,10 @@ void FileSystem::addRemovedApp(const std::string &smackLabel) const } } -AppLabelVector FileSystem::clearRemovedsApps() const +ClientIdVector FileSystem::clearRemovedsApps() const { // read the contents - AppLabelVector removedApps; + ClientIdVector removedApps; std::string line; std::ifstream removedAppsFile(getRemovedAppsPath()); diff --git a/src/manager/service/file-system.h b/src/manager/service/file-system.h index 2ed9e31..287fbf6 100644 --- a/src/manager/service/file-system.h +++ b/src/manager/service/file-system.h @@ -27,7 +27,7 @@ namespace CKM { -typedef std::vector AppLabelVector; +typedef std::vector ClientIdVector; typedef std::vector UidVector; class FileSystem { @@ -47,8 +47,8 @@ public: // Remove all ckm data related to user int removeUserData() const; - void addRemovedApp(const std::string &smackLabel) const; - AppLabelVector clearRemovedsApps() const; + void addRemovedApp(const ClientId &app) const; + ClientIdVector clearRemovedsApps() const; static int init(); static UidVector getUIDsFromDBFile(); diff --git a/src/manager/service/key-provider.cpp b/src/manager/service/key-provider.cpp index 98dedd4..95c68af 100644 --- a/src/manager/service/key-provider.cpp +++ b/src/manager/service/key-provider.cpp @@ -67,12 +67,12 @@ void WrappedKeyAndInfoContainer::setKeyInfoKeyLength(const unsigned int length) wrappedKeyAndInfo->keyInfo.keyLength = length; } -void WrappedKeyAndInfoContainer::setKeyInfoLabel(const std::string label) +void WrappedKeyAndInfoContainer::setKeyInfoClient(const std::string resized_client) { strncpy( - wrappedKeyAndInfo->keyInfo.label, - label.c_str(), - MAX_LABEL_SIZE-1); + wrappedKeyAndInfo->keyInfo.client, + resized_client.c_str(), + MAX_CLIENT_ID_SIZE-1); } void WrappedKeyAndInfoContainer::setKeyInfoSalt(const unsigned char *salt, @@ -165,7 +165,7 @@ KeyProvider::KeyProvider( uint8_t PKEK1[MAX_KEY_SIZE]; concat_user_pass = concat_password_user( - wkmcDKEK.getWrappedKeyAndInfo().keyInfo.label, + wkmcDKEK.getWrappedKeyAndInfo().keyInfo.client, password.c_str()); if (!PKCS5_PBKDF2_HMAC_SHA1( @@ -249,7 +249,7 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password) uint8_t PKEK1[MAX_KEY_SIZE]; concat_user_pass = concat_password_user( - m_kmcDKEK->getKeyAndInfo().keyInfo.label, + m_kmcDKEK->getKeyAndInfo().keyInfo.client, password.c_str()); if (!PKCS5_PBKDF2_HMAC_SHA1( @@ -307,8 +307,8 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm) int keyLength; if (!PKCS5_PBKDF2_HMAC_SHA1( - wkmcDEK.getWrappedKeyAndInfo().keyInfo.label, - strlen(wkmcDEK.getWrappedKeyAndInfo().keyInfo.label), + wkmcDEK.getWrappedKeyAndInfo().keyInfo.client, + strlen(wkmcDEK.getWrappedKeyAndInfo().keyInfo.client), m_kmcDKEK->getKeyAndInfo().key, MAX_SALT_SIZE, PBKDF2_ITERATIONS, @@ -334,18 +334,18 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm) (kmcDEK.getKeyAndInfo().key) + kmcDEK.getKeyAndInfo().keyInfo.keyLength); } -RawBuffer KeyProvider::generateDEK(const std::string &smackLabel) +RawBuffer KeyProvider::generateDEK(const ClientId &client) { if (!m_isInitialized) ThrowErr(Exc::InternalError, "Object not initialized!"); WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer(); - std::string resized_smackLabel; + std::string resized_client; - if (smackLabel.length() < APP_LABEL_SIZE) - resized_smackLabel = smackLabel; + if (client.length() < MAX_CLIENT_ID_SIZE) + resized_client = client; else - resized_smackLabel = smackLabel.substr(0, APP_LABEL_SIZE - 1); + resized_client = client.substr(0, MAX_CLIENT_ID_SIZE - 1); uint8_t key[MAX_KEY_SIZE], PKEK2[MAX_KEY_SIZE]; @@ -354,8 +354,8 @@ RawBuffer KeyProvider::generateDEK(const std::string &smackLabel) ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); if (!PKCS5_PBKDF2_HMAC_SHA1( - resized_smackLabel.c_str(), - strlen(resized_smackLabel.c_str()), + resized_client.c_str(), + strlen(resized_client.c_str()), m_kmcDKEK->getKeyAndInfo().key, MAX_SALT_SIZE, PBKDF2_ITERATIONS, @@ -375,7 +375,7 @@ RawBuffer KeyProvider::generateDEK(const std::string &smackLabel) ThrowErr(Exc::InternalError, "GenerateDEK Failed in KeyProvider::generateDEK"); wkmcDEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength); - wkmcDEK.setKeyInfoLabel(resized_smackLabel); + wkmcDEK.setKeyInfoClient(resized_client); LogDebug("GenerateDEK Success"); return toRawBuffer(wkmcDEK.getWrappedKeyAndInfo()); @@ -405,7 +405,7 @@ RawBuffer KeyProvider::reencrypt( concat_user_pass = concat_password_user( - wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.label, + wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.client, oldPass.c_str()); if (!PKCS5_PBKDF2_HMAC_SHA1( @@ -435,7 +435,7 @@ RawBuffer KeyProvider::reencrypt( kmcDKEK.setKeyInfoKeyLength((unsigned int)keyLength); concat_user_pass = concat_password_user( - kmcDKEK.getKeyAndInfo().keyInfo.label, + kmcDKEK.getKeyAndInfo().keyInfo.client, newPass.c_str()); if (!PKCS5_PBKDF2_HMAC_SHA1( @@ -513,7 +513,7 @@ RawBuffer KeyProvider::generateDomainKEK( "GenerateDomainKEK Failed in KeyProvider::generateDomainKEK"); wkmcDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength); - wkmcDKEK.setKeyInfoLabel(user); + wkmcDKEK.setKeyInfoClient(user); LogDebug("generateDomainKEK Success"); return toRawBuffer(wkmcDKEK.getWrappedKeyAndInfo()); @@ -621,8 +621,8 @@ char *KeyProvider::concat_password_user(const char *user, const char *password) std::string result(password); result += user; - if (strlen(user) > MAX_LABEL_SIZE - 1) - result.resize(strlen(password) + MAX_LABEL_SIZE - 1); + if (strlen(user) > MAX_CLIENT_ID_SIZE - 1) + result.resize(strlen(password) + MAX_CLIENT_ID_SIZE - 1); char *ret = new char[result.size() + 1]; memcpy(ret, result.c_str(), result.size() + 1); diff --git a/src/manager/service/key-provider.h b/src/manager/service/key-provider.h index 82b79e6..9994c90 100644 --- a/src/manager/service/key-provider.h +++ b/src/manager/service/key-provider.h @@ -57,15 +57,14 @@ #define MAX_SALT_SIZE 16 #define MAX_KEY_SIZE 32 #define MAX_WRAPPED_KEY_SIZE 32 -#define MAX_LABEL_SIZE 32 +#define MAX_CLIENT_ID_SIZE 32 #define DOMAIN_NAME_SIZE 32 -#define APP_LABEL_SIZE 32 namespace CKM { typedef struct KeyComponentsInfo_ { uint32_t keyLength; - char label[MAX_LABEL_SIZE]; + char client[MAX_CLIENT_ID_SIZE]; uint8_t salt[MAX_SALT_SIZE]; uint8_t iv[MAX_IV_SIZE]; uint8_t tag[MAX_IV_SIZE]; @@ -87,7 +86,7 @@ public: WrappedKeyAndInfoContainer(const unsigned char *); WrappedKeyAndInfo &getWrappedKeyAndInfo(); void setKeyInfoKeyLength(const unsigned int); - void setKeyInfoLabel(const std::string); + void setKeyInfoClient(const std::string); void setKeyInfoSalt(const unsigned char *, const int); void setKeyInfo(const KeyComponentsInfo *); ~WrappedKeyAndInfoContainer(); @@ -141,10 +140,10 @@ public: // This key will be used to decrypt/encrypt data in ROW RawBuffer getPureDEK(const RawBuffer &DEKInWrapForm); - // Returns WRAPPED DEK. This will be written to datbase. + // Returns WRAPPED DEK. This will be written to database. // This key will be used to encrypt all application information. - // All application are identified by smackLabel. - RawBuffer generateDEK(const std::string &smackLabel); + // All application are identified by client id. + RawBuffer generateDEK(const ClientId &client); // used by change user password. On error -> exception static RawBuffer reencrypt( diff --git a/src/manager/service/permission.cpp b/src/manager/service/permission.cpp new file mode 100644 index 0000000..e6e930a --- /dev/null +++ b/src/manager/service/permission.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2018 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. + */ +/* + * @file permission.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + */ + +#include + +namespace CKM { + +PermissionMask toPermissionMask(const PermissionMaskOptional& mask) +{ + return mask ? *mask : Permission::NONE; +} + +} // namespace CKM diff --git a/src/manager/service/permission.h b/src/manager/service/permission.h index b0218ba..a4860c1 100644 --- a/src/manager/service/permission.h +++ b/src/manager/service/permission.h @@ -17,7 +17,7 @@ * @file permission.h * @author Maciej Karpiuk (m.karpiuk2@samsung.com) * @version 1.0 - * @brief PermissionForLabel - helper to bind permissions with accessor label. + * @brief toPermissionMask - PermissionMaskOptional conversion helper. */ #pragma once @@ -26,23 +26,7 @@ namespace CKM { typedef boost::optional PermissionMaskOptional; -struct PermissionForLabel { - Label accessorLabel; // who is accessing the item - PermissionMask permissionMask; - PermissionForLabel(const Label &accessor, const PermissionMaskOptional mask) - { - accessorLabel = accessor; +PermissionMask toPermissionMask(const PermissionMaskOptional& mask); - if (mask) - permissionMask = *mask; - else - permissionMask = Permission::NONE; - } - - int operator&(const Permission &bit) const - { - return permissionMask & bit; - } -}; } // namespace CKM diff --git a/tests/DBFixture.cpp b/tests/DBFixture.cpp index f08846b..a7e42fe 100644 --- a/tests/DBFixture.cpp +++ b/tests/DBFixture.cpp @@ -89,15 +89,15 @@ void DBFixture::generate_name(unsigned int id, Name &output) output = ss.str(); } -void DBFixture::generate_label(unsigned int id, Label &output) +void DBFixture::generate_owner(unsigned int id, ClientId &output) { std::stringstream ss; - ss << "label_no_" << id; + ss << "owner_no_" << id; output = ss.str(); } void DBFixture::generate_perf_DB(unsigned int num_name, - unsigned int num_elements) + unsigned int names_per_owner) { // to speed up data creation - cache the row DB::Row rowPattern = create_default_row(DataType::BINARY_DATA); @@ -107,32 +107,32 @@ void DBFixture::generate_perf_DB(unsigned int num_name, for (unsigned int i = 0; i < num_name; i++) { generate_name(i, rowPattern.name); - generate_label(i / num_elements, rowPattern.ownerLabel); + generate_owner(i / names_per_owner, rowPattern.owner); BOOST_REQUIRE_NO_THROW(m_db.saveRow(rowPattern)); } } long DBFixture::add_full_access_rights(unsigned int num_name, - unsigned int num_name_per_label) + unsigned int num_name_per_owner) { long iterations = 0; - unsigned int num_labels = num_name / num_name_per_label; + unsigned int num_owners = num_name / num_name_per_owner; Name name; - Label owner_label, accessor_label; + ClientId owner, accessor; for (unsigned int a = 0; a < num_name; a++) { generate_name(a, name); - generate_label(a / num_name_per_label, owner_label); + generate_owner(a / num_name_per_owner, owner); - for (unsigned int l = 0; l < num_labels; l++) { - // bypass the owner label - if (l == (a / num_name_per_label)) + for (unsigned int l = 0; l < num_owners; l++) { + // bypass the owner + if (l == (a / num_name_per_owner)) continue; // add permission - generate_label(l, accessor_label); - add_permission(name, owner_label, accessor_label); + generate_owner(l, accessor); + add_permission(name, owner, accessor); iterations++; } } @@ -142,16 +142,16 @@ long DBFixture::add_full_access_rights(unsigned int num_name, DB::Row DBFixture::create_default_row(DataType type) { - return create_default_row(m_default_name, m_default_label, type); + return create_default_row(m_default_name, m_default_owner, type); } DB::Row DBFixture::create_default_row(const Name &name, - const Label &label, + const ClientId &owner, DataType type) { DB::Row row; row.name = name; - row.ownerLabel = label; + row.owner = owner; row.exportable = 1; row.algorithmType = DBCMAlgType::AES_GCM_256; row.dataType = type; @@ -169,9 +169,9 @@ void DBFixture::compare_row(const DB::Row &lhs, const DB::Row &rhs) "namees didn't match! Got: " << rhs.name << " , expected : " << lhs.name); - BOOST_CHECK_MESSAGE(lhs.ownerLabel == rhs.ownerLabel, - "smackLabel didn't match! Got: " << rhs.ownerLabel - << " , expected : " << lhs.ownerLabel); + BOOST_CHECK_MESSAGE(lhs.owner == rhs.owner, + "owner didn't match! Got: " << rhs.owner + << " , expected : " << lhs.owner); BOOST_CHECK_MESSAGE(lhs.exportable == rhs.exportable, "exportable didn't match! Got: " << rhs.exportable @@ -195,7 +195,7 @@ void DBFixture::check_DB_integrity(const DB::Row &rowPattern) BOOST_REQUIRE_NO_THROW(m_db.saveRow(rowPattern)); DB::Crypto::RowOptional optional_row; - BOOST_REQUIRE_NO_THROW(optional_row = m_db.getRow("name", "label", + BOOST_REQUIRE_NO_THROW(optional_row = m_db.getRow("name", "owner", DataType::BINARY_DATA)); BOOST_REQUIRE_MESSAGE(optional_row, "Select didn't return any row"); @@ -205,11 +205,11 @@ void DBFixture::check_DB_integrity(const DB::Row &rowPattern) name_duplicate.dataSize = name_duplicate.data.size(); unsigned int erased; - BOOST_REQUIRE_NO_THROW(erased = m_db.deleteRow("name", "label")); + BOOST_REQUIRE_NO_THROW(erased = m_db.deleteRow("name", "owner")); BOOST_REQUIRE_MESSAGE(erased > 0, "Inserted row didn't exist in db"); DB::Crypto::RowOptional row_optional; - BOOST_REQUIRE_NO_THROW(row_optional = m_db.getRow("name", "label", + BOOST_REQUIRE_NO_THROW(row_optional = m_db.getRow("name", "owner", DataType::BINARY_DATA)); BOOST_REQUIRE_MESSAGE(!row_optional, "Select should not return row after deletion"); @@ -217,12 +217,12 @@ void DBFixture::check_DB_integrity(const DB::Row &rowPattern) void DBFixture::insert_row() { - insert_row(m_default_name, m_default_label); + insert_row(m_default_name, m_default_owner); } -void DBFixture::insert_row(const Name &name, const Label &owner_label) +void DBFixture::insert_row(const Name &name, const ClientId &owner) { - DB::Row rowPattern = create_default_row(name, owner_label, + DB::Row rowPattern = create_default_row(name, owner, DataType::BINARY_DATA); rowPattern.data = RawBuffer(100, 20); rowPattern.dataSize = rowPattern.data.size(); @@ -230,27 +230,27 @@ void DBFixture::insert_row(const Name &name, const Label &owner_label) BOOST_REQUIRE_NO_THROW(m_db.saveRow(rowPattern)); } -void DBFixture::delete_row(const Name &name, const Label &owner_label) +void DBFixture::delete_row(const Name &name, const ClientId &owner) { bool exit_flag; - BOOST_REQUIRE_NO_THROW(exit_flag = m_db.deleteRow(name, owner_label)); + BOOST_REQUIRE_NO_THROW(exit_flag = m_db.deleteRow(name, owner)); BOOST_REQUIRE_MESSAGE(true == exit_flag, "remove name failed: no rows removed"); } -void DBFixture::add_permission(const Name &name, const Label &owner_label, - const Label &accessor_label) +void DBFixture::add_permission(const Name &name, const ClientId &owner, + const ClientId &accessor) { BOOST_REQUIRE_NO_THROW(m_db.setPermission(name, - owner_label, - accessor_label, + owner, + accessor, CKM::Permission::READ | CKM::Permission::REMOVE)); } void DBFixture::read_row_expect_success(const Name &name, - const Label &owner_label) + const ClientId &owner) { DB::Crypto::RowOptional row; - BOOST_REQUIRE_NO_THROW(row = m_db.getRow(name, owner_label, + BOOST_REQUIRE_NO_THROW(row = m_db.getRow(name, owner, DataType::BINARY_DATA)); BOOST_REQUIRE_MESSAGE(row, "row is empty"); BOOST_REQUIRE_MESSAGE(row->name == name, "name is not valid"); diff --git a/tests/DBFixture.h b/tests/DBFixture.h index 62f19a2..5b40820 100644 --- a/tests/DBFixture.h +++ b/tests/DBFixture.h @@ -33,15 +33,15 @@ public: DBFixture(const char *db_fname); constexpr static const char *m_default_name = "name"; - constexpr static const char *m_default_label = "label"; + constexpr static const char *m_default_owner = "owner"; // ::::::::::::::::::::::::: helper methods ::::::::::::::::::::::::: static void generate_name(unsigned int id, CKM::Name &output); - static void generate_label(unsigned int id, CKM::Label &output); + static void generate_owner(unsigned int id, CKM::ClientId &output); static CKM::DB::Row create_default_row(CKM::DataType type = CKM::DataType::BINARY_DATA); static CKM::DB::Row create_default_row(const CKM::Name &name, - const CKM::Label &label, + const CKM::ClientId &owner, CKM::DataType type = CKM::DataType::BINARY_DATA); static void compare_row(const CKM::DB::Row &lhs, const CKM::DB::Row &rhs); @@ -50,17 +50,17 @@ public: void performance_stop(long num_operations_performed); // ::::::::::::::::::::::::: DB ::::::::::::::::::::::::: - void generate_perf_DB(unsigned int num_name, unsigned int num_label); + void generate_perf_DB(unsigned int num_name, unsigned int names_per_owner); long add_full_access_rights(unsigned int num_name, - unsigned int num_names_per_label); + unsigned int num_names_per_owner); void check_DB_integrity(const CKM::DB::Row &rowPattern); void insert_row(); - void insert_row(const CKM::Name &name, const CKM::Label &owner_label); - void delete_row(const CKM::Name &name, const CKM::Label &owner_label); - void add_permission(const CKM::Name &name, const CKM::Label &owner_label, - const CKM::Label &accessor_label); + void insert_row(const CKM::Name &name, const CKM::ClientId &owner); + void delete_row(const CKM::Name &name, const CKM::ClientId &owner); + void add_permission(const CKM::Name &name, const CKM::ClientId &owner, + const CKM::ClientId &accessor); void read_row_expect_success(const CKM::Name &name, - const CKM::Label &owner_label); + const CKM::ClientId &owner); CKM::DB::Crypto m_db; diff --git a/tests/encryption-scheme/scheme-test.cpp b/tests/encryption-scheme/scheme-test.cpp index d0096ac..73cca05 100644 --- a/tests/encryption-scheme/scheme-test.cpp +++ b/tests/encryption-scheme/scheme-test.cpp @@ -53,7 +53,7 @@ const uid_t UID = 7654; const gid_t GID = 7654; const char *const DBPASS = "db-pass"; const char *const LABEL = "my-label"; -const Label DB_LABEL = "/" + string(LABEL); +const ClientId OWNER = "/" + string(LABEL); const int ENC_SCHEME_OFFSET = 24; const string TEST_DATA_STR = "test-data"; RawBuffer TEST_DATA(TEST_DATA_STR.begin(), TEST_DATA_STR.end()); @@ -743,7 +743,7 @@ size_t SchemeTest::CountObjects() for (const auto &i : g.items) { DB::RowVector rows; // it is assumed that aliases are different - m_db->getRows(i.alias, DB_LABEL, DataType::DB_FIRST, DataType::DB_LAST, rows); + m_db->getRows(i.alias, OWNER, DataType::DB_FIRST, DataType::DB_LAST, rows); ret += rows.size(); } } @@ -770,7 +770,7 @@ void SchemeTest::CheckSchemeVersion(const ItemFilter &filter, int version) continue; DB::RowVector rows; - m_db->getRows(i.alias, DB_LABEL, filter.typeFrom, filter.typeTo, rows); + m_db->getRows(i.alias, OWNER, filter.typeFrom, filter.typeTo, rows); BOOST_REQUIRE_MESSAGE(rows.size() > 0, "No rows found for " << i.alias); for (const auto &r : rows) { diff --git a/tests/secure-storage-old-data/README b/tests/secure-storage-old-data/README index a6c9ca0..6029963 100644 --- a/tests/secure-storage-old-data/README +++ b/tests/secure-storage-old-data/README @@ -27,8 +27,8 @@ All data is saved in both of is only used for migratable data re-encryption. -system db with owner label = "/System" and name = "" -admin user(owner) db with owner label = "/User" and name = "" +system db with owner = "/System" and name = "" +admin user(owner) db with owner = "/User" and name = "" storage name extraction examples) Client with... Case1:: = "client.service.label", = "data", = "secure-storage::client" diff --git a/tests/test_crypto-logic.cpp b/tests/test_crypto-logic.cpp index 6bb84cd..5784365 100644 --- a/tests/test_crypto-logic.cpp +++ b/tests/test_crypto-logic.cpp @@ -48,39 +48,39 @@ BOOST_AUTO_TEST_CASE(move_semantics) { CryptoLogic logic; - const std::string label = "test_label"; - BOOST_REQUIRE_NO_THROW(logic.pushKey(label, createRandom(10))); + const ClientId client = "test_client"; + BOOST_REQUIRE_NO_THROW(logic.pushKey(client, createRandom(10))); CryptoLogic moved(std::move(logic)); - BOOST_REQUIRE(!logic.haveKey(label)); - BOOST_REQUIRE(moved.haveKey(label)); + BOOST_REQUIRE(!logic.haveKey(client)); + BOOST_REQUIRE(moved.haveKey(client)); CryptoLogic moveAssigned = std::move(moved); - BOOST_REQUIRE(!moved.haveKey(label)); - BOOST_REQUIRE(moveAssigned.haveKey(label)); + BOOST_REQUIRE(!moved.haveKey(client)); + BOOST_REQUIRE(moveAssigned.haveKey(client)); moveAssigned = std::move(moveAssigned); - BOOST_REQUIRE(moveAssigned.haveKey(label)); + BOOST_REQUIRE(moveAssigned.haveKey(client)); } BOOST_AUTO_TEST_CASE(push_key) { CryptoLogic logic; - const std::string label = "test_label"; + const ClientId client = "test_client"; BOOST_REQUIRE_THROW(logic.pushKey(std::string(), createRandom(10)), Exc::InternalError); - BOOST_REQUIRE_THROW(logic.pushKey(label, RawBuffer()), + BOOST_REQUIRE_THROW(logic.pushKey(client, RawBuffer()), Exc::InternalError); - BOOST_REQUIRE_NO_THROW(logic.pushKey(label, createRandom(10))); - BOOST_REQUIRE_THROW(logic.pushKey(label, createRandom(10)), + BOOST_REQUIRE_NO_THROW(logic.pushKey(client, createRandom(10))); + BOOST_REQUIRE_THROW(logic.pushKey(client, createRandom(10)), Exc::InternalError); - std::string increasingLabel = "a"; - for (size_t i = 0; i < 20; ++i, increasingLabel.push_back('a')) { - BOOST_REQUIRE_NO_THROW(logic.pushKey(increasingLabel, createRandom(10))); - BOOST_REQUIRE_THROW(logic.pushKey(increasingLabel, createRandom(10)), + ClientId increasingOwner = "a"; + for (size_t i = 0; i < 20; ++i, increasingOwner.push_back('a')) { + BOOST_REQUIRE_NO_THROW(logic.pushKey(increasingOwner, createRandom(10))); + BOOST_REQUIRE_THROW(logic.pushKey(increasingOwner, createRandom(10)), Exc::InternalError); } } @@ -94,15 +94,15 @@ BOOST_AUTO_TEST_CASE(row_encryption) Token token = store.import(data, policy.password); Name name = "test_data"; - Label label = "test_owner"; - DB::Row row(token, name, label, static_cast(policy.extractable)); + ClientId owner = "test_owner"; + DB::Row row(token, name, owner, static_cast(policy.extractable)); CryptoLogic logic; BOOST_REQUIRE_THROW(logic.encryptRow(row), Exc::InternalError); auto key = createRandom(32); - BOOST_REQUIRE_NO_THROW(logic.pushKey(label, key)); + BOOST_REQUIRE_NO_THROW(logic.pushKey(owner, key)); BOOST_REQUIRE_NO_THROW(logic.encryptRow(row)); BOOST_REQUIRE_NO_THROW(logic.decryptRow(policy.password, row)); } @@ -116,22 +116,22 @@ BOOST_AUTO_TEST_CASE(row_encryption_negatives) Token token = store.import(data, policy.password); Name name = "test_data"; - Label label = "test_owner"; - DB::Row row(token, name, label, static_cast(policy.extractable)); + ClientId owner = "test_owner"; + DB::Row row(token, name, owner, static_cast(policy.extractable)); CryptoLogic logic; auto key = createRandom(32); - BOOST_REQUIRE_NO_THROW(logic.pushKey(label, key)); + BOOST_REQUIRE_NO_THROW(logic.pushKey(owner, key)); BOOST_REQUIRE_NO_THROW(logic.encryptRow(row)); BOOST_REQUIRE_THROW(logic.decryptRow(createRandomPass(10), row), Exc::AuthenticationFailed); - BOOST_REQUIRE_NO_THROW(logic.removeKey(label)); + BOOST_REQUIRE_NO_THROW(logic.removeKey(owner)); BOOST_REQUIRE_THROW(logic.decryptRow(Password(), row), Exc::AuthenticationFailed); - BOOST_REQUIRE_NO_THROW(logic.pushKey(label, key)); + BOOST_REQUIRE_NO_THROW(logic.pushKey(owner, key)); row.algorithmType = DBCMAlgType::NONE; BOOST_REQUIRE_THROW(logic.decryptRow(Password(), row), diff --git a/tests/test_db_crypto.cpp b/tests/test_db_crypto.cpp index e9f471b..7d6c698 100644 --- a/tests/test_db_crypto.cpp +++ b/tests/test_db_crypto.cpp @@ -39,7 +39,7 @@ const int restricted_global = 0; const unsigned int c_test_retries = 1000; const unsigned int c_num_names = 500; const unsigned int c_num_names_add_test = 5000; -const unsigned int c_names_per_label = 15; +const unsigned int c_names_per_owner = 15; } // namespace anonymous @@ -72,7 +72,7 @@ BOOST_AUTO_TEST_CASE(DBtestGlobal) BOOST_REQUIRE_NO_THROW(m_db.saveRow(rowPattern)); DB::Row name_duplicate = rowPattern; - rowPattern.ownerLabel = rowPattern.ownerLabel + "1"; + rowPattern.owner = rowPattern.owner + "1"; } BOOST_AUTO_TEST_CASE(DBtestTransaction) { @@ -87,7 +87,7 @@ BOOST_AUTO_TEST_CASE(DBtestTransaction) DB::Crypto::RowOptional row_optional; BOOST_REQUIRE_NO_THROW(row_optional = m_db.getRow(m_default_name, - m_default_label, + m_default_owner, DataType::BINARY_DATA)); BOOST_CHECK_MESSAGE(!row_optional, "Row still present after rollback"); } @@ -121,7 +121,7 @@ BOOST_AUTO_TEST_CASE(DBperfAddNames) performance_start("saveRow"); { - generate_perf_DB(c_num_names_add_test, c_names_per_label); + generate_perf_DB(c_num_names_add_test, c_names_per_owner); } performance_stop(c_num_names_add_test); @@ -130,40 +130,41 @@ BOOST_AUTO_TEST_CASE(DBperfAddNames) BOOST_AUTO_TEST_CASE(DBperfLookupAliasByOwner) { // prepare data - generate_perf_DB(c_num_names, c_names_per_label); + generate_perf_DB(c_num_names, c_names_per_owner); - unsigned int num_labels = c_num_names / c_names_per_label; + unsigned int num_owners = c_num_names / c_names_per_owner; Name name; - Label label; + ClientId owner; // actual test - successful lookup performance_start("getRow"); for (unsigned int t = 0; t < c_test_retries; t++) { - int label_num = rand_r(&t) % num_labels; - generate_label(label_num, label); + int owner_num = rand_r(&t) % num_owners; + generate_owner(owner_num, owner); - unsigned int start_name = label_num * c_names_per_label; + unsigned int start_name = owner_num * c_names_per_owner; for (unsigned int name_num = start_name; - name_num < (start_name + c_names_per_label); name_num++) { + name_num < (start_name + c_names_per_owner); name_num++) { generate_name(name_num, name); - read_row_expect_success(name, label); + read_row_expect_success(name, owner); } } performance_stop(c_test_retries * c_num_names); } +// TODO this test makes no sense. Rewrite it. BOOST_AUTO_TEST_CASE(DBperfLookupAliasRandomOwnershipNoPermissions) { // prepare data - generate_perf_DB(c_num_names, c_names_per_label); + generate_perf_DB(c_num_names, c_names_per_owner); Name name; - Label owner_label; - Label smack_label; - unsigned int num_labels = c_num_names / c_names_per_label; + ClientId owner; + //ClientId smack_label; + //unsigned int num_owners = c_num_names / c_names_per_owner; // actual test - random lookup performance_start("getRow"); @@ -171,11 +172,11 @@ BOOST_AUTO_TEST_CASE(DBperfLookupAliasRandomOwnershipNoPermissions) for (unsigned int t = 0; t < c_test_retries; t++) { int name_idx = rand_r(&t) % c_num_names; generate_name(name_idx, name); - generate_label(name_idx / c_names_per_label, owner_label); - generate_label(rand_r(&t) % num_labels, smack_label); + generate_owner(name_idx / c_names_per_owner, owner); + //generate_owner(rand_r(&t) % num_owners, smack_label); // do not care of result - m_db.getRow(name, owner_label, DataType::BINARY_DATA); + m_db.getRow(name, owner, DataType::BINARY_DATA); } performance_stop(c_test_retries * c_num_names); @@ -184,41 +185,41 @@ BOOST_AUTO_TEST_CASE(DBperfLookupAliasRandomOwnershipNoPermissions) BOOST_AUTO_TEST_CASE(DBperfAddPermissions) { // prepare data - generate_perf_DB(c_num_names, c_names_per_label); + generate_perf_DB(c_num_names, c_names_per_owner); // actual test - add access rights performance_start("setPermission"); - long iterations = add_full_access_rights(c_num_names, c_names_per_label); + long iterations = add_full_access_rights(c_num_names, c_names_per_owner); performance_stop(iterations); } BOOST_AUTO_TEST_CASE(DBperfAliasRemoval) { // prepare data - generate_perf_DB(c_num_names, c_names_per_label); - add_full_access_rights(c_num_names, c_names_per_label); + generate_perf_DB(c_num_names, c_names_per_owner); + add_full_access_rights(c_num_names, c_names_per_owner); // actual test - random lookup performance_start("deleteRow"); Name name; - Label label; + ClientId owner; for (unsigned int t = 0; t < c_num_names; t++) { generate_name(t, name); - generate_label(t / c_names_per_label, label); + generate_owner(t / c_names_per_owner, owner); - BOOST_REQUIRE_NO_THROW(m_db.deleteRow(name, label)); + BOOST_REQUIRE_NO_THROW(m_db.deleteRow(name, owner)); } performance_stop(c_num_names); // verify everything has been removed - unsigned int num_labels = c_num_names / c_names_per_label; + unsigned int num_owners = c_num_names / c_names_per_owner; - for (unsigned int l = 0; l < num_labels; l++) { - generate_label(l, label); - LabelNameVector expect_no_data; - BOOST_REQUIRE_NO_THROW(m_db.listNames(label, expect_no_data, + for (unsigned int l = 0; l < num_owners; l++) { + generate_owner(l, owner); + OwnerNameVector expect_no_data; + BOOST_REQUIRE_NO_THROW(m_db.listNames(owner, expect_no_data, DataType::BINARY_DATA)); BOOST_REQUIRE(0 == expect_no_data.size()); } @@ -227,25 +228,25 @@ BOOST_AUTO_TEST_CASE(DBperfAliasRemoval) BOOST_AUTO_TEST_CASE(DBperfGetAliasList) { // prepare data - generate_perf_DB(c_num_names, c_names_per_label); - add_full_access_rights(c_num_names, c_names_per_label); + generate_perf_DB(c_num_names, c_names_per_owner); + add_full_access_rights(c_num_names, c_names_per_owner); - unsigned int num_labels = c_num_names / c_names_per_label; - Label label; + unsigned int num_owners = c_num_names / c_names_per_owner; + ClientId owner; // actual test - random lookup performance_start("listNames"); - for (unsigned int t = 0; t < (c_test_retries / num_labels); t++) { - LabelNameVector ret_list; - generate_label(rand_r(&t) % num_labels, label); + for (unsigned int t = 0; t < (c_test_retries / num_owners); t++) { + OwnerNameVector ret_list; + generate_owner(rand_r(&t) % num_owners, owner); - BOOST_REQUIRE_NO_THROW(m_db.listNames(label, ret_list, DataType::BINARY_DATA)); + BOOST_REQUIRE_NO_THROW(m_db.listNames(owner, ret_list, DataType::BINARY_DATA)); BOOST_REQUIRE(c_num_names == ret_list.size()); ret_list.clear(); } - performance_stop(c_test_retries / num_labels); + performance_stop(c_test_retries / num_owners); } BOOST_AUTO_TEST_SUITE_END() @@ -253,51 +254,52 @@ BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(DBCRYPTO_MIGRATION_TEST) namespace { const unsigned migration_names = 16107; -const unsigned migration_labels = 273; -const unsigned migration_reference_label_idx = 0; +const unsigned migration_owners = 273; +const unsigned migration_reference_owner_idx = 0; const unsigned migration_accessed_element_idx = 7; void verifyDBisValid(DBFixture &fixture) { /** - * there are (migration_labels), each having (migration_names)/(migration_labels) entries. - * reference label (migration_reference_label_idx) exists such that it has access to - * all others' label element with index (migration_accessed_element_idx). + * There are (migration_owners), each having (migration_names)/(migration_owners) + * entries. Reference owner (migration_reference_owner_idx) exists such that + * it has access to all other owners' elements with index + * (migration_accessed_element_idx). * * Example: - * - migration_label_63 has access to all items owned by migration_label_63, - * which gives (migration_names)/(migration_labels) entries. + * - migration_owner_63 has access to all items owned by migration_owner_63, + * which gives (migration_names)/(migration_owners) entries. * - * - migration_label_0 (0 is the reference label) has access to all items - * owned by migration_label_0 and all others' label element index 7, - * which gives (migration_names)/(migration_labels) + (migration_labels-1) entries. + * - migration_owner_0 (0 is the reference owner) has access to all items + * owned by migration_owner_0 and all other owners' elements with index 7, + * which gives (migration_names)/(migration_owners) + (migration_owners-1) entries. * */ - Label reference_label; - fixture.generate_label(migration_reference_label_idx, reference_label); + ClientId reference_owner; + fixture.generate_owner(migration_reference_owner_idx, reference_owner); - // check number of elements accessible to the reference label - LabelNameVector ret_list; - BOOST_REQUIRE_NO_THROW(fixture.m_db.listNames(reference_label, ret_list, + // check number of elements accessible to the reference owner + OwnerNameVector ret_list; + BOOST_REQUIRE_NO_THROW(fixture.m_db.listNames(reference_owner, ret_list, DataType::BINARY_DATA)); - BOOST_REQUIRE((migration_names / migration_labels)/*own items*/ + - (migration_labels - 1)/*other labels'*/ == ret_list.size()); + BOOST_REQUIRE((migration_names / migration_owners)/*own items*/ + + (migration_owners - 1)/*other owners'*/ == ret_list.size()); ret_list.clear(); - // check number of elements accessible to the other labels - for (unsigned int l = 0; l < migration_labels; l++) { - // bypass the reference owner label - if (l == migration_reference_label_idx) + // check number of elements accessible to the other owners + for (unsigned int l = 0; l < migration_owners; l++) { + // bypass the reference owner + if (l == migration_reference_owner_idx) continue; - Label current_label; - fixture.generate_label(l, current_label); - BOOST_REQUIRE_NO_THROW(fixture.m_db.listNames(current_label, ret_list, + ClientId current_owner; + fixture.generate_owner(l, current_owner); + BOOST_REQUIRE_NO_THROW(fixture.m_db.listNames(current_owner, ret_list, DataType::BINARY_DATA)); - BOOST_REQUIRE((migration_names / migration_labels) == ret_list.size()); + BOOST_REQUIRE((migration_names / migration_owners) == ret_list.size()); for (auto it : ret_list) - BOOST_REQUIRE(it.first == current_label); + BOOST_REQUIRE(it.first == current_owner); ret_list.clear(); } @@ -339,27 +341,27 @@ BOOST_AUTO_TEST_CASE(DBMigrationDBCurrent) DBFixture currentDB; // prepare data using current DB mechanism - Label reference_label; - currentDB.generate_label(migration_reference_label_idx, reference_label); + ClientId reference_owner; + currentDB.generate_owner(migration_reference_owner_idx, reference_owner); { - currentDB.generate_perf_DB(migration_names, migration_names / migration_labels); + currentDB.generate_perf_DB(migration_names, migration_names / migration_owners); - // only the reference label has access to the other labels element - for (unsigned int l = 0; l < migration_labels; l++) { - // bypass the reference owner label - if (l == migration_reference_label_idx) + // only the reference owner has access to the other owners' elements + for (unsigned int l = 0; l < migration_owners; l++) { + // bypass the reference owner + if (l == migration_reference_owner_idx) continue; unsigned element_index = migration_accessed_element_idx + l * migration_names / - migration_labels; + migration_owners; // add permission Name accessed_name; currentDB.generate_name(element_index, accessed_name); - Label current_label; - currentDB.generate_label(l, current_label); - currentDB.add_permission(accessed_name, current_label, reference_label); + ClientId current_owner; + currentDB.generate_owner(l, current_owner); + currentDB.add_permission(accessed_name, current_owner, reference_owner); } } diff --git a/tests/test_key-provider.cpp b/tests/test_key-provider.cpp index 274080d..abca989 100644 --- a/tests/test_key-provider.cpp +++ b/tests/test_key-provider.cpp @@ -33,8 +33,8 @@ const CKM::Password NEW_PASSWORD = "NEW12345TIZEN12345NEW"; const std::string USERNAME_SHORT = "AB"; const std::string USERNAME_LONG = "SOFTWARE_CENTER_SYSTEM_SW_LAB_SECURITY_PART"; -const std::string SMACK_LABEL_1 = "SAMPLE_SMACK_LABEL_1"; -const std::string SMACK_LABEL_2 = "SAMPLE_SMACK_LABEL_2"; +const std::string CLIENT_ID_1 = "SAMPLE_CLIENT_ID_1"; +const std::string CLIENT_ID_2 = "SAMPLE_CLIENT_ID_2"; extern bool isLibInitialized; @@ -106,7 +106,7 @@ BOOST_AUTO_TEST_CASE(KeyGenerateDEK) BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD)); BOOST_REQUIRE_MESSAGE(keyProvider.isInitialized(), "KeyProvider created, but uninitialized"); - BOOST_REQUIRE_NO_THROW(rb_DEK1 = keyProvider.generateDEK(SMACK_LABEL_1)); + BOOST_REQUIRE_NO_THROW(rb_DEK1 = keyProvider.generateDEK(CLIENT_ID_1)); } BOOST_AUTO_TEST_CASE(KeyGetPureDEK) @@ -122,7 +122,7 @@ BOOST_AUTO_TEST_CASE(KeyGetPureDEK) BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD)); BOOST_REQUIRE_MESSAGE(keyProvider.isInitialized(), "KeyProvider created, but uninitialized"); - BOOST_REQUIRE_NO_THROW(rb_DEK1 = keyProvider.generateDEK(SMACK_LABEL_1)); + BOOST_REQUIRE_NO_THROW(rb_DEK1 = keyProvider.generateDEK(CLIENT_ID_1)); BOOST_REQUIRE_NO_THROW(rb_pureDEK1 = keyProvider.getPureDEK(rb_DEK1)); } @@ -159,7 +159,7 @@ BOOST_AUTO_TEST_CASE(KeyGetPureDEK_after_reencrypt) BOOST_REQUIRE_NO_THROW(rb_test = CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD)); BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD)); - BOOST_REQUIRE_NO_THROW(rb_DEK1 = keyProvider.generateDEK(SMACK_LABEL_1)); + BOOST_REQUIRE_NO_THROW(rb_DEK1 = keyProvider.generateDEK(CLIENT_ID_1)); BOOST_REQUIRE_NO_THROW(keyProvider.getPureDEK(rb_DEK1)); } @@ -169,7 +169,7 @@ BOOST_AUTO_TEST_CASE(wrapped_container) auto salt = createRandom(20); BOOST_REQUIRE_NO_THROW(wrappedContainer.setKeyInfoSalt(salt.data(), salt.size())); - BOOST_REQUIRE_NO_THROW(wrappedContainer.setKeyInfoLabel("key_info_label")); + BOOST_REQUIRE_NO_THROW(wrappedContainer.setKeyInfoClient("key_info_client")); CKM::WrappedKeyAndInfoContainer wrappedContainer2; BOOST_REQUIRE_NO_THROW( @@ -183,9 +183,9 @@ BOOST_AUTO_TEST_CASE(wrapped_container) wrappedContainer2.getWrappedKeyAndInfo().keyInfo.salt, sizeof(wrappedContainer.getWrappedKeyAndInfo().keyInfo.salt)) == 0); BOOST_REQUIRE(memcmp( - wrappedContainer.getWrappedKeyAndInfo().keyInfo.label, - wrappedContainer2.getWrappedKeyAndInfo().keyInfo.label, - sizeof(wrappedContainer.getWrappedKeyAndInfo().keyInfo.label)) == 0); + wrappedContainer.getWrappedKeyAndInfo().keyInfo.client, + wrappedContainer2.getWrappedKeyAndInfo().keyInfo.client, + sizeof(wrappedContainer.getWrappedKeyAndInfo().keyInfo.client)) == 0); } BOOST_AUTO_TEST_CASE(container) diff --git a/tools/ckm_db_tool/CMakeLists.txt b/tools/ckm_db_tool/CMakeLists.txt index 4a47a1d..be82e81 100644 --- a/tools/ckm_db_tool/CMakeLists.txt +++ b/tools/ckm_db_tool/CMakeLists.txt @@ -77,6 +77,7 @@ SET(CKM_DB_TOOLS_SOURCES ${KEY_MANAGER_PATH}/service/key-provider.cpp ${KEY_MANAGER_PATH}/service/ss-migrate.cpp ${KEY_MANAGER_PATH}/service/ss-crypto.cpp + ${KEY_MANAGER_PATH}/service/permission.cpp ${KEY_MANAGER_PATH}/sqlcipher/sqlcipher.c ) -- 2.7.4 From 144715efed149cf7d0bb16a9c404f05222b71159 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 24 Jul 2018 10:44:23 +0200 Subject: [PATCH 05/16] Add log for invalid system service owner id System services (uid < 5000) should always use "/System" owner id. Eiter by explicitly adding it to the alias or by running with "System" label. Add log to make the reason of the failure more apparent. Change-Id: I1be9861eadcae6eadd6d682b4cc66972c93d1728 --- src/manager/service/ckm-logic.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/manager/service/ckm-logic.cpp b/src/manager/service/ckm-logic.cpp index 635f8b9..f3c2154 100644 --- a/src/manager/service/ckm-logic.cpp +++ b/src/manager/service/ckm-logic.cpp @@ -1224,8 +1224,10 @@ int CKMLogic::saveDataHelper( const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner; if (m_accessControl.isSystemService(cred) && - owner.compare(CLIENT_ID_SYSTEM) != 0) + owner.compare(CLIENT_ID_SYSTEM) != 0) { + LogError("System services can only use " << CLIENT_ID_SYSTEM << " as owner id") ; return CKM_API_ERROR_INPUT_PARAM; + } // check if save is possible DB::Crypto::Transaction transaction(&handler.database); -- 2.7.4 From 1cc408882ddfdafdc69492d0d728c5127835909c Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 28 Aug 2018 17:16:36 +0200 Subject: [PATCH 06/16] Fix buildbreak caused by improper rebase Refactoring commit has been improperly rebased which led to buildbreak. Change-Id: I2d04143cf1eb929c8f8226826336b2e825996149 --- tools/ckm_db_tool/ckm_db_merge.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/ckm_db_tool/ckm_db_merge.cpp b/tools/ckm_db_tool/ckm_db_merge.cpp index 17e308c..fe82bb7 100644 --- a/tools/ckm_db_tool/ckm_db_merge.cpp +++ b/tools/ckm_db_tool/ckm_db_merge.cpp @@ -44,7 +44,7 @@ bool printRow(const DB::Row &row) { } cout << "Read row:"; cout << "\n Name: " << row.name; - cout << "\n Owner: " << row.ownerLabel; + cout << "\n Owner: " << row.owner; cout << "\n Exportable: " << row.exportable; cout << "\n Alg type: " << static_cast(row.algorithmType); cout << "\n Enc schema: " << row.encryptionScheme; @@ -158,7 +158,7 @@ int main(int argc, char *argv[]) { break; case 'o': owner = optarg; // I cannot pass optarg to lambda because it's pointer - filters.push_back([=](DB::Row &row) {row.ownerLabel = owner; return true;}); + filters.push_back([=](DB::Row &row) {row.owner = owner; return true;}); break; case 'h': printUsage(); -- 2.7.4 From 3cadb98befc315f3e414d38e7cf6d3cfd049b9a7 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Thu, 20 Sep 2018 13:26:06 +0200 Subject: [PATCH 07/16] Simplify key related functions in tz-backend - Use proper parameter for tag length - Move default param values to TrustZoneContext where possible - Remove unnecessary arguments Change-Id: I00f8909ede4f80b77a937b52a5bce5698d4516a5 --- src/manager/crypto/tz-backend/internals.cpp | 6 +----- src/manager/crypto/tz-backend/tz-context.cpp | 23 ++++++++++------------- src/manager/crypto/tz-backend/tz-context.h | 5 +---- 3 files changed, 12 insertions(+), 22 deletions(-) diff --git a/src/manager/crypto/tz-backend/internals.cpp b/src/manager/crypto/tz-backend/internals.cpp index bfb78d7..d2753bc 100644 --- a/src/manager/crypto/tz-backend/internals.cpp +++ b/src/manager/crypto/tz-backend/internals.cpp @@ -73,7 +73,7 @@ tz_algo_type getAlgType(KeyType keyType) RawBuffer generateIV() { RawBuffer result; - TrustZoneContext::Instance().generateIV(Params::DEFAULT_AES_IV_LEN, result); + TrustZoneContext::Instance().generateIV(result); return result; } @@ -96,7 +96,6 @@ Data generateSKey(const CryptoAlgorithm &alg, RawBuffer pwdBuf(pwd.begin(), pwd.end()); TrustZoneContext::Instance().generateSKeyPwd(getGenKeyType(keyType), pwdBuf, iv, keyBits, - Params::DEFAULT_AES_GCM_TAG_LEN_BITS, keyData.data, tag); } else { TrustZoneContext::Instance().generateSKey(getGenKeyType(keyType), keyBits, @@ -128,13 +127,10 @@ RawBuffer importKey(const Data &data, RawBuffer result; RawBuffer pwdBuf(pwd.begin(), pwd.end()); - uint32_t keySizeBits = data.data.size() * 8; TrustZoneContext::Instance().importKey(algo, data.data, pwdBuf, iv, - keySizeBits, - Params::DERIVED_KEY_LENGTH_BITS, result, tag); return result; diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index 7a59fbe..e088163 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -68,7 +68,7 @@ TrustZoneContext& TrustZoneContext::Instance() return instance; } -void TrustZoneContext::generateIV(uint32_t ivSize, RawBuffer& iv) +void TrustZoneContext::generateIV(RawBuffer& iv) { // command ID = CMD_GENERATE_IV // @@ -81,6 +81,7 @@ void TrustZoneContext::generateIV(uint32_t ivSize, RawBuffer& iv) // IV generation is a simple call - no need to serialize data // just provide the output buffer with size equal to iv. + uint32_t ivSize = Params::DEFAULT_AES_IV_LEN; TrustZoneMemory ivMemory(m_Context, ivSize, TEEC_MEM_OUTPUT); TEEC_Operation op; @@ -150,7 +151,6 @@ void TrustZoneContext::generateSKeyPwd(tz_algo_type algo, const RawBuffer &pwd, const RawBuffer &iv, const uint32_t keySizeBits, - const uint32_t pwdTagSizeBits, RawBuffer &keyId, RawBuffer &pwdTag) { @@ -176,7 +176,7 @@ void TrustZoneContext::generateSKeyPwd(tz_algo_type algo, memset(&bufSize, 0, sizeof(KM_BufferSizeDesc)); bufSize.out_size = KM_KEY_ID_SIZE; - bufSize.tag_size = pwdTagSizeBits / 8; + bufSize.tag_size = Params::DEFAULT_AES_GCM_TAG_LEN_BYTES; uint32_t keyMemorySize = KM_CalcBufferSize(bufSize); TrustZoneMemory keyMemory(m_Context, keyMemorySize, TEEC_MEM_OUTPUT); @@ -188,7 +188,7 @@ void TrustZoneContext::generateSKeyPwd(tz_algo_type algo, ret = KM_ParamsSerializePwdData(input, pwd.data(), pwd.size(), iv.data(), iv.size(), nullptr, 0, Params::DERIVED_KEY_LENGTH_BITS, - Params::DERIVED_KEY_ITERATIONS, pwdTagSizeBits); + Params::DERIVED_KEY_ITERATIONS, bufSize.tag_size * 8); if (ret) { ThrowErr(Exc::Crypto::InternalError, "Failed to serialize password data for TZ crypto operation: ", ret); } @@ -244,8 +244,6 @@ void TrustZoneContext::importKey(tz_algo_type algo, const RawBuffer &key, const RawBuffer &pwd, const RawBuffer &iv, - const uint32_t keySizeBits, - const uint32_t pwdTagSizeBits, RawBuffer &keyId, RawBuffer &pwdTag) { @@ -274,7 +272,7 @@ void TrustZoneContext::importKey(tz_algo_type algo, memset(&bufSize, 0, sizeof(KM_BufferSizeDesc)); bufSize.out_size = KM_KEY_ID_SIZE; - bufSize.tag_size = pwdTagSizeBits / 8; + bufSize.tag_size = Params::DEFAULT_AES_GCM_TAG_LEN_BYTES; uint32_t keyMemorySize = KM_CalcBufferSize(bufSize); TrustZoneMemory keyMemory(m_Context, keyMemorySize, TEEC_MEM_OUTPUT); @@ -292,7 +290,7 @@ void TrustZoneContext::importKey(tz_algo_type algo, if (!pwd.empty()) { ret = KM_ParamsSerializePwdData(input, pwd.data(), pwd.size(), iv.data(), iv.size(), nullptr, 0, Params::DERIVED_KEY_LENGTH_BITS, - Params::DERIVED_KEY_ITERATIONS, pwdTagSizeBits); + Params::DERIVED_KEY_ITERATIONS, bufSize.tag_size * 8); if (ret) { ThrowErr(Exc::Crypto::InternalError, "Failed to serialize key data for import: ", ret); } @@ -302,7 +300,7 @@ void TrustZoneContext::importKey(tz_algo_type algo, op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_WHOLE, TEEC_MEMREF_WHOLE, TEEC_NONE); op.params[0].value.a = algo; - op.params[0].value.b = keySizeBits; + op.params[0].value.b = key.size() * 8; op.params[1].memref.parent = inMemory.Get(); op.params[1].memref.offset = 0; op.params[1].memref.size = inMemory.Get()->size; @@ -332,19 +330,18 @@ void TrustZoneContext::importKey(tz_algo_type algo, if (!pwd.empty()) { KM_TagData* tagData = nullptr; - uint32_t pwdTagSizeBytes = pwdTagSizeBits / 8; ret = KM_ParamsDeserializeTagData(output, &tagData); if (ret) { ThrowErr(Exc::Crypto::InternalError, "Failed to deserialize imported key's tag"); } - if (tagData == nullptr || tagData->data_size != pwdTagSizeBytes) { + if (tagData == nullptr || tagData->data_size != bufSize.tag_size) { ThrowErr(Exc::Crypto::InternalError, "Deserialized incorrect key tag"); } - pwdTag.resize(pwdTagSizeBytes); - memcpy(pwdTag.data(), tagData->data, pwdTagSizeBytes); + pwdTag.resize(bufSize.tag_size); + memcpy(pwdTag.data(), tagData->data, bufSize.tag_size); } } diff --git a/src/manager/crypto/tz-backend/tz-context.h b/src/manager/crypto/tz-backend/tz-context.h index 44ad38c..86fe08b 100644 --- a/src/manager/crypto/tz-backend/tz-context.h +++ b/src/manager/crypto/tz-backend/tz-context.h @@ -37,7 +37,7 @@ class TrustZoneContext final public: static TrustZoneContext& Instance(); - void generateIV(uint32_t ivSize, RawBuffer &iv); + void generateIV(RawBuffer &iv); void generateSKey(tz_algo_type algo, uint32_t keySizeBits, RawBuffer &keyId); @@ -45,15 +45,12 @@ public: const RawBuffer &pwd, const RawBuffer &iv, const uint32_t pwdKeySizeBits, - const uint32_t pwdTagSizeBits, RawBuffer &keyId, RawBuffer &pwdTag); void importKey(tz_algo_type algo, const RawBuffer &key, const RawBuffer &pwd, const RawBuffer &iv, - const uint32_t keySizeBits, - const uint32_t pwdTagSizeBits, RawBuffer &keyId, RawBuffer &pwdTag); -- 2.7.4 From 2ff75c9bc6dbaaf7d521edfe393b84a8a1186f45 Mon Sep 17 00:00:00 2001 From: Tomasz Swierczek Date: Wed, 26 Sep 2018 11:18:43 +0200 Subject: [PATCH 08/16] Add support for TrustZone backend data storage Change-Id: Idfd0909d03e40b7e5cd5aeb1116b844be1901cf1 --- src/manager/crypto/platform/decider.cpp | 10 +- src/manager/crypto/tz-backend/internals.cpp | 31 +++ src/manager/crypto/tz-backend/internals.h | 11 ++ src/manager/crypto/tz-backend/store.cpp | 34 +++- src/manager/crypto/tz-backend/tz-context.cpp | 280 +++++++++++++++++++++++++++ src/manager/crypto/tz-backend/tz-context.h | 14 ++ 6 files changed, 367 insertions(+), 13 deletions(-) diff --git a/src/manager/crypto/platform/decider.cpp b/src/manager/crypto/platform/decider.cpp index a2f16e2..a7e6b32 100644 --- a/src/manager/crypto/platform/decider.cpp +++ b/src/manager/crypto/platform/decider.cpp @@ -76,13 +76,13 @@ CryptoBackend chooseCryptoBackend(DataType data, if (encrypted) return CryptoBackend::OpenSSL; - // Only software backend allows for key export - if (policy.extractable) + // tz-backend allows only for data binary export + if (policy.extractable && !data.isBinaryData()) return CryptoBackend::OpenSSL; - // Use TrustZone only with symmetric keys until asymmetric - // cryptography is implemented - if (!data.isSKey()) + // Use TrustZone only with symmetric keys or unencrypted binary + // data until asymmetric cryptography is implemented + if (!data.isSKey() && !data.isBinaryData()) return CryptoBackend::OpenSSL; try { diff --git a/src/manager/crypto/tz-backend/internals.cpp b/src/manager/crypto/tz-backend/internals.cpp index d2753bc..578241d 100644 --- a/src/manager/crypto/tz-backend/internals.cpp +++ b/src/manager/crypto/tz-backend/internals.cpp @@ -136,6 +136,37 @@ RawBuffer importKey(const Data &data, return result; } + +RawBuffer importData(const Data &data, + const Password &pwd, + const RawBuffer &iv, + RawBuffer &tag) +{ + RawBuffer result; + RawBuffer pwdBuf(pwd.begin(), pwd.end()); + TrustZoneContext::Instance().importData(data.data, + pwdBuf, + iv, + result, + tag); + return result; +} + +RawBuffer getData(const RawBuffer &dataId, + const Pwd &pwd) +{ + RawBuffer result; + TrustZoneContext::Instance().getData(dataId, + pwd, + result); + return result; +} + +void destroyData(const RawBuffer &dataId) +{ + TrustZoneContext::Instance().destroyData(dataId); +} + BufferPair encryptDataAesGcm(const RawBuffer &key, const Pwd &pwd, const RawBuffer &iv, diff --git a/src/manager/crypto/tz-backend/internals.h b/src/manager/crypto/tz-backend/internals.h index c8af8c7..d9748e9 100644 --- a/src/manager/crypto/tz-backend/internals.h +++ b/src/manager/crypto/tz-backend/internals.h @@ -49,6 +49,17 @@ RawBuffer importKey(const Data &key, const Password &pwd, const RawBuffer &iv, RawBuffer &tag); + +RawBuffer importData(const Data &data, + const Password &pwd, + const RawBuffer &iv, + RawBuffer &tag); + +RawBuffer getData(const RawBuffer &dataId, + const Pwd &pwd); + +void destroyData(const RawBuffer &dataId); + void destroyKey(const RawBuffer &key); RawBuffer symmetricEncrypt( diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index 76cb253..3d0179b 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -101,20 +101,22 @@ Store::Store(CryptoBackend backendId) : GObjUPtr Store::getObject(const Token &token, const Password &pass) { int scheme; - RawBuffer data; + RawBuffer id; RawBuffer iv; RawBuffer tag; - unpack(token.data, scheme, data, iv, tag); + unpack(token.data, scheme, id, iv, tag); // TODO AKeys - if (token.dataType == DataType(DataType::KEY_AES)) - return make_unique(scheme, data, Pwd(pass, iv, tag), token.dataType); + if (token.dataType.isSKey()) + return make_unique(scheme, id, Pwd(pass, iv, tag), token.dataType); // TODO certificate/chaincert - if (token.dataType.isBinaryData()) - return make_unique(scheme, data, Pwd(pass, iv, tag), token.dataType); + if (token.dataType.isBinaryData()) { + RawBuffer exported_data = Internals::getData(id, Pwd(pass, iv, tag)); + return make_unique(scheme, exported_data, Pwd(pass, iv, tag), token.dataType); + } ThrowErr(Exc::Crypto::DataTypeNotSupported, "This type of data is not supported by trustzone backend: ", (int)token.dataType); @@ -142,6 +144,17 @@ Token Store::generateSKey(const CryptoAlgorithm &alg, const Password &pass) Token Store::import(const Data &data, const Password &pass) { + if (data.type.isBinaryData()) { + RawBuffer iv; + RawBuffer tag; + if (!pass.empty()) { + // IV is needed for data encryption with pwd + iv = Internals::generateIV(); + } + RawBuffer dataId = Internals::importData(data, pass, iv, tag); + return Token(m_backendId, data.type, pack(dataId, pass, iv, tag)); + } + if (!data.type.isKey()) ThrowErr(Exc::Crypto::InputParam, "Invalid data provided for import"); @@ -168,8 +181,13 @@ Token Store::importEncrypted(const Data &, const Password &, void Store::destroy(const Token &token) { - RawBuffer data = unpackData(token.data); - Internals::destroyKey(data); + RawBuffer id = unpackData(token.data); + if (token.dataType.isBinaryData()) { + // TODO this should be a generic "destroy persistent memory object" once + // serialization in key-manager-ta is unified + Internals::destroyData(id); + } + Internals::destroyKey(id); } } // namespace TZ diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index e088163..60dcd80 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -48,6 +48,21 @@ const uint32_t CIPHER_EXTRA_PADDING_SIZE = 16; // Identifier of our TA const TEEC_UUID KEY_MANAGER_TA_UUID = KM_TA_UUID; +//raw to hex string conversion to print persistent storage data ID +static std::string rawToHexString(const RawBuffer &raw) +{ + std::string dump; + + for (auto &e : raw) { + char buf[3]; + snprintf(buf, sizeof(buf), "%02x", (e & 0xff)); + dump.push_back(buf[0]); + dump.push_back(buf[1]); + } + + return dump; +} + } // anonymous namespace TrustZoneContext::TrustZoneContext() @@ -729,6 +744,271 @@ void TrustZoneContext::executeDestroy(const RawBuffer &keyId) Execute(CMD_DESTROY_KEY, &op); } +void TrustZoneContext::importData(const RawBuffer &data, + const RawBuffer &pwd, + const RawBuffer &iv, + RawBuffer &dataId, + RawBuffer &pwdTag) +{ + // command ID = CMD_IMPORT_DATA + // input: + // [1].memref - reference to serialized buffer: + // KM_BinaryData with binary data + // uint32_t boolean value - true if password is provided + // KM_PwdData with password (optional) + // Output: + // [0].value.a - return code + // [2].memref - reference to serialized buffer: + // KM_BinaryData with data id + // KM_BinaryData with tag id (optional, if password was provided) + KM_BinaryData kmTaData; + uint32_t pwd_flag = pwd.empty() ? 0 : 1; + uint32_t pwdTagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS; + kmTaData.data_size = static_cast(data.size()); + kmTaData.data = const_cast(data.data()); + uint32_t inMemorySize = KM_SizeOfBinaryData(&kmTaData) + KM_SizeOfFlag(); + KM_PwdData kmPwdData; + if (pwd_flag) { + memset(&kmPwdData, 0, sizeof(KM_PwdData)); + kmPwdData.pwd = const_cast(pwd.data()); + kmPwdData.pwd_size = pwd.size(); + kmPwdData.iv = const_cast(iv.data()); + kmPwdData.iv_size = iv.size(); + kmPwdData.tag = NULL; + kmPwdData.tag_size = 0; + kmPwdData.derive_len_bits = Params::DERIVED_KEY_LENGTH_BITS; + kmPwdData.it_count = Params::DERIVED_KEY_ITERATIONS; + kmPwdData.tag_len_bits = pwdTagSizeBits; + + inMemorySize += KM_SizeOfPwdData(&kmPwdData); + } + + TrustZoneMemory inMemory(m_Context, inMemorySize, TEEC_MEM_INPUT); + void *inMemoryPtr = inMemory.Get()->buffer; + + int ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &kmTaData); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + ret = KM_SerializeFlag(&inMemoryPtr, &inMemorySize, pwd_flag); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + if (pwd_flag) { + ret = KM_SerializePwdData(&inMemoryPtr, &inMemorySize, &kmPwdData); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + } + + KM_BinaryData kmDataId; + KM_BinaryData kmTag; + memset(&kmDataId, 0, sizeof(KM_BinaryData)); + memset(&kmTag, 0, sizeof(KM_BinaryData)); + kmDataId.data_size = KM_DATA_ID_SIZE; + uint32_t outMemorySize = KM_SizeOfBinaryData(&kmDataId); + if (pwd_flag) { + kmTag.data_size = pwdTagSizeBits / 8; + outMemorySize += KM_SizeOfBinaryData(&kmTag); + } + + TrustZoneMemory outMemory(m_Context, outMemorySize, TEEC_MEM_OUTPUT); + void *outMemoryPtr = outMemory.Get()->buffer; + + TEEC_Operation op; + op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_WHOLE, + TEEC_MEMREF_WHOLE, TEEC_NONE); + op.params[1].memref.parent = inMemory.Get(); + op.params[1].memref.offset = 0; + op.params[1].memref.size = inMemory.Get()->size; + op.params[2].memref.parent = outMemory.Get(); + op.params[2].memref.offset = 0; + op.params[2].memref.size = outMemory.Get()->size; + + Execute(CMD_IMPORT_DATA, &op); + + ret = KM_DeserializeBinaryData(&outMemoryPtr, &outMemorySize, &kmDataId); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to deserialize data, ret: ", ret); + } + dataId.resize(kmDataId.data_size); + memcpy(dataId.data(), kmDataId.data, kmDataId.data_size); + if (pwd_flag) { + ret = KM_DeserializeBinaryData(&outMemoryPtr, &outMemorySize, &kmTag); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to deserialize data, ret: ", ret); + } + pwdTag.resize(kmTag.data_size); + memcpy(pwdTag.data(), kmTag.data, kmTag.data_size); + } + + LogDebug("Imported object ID is (hex): " << rawToHexString(dataId)); +} + +void TrustZoneContext::GetDataSize(const RawBuffer &dataId, uint32_t &dataSize) +{ + // command ID = CMD_GET_DATA_SIZE + // TA will decrypt data with password if provided + // Parameters: + // [1].memref - reference to serialized buffer: + // KM_BinaryData with object ID + // Output: + // [0].value.a - return code + // [0].value.b - size of buffer to be passed from CA + LogDebug("Object ID (passed to CMD_GET_DATA_SIZE) is (hex): " << rawToHexString(dataId)); + KM_BinaryData kmDataId; + kmDataId.data_size = static_cast(dataId.size()); + kmDataId.data = const_cast(dataId.data()); + uint32_t inMemorySize = KM_SizeOfBinaryData(&kmDataId); + TrustZoneMemory inMemory(m_Context, inMemorySize, TEEC_MEM_INPUT); + void *inMemoryPtr = inMemory.Get()->buffer; + int ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &kmDataId); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to deserialize data, ret: ", ret); + } + TEEC_Operation op; + op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_OUTPUT, TEEC_MEMREF_WHOLE, + TEEC_NONE, TEEC_NONE); + + op.params[1].memref.parent = inMemory.Get(); + op.params[1].memref.offset = 0; + op.params[1].memref.size = inMemory.Get()->size; + Execute(CMD_GET_DATA_SIZE, &op); + dataSize = op.params[0].value.b; +} + +void TrustZoneContext::getData(const RawBuffer &dataId, + const Pwd &pwd, + RawBuffer &data) +{ + // command ID = CMD_GET_DATA + // TA will decrypt data with password if provided + // Parameters: + // [1].memref - reference to serialized buffer: + // KM_BinaryData with object ID + // uint32_t boolean value - true if password is provided + // KM_PwdData with password (optional) + // Output: + // [0].value.a - return code + // [2].memref - reference to serialized buffer: + // KM_BinaryData with binary data + LogDebug("Object ID (passed to CMD_GET_DATA) is (hex): " << rawToHexString(dataId)); + uint32_t data_size = 0; + GetDataSize(dataId, data_size); + + KM_BinaryData kmDataId; + kmDataId.data_size = static_cast(dataId.size()); + kmDataId.data = const_cast(dataId.data()); + uint32_t inMemorySize = KM_SizeOfBinaryData(&kmDataId) + KM_SizeOfFlag(); + uint32_t pwd_flag = pwd.getPassword().empty() ? 0 : 1; + uint32_t pwdTagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS; + + KM_PwdData kmPwdData; + if (pwd_flag) { + memset(&kmPwdData, 0, sizeof(KM_PwdData)); + kmPwdData.pwd = const_cast(pwd.getPassword().data()); + kmPwdData.pwd_size = pwd.getPassword().size(); + kmPwdData.iv = const_cast(pwd.getIV().data()); + kmPwdData.iv_size = pwd.getIV().size(); + kmPwdData.tag = const_cast(pwd.getTag().data()); + kmPwdData.tag_size = pwd.getTag().size(); + kmPwdData.derive_len_bits = Params::DERIVED_KEY_LENGTH_BITS; + kmPwdData.it_count = Params::DERIVED_KEY_ITERATIONS; + kmPwdData.tag_len_bits = pwdTagSizeBits; + + inMemorySize += KM_SizeOfPwdData(&kmPwdData); + } + + TrustZoneMemory inMemory(m_Context, inMemorySize, TEEC_MEM_INPUT); + void *inMemoryPtr = inMemory.Get()->buffer; + + int ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &kmDataId); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + ret = KM_SerializeFlag(&inMemoryPtr, &inMemorySize, pwd_flag); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + if (pwd_flag) { + ret = KM_SerializePwdData(&inMemoryPtr, &inMemorySize, &kmPwdData); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + } + + KM_BinaryData kmExtractedData; + memset(&kmExtractedData, 0, sizeof(KM_BinaryData)); + kmExtractedData.data_size = data_size; + + uint32_t outMemorySize = KM_SizeOfBinaryData(&kmExtractedData); + uint32_t outMemorySize2 = outMemorySize; + + TrustZoneMemory outMemory(m_Context, outMemorySize, TEEC_MEM_OUTPUT); + void *outMemoryPtr = outMemory.Get()->buffer; + void *outMemoryPtr2 = outMemory.Get()->buffer; + + // requesting size is saved in this buffer + ret = KM_SerializeBinaryData(&outMemoryPtr2, &outMemorySize2, &kmExtractedData); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + + TEEC_Operation op; + op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_WHOLE, + TEEC_MEMREF_WHOLE, TEEC_NONE); + op.params[1].memref.parent = inMemory.Get(); + op.params[1].memref.offset = 0; + op.params[1].memref.size = inMemory.Get()->size; + op.params[2].memref.parent = outMemory.Get(); + op.params[2].memref.offset = 0; + op.params[2].memref.size = outMemory.Get()->size; + + Execute(CMD_GET_DATA, &op); + + ret = KM_DeserializeBinaryData(&outMemoryPtr, &outMemorySize, &kmExtractedData); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + + data.resize(kmExtractedData.data_size); + memcpy(data.data(), kmExtractedData.data, kmExtractedData.data_size); +} + + +void TrustZoneContext::destroyData(const RawBuffer &dataId) +{ + // command ID = CMD_DESTROY_DATA + // TEEC_Operation parameters layout: + // input: + // [1].memref - reference to serialized buffer: + // KM_BinaryData with object ID + // output: + // [0].value.a - return code + LogDebug("Object ID (passed to CMD_GET_DATA) is (hex): " << rawToHexString(dataId)); + KM_BinaryData kmDataId; + kmDataId.data_size = static_cast(dataId.size()); + kmDataId.data = const_cast(dataId.data()); + uint32_t inMemorySize = KM_SizeOfBinaryData(&kmDataId); + TrustZoneMemory inMemory(m_Context, inMemorySize, TEEC_MEM_INPUT); + void *inMemoryPtr = inMemory.Get()->buffer; + + int ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &kmDataId); + + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + + TEEC_Operation op; + op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_OUTPUT, TEEC_MEMREF_WHOLE, + TEEC_NONE, TEEC_NONE); + + op.params[1].memref.parent = inMemory.Get(); + op.params[1].memref.offset = 0; + op.params[1].memref.size = inMemory.Get()->size; + Execute(CMD_DESTROY_DATA, &op); +} + void TrustZoneContext::Initialize() { TEEC_Operation op; diff --git a/src/manager/crypto/tz-backend/tz-context.h b/src/manager/crypto/tz-backend/tz-context.h index 86fe08b..2dd2497 100644 --- a/src/manager/crypto/tz-backend/tz-context.h +++ b/src/manager/crypto/tz-backend/tz-context.h @@ -81,6 +81,18 @@ public: void executeDestroy(const RawBuffer &keyId); + void importData(const RawBuffer &data, + const RawBuffer &pwd, + const RawBuffer &iv, + RawBuffer &dataId, + RawBuffer &pwdTag); + + void getData(const RawBuffer &dataId, + const Pwd &pwd, + RawBuffer &data); + + void destroyData(const RawBuffer &dataId); + private: TrustZoneContext(); ~TrustZoneContext(); @@ -91,6 +103,8 @@ private: void Destroy(); void Reload(); + void GetDataSize(const RawBuffer &dataId, uint32_t &dataSize); + void Execute(tz_command commandID, TEEC_Operation* op); TEEC_Context m_Context; -- 2.7.4 From 4cb37a79cc9b4f2b8d5389431e4d528e9ae74501 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Wed, 26 Sep 2018 17:14:20 +0200 Subject: [PATCH 09/16] Introduce Key class in tz backend Add an intermediate Key class that removes the need to keep credentials from binary data object (BData). Change-Id: I638de81aedf47bc51421a7c362459ced801fd650 --- src/manager/crypto/tz-backend/obj.h | 27 ++++++++++++++++++--------- src/manager/crypto/tz-backend/store.cpp | 2 +- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/manager/crypto/tz-backend/obj.h b/src/manager/crypto/tz-backend/obj.h index f3459c1..32c6444 100644 --- a/src/manager/crypto/tz-backend/obj.h +++ b/src/manager/crypto/tz-backend/obj.h @@ -59,15 +59,25 @@ private: class BData : public GObj { public: - BData(int scheme, RawBuffer buffer, Pwd pwd, DataType keyType): - m_scheme(scheme), m_raw(std::move(buffer)), m_password(std::move(pwd)), - m_type(keyType) {} + explicit BData(RawBuffer buffer) : m_raw(std::move(buffer)) {} virtual RawBuffer getBinary() const override { return m_raw; } +protected: + RawBuffer m_raw; +}; + +class Key : public BData { +public: + Key(int scheme, RawBuffer buffer, Pwd pwd, DataType dataType) : + BData(std::move(buffer)), + m_scheme(scheme), + m_password(std::move(pwd)), + m_type(dataType) {} + virtual int getScheme() const { return m_scheme; @@ -80,24 +90,23 @@ public: protected: int m_scheme; - RawBuffer m_raw; Pwd m_password; DataType m_type; }; -class SKey : public BData { +class SKey : public Key { public: - SKey(int scheme, RawBuffer buffer, Pwd pwd, DataType keyType) : - BData(scheme, std::move(buffer), std::move(pwd), keyType) {} + SKey(int scheme, RawBuffer buffer, Pwd pwd, DataType dataType) : + Key(scheme, std::move(buffer), std::move(pwd), dataType) {} virtual RawBuffer encrypt(const CryptoAlgorithm &, const RawBuffer &); virtual RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &); }; -class AKey : public BData { +class AKey : public Key { public: AKey(int scheme, RawBuffer buffer, Pwd pwd, DataType dataType) : - BData(scheme, std::move(buffer), std::move(pwd), dataType) {} + Key(scheme, std::move(buffer), std::move(pwd), dataType) {} virtual RawBuffer sign(const CryptoAlgorithm &alg, const RawBuffer &message); virtual int verify(const CryptoAlgorithm &alg, const RawBuffer &message, diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index 3d0179b..92aaad5 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -115,7 +115,7 @@ GObjUPtr Store::getObject(const Token &token, const Password &pass) if (token.dataType.isBinaryData()) { RawBuffer exported_data = Internals::getData(id, Pwd(pass, iv, tag)); - return make_unique(scheme, exported_data, Pwd(pass, iv, tag), token.dataType); + return make_unique(std::move(exported_data)); } ThrowErr(Exc::Crypto::DataTypeNotSupported, -- 2.7.4 From a42856cbf7fa08b9971cf689a535eef3da93fd90 Mon Sep 17 00:00:00 2001 From: Bartlomiej Grzelewski Date: Mon, 17 Sep 2018 17:09:47 +0200 Subject: [PATCH 10/16] Add backend attribute in xml schema Initial values may be saved in two locations: software backend and hardware backend. Until now there were no way to choose backend of to store initial values. Change-Id: Iaee057e8c78f6d3066e119adcf4e6fe174846990 --- doc/example.xml | 10 +--------- doc/initial_values.xsd | 42 +++++++++++++++++++++++++++--------------- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/doc/example.xml b/doc/example.xml index 2be09cf..cccc214 100644 --- a/doc/example.xml +++ b/doc/example.xml @@ -1,18 +1,10 @@ - + - - QL/5RW1VfS1uya04CWkVy1eykdhnRaTFiQ6Lcv0XFYhqgUKp6+PxxT1xjaz8TCVp - UcKorZayMPCuStRAylViZfxHFhXKR3awH+FcnGMZrhV6kORy39YCba0NGc5eAk3s - CBPYdRRiV7ejJSOI8n3zFjituVhHLcLuZB6xHvQQpQFFYV0BuF3BXfx6roP4+Olj - bZ1fYDrj8QIzqi3RV/ORGbl1BqHVRoMN/5XB+8oVKVn/EMRZPao4hnkV3pTI01Ss - Wid4fIHzBpi8rkkxr80/ym2BkeA/piaPNGOQtKjVfBOn/SuR2LQJreG6QbI6MYXC - ZVOanzc0euaenw1q9b+yEQ== - -----BEGIN PUBLIC KEY----- diff --git a/doc/initial_values.xsd b/doc/initial_values.xsd index 9a836fa..54672d9 100644 --- a/doc/initial_values.xsd +++ b/doc/initial_values.xsd @@ -3,21 +3,25 @@ - - - - - - - - - - - - + + + + + + + + + + + + + + + + @@ -37,6 +41,14 @@ + + + + + + + + -- 2.7.4 From f6e9b94fd69a801f9594b92e8fff59410a089736 Mon Sep 17 00:00:00 2001 From: Bartlomiej Grzelewski Date: Tue, 18 Sep 2018 15:49:00 +0200 Subject: [PATCH 11/16] Add parser support of new schema version Version 1 of xml with initial values is not supported from now. From now software backend will not support encrypted data. Allow parser to accept xml version 2. Initial values files will contain information about type of backend that should be used to store data. Change-Id: Ib3a73b14148a2476ab288ca364fffe9289400ebd --- src/manager/crypto/generic-backend/gstore.h | 24 +++++------------ src/manager/crypto/sw-backend/store.cpp | 27 +------------------ src/manager/crypto/sw-backend/store.h | 4 +-- src/manager/crypto/tz-backend/store.cpp | 7 ++--- src/manager/crypto/tz-backend/store.h | 7 ++--- src/manager/initial-values/InitialValueHandler.cpp | 30 ++++++++++++++-------- src/manager/initial-values/InitialValueHandler.h | 20 ++++++++++----- src/manager/initial-values/InitialValuesFile.cpp | 16 +++--------- src/manager/initial-values/InitialValuesFile.h | 3 +-- src/manager/service/ckm-logic.cpp | 13 +++++----- src/manager/service/ckm-logic.h | 4 +-- tests/test_generic-backend.cpp | 4 +-- tests/test_tz-backend.cpp | 4 +-- 13 files changed, 68 insertions(+), 95 deletions(-) diff --git a/src/manager/crypto/generic-backend/gstore.h b/src/manager/crypto/generic-backend/gstore.h index d66d9ea..564e4dd 100644 --- a/src/manager/crypto/generic-backend/gstore.h +++ b/src/manager/crypto/generic-backend/gstore.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -39,26 +39,15 @@ struct Data { RawBuffer data; // buffer will be better? }; -// Too generic. The name does not say anything aobut content. -struct DataEncryption { - DataEncryption() {} - DataEncryption(RawBuffer encKey, RawBuffer ivector) - : encryptedKey(std::move(encKey)) - , iv(std::move(ivector)) - { - } - RawBuffer encryptedKey; - RawBuffer iv; -}; - class GStore { public: virtual GObjUPtr getObject(const Token &, const Password &) { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual TokenPair generateAKey(const CryptoAlgorithm &, const Password &, - const Password &) + virtual TokenPair generateAKey(const CryptoAlgorithm &, + const Password &, + const Password &) { ThrowErr(Exc::Crypto::OperationNotSupported); } @@ -70,8 +59,9 @@ public: { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual Token importEncrypted(const Data &, const Password &, - const DataEncryption &) + virtual Token importEncrypted(const Data &, + const Password &, + const RawBuffer & /* iv */) { ThrowErr(Exc::Crypto::OperationNotSupported); } diff --git a/src/manager/crypto/sw-backend/store.cpp b/src/manager/crypto/sw-backend/store.cpp index 63cd046..6930873 100644 --- a/src/manager/crypto/sw-backend/store.cpp +++ b/src/manager/crypto/sw-backend/store.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -224,31 +224,6 @@ Token Store::import(const Data &data, const Password &pass) return Token(m_backendId, data.type, pack(data.data, pass)); } -Token Store::importEncrypted(const Data &data, const Password &pass, - const DataEncryption &enc) -{ - if (!m_deviceKey) - ThrowErr(Exc::Crypto::InternalError, "No device key present"); - - // decrypt the AES key using device key - CryptoAlgorithm algorithmRSAOAEP; - algorithmRSAOAEP.setParam(ParamName::ALGO_TYPE, AlgoType::RSA_OAEP); - Crypto::SW::SKey aesKey(m_deviceKey->decrypt(algorithmRSAOAEP, - enc.encryptedKey), DataType::KEY_AES); - - // decrypt the buffer using AES key - CryptoAlgorithm algorithmAESCBC; - algorithmAESCBC.setParam(ParamName::ALGO_TYPE, AlgoType::AES_CBC); - algorithmAESCBC.setParam(ParamName::ED_IV, enc.iv); - RawBuffer rawData = aesKey.decrypt(algorithmAESCBC, data.data); - - if (!Internals::verifyBinaryData(data.type, rawData)) - ThrowErr(Exc::Crypto::InputParam, - "Verification failed. Data could not be imported!"); - - return Token(m_backendId, data.type, pack(rawData, pass)); -} - } // namespace SW } // namespace Crypto } // namespace CKM diff --git a/src/manager/crypto/sw-backend/store.h b/src/manager/crypto/sw-backend/store.h index 6132b92..a12e561 100644 --- a/src/manager/crypto/sw-backend/store.h +++ b/src/manager/crypto/sw-backend/store.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -36,8 +36,6 @@ public: const Password &); virtual Token generateSKey(const CryptoAlgorithm &, const Password &); virtual Token import(const Data &data, const Password &); - virtual Token importEncrypted(const Data &, const Password &, - const DataEncryption &); virtual void destroy(const Token &) {} private: diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index 92aaad5..3404acb 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -172,8 +172,9 @@ Token Store::import(const Data &data, const Password &pass) return Token(m_backendId, data.type, pack(keyId, pass, iv, tag)); } -Token Store::importEncrypted(const Data &, const Password &, - const DataEncryption &) +Token Store::importEncrypted(const Data &, + const Password &, + const RawBuffer &) { ThrowErr(Exc::Crypto::OperationNotSupported, "Encrypted import is not yet supported on TrustZone backend!"); diff --git a/src/manager/crypto/tz-backend/store.h b/src/manager/crypto/tz-backend/store.h index 2eddfbe..706c341 100644 --- a/src/manager/crypto/tz-backend/store.h +++ b/src/manager/crypto/tz-backend/store.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -36,8 +36,9 @@ public: const Password &); virtual Token generateSKey(const CryptoAlgorithm &, const Password &); virtual Token import(const Data &, const Password &); - virtual Token importEncrypted(const Data &, const Password &, - const DataEncryption &); + virtual Token importEncrypted(const Data &, + const Password &, + const RawBuffer &); virtual void destroy(const Token &); // TODO device key ID is needed here to support importEncrypted diff --git a/src/manager/initial-values/InitialValueHandler.cpp b/src/manager/initial-values/InitialValueHandler.cpp index cd92dd6..acb2e4b 100644 --- a/src/manager/initial-values/InitialValueHandler.cpp +++ b/src/manager/initial-values/InitialValueHandler.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -32,6 +32,9 @@ namespace { const char *const XML_ATTR_NAME = "name"; const char *const XML_ATTR_PASSWORD = "password"; const char *const XML_ATTR_EXPORTABLE = "exportable"; +const char *const XML_ATTR_BACKEND = "backend"; +const char *const XML_ATTR_BACKEND_SW = "software"; +const char *const XML_ATTR_BACKEND_HW = "hardware"; } namespace CKM { @@ -54,6 +57,15 @@ void InitialValueHandler::Start(const XML::Parser::Attributes &attr) std::istringstream is(flagVal); is >> std::boolalpha >> m_exportable; } + + // get backend + if (attr.find(XML_ATTR_BACKEND) != attr.end()) { + std::string value = attr.at(XML_ATTR_BACKEND); + if (value == XML_ATTR_BACKEND_SW) + m_backend = PolicyBackend::FORCE_SOFTWARE; + else if (value == XML_ATTR_BACKEND_HW) + m_backend = PolicyBackend::FORCE_HARDWARE; + } } void InitialValueHandler::End() @@ -64,19 +76,17 @@ void InitialValueHandler::End() } // save data - Policy policy(m_password, m_exportable); + Policy policy(m_password, m_exportable, m_backend); - Crypto::DataEncryption de; + RawBuffer iv; - if (m_bufferHandler->isEncrypted()) { - de.encryptedKey = m_encryptedKey; - de.iv = m_bufferHandler->getIV(); - } + if (m_bufferHandler->isEncrypted()) + iv = m_bufferHandler->getIV(); int ec = m_db_logic.importInitialData(m_name, - Crypto::Data(getDataType(), m_bufferHandler->getData()), - de, - policy); + Crypto::Data(getDataType(), m_bufferHandler->getData()), + iv, + policy); if (CKM_API_SUCCESS != ec) { LogError("Saving type: " << getDataType() << " with params: name(" << diff --git a/src/manager/initial-values/InitialValueHandler.h b/src/manager/initial-values/InitialValueHandler.h index 5a73ee9..f8d8a25 100644 --- a/src/manager/initial-values/InitialValueHandler.h +++ b/src/manager/initial-values/InitialValueHandler.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -39,9 +39,13 @@ class InitialValueHandler : public NoCharactersHandler { public: typedef std::shared_ptr InitialValueHandlerPtr; - explicit InitialValueHandler(CKMLogic &db_logic, - const CKM::RawBuffer &encryptedKey) - : m_exportable(false), m_db_logic(db_logic), m_encryptedKey(encryptedKey) {} + explicit InitialValueHandler(CKMLogic &db_logic, const CKM::RawBuffer &encryptedKey) : + m_exportable(false), + m_backend(PolicyBackend::DEFAULT), + m_db_logic(db_logic), + m_encryptedKey(encryptedKey) + {} + virtual ~InitialValueHandler() {} BufferHandler::BufferHandlerPtr CreateBufferHandler(EncodingType type); @@ -52,9 +56,11 @@ public: protected: virtual DataType getDataType() const = 0; - Alias m_name; - Password m_password; - bool m_exportable; + Alias m_name; + Password m_password; + bool m_exportable; + PolicyBackend m_backend; + CKMLogic &m_db_logic; const CKM::RawBuffer &m_encryptedKey; diff --git a/src/manager/initial-values/InitialValuesFile.cpp b/src/manager/initial-values/InitialValuesFile.cpp index 854567e..8108af1 100644 --- a/src/manager/initial-values/InitialValuesFile.cpp +++ b/src/manager/initial-values/InitialValuesFile.cpp @@ -33,9 +33,8 @@ #include namespace { -const int XML_CURRENT_VERSION = 1; +const int XML_CURRENT_VERSION = 2; const char *const XML_TAG_INITIAL_VALUES = "InitialValues"; -const char *const XML_TAG_ENCRYPTION_KEY = "EncryptionKey"; const char *const XML_TAG_KEY = "Key"; const char *const XML_TAG_DATA = "Data"; const char *const XML_TAG_CERT = "Cert"; @@ -56,8 +55,7 @@ namespace InitialValues { InitialValuesFile::InitialValuesFile(const std::string &XML_filename, CKMLogic &db_logic) : m_parser(XML_filename), m_db_logic(db_logic), - m_header(std::make_shared(*this)), - m_encryptionKeyHandler(std::make_shared(*this)) + m_header(std::make_shared(*this)) { m_parser.RegisterErrorCb(InitialValuesFile::Error); m_parser.RegisterElementCb(XML_TAG_INITIAL_VALUES, @@ -65,13 +63,6 @@ InitialValuesFile::InitialValuesFile(const std::string &XML_filename, return m_header; }, [this](const XML::Parser::ElementHandlerPtr &) {}); - m_parser.RegisterElementCb(XML_TAG_ENCRYPTION_KEY, - [this]() -> XML::Parser::ElementHandlerPtr { - return m_encryptionKeyHandler; - }, - [this](const XML::Parser::ElementHandlerPtr &) { - m_encryptedAESkey = m_encryptionKeyHandler->getEncryptedKey(); - }); } void InitialValuesFile::registerElementListeners() @@ -290,9 +281,10 @@ void InitialValuesFile::HeaderHandler::Start(const XML::Parser::Attributes m_parent.registerElementListeners(); } } + bool InitialValuesFile::HeaderHandler::isCorrectVersion() const { - return m_version == XML_CURRENT_VERSION; + return XML_CURRENT_VERSION == m_version; } } diff --git a/src/manager/initial-values/InitialValuesFile.h b/src/manager/initial-values/InitialValuesFile.h index a11747b..51a478e 100644 --- a/src/manager/initial-values/InitialValuesFile.h +++ b/src/manager/initial-values/InitialValuesFile.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -97,7 +97,6 @@ private: typedef std::shared_ptr HeaderHandlerPtr; typedef std::shared_ptr EncryptionKeyHandlerPtr; HeaderHandlerPtr m_header; - EncryptionKeyHandlerPtr m_encryptionKeyHandler; CKM::RawBuffer m_encryptedAESkey; void registerElementListeners(); diff --git a/src/manager/service/ckm-logic.cpp b/src/manager/service/ckm-logic.cpp index f3c2154..e988b7f 100644 --- a/src/manager/service/ckm-logic.cpp +++ b/src/manager/service/ckm-logic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014 - 2018 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. @@ -1159,7 +1159,7 @@ RawBuffer CKMLogic::getDataList( int CKMLogic::importInitialData( const Name &name, const Crypto::Data &data, - const Crypto::DataEncryption &enc, + const RawBuffer &iv, const Policy &policy) { try { @@ -1175,21 +1175,22 @@ int CKMLogic::importInitialData( if (retCode != CKM_API_SUCCESS) return retCode; - Crypto::GStore &store = m_decider.getStore(data.type, policy, !enc.encryptedKey.empty()); + Crypto::GStore &store = m_decider.getStore(data.type, policy, !iv.empty()); Token token; - if (enc.encryptedKey.empty()) { + if (iv.empty()) { Crypto::Data binaryData; if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData))) return retCode; token = store.import(binaryData, - m_accessControl.isCCMode() ? "" : policy.password); + m_accessControl.isCCMode() ? "" : policy.password); } else { token = store.importEncrypted(data, - m_accessControl.isCCMode() ? "" : policy.password, enc); + m_accessControl.isCCMode() ? "" : policy.password, + iv); } DB::Row row(std::move(token), name, CLIENT_ID_SYSTEM, diff --git a/src/manager/service/ckm-logic.h b/src/manager/service/ckm-logic.h index 95048cb..8115117 100644 --- a/src/manager/service/ckm-logic.h +++ b/src/manager/service/ckm-logic.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2014 - 2018 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. @@ -209,7 +209,7 @@ public: int importInitialData( const Name &name, const Crypto::Data &data, - const Crypto::DataEncryption &enc, + const RawBuffer &iv, const Policy &policy); int unlockSystemDB(); diff --git a/tests/test_generic-backend.cpp b/tests/test_generic-backend.cpp index c2e80a0..114d794 100644 --- a/tests/test_generic-backend.cpp +++ b/tests/test_generic-backend.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2017 - 2018 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. @@ -75,7 +75,7 @@ BOOST_AUTO_TEST_CASE(gstore) BOOST_REQUIRE_THROW(store.import(Crypto::Data(), Password()), Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.importEncrypted(Crypto::Data(), Password(), - Crypto::DataEncryption()), + RawBuffer()), Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.destroy(Token()), Exc::Crypto::OperationNotSupported); diff --git a/tests/test_tz-backend.cpp b/tests/test_tz-backend.cpp index 745d3f8..853326c 100644 --- a/tests/test_tz-backend.cpp +++ b/tests/test_tz-backend.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2017 - 2018 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. @@ -32,7 +32,7 @@ BOOST_AUTO_TEST_CASE(store) Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.import(Data(), Password()), Exc::Crypto::OperationNotSupported); - BOOST_REQUIRE_THROW(store.importEncrypted(Data(), Password(), DataEncryption()), + BOOST_REQUIRE_THROW(store.importEncrypted(Data(), Password(), RawBuffer()), Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_NO_THROW(store.destroy(Token())); } -- 2.7.4 From 2e5203cfd1f18b4c86dcab6e594d66ff8d0b8c95 Mon Sep 17 00:00:00 2001 From: Bartlomiej Grzelewski Date: Fri, 21 Sep 2018 12:41:37 +0200 Subject: [PATCH 12/16] Unification of import methods in gstore Change-Id: I31dca502533360b759d6aea20e75a9e823eccc34 --- src/manager/crypto/generic-backend/gstore.h | 14 +++++++------- src/manager/crypto/sw-backend/store.cpp | 6 +++++- src/manager/crypto/sw-backend/store.h | 2 +- src/manager/crypto/tz-backend/internals.cpp | 8 +++++--- src/manager/crypto/tz-backend/internals.h | 5 +++-- src/manager/crypto/tz-backend/store.cpp | 12 ++---------- src/manager/crypto/tz-backend/store.h | 5 +---- src/manager/crypto/tz-backend/tz-context.cpp | 10 ++++++---- src/manager/crypto/tz-backend/tz-context.h | 5 +++-- src/manager/initial-values/BufferHandler.h | 10 +--------- src/manager/initial-values/InitialValueHandler.cpp | 7 +------ src/manager/service/ckm-logic.cpp | 15 +++++++++------ tests/test_crypto-logic.cpp | 6 +++--- tests/test_generic-backend.cpp | 5 +---- tests/test_tz-backend.cpp | 4 +--- 15 files changed, 49 insertions(+), 65 deletions(-) diff --git a/src/manager/crypto/generic-backend/gstore.h b/src/manager/crypto/generic-backend/gstore.h index 564e4dd..2984fdc 100644 --- a/src/manager/crypto/generic-backend/gstore.h +++ b/src/manager/crypto/generic-backend/gstore.h @@ -55,13 +55,13 @@ public: { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual Token import(const Data &, const Password &) - { - ThrowErr(Exc::Crypto::OperationNotSupported); - } - virtual Token importEncrypted(const Data &, - const Password &, - const RawBuffer & /* iv */) + + /* + * IV parameter makes sense only on device with built in key. + * IV parameter is used for decryption of Data. + * If Data is not encrypted it's ok to pass empty IV. + */ + virtual Token import(const Data &, const Password &, const RawBuffer & /* iv */) { ThrowErr(Exc::Crypto::OperationNotSupported); } diff --git a/src/manager/crypto/sw-backend/store.cpp b/src/manager/crypto/sw-backend/store.cpp index 6930873..b41b8fd 100644 --- a/src/manager/crypto/sw-backend/store.cpp +++ b/src/manager/crypto/sw-backend/store.cpp @@ -219,8 +219,12 @@ Token Store::generateSKey(const CryptoAlgorithm &algorithm, return Token(m_backendId, ret.type, pack(ret.buffer, pass)); } -Token Store::import(const Data &data, const Password &pass) +Token Store::import(const Data &data, const Password &pass, const RawBuffer &iv) { + if (!iv.empty()) + ThrowErr(Exc::Crypto::OperationNotSupported, + "Encrypted import is not yet supported on software backend!"); + return Token(m_backendId, data.type, pack(data.data, pass)); } diff --git a/src/manager/crypto/sw-backend/store.h b/src/manager/crypto/sw-backend/store.h index a12e561..82798cd 100644 --- a/src/manager/crypto/sw-backend/store.h +++ b/src/manager/crypto/sw-backend/store.h @@ -35,7 +35,7 @@ public: virtual TokenPair generateAKey(const CryptoAlgorithm &, const Password &, const Password &); virtual Token generateSKey(const CryptoAlgorithm &, const Password &); - virtual Token import(const Data &data, const Password &); + virtual Token import(const Data &data, const Password &, const RawBuffer &); virtual void destroy(const Token &) {} private: diff --git a/src/manager/crypto/tz-backend/internals.cpp b/src/manager/crypto/tz-backend/internals.cpp index 578241d..03189d4 100644 --- a/src/manager/crypto/tz-backend/internals.cpp +++ b/src/manager/crypto/tz-backend/internals.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2017 - 2018 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. @@ -119,8 +119,9 @@ void destroyKey(const RawBuffer &key) } RawBuffer importKey(const Data &data, + const RawBuffer &encIV, const Password &pwd, - const RawBuffer &iv, + const RawBuffer &pwdIV, RawBuffer &tag) { tz_algo_type algo = getAlgType(data.type); @@ -129,8 +130,9 @@ RawBuffer importKey(const Data &data, RawBuffer pwdBuf(pwd.begin(), pwd.end()); TrustZoneContext::Instance().importKey(algo, data.data, + encIV, pwdBuf, - iv, + pwdIV, result, tag); return result; diff --git a/src/manager/crypto/tz-backend/internals.h b/src/manager/crypto/tz-backend/internals.h index d9748e9..1fed4b0 100644 --- a/src/manager/crypto/tz-backend/internals.h +++ b/src/manager/crypto/tz-backend/internals.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2017 - 2018 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. @@ -46,8 +46,9 @@ Data generateSKey(const CryptoAlgorithm &alg, const RawBuffer &iv, RawBuffer &tag); RawBuffer importKey(const Data &key, + const RawBuffer &encIV, const Password &pwd, - const RawBuffer &iv, + const RawBuffer &pwdIV, RawBuffer &tag); RawBuffer importData(const Data &data, diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index 3404acb..c688024 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -142,7 +142,7 @@ Token Store::generateSKey(const CryptoAlgorithm &alg, const Password &pass) return Token(m_backendId, ret.type, pack(ret.data, pass, iv, tag)); } -Token Store::import(const Data &data, const Password &pass) +Token Store::import(const Data &data, const Password &pass, const RawBuffer &encIV) { if (data.type.isBinaryData()) { RawBuffer iv; @@ -168,18 +168,10 @@ Token Store::import(const Data &data, const Password &pass) iv = Internals::generateIV(); } - RawBuffer keyId = Internals::importKey(data, pass, iv, tag); + RawBuffer keyId = Internals::importKey(data, encIV, pass, iv, tag); return Token(m_backendId, data.type, pack(keyId, pass, iv, tag)); } -Token Store::importEncrypted(const Data &, - const Password &, - const RawBuffer &) -{ - ThrowErr(Exc::Crypto::OperationNotSupported, - "Encrypted import is not yet supported on TrustZone backend!"); -} - void Store::destroy(const Token &token) { RawBuffer id = unpackData(token.data); diff --git a/src/manager/crypto/tz-backend/store.h b/src/manager/crypto/tz-backend/store.h index 706c341..4d44b6b 100644 --- a/src/manager/crypto/tz-backend/store.h +++ b/src/manager/crypto/tz-backend/store.h @@ -35,10 +35,7 @@ public: virtual TokenPair generateAKey(const CryptoAlgorithm &, const Password &, const Password &); virtual Token generateSKey(const CryptoAlgorithm &, const Password &); - virtual Token import(const Data &, const Password &); - virtual Token importEncrypted(const Data &, - const Password &, - const RawBuffer &); + virtual Token import(const Data &, const Password &, const RawBuffer &); virtual void destroy(const Token &); // TODO device key ID is needed here to support importEncrypted diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index 60dcd80..1387491 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2017 - 2018 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. @@ -257,11 +257,13 @@ void TrustZoneContext::generateSKeyPwd(tz_algo_type algo, void TrustZoneContext::importKey(tz_algo_type algo, const RawBuffer &key, + const RawBuffer &encIV, const RawBuffer &pwd, - const RawBuffer &iv, + const RawBuffer &pwdIV, RawBuffer &keyId, RawBuffer &pwdTag) { + (void)encIV; // command ID = CMD_IMPORT_KEY // // TEEC_Operation layout: @@ -280,7 +282,7 @@ void TrustZoneContext::importKey(tz_algo_type algo, if (!pwd.empty()) { bufSize.with_pwd_data = true; bufSize.pwd_size = static_cast(pwd.size()); - bufSize.pwd_iv_size = static_cast(iv.size()); + bufSize.pwd_iv_size = static_cast(pwdIV.size()); } uint32_t inMemorySize = KM_CalcBufferSize(bufSize); TrustZoneMemory inMemory(m_Context, inMemorySize, TEEC_MEM_INPUT); @@ -303,7 +305,7 @@ void TrustZoneContext::importKey(tz_algo_type algo, } if (!pwd.empty()) { - ret = KM_ParamsSerializePwdData(input, pwd.data(), pwd.size(), iv.data(), iv.size(), + ret = KM_ParamsSerializePwdData(input, pwd.data(), pwd.size(), pwdIV.data(), pwdIV.size(), nullptr, 0, Params::DERIVED_KEY_LENGTH_BITS, Params::DERIVED_KEY_ITERATIONS, bufSize.tag_size * 8); if (ret) { diff --git a/src/manager/crypto/tz-backend/tz-context.h b/src/manager/crypto/tz-backend/tz-context.h index 2dd2497..cd7ae74 100644 --- a/src/manager/crypto/tz-backend/tz-context.h +++ b/src/manager/crypto/tz-backend/tz-context.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2017 - 2018 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. @@ -49,8 +49,9 @@ public: RawBuffer &pwdTag); void importKey(tz_algo_type algo, const RawBuffer &key, + const RawBuffer &encIV, const RawBuffer &pwd, - const RawBuffer &iv, + const RawBuffer &pwdIV, RawBuffer &keyId, RawBuffer &pwdTag); diff --git a/src/manager/initial-values/BufferHandler.h b/src/manager/initial-values/BufferHandler.h index 572244d..08bca52 100644 --- a/src/manager/initial-values/BufferHandler.h +++ b/src/manager/initial-values/BufferHandler.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2015 - 2018 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. @@ -47,14 +47,6 @@ public: return m_data; } - bool isEncrypted() const - { - if (m_encoding == EncodingType::ENCRYPTED) - return true; - - return false; - } - const RawBuffer &getIV() const { return m_IV; diff --git a/src/manager/initial-values/InitialValueHandler.cpp b/src/manager/initial-values/InitialValueHandler.cpp index acb2e4b..7853d39 100644 --- a/src/manager/initial-values/InitialValueHandler.cpp +++ b/src/manager/initial-values/InitialValueHandler.cpp @@ -78,14 +78,9 @@ void InitialValueHandler::End() // save data Policy policy(m_password, m_exportable, m_backend); - RawBuffer iv; - - if (m_bufferHandler->isEncrypted()) - iv = m_bufferHandler->getIV(); - int ec = m_db_logic.importInitialData(m_name, Crypto::Data(getDataType(), m_bufferHandler->getData()), - iv, + m_bufferHandler->getIV(), policy); if (CKM_API_SUCCESS != ec) { diff --git a/src/manager/service/ckm-logic.cpp b/src/manager/service/ckm-logic.cpp index e988b7f..98248ec 100644 --- a/src/manager/service/ckm-logic.cpp +++ b/src/manager/service/ckm-logic.cpp @@ -404,7 +404,8 @@ DB::Row CKMLogic::createEncryptedRow( // do not encrypt data with password during cc_mode on Token token = store.import(data, - m_accessControl.isCCMode() ? "" : policy.password); + m_accessControl.isCCMode() ? "" : policy.password, + RawBuffer()); DB::Row row(std::move(token), name, owner, static_cast(policy.extractable)); crypto.encryptRow(row); @@ -803,7 +804,7 @@ Crypto::GObjUPtr CKMLogic::rowToObject( store.destroy(row); // import it to store with new scheme: data -> pass(data) - Token token = store.import(Crypto::Data(row.dataType, row.data), pass); + Token token = store.import(Crypto::Data(row.dataType, row.data), pass, RawBuffer()); // get it from the store (it can be different than the data we imported into store) obj = store.getObject(token, pass); @@ -1180,17 +1181,19 @@ int CKMLogic::importInitialData( Token token; if (iv.empty()) { + // Data are not encrypted, let's try to verify them Crypto::Data binaryData; if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData))) return retCode; token = store.import(binaryData, - m_accessControl.isCCMode() ? "" : policy.password); + m_accessControl.isCCMode() ? "" : policy.password, + iv); } else { - token = store.importEncrypted(data, - m_accessControl.isCCMode() ? "" : policy.password, - iv); + token = store.import(data, + m_accessControl.isCCMode() ? "" : policy.password, + iv); } DB::Row row(std::move(token), name, CLIENT_ID_SYSTEM, diff --git a/tests/test_crypto-logic.cpp b/tests/test_crypto-logic.cpp index 5784365..f519e27 100644 --- a/tests/test_crypto-logic.cpp +++ b/tests/test_crypto-logic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000 - 2017 Samsung Electronics Co., Ltd All Rights Reserved + * Copyright (c) 2017 - 2018 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. @@ -91,7 +91,7 @@ BOOST_AUTO_TEST_CASE(row_encryption) Crypto::Data data(DataType(DataType::Type::BINARY_DATA), createRandom(10)); Crypto::Decider decider; Crypto::GStore &store = decider.getStore(data.type, policy); - Token token = store.import(data, policy.password); + Token token = store.import(data, policy.password, RawBuffer()); Name name = "test_data"; ClientId owner = "test_owner"; @@ -113,7 +113,7 @@ BOOST_AUTO_TEST_CASE(row_encryption_negatives) Crypto::Data data(DataType(DataType::Type::BINARY_DATA), createRandom(10)); Crypto::Decider decider; Crypto::GStore &store = decider.getStore(data.type, policy); - Token token = store.import(data, policy.password); + Token token = store.import(data, policy.password, RawBuffer()); Name name = "test_data"; ClientId owner = "test_owner"; diff --git a/tests/test_generic-backend.cpp b/tests/test_generic-backend.cpp index 114d794..0b39bf3 100644 --- a/tests/test_generic-backend.cpp +++ b/tests/test_generic-backend.cpp @@ -72,10 +72,7 @@ BOOST_AUTO_TEST_CASE(gstore) Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.generateSKey(CryptoAlgorithm(), Password()), Exc::Crypto::OperationNotSupported); - BOOST_REQUIRE_THROW(store.import(Crypto::Data(), Password()), - Exc::Crypto::OperationNotSupported); - BOOST_REQUIRE_THROW(store.importEncrypted(Crypto::Data(), Password(), - RawBuffer()), + BOOST_REQUIRE_THROW(store.import(Crypto::Data(), Password(), RawBuffer()), Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.destroy(Token()), Exc::Crypto::OperationNotSupported); diff --git a/tests/test_tz-backend.cpp b/tests/test_tz-backend.cpp index 853326c..880211b 100644 --- a/tests/test_tz-backend.cpp +++ b/tests/test_tz-backend.cpp @@ -30,9 +30,7 @@ BOOST_AUTO_TEST_CASE(store) Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.generateAKey(CryptoAlgorithm(), Password(), Password()), Exc::Crypto::OperationNotSupported); - BOOST_REQUIRE_THROW(store.import(Data(), Password()), - Exc::Crypto::OperationNotSupported); - BOOST_REQUIRE_THROW(store.importEncrypted(Data(), Password(), RawBuffer()), + BOOST_REQUIRE_THROW(store.import(Data(), Password(), RawBuffer()), Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_NO_THROW(store.destroy(Token())); } -- 2.7.4 From 78b884add004bc306a81bb79e91aacab44cb98a9 Mon Sep 17 00:00:00 2001 From: Bartlomiej Grzelewski Date: Tue, 25 Sep 2018 13:39:22 +0200 Subject: [PATCH 13/16] Reduce number of import methods in tz-backend Change-Id: I44fe9737dd34d8b61d2ab099c3f611903a5cc9a1 --- src/manager/crypto/tz-backend/internals.cpp | 44 ++++--- src/manager/crypto/tz-backend/internals.h | 18 +-- src/manager/crypto/tz-backend/store.cpp | 29 ++--- src/manager/crypto/tz-backend/tz-context.cpp | 164 ++++++++------------------- src/manager/crypto/tz-backend/tz-context.h | 12 +- 5 files changed, 90 insertions(+), 177 deletions(-) diff --git a/src/manager/crypto/tz-backend/internals.cpp b/src/manager/crypto/tz-backend/internals.cpp index 03189d4..90cc9fb 100644 --- a/src/manager/crypto/tz-backend/internals.cpp +++ b/src/manager/crypto/tz-backend/internals.cpp @@ -118,42 +118,40 @@ void destroyKey(const RawBuffer &key) TrustZoneContext::Instance().executeDestroy(key); } -RawBuffer importKey(const Data &data, - const RawBuffer &encIV, - const Password &pwd, - const RawBuffer &pwdIV, - RawBuffer &tag) +RawBuffer importData(const Data &data, + const RawBuffer &encIV, + const Password &pwd, + const RawBuffer &pwdIV, + RawBuffer &tag) { - tz_algo_type algo = getAlgType(data.type); + + uint32_t dataType; + + if (data.type.isSKey()) { + dataType = TYPE_SKEY; + } else if (data.type.isBinaryData()) { + dataType = TYPE_GENERIC_SECRET; + } else { + ThrowErr(Exc::Crypto::DataTypeNotSupported, + "Data type could not be impoted by tz-backend"); + } + RawBuffer result; RawBuffer pwdBuf(pwd.begin(), pwd.end()); - TrustZoneContext::Instance().importKey(algo, + uint32_t keySizeBits = data.data.size() * 8; + TrustZoneContext::Instance().importData(dataType, data.data, encIV, pwdBuf, pwdIV, + keySizeBits, + Params::DERIVED_KEY_LENGTH_BITS, result, tag); return result; } - -RawBuffer importData(const Data &data, - const Password &pwd, - const RawBuffer &iv, - RawBuffer &tag) -{ - RawBuffer result; - RawBuffer pwdBuf(pwd.begin(), pwd.end()); - TrustZoneContext::Instance().importData(data.data, - pwdBuf, - iv, - result, - tag); - return result; -} - RawBuffer getData(const RawBuffer &dataId, const Pwd &pwd) { diff --git a/src/manager/crypto/tz-backend/internals.h b/src/manager/crypto/tz-backend/internals.h index 1fed4b0..c27933b 100644 --- a/src/manager/crypto/tz-backend/internals.h +++ b/src/manager/crypto/tz-backend/internals.h @@ -38,23 +38,21 @@ using BufferPair = std::pair; using KeyIdPair = std::pair; RawBuffer generateIV(); + DataPair generateAKey(const CryptoAlgorithm &alg, const Password &pwd, const RawBuffer &iv); + Data generateSKey(const CryptoAlgorithm &alg, const Password &pwd, const RawBuffer &iv, RawBuffer &tag); -RawBuffer importKey(const Data &key, - const RawBuffer &encIV, - const Password &pwd, - const RawBuffer &pwdIV, - RawBuffer &tag); -RawBuffer importData(const Data &data, - const Password &pwd, - const RawBuffer &iv, - RawBuffer &tag); +RawBuffer importData(const Data &key, + const RawBuffer &encIV, + const Password &pwd, + const RawBuffer &pwdIV, + RawBuffer &tag); RawBuffer getData(const RawBuffer &dataId, const Pwd &pwd); @@ -68,6 +66,7 @@ RawBuffer symmetricEncrypt( const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &data); + RawBuffer symmetricDecrypt( const RawBuffer &key, const Pwd &pwd, @@ -79,6 +78,7 @@ RawBuffer asymmetricEncrypt( const Pwd &pwd, const CryptoAlgorithm &alg, const RawBuffer &data); + RawBuffer asymmetricDecrypt( const RawBuffer &key, const Pwd &pwd, diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index c688024..a3d65c7 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -144,32 +144,19 @@ Token Store::generateSKey(const CryptoAlgorithm &alg, const Password &pass) Token Store::import(const Data &data, const Password &pass, const RawBuffer &encIV) { - if (data.type.isBinaryData()) { - RawBuffer iv; - RawBuffer tag; - if (!pass.empty()) { - // IV is needed for data encryption with pwd - iv = Internals::generateIV(); - } - RawBuffer dataId = Internals::importData(data, pass, iv, tag); - return Token(m_backendId, data.type, pack(dataId, pass, iv, tag)); - } - - if (!data.type.isKey()) - ThrowErr(Exc::Crypto::InputParam, "Invalid data provided for import"); + if (!data.type.isBinaryData() && !data.type.isSKey()) + ThrowErr(Exc::Crypto::DataTypeNotSupported, "Invalid data provided for import"); - if (!data.type.isSKey()) - ThrowErr(Exc::Crypto::DataTypeNotSupported, "Asymmetric keys are not supported"); - - RawBuffer iv; + RawBuffer passIV; RawBuffer tag; + if (!pass.empty()) { - // IV is needed for key encryption - iv = Internals::generateIV(); + // IV is needed for data encryption with pwd + passIV = Internals::generateIV(); } - RawBuffer keyId = Internals::importKey(data, encIV, pass, iv, tag); - return Token(m_backendId, data.type, pack(keyId, pass, iv, tag)); + RawBuffer dataId = Internals::importData(data, encIV, pass, passIV, tag); + return Token(m_backendId, data.type, pack(dataId, pass, passIV, tag)); } void Store::destroy(const Token &token) diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index 1387491..859c5a2 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -254,114 +254,6 @@ void TrustZoneContext::generateSKeyPwd(tz_algo_type algo, memcpy(pwdTag.data(), tagData->data, Params::DEFAULT_AES_GCM_TAG_LEN_BYTES); } - -void TrustZoneContext::importKey(tz_algo_type algo, - const RawBuffer &key, - const RawBuffer &encIV, - const RawBuffer &pwd, - const RawBuffer &pwdIV, - RawBuffer &keyId, - RawBuffer &pwdTag) -{ - (void)encIV; - // command ID = CMD_IMPORT_KEY - // - // TEEC_Operation layout: - // params: - // [0].value.a - key type - // [0].value.b - key size in bits - // [1].memref - seralized key & password data - // output: - // [0].value.a - return code - // [2].memref - serialized key reference ID - - KM_BufferSizeDesc bufSize; - - memset(&bufSize, 0, sizeof(KM_BufferSizeDesc)); - bufSize.input_size = static_cast(key.size()); - if (!pwd.empty()) { - bufSize.with_pwd_data = true; - bufSize.pwd_size = static_cast(pwd.size()); - bufSize.pwd_iv_size = static_cast(pwdIV.size()); - } - uint32_t inMemorySize = KM_CalcBufferSize(bufSize); - TrustZoneMemory inMemory(m_Context, inMemorySize, TEEC_MEM_INPUT); - - memset(&bufSize, 0, sizeof(KM_BufferSizeDesc)); - bufSize.out_size = KM_KEY_ID_SIZE; - bufSize.tag_size = Params::DEFAULT_AES_GCM_TAG_LEN_BYTES; - uint32_t keyMemorySize = KM_CalcBufferSize(bufSize); - TrustZoneMemory keyMemory(m_Context, keyMemorySize, TEEC_MEM_OUTPUT); - - KM_SymmetricInput* input = nullptr; - int ret = KM_ParamsSerializationInit(inMemory.Get()->buffer, inMemory.Get()->size, &input); - if (ret) { - ThrowErr(Exc::Crypto::InternalError, "Failed to initialize data serialization for key import: ", ret); - } - - ret = KM_ParamsSerializeInputData(input, key.data(), key.size()); - if (ret) { - ThrowErr(Exc::Crypto::InternalError, "Failed to serialize key to import: ", ret); - } - - if (!pwd.empty()) { - ret = KM_ParamsSerializePwdData(input, pwd.data(), pwd.size(), pwdIV.data(), pwdIV.size(), - nullptr, 0, Params::DERIVED_KEY_LENGTH_BITS, - Params::DERIVED_KEY_ITERATIONS, bufSize.tag_size * 8); - if (ret) { - ThrowErr(Exc::Crypto::InternalError, "Failed to serialize key data for import: ", ret); - } - } - - TEEC_Operation op; - op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_WHOLE, - TEEC_MEMREF_WHOLE, TEEC_NONE); - op.params[0].value.a = algo; - op.params[0].value.b = key.size() * 8; - op.params[1].memref.parent = inMemory.Get(); - op.params[1].memref.offset = 0; - op.params[1].memref.size = inMemory.Get()->size; - op.params[2].memref.parent = keyMemory.Get(); - op.params[2].memref.offset = 0; - op.params[2].memref.size = keyMemory.Get()->size; - Execute(CMD_IMPORT_KEY, &op); - - KM_SymmetricInput* output = nullptr; - ret = KM_ParamsDeserializationInit(keyMemory.Get()->buffer, keyMemory.Get()->size, &output); - if (ret) { - ThrowErr(Exc::Crypto::InternalError, "Failed to initialize deserialization for imported key ID"); - } - - KM_OutData* outData = nullptr; - ret = KM_ParamsDeserializeOutData(output, &outData); - if (ret) { - ThrowErr(Exc::Crypto::InternalError, "Failed to deserialize imported key ID"); - } - - if (outData == nullptr || outData->data_size != KM_KEY_ID_SIZE) { - ThrowErr(Exc::Crypto::InternalError, "Deserialized incorrect key ID"); - } - - keyId.resize(KM_KEY_ID_SIZE); - memcpy(keyId.data(), outData->data, KM_KEY_ID_SIZE); - - if (!pwd.empty()) { - KM_TagData* tagData = nullptr; - - ret = KM_ParamsDeserializeTagData(output, &tagData); - if (ret) { - ThrowErr(Exc::Crypto::InternalError, "Failed to deserialize imported key's tag"); - } - - if (tagData == nullptr || tagData->data_size != bufSize.tag_size) { - ThrowErr(Exc::Crypto::InternalError, "Deserialized incorrect key tag"); - } - - pwdTag.resize(bufSize.tag_size); - memcpy(pwdTag.data(), tagData->data, bufSize.tag_size); - } -} - void TrustZoneContext::executeCrypt(tz_command cmd, tz_algo_type algo, const RawBuffer &key, @@ -746,29 +638,52 @@ void TrustZoneContext::executeDestroy(const RawBuffer &keyId) Execute(CMD_DESTROY_KEY, &op); } -void TrustZoneContext::importData(const RawBuffer &data, +void TrustZoneContext::importData( + const uint32_t dataType, + const RawBuffer &data, + const RawBuffer &encIV, const RawBuffer &pwd, const RawBuffer &iv, + const uint32_t keySizeBits, + const uint32_t pwdTagSizeBits, RawBuffer &dataId, RawBuffer &pwdTag) { // command ID = CMD_IMPORT_DATA // input: // [1].memref - reference to serialized buffer: + // uint32_t dataType contains information about type stored as binary data // KM_BinaryData with binary data - // uint32_t boolean value - true if password is provided + // uint32_t binary/key size in bits + // KM_BinaryData IV for data decryption with build in key + // uint32_t boolean value - true if password is provided // KM_PwdData with password (optional) // Output: // [0].value.a - return code // [2].memref - reference to serialized buffer: // KM_BinaryData with data id // KM_BinaryData with tag id (optional, if password was provided) - KM_BinaryData kmTaData; + uint32_t inMemorySize = 0; + + // place for dataType + inMemorySize += KM_SizeOfFlag(); + + KM_BinaryData ta_data; + ta_data.data_size = static_cast(data.size()); + ta_data.data = const_cast(data.data()); + inMemorySize += KM_SizeOfBinaryData(&ta_data); + + uint32_t keySizeBits_flags = static_cast(keySizeBits); + inMemorySize += KM_SizeOfFlag(); + + KM_BinaryData ta_data_enc_iv; + ta_data_enc_iv.data_size = static_cast(encIV.size()); + ta_data_enc_iv.data = const_cast(encIV.data()); + inMemorySize += KM_SizeOfBinaryData(&ta_data_enc_iv); + uint32_t pwd_flag = pwd.empty() ? 0 : 1; - uint32_t pwdTagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS; - kmTaData.data_size = static_cast(data.size()); - kmTaData.data = const_cast(data.data()); - uint32_t inMemorySize = KM_SizeOfBinaryData(&kmTaData) + KM_SizeOfFlag(); + inMemorySize += KM_SizeOfFlag(); + KM_PwdData kmPwdData; if (pwd_flag) { memset(&kmPwdData, 0, sizeof(KM_PwdData)); @@ -788,14 +703,31 @@ void TrustZoneContext::importData(const RawBuffer &data, TrustZoneMemory inMemory(m_Context, inMemorySize, TEEC_MEM_INPUT); void *inMemoryPtr = inMemory.Get()->buffer; - int ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &kmTaData); + int ret = KM_SerializeFlag(&inMemoryPtr, &inMemorySize, dataType); + if (ret){ + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + + ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &ta_data); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + + ret = KM_SerializeFlag(&inMemoryPtr, &inMemorySize, keySizeBits_flags); if (ret) { ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); } + + ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &ta_data_enc_iv); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + ret = KM_SerializeFlag(&inMemoryPtr, &inMemorySize, pwd_flag); if (ret) { ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); } + if (pwd_flag) { ret = KM_SerializePwdData(&inMemoryPtr, &inMemorySize, &kmPwdData); if (ret) { diff --git a/src/manager/crypto/tz-backend/tz-context.h b/src/manager/crypto/tz-backend/tz-context.h index cd7ae74..fdce3eb 100644 --- a/src/manager/crypto/tz-backend/tz-context.h +++ b/src/manager/crypto/tz-backend/tz-context.h @@ -47,11 +47,13 @@ public: const uint32_t pwdKeySizeBits, RawBuffer &keyId, RawBuffer &pwdTag); - void importKey(tz_algo_type algo, - const RawBuffer &key, + void importData(uint32_t dataType, + const RawBuffer &data, const RawBuffer &encIV, const RawBuffer &pwd, const RawBuffer &pwdIV, + const uint32_t keySizeBits, + const uint32_t powTagSizeBits, RawBuffer &keyId, RawBuffer &pwdTag); @@ -82,12 +84,6 @@ public: void executeDestroy(const RawBuffer &keyId); - void importData(const RawBuffer &data, - const RawBuffer &pwd, - const RawBuffer &iv, - RawBuffer &dataId, - RawBuffer &pwdTag); - void getData(const RawBuffer &dataId, const Pwd &pwd, RawBuffer &data); -- 2.7.4 From f0a0b4b6f6f5047df98a75ec999a964ce772b012 Mon Sep 17 00:00:00 2001 From: Bartlomiej Grzelewski Date: Fri, 28 Sep 2018 13:46:21 +0200 Subject: [PATCH 14/16] Support for encrypted initial-values Add tag attribute in xml schema Change-Id: Idc058e756ab6053103e1477292cacbacf57a9879 --- doc/example.xml | 190 ++------------------- doc/initial_values.xsd | 5 +- .../crypto/generic-backend/encryption-params.h | 42 +++++ src/manager/crypto/generic-backend/gstore.h | 9 +- src/manager/crypto/sw-backend/store.cpp | 4 +- src/manager/crypto/sw-backend/store.h | 2 +- src/manager/crypto/tz-backend/internals.cpp | 4 +- src/manager/crypto/tz-backend/internals.h | 2 +- src/manager/crypto/tz-backend/store.cpp | 4 +- src/manager/crypto/tz-backend/store.h | 2 +- src/manager/crypto/tz-backend/tz-context.cpp | 20 ++- src/manager/crypto/tz-backend/tz-context.h | 3 +- src/manager/initial-values/BufferHandler.cpp | 13 +- src/manager/initial-values/BufferHandler.h | 8 +- src/manager/initial-values/InitialValueHandler.cpp | 2 +- src/manager/service/ckm-logic.cpp | 20 ++- src/manager/service/ckm-logic.h | 4 +- tests/test_crypto-logic.cpp | 4 +- tests/test_generic-backend.cpp | 5 +- tests/test_tz-backend.cpp | 3 +- 20 files changed, 128 insertions(+), 218 deletions(-) create mode 100644 src/manager/crypto/generic-backend/encryption-params.h diff --git a/doc/example.xml b/doc/example.xml index cccc214..3c6eb2a 100644 --- a/doc/example.xml +++ b/doc/example.xml @@ -76,183 +76,19 @@ - - - - BflJyNgOcGyJSqTegG+y7MJXI1crgsGY3PjFfMpbmMbwJkVexvxoEPdf2yE5Z7da - 6Vp4Qo2WOCUv/hllNTfm/dH7kOJOjcs/vaV1eRIfzEx3hvgKOyP82Hhkm1POynsF - 0GyMm/VwtJFwFHA5DaJzwLln2/AoD//vC731Qhucw0Zvi2hi74d6igPog9EugIj/ - tStvpgiNE6/Hb2ZRMDswgZ8o+tKCn+QHktR/YoZ19HfX7nDVRkMQxsiA8P4zO9Do - +iuiu/mGPVavlZA3df47TLG0kz+sz72jzPeEbfmvQo3gHWSuJ87TUwIcIoXDvaxY - xE8/On5OTqJy8HZ+jGvEThKI/96LQsFqKlEeGGenvzVJ+BVAF9x65uOkRll9yE6v - FIQcqbgipuBkdC6XLLaWTMgs5iiWvMn/lpNYrfZr52/TKqr09mNdei6yGvy+YuG8 - vu/xN7/3An/zE4FOIJadgI5eADj+Dz7exml3tKTuuDpR9fhxiXd7HmZhCCf11C3r - 54S6X9bZb7335L/5UfLxs4jMMfGhYD+1UF1Qb5zVW9IVMZ+owGeC6QQPUiX6HAxy - Rx7kLzd78uSbLNqeuiUeGiprxnuwMY2BgSqLq4WNCDWxY4hGTdkC7yg6DgY+L9Lz - wqVuJ6STmK9Hj9bL9YUe0KrzmVUfmsaq5PL+gfcv+S5lp2YlKw1cIVP9utw1ZuOo - j25EozWU8J+tuEa3l60Mmmh/sKzH9SH7C9EscwTYWOYjYYPwfCM9UIlNE9lnbl9s - bzkqJvaaXpB/HVY/b4wrldr1rK73+y9LOOzfNpV4L+R4spZXXjZ2HIW/iKQj/c14 + + + + + + pawxDIglDfneINm8O7Nv6jxm21G9UEgDXK3yG6VK0fw= - - - - pPjY7wULPaBIwPKkgwKyKSZPa6NVJN3312q829KaXcNdQSoNJmsyyPDMqLr1W3Nw - /5DSfstMCh/MiUq4Dc1VCaHbVkRFVZMvitg7nfjDVkI9HGLpSGWzz1dc6kxn/rPv - l1Ox3sVog96Ebss+Givm4cKKYSQihCLTxcQcP6v4RGvTMhXIZmlz8n4Tr3MgyRB7 - XTWdoowosEUWrzPMSD39y18gRJVZ/ZKv68o5mntatSE8FS1L6dgb2TdKEFdydVd2 - /ob9GVwRkMxpBsQeUvPRYXnZS2f1L18IRPrKLKLKsDB+FysyXMAHMaxGWWil29/d - osOwMt34i6Bv21132lGt08t2LebmDJViZRVjzz9edIChBzsoG/E/3hX6v32ruJGU - 2kq5l0bOmpQFs9M0TTNNWnaZKvpFPA8b3ywaDRWeKAPHsNQpnrx0WygCmvbjUChf - TP1E5BVm6YjWxptvFvEINcotCj2+0fvG3zIcq01O/MpSFWbGdu9MLZtFl1rTRt8e - ER8+nOKZNi9JUOfsYJyrZmtwm56LXTPjgNYY+a8yp2EXFtHjO62QKYr8zAi98PxL - oiELHLF2xwFufvBAssSOPwRmDSIhljPbUy4UKUxFCeMJzdxgK0DMZw4FtcyBXGgG - ABP57OQ60HomoZZDwAQ/4B8unuOCp7uERsQH5Z4Ns+PiIM4Tk8j9Qg4YVN43FJtJ - tCsfagBPuQM+Cm5law0Y01asMr0wq/VlILMKX0KXpwgnVmQClRfcYBLHQmDTyCos - kYSWrSYDesvXJnB1j/hn1puCQHfyrmPH5fQTzanD5whyed7DeXBl+F5+f73uj9pC - DrtqG+YEOeJNj0PCAMq9B4Qe6xi06P6D/sG17Phl9wH5DSzfxxlst1xeaPBko9Bo - LM6Sh6echKIh0HddStmaBICXNeVKz958tD0piVYMVipZm5/+cpDxdGSuemUxWXJO - XAuYydZkuLksYjLyXDO5vEaqcVMtu54tjfdFS7vO87a9IF+mI7HHHdnNaDRHaAFi - 4rXdaGQr8zohq91NE3JYgSMbk1DlGfL1m9GN6IEUjqMQlAkGWal1Et9uwO98PpOk - a+r+N4lsYPKJbX2ywUvDHg== - - - - - zuBDjp8ptFthrU69Ua5cfg== - - - - - weK/LmGIPHeNA2YipqJa4K1+KPkE/Jl5EtfJjzP5x5ZGhf/OOTYe+fj4p2Wx47AC - Nd/heOAi3MkFrwu5x+swFMIeQMCMzQpRbXeCvTEuTXWnmRMoyMbHlPd7Nnk9xooF - oYfbKhVd5DOcHN3pwc+5DQkrRy/XaD1faj3YR3JEYSfOLq4F6hLlj4U7rYJyyFuf - kSBOTAQOXs0q83cc2L7RaK7OzFJPKYJjDkVYIakpIHXUcvNrb2DrJ13se4pcX6Zk - KARviziVu4x9r7hTRErU8SNEWrO6E63oDfyetWvtymT17MEhRsRKS39zhrVLHzGy - iWx2Igh6eH6t4UNkMIHZvJW4j8hxdmbRwhQstXrVq7Uyne0B1Fl2w7Lpn48jYEq8 - gaNlTZDzd8Pjz2ByrRq3/jln/xWnFwEY9oV/H53j6ctoJ2KUMiVYKej8anan8Fju - yO86HVEIYx++LblhqzuaqBhveVfB/feMYWpP8hi4AeWKcAGdM3L9QOYxbQ9OAOuC - Totu55NULkrzb5b+Rr+exTFpdEyic7sSEpBRV0vi6t/Lz72ebBq1oY3kn0dzZ6Ps - ia6ccITSdHW1MmW7cOkiA4XtyfvXtZtEJgmVnAnRrj4Qh0Oa9gxNOZrY/tlyyJod - v8JLYeBi3HRSlm2TME5hCHpBShVCRpkjLMQQ/nTPHvRNqr/BlPoXZg2FbJwreEzW - NZ2BaiKylRds5gnmmSnqnYUl4QtVSGsJPn8Hx0bNWwUeImjrXO9Nm01P8e5Iy+Ti - udxXTwpxZGyK2pbTs6EVxFY+fRF3SB4xcpup5fB6NHVPjiSrWABN848OReny3iS0 - FXwimWaVzmA5Ppnfqx1HGopmhH++oZyKt8W/f8GbhOffON0Gg3bsewhysW5Rz+Rx - IAGqzV5RR1lOb+UKPBI2OPXqYUWZ9ipicSw1LC39olImBZbDmmxLDEjX5r+rg77h - ss0hG/6847KQybmemJ7zUVE2oxmic2fONpgjn3OLecOZpUY/5n/1cvN8utLBJ2nx - asan7zBT+nW5RjAny8pOyyV1Ux2qga/CyV46LajHJiFPokAAl6JnDYRmahtA5BM0 - +jBvvnvSDGSM5qTh0EBLIN50WmN2TeEy/u2ZjuHFwJ41gtB6pARdJ1OT59+g5TcA - Ffc8twDzdbPbmWq8CGXVQHCvfS+2N2ECjwgnfVL1UZF69d5t9b5ysK17pU+ITPyI - Bxxde23I6U7sh2owrZgRAOVoA804flRg6g6rDJyVfu00oDkuui+Z/3RAsu6EiqiK - XISmLg236iumsxXcdAtOYyXn0nPZolsZnxzY2/bI0Df7rNSQ7RF5SSqhkFg1+OYT - gM4wMYYU0ts9jqr3ckJRWMRMdJxRsVVqSBo4fz8M5/dXMsOvGbLfnbwrqZSPCXrg - g+MX3QQdemmOgiEAGE+hxFBQMyQ6nIrDP061F4TVVhu4kGkZGxs/2W+CcQJT0aF8 - DC0EwfEBVP8yq4ytCU7Js72KkA4YsK2udUsQF/90cuzPSgT8FPDEOzszKsLGuct4 - T7Fj2Du1bVeVq4gPfdLgOdVRrZLab6vS5GFbli8UO0oAbM/Srxfh2Ghn4zS7Ol3q - MnwX36r3+KFNJYkBxCDMNEnj/QrSWpOlKo8LfAyGdvP/29CpmzPIGTUc1u8xZpJ0 - CmFOaxjaAFJH3BjW625QbcicOnN02p0Pv00andcDNEO4k3b3MgW6yjkDBKqQ61dz - traH19g0fFa0pjXycMqy2uwq7PhLW0QqYt4Q7cfvWRMnAOwJqhHOGGyzEixB1U5c - q4d8izdqb0JacE6px+WJ44a530L1nhy2O5jpaKVQmNYIKTBM+HYVuHNWTWmnauKP - ag4q8G+9EI/SRp9wKoGy81W5GwonV3D6/4N9hnQfqqRKUrbrhWc9NcUciWKh4b1n - Om499jdDw+7qXipi3ggPCFq0H3b9CPkKMFh4Y/YDy1SvXEDSlwJ4bXXakOpVzW9t - gDxk/fvZ8AHrFAYzW1wiDFZ8H5ZnhgBMyfztLOYBbjr5YSGej++Sq0DYoOkrK4X3 - 7+2nMrrhqmlukI7ufoP+8nsJjHdQK8yoQYGmwEEw9QHLyupqPVIQrO/VDgSN+6mW - YsulTKW9wPhk6dvsSMOscLUdDiOTeK0jGH7Qa6QQwk/u/agHSPWh7qLpEICjKBxx - pOMbZ3mGqTXIj+7tG0yO1/y2UXE6JTIXiMEvMmdCEiRcz1RJ6xx/aBwC2//tfiys - nNMswTCXePtv5P9Zn+ibIiOhpm0napHopQcqmevn/DSkxSuDfwevae3bgEcJ1gN9 - pkTnOm22CQzoGJY/b0wgNvxXdWhAAfeRhzpdh3V1C4dZEF8VXHDDt5gdjb0s1fNI - 2LiSruLVdAWmRNX5mrkUFfBOzWwsN3D34pG2Vaj6GuH8mAoko68oy6fUdjCjZooY - hn+u5bGm1T8Mf/YYloTWg4hlOWIEfOiLP7nCdCgRdsg+y0Gi5MY04fS29SlfffUp - VUdLzQAij+a/wbBLJZMLzJiYeHv+pFY6m1SbMoUsDbAo4PTRaLHmMOFKa6s/hlka - lfN408DHSNs63Gd6s3W+Owe5hMccfKyRvWdNRVrXBe39I101Sci7GwWAvHhhS9EP - 2HxxNyiwF1OCovnRHcm1b8Fcd42gbAveRVuFdI96dbFIeP0Z4I2gj+nk/yzlsG32 - LYYzE9D4WR2zjrTyVnylsJN76lyvjvkYjMt7fPt7lFYz7QLdZX8riGxqeFmim6Sk - UQ4RXxw/ObCw4omILxvgigW+eAhgng63Yb9mRDOrqk/cL5XECiahSs3VWTjV9sy2 - rNSPViWZW/LFOjuC3cT5rWEbc64cl0eKJTivEangOXxirRGW1ltTlzQo5kA933l/ - sRMr2tBSrX/+LqfPWNA8UZWSdMBcc0oDvDGrpTUtLcor5kshYN7PPdaR9TAf8ikY - 631mOef0HkQFsBUCFp9sr6QJD0/cfLlK5iLlyt+qFo2IgX2boddFwMtpYCt1+Uy1 - H2u6FuItIfpRu9lZ7MZf24HGibGx5/fzTXjqGMObPOaoLxI4eh1GGhIfVqmT9ntv - e2xHoNH+tLxOHPRNHEkKRtJoB1HH20+mT6JzEdPNPmsdTcN4R0xjw0ZHTha2iBkt - ocGow+1nYgkoieq1QweEbbCbF71XtUpyMxMSd+BAPIJJReRGvt3mD9RZ54HqlczW - MA0LYe1rUX0Mh2Ic0x1rXZuo33PXcsKsUpfb+EIPhBjpx2vCNMiFPcM+F0NVh/PP - zgbdjlnHr6DXn3rut6Y9fTau6UY8BmeOjG4LcNzcvcHHr9/8jXyW9wWAYYVRUI3J - 89/GR+YxW4WGuRBIV+wMkzBJmP7QDwAedSNBSAKa+08GKfJJRL2zIVgjffeBO+Un - TMTT7Q/a3bm+yekGsM6bchWTpY2ywdYQr936D55THonqCGlvPKyVHQaEa4U2eFDb - aIH84kP4olPCcC+TmWHBeBwMGvbW160hRCr3kSGY7hHcD0aXkdZPh1bYyWsIz/yS - eyUYCR+4Abu9lT1rTwHiSeo4YjNHOwQcfzBN9BwFUs6G1R81oC3qCwTYuJS2Eo09 - +sii/oH/o/7VjvewMmUzDHVJ4iMa8yRXtfOObrM9MfsQ0p9GnP7UTG3VwleIenFZ - 43DhvDl+kolw9phRuyCuCy7fSI8e7ejcQ3gSYWcIcgIIA5y/KdoCJDNdTjj3xDdo - p+hzg0OTjK57Fw286IVdzO5e5zznX0SPqXnZYncHHl2OmGZ+DT8ftkvD4BUJ74aO - fLsVwAZYJT1tSG2ymzu9yJR5p+hPTScpPi8HUDCnL4xL304Lmj3UfDauNJQcM/gT - mAJ/bfEtRqldMtN1EuH1TexvSkwkPrTUkryq2TYcw7vS72tNi+g6aZ7NdrQ8l4KZ - ZmrfwFnKNiVWus+zrffSDooEFZ3mj/vsFvV6fhw/Ni4QD1XAb0fJawUHvt0WHqZA - YnszBOzdmd8coJI17XbcwcP7DEoKIhLbPl1n0KNjL6j4EEoClwxZC+hAhi8kKMB3 - aWj4zpeIExYST8NgtCz44SoBTv5U0iCR19mhdcTnafGyRK82dGiBNguk8//siUiC - jt3Aa7chapoiQNwZGDCmSrZOxOoxMYlBuPRVQqeokPinsw5rkLh8+arz1XRDyuTK - vQ+jttyIVA9OFI5+e/hN0ryn4GPbiCG5wV5SKweRUCcX9m8TK5u6A3rhMvlcls3T - INn9/XjCX6HhVGgZ47LSmcZ5ojtWzOKpad0v8qjD3z2BWzUlbalgYsdWrsRPSeDA - wiGpKbqb9u0S1e6hMmGyNa8UbzhYtJ/AQ0qh003YR7j+nlfJXffNkt2B4DkDdsG3 - Alfhalwn5YUdcgm/6E+gnIg7JR4gXZhBL1R5SV1mzUgzyDEq5w2LBOx+TU33a3qf - ld0dJDJl0cG22n+GzQmm/6nPMnWX1ymK49h0tO9fLBLZsL8T1muo/PshhjhIv5VR - 9ET5UN5I+9d0nHWAv2DjNwetyD3WGZDHnuq0mpti58xzkOr4jfYqy9qKwFk/coAu - Briwv8OJ2U5XEOuU/9fEL+NdYWkHga++oObyxJUU5Qgfs6OWUXERyPwzgXHkbDqm - q6+GP1AxBAP32zD0XyGUht1nl+L5qpnbOpISJjMMrl7wuKezWbFAE8VzQNbbp62O - eI1GEX2c2resPXZ/tS5LtoZ2TrT8TKYRZ0k1qLuQhOTXXNYQhP8i4PGOAL6BMZsZ - USAEHcAZnlByBS8i49IlvJMewPfHmm7ceLu8aYlm3yOAr1QBNRMkxoJBXjAAnCCx - qCGIQtINrVIJNQDSogMPXa4JQzCRSsT0Hz8ejQeQ9xmaK4VjM64VRj11RWsHFexk - p+GdAGVteipz1xEQHBvnUdOVm/5ULHK+8w+5LgEwN0jGXlsQ6KhUX5BLQMWob0jL - 1np3Hml3MDxsPJPJjT4OKxNdWyyyP6PIDZj7DFqEa6+9Eg5Io7TSNk4e+LylfpPS - orsF2xaUzCaKOXjyXwPrW57UH8HtjnaeWh03qqdZCozCDdQ0pNpPk2vJYStZR/rY - BpQHZ6kZyLFdqLs+wMoPphF7q4bhjYk6MXwdHp5Q9q+MWPuM916g6vKaHUX+q6pL - YM8s13NkuUX1hEHaOC8I2dEsgcVPk++kDAR7JL5tn5hfJ06K8u5IHwuLUMtLKPt5 - ZA3LfrnXxqlZD164blhAvb1qPlRTh79+Tj+3zfwaUPma3PmTY12fvJiOn1aD4aYm - HgA0yrl2cApzB3C6M1S2QllsoJ/KrWVeSg16XuC+vjSnsRWgIj3PSvSwh9YVZT0h - TQlD/PoxrMOlPtQnpHzryQ8YKrTBc4SAuO23wKGkfUBkaBDFrUeprO2p0K9Eeus9 - jLkIgwTBwmF9bWMi214VdAI3I2BrJkGnx8Rb11C6rEu/5ZeI7g2dACSO27OhckNQ - ex490kQvqs1OJ6Fb/CyO8BsLBIyOhkEtglJsVibbcZrHnvoRYeRaWZj9TNdN6I3B - Dj0SwxDK9XAwGgWb+E4iwFUUg6yGrbBhUDWv5K7/ncgXz8iESXFKRowuD/J7rriU - V/s+yZ8URntBrZ35unuKu4xRieOEkn/JZg+HP0Grs5q3OQumEvZVjHqeJt40WaZ5 - RJ3NiiHGwWVa6Db/1q0cfETbTn5Qcy2k8ZE+OnRzAmI14nr6lt4eJRnMJ63k4nGc - Xj0WpVm7vhVWAQ9gfiYCcbYrR31dUeOBxsRtF+Lvg3TNEx8/x4LeGfxC9c5Ho1Sc - Z7fz+/ZycHFx+08W5Mb6PlKhI44uY8bed2Xz5gQhZ1hyXk6Y41uxabUryeCvrLrh - PJX25FkOcLhZnWDcyCQ1Rt4JltnZcZzHq12Ipgovos3lPOarySOzSHjs1TjB6Bv1 - zfBrCAGiY3rrG/W5gXs5eb97dWn5P8CD2uuZCBbTo0GVHdSHV9+JFHQO/0udmnEV - e9KRka43HU7AC+3aLeCq1KMoW/anl4DwPXdBCV6hj75TZ0EaA7Q51ETYFCLtyXzt - eiU9PE+bEymV6nk927wg7v38GLmdLTJ0F/G4MV0T4UxAdUrsAW33MGXC9/8YyOAz - zGh36fBdxTpM6hb1FHJl/tdboIAcTBJRobgmvhaDDVhsJiMJMwRhSFqcE7Q04c3c - 6rLNGZQ3/u5/Atj5ApZ60ZMH0N5LYcTm98HOROGiFbrYSiSqUyeoIPvME5FwijLw - eCxbwjP3WvUSw8XTeIoAf5QwzdI6GRX+6ontCvw6m3l1TohH/ACA+MK+qV1cTgMV - HdjywH4SKs3KfwCcTF4gxkHdYlNYDW63Z0lhAtDBXMxUNM/u215Wo+zX0gaSUqeu - by47hfhTHP5mW6ITRFvKcS/qUqo3iELljwSXhdw7PwM0whLnSEMGsYh27YVxEzBT - n9vcM5tqGykKs1wwmpXpEa6Zliu9swprpQCL5TcOVFKVMjSmDH2OwmaDwcFeTM50 - mg7BpiA5xLyQFphs8BPbyzkxNlbSI20S67Gx6yScrjsDxcEcVqmcyVVPwn/SqzVL - PyklAUbvRcRzkhvibBngIaFUfXXdCOrdQc8Ym/5kKeQ+QLiXxfIYmYKa2uyvMeTe - xoag7cmuUnICIYBrmHnVDNxXtC9mNiooUaX2S1lH2ct4s/NwRJm2c5O/igKO/byg - wQjiGqDZHyLlPSRxXbxG+tTf3qx8thYbJAO0r+AXYRj+sjJ+MtRozgY0nUeFEJb0 - ZeYQGlvtoXlGo876JWJ/e7JMatHxGGQ58vJApMTphe/PPh3WTJTE02Bs3Ylft2bp - EK5ODopXJ0UmQTn6T1hUwBRu9RO5rICr34XnFav06WekBT5/QTqHEvZ4k4//hvGr - d7PQS/EVLApiYWySLg56svmjn4RwfPSPHOwGagU311QOx7woYJD/vb4NBxXb99Qb - 7z42exUoZgqX+uKwHCuTzH/OVxhqrSoMX2yj09V6ZDUVHU11GOtDzVv07OU+u2vi - F0wPdrbedpmIr5BMCdCmqlIPYeBiaMVa/2+q3ud4o6/TeWmQpDZJCQ3xtxrNORQ7 - HTlY0MDp7G+sdPWJCN5OJ0Ac7uKW72ZC/5yHBJY7Lmrhi3V3vA+DH7A4GgPAphQM - yWlBP7sQqVWcA1XlgTycRzkfffXEUoS6qef+IgU/3i/kXmeNnf2kSvmtbiO4GRhC - Nhk2s71NUtYXNFJPav5/ZPXI3qOuySow5GYp3njGYmDhO45IzFCcQu40FqiOeyoV - lRYTS/BrybkMCu2S3VmIY9/2e7gguYigmyZRvvqOUED9JRqOfC14n5+wtxzSj/nw - xFFukVHQRNF6jcZLUNs0SoeFS/obPCE+QiDYBKVrTeT54LuwNLpTrgTnTkDE5VIm - LpX9ERh0Yh8HAO7eLHIPAiU/G1Etlc43GcDLN7bbGPQbCvKRzWKSUrLwKmryvTPi - eC36fh/yZEWtT2zEtddwbncRgXT20opzMJxB3qF5ZMQ1qLIsQbGYeUsRl9lxsT7A - CE6vCP235+urdA9IaBRPN1VpWDpV7YDbF/ZIkRDJevSnSSrBTed4WcXcSe7JNGFb - U3eFPi2vsekvb59CHqHPD8QvvqF3N/3Xp1uQZV+eBOCtRpMOZduBJ6QdZlGBaGrB - +RKJEl9ziqGkiqiQzw8MR2kSrRVKIs5cISbl/dOEqfkbp2A1Siy4kWt+2Zk5V+Sw - IPJDrjYIZKSzV6XhhN+fhMNOYJjByxEXXLvHRTydIUQpS5JPe3T1sMJCN8o41uKx - 4g+oPomYfJzKSbdpP84fVC4WQCMj+CiMGz/dWV27LgKPF0X9wel5s5gke4UDYQKe - FDf/4n3+neMgKohFUIcnqGnBTtThXqvK637m37WfQTIqNWkRH4pU/Acl/djkd+TD - yYRBt5UqwGovABM08jYkuA== - - diff --git a/doc/initial_values.xsd b/doc/initial_values.xsd index 54672d9..74b33a6 100644 --- a/doc/initial_values.xsd +++ b/doc/initial_values.xsd @@ -148,11 +148,12 @@ - + + - + diff --git a/src/manager/crypto/generic-backend/encryption-params.h b/src/manager/crypto/generic-backend/encryption-params.h new file mode 100644 index 0000000..5fa8e9c --- /dev/null +++ b/src/manager/crypto/generic-backend/encryption-params.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2018 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 + */ +/* + * @file encryption-params.h + * @author Bartłomiej Grzelewski (b.grzelewski@samsung.com) + * @version 1.0 + */ +#pragma once + +#include + +namespace CKM { +namespace Crypto { + +struct EncryptionParams { + EncryptionParams() {} + + EncryptionParams(RawBuffer iv, RawBuffer tag) : + iv(std::move(iv)), + tag(std::move(tag)) + {} + + RawBuffer iv; + RawBuffer tag; +}; + +} // namespace Crypto +} // namespace CKM + diff --git a/src/manager/crypto/generic-backend/gstore.h b/src/manager/crypto/generic-backend/gstore.h index 2984fdc..638532d 100644 --- a/src/manager/crypto/generic-backend/gstore.h +++ b/src/manager/crypto/generic-backend/gstore.h @@ -24,6 +24,7 @@ #include #include +#include #include #include #include @@ -57,11 +58,11 @@ public: } /* - * IV parameter makes sense only on device with built in key. - * IV parameter is used for decryption of Data. - * If Data is not encrypted it's ok to pass empty IV. + * EncryptionParams parameter makes sense only on device with built-in key. + * EncryptionParams parameter is used for decryption of Data. + * If Data is not encrypted it's ok to pass empty EncryptionParams. */ - virtual Token import(const Data &, const Password &, const RawBuffer & /* iv */) + virtual Token import(const Data &, const Password &, const EncryptionParams &) { ThrowErr(Exc::Crypto::OperationNotSupported); } diff --git a/src/manager/crypto/sw-backend/store.cpp b/src/manager/crypto/sw-backend/store.cpp index b41b8fd..b4fd718 100644 --- a/src/manager/crypto/sw-backend/store.cpp +++ b/src/manager/crypto/sw-backend/store.cpp @@ -219,9 +219,9 @@ Token Store::generateSKey(const CryptoAlgorithm &algorithm, return Token(m_backendId, ret.type, pack(ret.buffer, pass)); } -Token Store::import(const Data &data, const Password &pass, const RawBuffer &iv) +Token Store::import(const Data &data, const Password &pass, const EncryptionParams &e) { - if (!iv.empty()) + if (!e.iv.empty()) ThrowErr(Exc::Crypto::OperationNotSupported, "Encrypted import is not yet supported on software backend!"); diff --git a/src/manager/crypto/sw-backend/store.h b/src/manager/crypto/sw-backend/store.h index 82798cd..3dc50b8 100644 --- a/src/manager/crypto/sw-backend/store.h +++ b/src/manager/crypto/sw-backend/store.h @@ -35,7 +35,7 @@ public: virtual TokenPair generateAKey(const CryptoAlgorithm &, const Password &, const Password &); virtual Token generateSKey(const CryptoAlgorithm &, const Password &); - virtual Token import(const Data &data, const Password &, const RawBuffer &); + virtual Token import(const Data &data, const Password &, const EncryptionParams &); virtual void destroy(const Token &) {} private: diff --git a/src/manager/crypto/tz-backend/internals.cpp b/src/manager/crypto/tz-backend/internals.cpp index 90cc9fb..317a775 100644 --- a/src/manager/crypto/tz-backend/internals.cpp +++ b/src/manager/crypto/tz-backend/internals.cpp @@ -119,7 +119,7 @@ void destroyKey(const RawBuffer &key) } RawBuffer importData(const Data &data, - const RawBuffer &encIV, + const EncryptionParams &encData, const Password &pwd, const RawBuffer &pwdIV, RawBuffer &tag) @@ -142,7 +142,7 @@ RawBuffer importData(const Data &data, uint32_t keySizeBits = data.data.size() * 8; TrustZoneContext::Instance().importData(dataType, data.data, - encIV, + encData, pwdBuf, pwdIV, keySizeBits, diff --git a/src/manager/crypto/tz-backend/internals.h b/src/manager/crypto/tz-backend/internals.h index c27933b..1c76f8d 100644 --- a/src/manager/crypto/tz-backend/internals.h +++ b/src/manager/crypto/tz-backend/internals.h @@ -49,7 +49,7 @@ Data generateSKey(const CryptoAlgorithm &alg, RawBuffer &tag); RawBuffer importData(const Data &key, - const RawBuffer &encIV, + const EncryptionParams &encData, const Password &pwd, const RawBuffer &pwdIV, RawBuffer &tag); diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index a3d65c7..166ae74 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -142,7 +142,7 @@ Token Store::generateSKey(const CryptoAlgorithm &alg, const Password &pass) return Token(m_backendId, ret.type, pack(ret.data, pass, iv, tag)); } -Token Store::import(const Data &data, const Password &pass, const RawBuffer &encIV) +Token Store::import(const Data &data, const Password &pass, const EncryptionParams &e) { if (!data.type.isBinaryData() && !data.type.isSKey()) ThrowErr(Exc::Crypto::DataTypeNotSupported, "Invalid data provided for import"); @@ -155,7 +155,7 @@ Token Store::import(const Data &data, const Password &pass, const RawBuffer &enc passIV = Internals::generateIV(); } - RawBuffer dataId = Internals::importData(data, encIV, pass, passIV, tag); + RawBuffer dataId = Internals::importData(data, e, pass, passIV, tag); return Token(m_backendId, data.type, pack(dataId, pass, passIV, tag)); } diff --git a/src/manager/crypto/tz-backend/store.h b/src/manager/crypto/tz-backend/store.h index 4d44b6b..664c756 100644 --- a/src/manager/crypto/tz-backend/store.h +++ b/src/manager/crypto/tz-backend/store.h @@ -35,7 +35,7 @@ public: virtual TokenPair generateAKey(const CryptoAlgorithm &, const Password &, const Password &); virtual Token generateSKey(const CryptoAlgorithm &, const Password &); - virtual Token import(const Data &, const Password &, const RawBuffer &); + virtual Token import(const Data &, const Password &, const EncryptionParams &); virtual void destroy(const Token &); // TODO device key ID is needed here to support importEncrypted diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp index 859c5a2..83ac694 100644 --- a/src/manager/crypto/tz-backend/tz-context.cpp +++ b/src/manager/crypto/tz-backend/tz-context.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -641,7 +642,7 @@ void TrustZoneContext::executeDestroy(const RawBuffer &keyId) void TrustZoneContext::importData( const uint32_t dataType, const RawBuffer &data, - const RawBuffer &encIV, + const Crypto::EncryptionParams &encData, const RawBuffer &pwd, const RawBuffer &iv, const uint32_t keySizeBits, @@ -655,7 +656,8 @@ void TrustZoneContext::importData( // uint32_t dataType contains information about type stored as binary data // KM_BinaryData with binary data // uint32_t binary/key size in bits - // KM_BinaryData IV for data decryption with build in key + // KM_BinaryData IV for data decryption with built in key + // KM_BinaryData TAG for data decryption with built in key // uint32_t boolean value - true if password is provided // KM_PwdData with password (optional) // Output: @@ -677,10 +679,15 @@ void TrustZoneContext::importData( inMemorySize += KM_SizeOfFlag(); KM_BinaryData ta_data_enc_iv; - ta_data_enc_iv.data_size = static_cast(encIV.size()); - ta_data_enc_iv.data = const_cast(encIV.data()); + ta_data_enc_iv.data_size = static_cast(encData.iv.size()); + ta_data_enc_iv.data = const_cast(encData.iv.data()); inMemorySize += KM_SizeOfBinaryData(&ta_data_enc_iv); + KM_BinaryData ta_data_enc_tag; + ta_data_enc_tag.data_size = static_cast(encData.tag.size()); + ta_data_enc_tag.data = const_cast(encData.tag.data()); + inMemorySize += KM_SizeOfBinaryData(&ta_data_enc_tag); + uint32_t pwd_flag = pwd.empty() ? 0 : 1; inMemorySize += KM_SizeOfFlag(); @@ -723,6 +730,11 @@ void TrustZoneContext::importData( ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); } + ret = KM_SerializeBinaryData(&inMemoryPtr, &inMemorySize, &ta_data_enc_tag); + if (ret) { + ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); + } + ret = KM_SerializeFlag(&inMemoryPtr, &inMemorySize, pwd_flag); if (ret) { ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret); diff --git a/src/manager/crypto/tz-backend/tz-context.h b/src/manager/crypto/tz-backend/tz-context.h index fdce3eb..123c21e 100644 --- a/src/manager/crypto/tz-backend/tz-context.h +++ b/src/manager/crypto/tz-backend/tz-context.h @@ -26,6 +26,7 @@ #include #include #include +#include namespace CKM { namespace Crypto { @@ -49,7 +50,7 @@ public: RawBuffer &pwdTag); void importData(uint32_t dataType, const RawBuffer &data, - const RawBuffer &encIV, + const Crypto::EncryptionParams &encData, const RawBuffer &pwd, const RawBuffer &pwdIV, const uint32_t keySizeBits, diff --git a/src/manager/initial-values/BufferHandler.cpp b/src/manager/initial-values/BufferHandler.cpp index cca06b2..5917844 100644 --- a/src/manager/initial-values/BufferHandler.cpp +++ b/src/manager/initial-values/BufferHandler.cpp @@ -29,6 +29,7 @@ namespace { const char *const XML_ATTR_IV = "IV"; +const char *const XML_ATTR_TAG = "tag"; } namespace CKM { @@ -39,14 +40,22 @@ BufferHandler::~BufferHandler() {} void BufferHandler::Start(const XML::Parser::Attributes &attr) { - // get key type if (attr.find(XML_ATTR_IV) != attr.end()) { std::string IVstring = attr.at(XML_ATTR_IV); Base64Decoder base64; base64.reset(); base64.append(RawBuffer(IVstring.begin(), IVstring.end())); base64.finalize(); - m_IV = base64.get(); + m_encryptionParams.iv = base64.get(); + } + + if (attr.find(XML_ATTR_TAG) != attr.end()) { + std::string tag = attr.at(XML_ATTR_TAG); + Base64Decoder base64; + base64.reset(); + base64.append(RawBuffer(tag.begin(), tag.end())); + base64.finalize(); + m_encryptionParams.tag = base64.get(); } } diff --git a/src/manager/initial-values/BufferHandler.h b/src/manager/initial-values/BufferHandler.h index 08bca52..1b45839 100644 --- a/src/manager/initial-values/BufferHandler.h +++ b/src/manager/initial-values/BufferHandler.h @@ -26,7 +26,7 @@ #include #include #include -#include +#include namespace CKM { namespace InitialValues { @@ -47,14 +47,14 @@ public: return m_data; } - const RawBuffer &getIV() const + const Crypto::EncryptionParams &getEncryptionParams() const { - return m_IV; + return m_encryptionParams; } private: EncodingType m_encoding; - RawBuffer m_IV; + Crypto::EncryptionParams m_encryptionParams; RawBuffer m_data; }; diff --git a/src/manager/initial-values/InitialValueHandler.cpp b/src/manager/initial-values/InitialValueHandler.cpp index 7853d39..6ca335a 100644 --- a/src/manager/initial-values/InitialValueHandler.cpp +++ b/src/manager/initial-values/InitialValueHandler.cpp @@ -80,7 +80,7 @@ void InitialValueHandler::End() int ec = m_db_logic.importInitialData(m_name, Crypto::Data(getDataType(), m_bufferHandler->getData()), - m_bufferHandler->getIV(), + m_bufferHandler->getEncryptionParams(), policy); if (CKM_API_SUCCESS != ec) { diff --git a/src/manager/service/ckm-logic.cpp b/src/manager/service/ckm-logic.cpp index 98248ec..6a10ad7 100644 --- a/src/manager/service/ckm-logic.cpp +++ b/src/manager/service/ckm-logic.cpp @@ -405,7 +405,7 @@ DB::Row CKMLogic::createEncryptedRow( // do not encrypt data with password during cc_mode on Token token = store.import(data, m_accessControl.isCCMode() ? "" : policy.password, - RawBuffer()); + Crypto::EncryptionParams()); DB::Row row(std::move(token), name, owner, static_cast(policy.extractable)); crypto.encryptRow(row); @@ -804,7 +804,7 @@ Crypto::GObjUPtr CKMLogic::rowToObject( store.destroy(row); // import it to store with new scheme: data -> pass(data) - Token token = store.import(Crypto::Data(row.dataType, row.data), pass, RawBuffer()); + Token token = store.import(Crypto::Data(row.dataType, row.data), pass, Crypto::EncryptionParams()); // get it from the store (it can be different than the data we imported into store) obj = store.getObject(token, pass); @@ -1160,10 +1160,15 @@ RawBuffer CKMLogic::getDataList( int CKMLogic::importInitialData( const Name &name, const Crypto::Data &data, - const RawBuffer &iv, + const Crypto::EncryptionParams &encParams, const Policy &policy) { try { + if (encParams.iv.empty() != encParams.tag.empty()) { + LogError("Both iv and tag must be empty or set"); + return CKM_API_ERROR_INPUT_PARAM; + } + // Inital values are always imported with root credentials. Client id is not important. Credentials rootCred(0, ""); @@ -1176,11 +1181,12 @@ int CKMLogic::importInitialData( if (retCode != CKM_API_SUCCESS) return retCode; - Crypto::GStore &store = m_decider.getStore(data.type, policy, !iv.empty()); + Crypto::GStore &store = + m_decider.getStore(data.type, policy, !encParams.iv.empty()); Token token; - if (iv.empty()) { + if (encParams.iv.empty()) { // Data are not encrypted, let's try to verify them Crypto::Data binaryData; @@ -1189,11 +1195,11 @@ int CKMLogic::importInitialData( token = store.import(binaryData, m_accessControl.isCCMode() ? "" : policy.password, - iv); + encParams); } else { token = store.import(data, m_accessControl.isCCMode() ? "" : policy.password, - iv); + encParams); } DB::Row row(std::move(token), name, CLIENT_ID_SYSTEM, diff --git a/src/manager/service/ckm-logic.h b/src/manager/service/ckm-logic.h index 8115117..7f9b5f0 100644 --- a/src/manager/service/ckm-logic.h +++ b/src/manager/service/ckm-logic.h @@ -36,7 +36,7 @@ #include #include #include - +#include #include namespace CKM { @@ -209,7 +209,7 @@ public: int importInitialData( const Name &name, const Crypto::Data &data, - const RawBuffer &iv, + const Crypto::EncryptionParams &encData, const Policy &policy); int unlockSystemDB(); diff --git a/tests/test_crypto-logic.cpp b/tests/test_crypto-logic.cpp index f519e27..d13f6af 100644 --- a/tests/test_crypto-logic.cpp +++ b/tests/test_crypto-logic.cpp @@ -91,7 +91,7 @@ BOOST_AUTO_TEST_CASE(row_encryption) Crypto::Data data(DataType(DataType::Type::BINARY_DATA), createRandom(10)); Crypto::Decider decider; Crypto::GStore &store = decider.getStore(data.type, policy); - Token token = store.import(data, policy.password, RawBuffer()); + Token token = store.import(data, policy.password, Crypto::EncryptionParams()); Name name = "test_data"; ClientId owner = "test_owner"; @@ -113,7 +113,7 @@ BOOST_AUTO_TEST_CASE(row_encryption_negatives) Crypto::Data data(DataType(DataType::Type::BINARY_DATA), createRandom(10)); Crypto::Decider decider; Crypto::GStore &store = decider.getStore(data.type, policy); - Token token = store.import(data, policy.password, RawBuffer()); + Token token = store.import(data, policy.password, Crypto::EncryptionParams()); Name name = "test_data"; ClientId owner = "test_owner"; diff --git a/tests/test_generic-backend.cpp b/tests/test_generic-backend.cpp index 0b39bf3..5814a26 100644 --- a/tests/test_generic-backend.cpp +++ b/tests/test_generic-backend.cpp @@ -15,7 +15,8 @@ */ #include #include -//#include +#include +#include #include @@ -72,7 +73,7 @@ BOOST_AUTO_TEST_CASE(gstore) Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.generateSKey(CryptoAlgorithm(), Password()), Exc::Crypto::OperationNotSupported); - BOOST_REQUIRE_THROW(store.import(Crypto::Data(), Password(), RawBuffer()), + BOOST_REQUIRE_THROW(store.import(Crypto::Data(), Password(), Crypto::EncryptionParams()), Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.destroy(Token()), Exc::Crypto::OperationNotSupported); diff --git a/tests/test_tz-backend.cpp b/tests/test_tz-backend.cpp index 880211b..93447de 100644 --- a/tests/test_tz-backend.cpp +++ b/tests/test_tz-backend.cpp @@ -14,6 +14,7 @@ * limitations under the License */ #include +#include #include @@ -30,7 +31,7 @@ BOOST_AUTO_TEST_CASE(store) Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_THROW(store.generateAKey(CryptoAlgorithm(), Password(), Password()), Exc::Crypto::OperationNotSupported); - BOOST_REQUIRE_THROW(store.import(Data(), Password(), RawBuffer()), + BOOST_REQUIRE_THROW(store.import(Data(), Password(), Crypto::EncryptionParams()), Exc::Crypto::OperationNotSupported); BOOST_REQUIRE_NO_THROW(store.destroy(Token())); } -- 2.7.4 From 3195a9624186ca5b6b681148b192e9ef48cfe872 Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Tue, 2 Oct 2018 14:27:27 +0200 Subject: [PATCH 15/16] Initial values tool Add a tool able to create and/or update an initial values xml. It is also possible to add encrypted ininial values. Add rpm package for potential use in gbs buildroot during image creation. Limitations: - Hardcoded IV & tag length - Hardcoded Data format Testing: dd if=/dev/random of=/tmp/key bs=32 count=1 dd if=/dev/random of=/tmp/data bs=32 count=1 ckm_initial_values -k /tmp/key -d /tmp/data -n name -t Key -s AES -p pass -e -b hardware -a acc1,acc2,acc3 Change-Id: Id29d0eb58d9dba3e78b3437534cb566046a39877 --- LICENSE.BSD-2-Clause | 24 ++ packaging/key-manager.spec | 17 ++ tools/CMakeLists.txt | 1 + tools/ckm_initial_values/CMakeLists.txt | 49 ++++ tools/ckm_initial_values/base64.cpp | 204 ++++++++++++++ tools/ckm_initial_values/base64.h | 65 +++++ tools/ckm_initial_values/main.cpp | 468 ++++++++++++++++++++++++++++++++ 7 files changed, 828 insertions(+) create mode 100644 LICENSE.BSD-2-Clause create mode 100644 tools/ckm_initial_values/CMakeLists.txt create mode 100644 tools/ckm_initial_values/base64.cpp create mode 100644 tools/ckm_initial_values/base64.h create mode 100644 tools/ckm_initial_values/main.cpp diff --git a/LICENSE.BSD-2-Clause b/LICENSE.BSD-2-Clause new file mode 100644 index 0000000..03f5f58 --- /dev/null +++ b/LICENSE.BSD-2-Clause @@ -0,0 +1,24 @@ +Copyright (c) 2014, STMicroelectronics International N.V. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/packaging/key-manager.spec b/packaging/key-manager.spec index 1a3dd0b..4daa444 100644 --- a/packaging/key-manager.spec +++ b/packaging/key-manager.spec @@ -125,6 +125,18 @@ Requires(postun): %{sbin_dir}/ldconfig CKM login/password module to PAM. Used to monitor user login/logout and password change events from PAM +%package -n key-manager-initial-values +Summary: CKM initial values tool +Group: Security/Libraries +License: Apache-2.0 and BSD-2-Clause +BuildRequires: cmake +BuildRequires: pkgconfig(openssl) +BuildRequires: pkgconfig(libxml-2.0) +Requires(post): %{sbin_dir}/ldconfig +Requires(postun): %{sbin_dir}/ldconfig + +%description -n key-manager-initial-values +Includes ckm_initial_values tool for initial values XML generation %prep %setup -q @@ -322,3 +334,8 @@ fi %{bin_dir}/ckm_db_merge %{bin_dir}/ckm_generate_db %test_dir + +%files -n key-manager-initial-values +%license LICENSE +%license LICENSE.BSD-2-Clause +%{bin_dir}/ckm_initial_values diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index c824559..9d12bb7 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -46,3 +46,4 @@ INSTALL(TARGETS ${CKM_TOOL} WORLD_EXECUTE ) ADD_SUBDIRECTORY(ckm_db_tool) +ADD_SUBDIRECTORY(ckm_initial_values) \ No newline at end of file diff --git a/tools/ckm_initial_values/CMakeLists.txt b/tools/ckm_initial_values/CMakeLists.txt new file mode 100644 index 0000000..c23f1e6 --- /dev/null +++ b/tools/ckm_initial_values/CMakeLists.txt @@ -0,0 +1,49 @@ +#### This is to allow local build without gbs #### +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +INCLUDE(FindPkgConfig) +INCLUDE(GNUInstallDirs) + +IF(NOT DEFINED BIN_DIR) + SET(BIN_DIR "${CMAKE_INSTALL_FULL_BINDIR}" CACHE PATH "User executables directory") +ENDIF() + +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") +################################################## + + +SET(CKM_INITIAL_VALUES "ckm_initial_values") + +PKG_CHECK_MODULES(CKM_INITIAL_VALUES_DEP + REQUIRED + openssl + libxml-2.0 + ) + +INCLUDE_DIRECTORIES( + ${CKM_INITIAL_VALUES_DEP_INCLUDE_DIRS} + ) + +SET(CKM_INITIAL_VALUES_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/base64.cpp + ) + +LINK_DIRECTORIES(${CKM_INITIAL_VALUES_DEP_LIBRARY_DIRS}) + +ADD_EXECUTABLE(${CKM_INITIAL_VALUES} ${CKM_INITIAL_VALUES_SOURCES}) + +TARGET_LINK_LIBRARIES(${CKM_INITIAL_VALUES} + ${CKM_INITIAL_VALUES_DEP_LIBRARIES} + ) + +INSTALL(TARGETS ${CKM_INITIAL_VALUES} + DESTINATION ${BIN_DIR} + PERMISSIONS OWNER_READ + OWNER_WRITE + OWNER_EXECUTE + GROUP_READ + GROUP_EXECUTE + WORLD_READ + WORLD_EXECUTE + ) + diff --git a/tools/ckm_initial_values/base64.cpp b/tools/ckm_initial_values/base64.cpp new file mode 100644 index 0000000..aa1520a --- /dev/null +++ b/tools/ckm_initial_values/base64.cpp @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2011 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 +#include +#include +#include + +#include "base64.h" + +namespace CKM { + +Base64Encoder::Base64Encoder() : + m_b64(0), + m_bmem(0), + m_finalized(false) +{ +} + +void Base64Encoder::append(const RawBuffer &data) +{ + if (m_finalized) { + throw std::logic_error("Already finalized"); + } + + if (!m_b64) + reset(); + + BIO_write(m_b64, data.data(), data.size()); +} + +void Base64Encoder::finalize() +{ + if (m_finalized) { + throw std::logic_error("Already finalized."); + } + + m_finalized = true; + (void)BIO_flush(m_b64); +} + +RawBuffer Base64Encoder::get() +{ + if (!m_finalized) { + throw std::logic_error("Not finalized"); + } + + BUF_MEM *bptr = nullptr; + BIO_get_mem_ptr(m_b64, &bptr); + + if (!bptr) { + throw std::logic_error("Bio internal error"); + } + + if (bptr->length > 0) + return RawBuffer(bptr->data, bptr->data + bptr->length); + + return RawBuffer(); +} + +void Base64Encoder::reset() +{ + m_finalized = false; + BIO_free_all(m_b64); + m_b64 = BIO_new(BIO_f_base64()); + m_bmem = BIO_new(BIO_s_mem()); + + if (!m_b64 || !m_bmem) { + throw std::logic_error("Error during allocation memory in BIO"); + } + + BIO_set_flags(m_b64, BIO_FLAGS_BASE64_NO_NL); + m_b64 = BIO_push(m_b64, m_bmem); +} + +Base64Encoder::~Base64Encoder() +{ + BIO_free_all(m_b64); +} + +Base64Decoder::Base64Decoder() : + m_finalized(false) +{ +} + +void Base64Decoder::append(const RawBuffer &data) +{ + if (m_finalized) { + throw std::logic_error("Already finalized."); + } + + std::copy(data.begin(), data.end(), std::back_inserter(m_input)); +} + +static bool whiteCharacter(char a) +{ + return a == '\n'; +} + +bool Base64Decoder::finalize() +{ + if (m_finalized) { + throw std::logic_error("Already finalized."); + } + + m_finalized = true; + + m_input.erase(std::remove_if(m_input.begin(), + m_input.end(), + whiteCharacter), + m_input.end()); + + for (size_t i = 0; i < m_input.size(); ++i) { + if (isalnum(m_input[i]) + || m_input[i] == '+' + || m_input[i] == '/' + || m_input[i] == '=') + continue; + + return false; + } + + BIO *b64, *bmem; + size_t len = m_input.size(); + + RawBuffer buffer(len); + + if (!buffer.data()) { + throw std::logic_error("Error in malloc."); + } + + memset(buffer.data(), 0, buffer.size()); + b64 = BIO_new(BIO_f_base64()); + + if (!b64) { + throw std::logic_error("Couldn't create BIO object."); + } + + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); + RawBuffer tmp(m_input); + m_input.clear(); + + bmem = BIO_new_mem_buf(tmp.data(), len); + + if (!bmem) { + BIO_free(b64); + throw std::logic_error("Internal error in BIO"); + } + + bmem = BIO_push(b64, bmem); + + if (!bmem) { + BIO_free(b64); + throw std::logic_error("Internal error in BIO"); + } + + int readlen = BIO_read(bmem, buffer.data(), buffer.size()); + m_output.clear(); + + bool status = true; + + if (readlen > 0) { + buffer.resize(readlen); + m_output = std::move(buffer); + } else { + status = false; + } + + BIO_free_all(bmem); + return status; +} + +RawBuffer Base64Decoder::get() const +{ + if (!m_finalized) { + throw std::logic_error("Not finalized"); + } + + return m_output; +} + +void Base64Decoder::reset() +{ + m_finalized = false; + m_input.clear(); + m_output.clear(); +} + +} // namespace CKM diff --git a/tools/ckm_initial_values/base64.h b/tools/ckm_initial_values/base64.h new file mode 100644 index 0000000..c9085bf --- /dev/null +++ b/tools/ckm_initial_values/base64.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2011 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. + */ +#ifndef _BASE64_H_ +#define _BASE64_H_ + +#include +#include + +typedef std::vector RawBuffer; + +struct bio_st; +typedef bio_st BIO; + +namespace CKM { + +class Base64Encoder { +public: + Base64Encoder(); + void append(const RawBuffer &data); + void finalize(); + RawBuffer get(); + void reset(); + ~Base64Encoder(); + +private: + BIO *m_b64; + BIO *m_bmem; + bool m_finalized; +}; + +class Base64Decoder { +public: + Base64Decoder(); + void append(const RawBuffer &data); + + /* + * Function will return false when BIO_read fails + * (for example: when string was not in base64 format). + */ + bool finalize(); + RawBuffer get() const; + void reset(); + ~Base64Decoder() {} + +private: + RawBuffer m_input; + RawBuffer m_output; + bool m_finalized; +}; +} // namespace CKM + +#endif diff --git a/tools/ckm_initial_values/main.cpp b/tools/ckm_initial_values/main.cpp new file mode 100644 index 0000000..4e9e0a1 --- /dev/null +++ b/tools/ckm_initial_values/main.cpp @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2018 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 + */ +/* + * @file main.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief + */ + +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include "base64.h" + +typedef std::vector Buffer; +typedef std::istreambuf_iterator InputIterator; + +const size_t DEFAULT_TAG_LEN = 16; +const size_t DEFAULT_IV_LEN = 16; + +const struct option OPTS[] = { + {"xml", required_argument, 0, 'x'}, + {"key", required_argument, 0, 'k'}, + {"name", required_argument, 0, 'n'}, + {"data", required_argument, 0, 'd'}, + {"type", required_argument, 0, 't'}, + {"subtype", required_argument, 0, 's'}, + {"password", required_argument, 0, 'p'}, + {"exportable", no_argument, 0, 'e'}, + {"accessors", required_argument, 0, 'a'}, + {"backend", required_argument, 0, 'b'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0 } +}; + +const std::string KEY = "Key"; +const std::string DATA = "Data"; +const std::string CERT = "Cert"; +const std::set TYPES = { KEY, DATA, CERT }; +const std::set SUBTYPES = { "RSA_PRV", "RSA_PUB", + "DSA_PRV", "DSA_PUB", + "ECDSA_PRV", "ECDSA_PUB", + "AES" +}; +const std::set BACKENDS = { "software", "hardware" }; + +struct FormatTag { + const std::string plain; + const std::string encrypted; +}; + +const std::unordered_map FORMAT = { + { KEY, {"DER", "EncryptedDER"}}, + { DATA, {"Base64", "EncryptedBinary"}}, + { CERT, {"DER", "EncryptedDER"}}, +}; + +std::string base64(const Buffer& data) +{ + try { + CKM::Base64Encoder encoder; + encoder.append(data); + encoder.finalize(); + auto result = encoder.get(); + return std::string(result.begin(), result.end()); + } catch (std::exception &e) { + std::cerr << "Error: " << e.what() << std::endl; + } + return std::string(); +} + +struct InitialValue { + InitialValue() {} + + std::string name, type, subType, data, iv, tag, password, format, backend, exportable; + std::set accessors; +}; + +void usage() +{ + std::cout << std::endl << + "Usage: ckm_initial_values " << std::endl << + std::endl << + "Mandatory options:" << std::endl << + " -d|--data Path to file containing initial value to be added. Supported" << std::endl << + " formats:" << std::endl << + " - Key:" << std::endl << + " - raw binary (symmetric keys)" << std::endl << + " - DER (asymmetric keys)" << std::endl << + " - Data: raw binary" << std::endl << + " - Cert: DER" << std::endl << + " -n|--name Name, under which the initial value will be saved." << std::endl << + " -t|--type Initial value type. One of: Key, Data, Cert." << std::endl << + " -s|--subtype Initial value subtype. For 'Key' type allowed values are:" << std::endl << + " RSA_PRV, RSA_PUB, DSA_PRV, DSA_PUB, ECDSA_PRV, ECDSA_PUB, AES." << std::endl << + " For other types this option should not be used." << std::endl << + std::endl << + "Optional:" << std::endl << + " -x|--xml Path to XML file that should be modified. If not provided output" << std::endl << + " will be printed to stdout." << std::endl << + " -k|--key Path to file containing AES key in binary form used for initial" << std::endl << + " value encryption." << std::endl << + " -p|--password Password used to encrypt the initial value." << std::endl << + " -e|--exportable If present the stored value can be later extracted via" << std::endl << + " key-manager API." << std::endl << + " -a|--accessors [,[,...]]" << std::endl << + " A list of key-manager clients allowed to access given initial" << std::endl << + " value separated by commas." << std::endl << + " -b|--backend A key-manager's backed to use when saving the initial values." << std::endl; +} + +Buffer readFile(const std::string& file) +{ + if (file.empty()) + return Buffer(); + + std::ifstream stream(file); + if (!stream.good()) { + std::cerr << "Invalid file " << file << std::endl; + ::exit(EXIT_FAILURE); + } + + Buffer data(InputIterator(stream), { }); + return data; +} + + +bool encrypt(const Buffer& data, const Buffer& key, Buffer& output, Buffer& iv, Buffer& tag) +{ + OPENSSL_init(); + + iv.resize(DEFAULT_IV_LEN); + + std::ifstream stream("/dev/urandom"); + if (!stream.good()) { + std::cerr << "Can't open /dev/urandom" << std::endl; + return false; + } + // FIXIT + stream.read(reinterpret_cast(iv.data()), DEFAULT_IV_LEN); + + std::unique_ptr ctx(EVP_CIPHER_CTX_new(), + EVP_CIPHER_CTX_free); + + if (!ctx) { + std::cerr << "EVP_CIPHER_CTX_new() failed" << std::endl; + return false; + } + + if (1 != EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL)) { + std::cerr << "EVP_EncryptInit_ex() failed" << std::endl; + return false; + } + + if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, iv.size(), NULL)) { + std::cerr << "EVP_CIPHER_CTX_ctrl() failed" << std::endl; + return false; + } + + if (1 != EVP_EncryptInit_ex(ctx.get(), NULL, NULL, key.data(), iv.data())) { + std::cerr << "EVP_EncryptInit_ex() failed" << std::endl; + return false; + } + + int outputLen = 0; + output.resize(data.size() + EVP_CIPHER_CTX_block_size(ctx.get())); + int written = 0; + + if (1 != EVP_EncryptUpdate(ctx.get(), output.data(), &written, data.data(), data.size())) { + std::cerr << "EVP_EncryptUpdate() failed" << std::endl; + return false; + } + outputLen += written; + + if (1 != EVP_EncryptFinal_ex(ctx.get(), &output.data()[written], &written)) { + std::cerr << "EVP_EncryptFinal_ex() failed" << std::endl; + return false; + } + outputLen += written; + output.resize(outputLen); + + tag.resize(DEFAULT_TAG_LEN); + if (1 != EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, DEFAULT_TAG_LEN, tag.data())) { + std::cerr << "EVP_CIPHER_CTX_ctrl() failed" << std::endl; + return false; + } + + return true; +} + +struct ScopedXmlLib { + ScopedXmlLib() : doc(NULL), commit(false) { + xmlInitParser(); + LIBXML_TEST_VERSION; + xmlKeepBlanksDefault(0); + } + + ~ScopedXmlLib() { + xmlFreeDoc(doc); + xmlCleanupParser(); + } + + xmlDocPtr doc; + bool commit; +}; + +xmlNodePtr addChild(xmlNodePtr parent, const std::string& name) +{ + auto childNode = xmlNewNode(NULL, BAD_CAST name.c_str()); + if (childNode == NULL) { + std::cerr << "xmlNewNode() failed for " << name << std::endl; + return NULL; + } + + if (xmlAddChild(parent, childNode) == NULL) { + std::cerr << "xmlAddChild() failed" << std::endl; + xmlFreeNode(childNode); + return NULL; + } + + return childNode; +} + +bool addProperty(xmlNodePtr element, const std::string& name, const std::string& value) +{ + if (value.empty()) + return true; + + if (xmlNewProp(element, BAD_CAST name.c_str(), BAD_CAST value.c_str()) == NULL) { + std::cerr << "xmlNewProp() failed for " << name << std::endl; + return false; + } + return true; +} + +bool addInitialValue(const std::string& xmlFile, const InitialValue& val) +{ + ScopedXmlLib lib; + + lib.doc = xmlReadFile(xmlFile.c_str(), NULL, XML_PARSE_NOWARNING); + if (lib.doc == NULL) { + lib.doc = xmlNewDoc(BAD_CAST "1.0"); + if (lib.doc == NULL) { + std::cerr << "xmlNewDoc() failed" << std::endl; + return false; + } + } + + // root node + auto rootNode = xmlDocGetRootElement(lib.doc); + if (rootNode == NULL) { + rootNode = xmlNewNode(NULL, BAD_CAST "InitialValues"); + if (rootNode == NULL) { + std::cerr << "xmlNewNode() failed" << std::endl; + return false; + } + + xmlDocSetRootElement(lib.doc, rootNode); + + if (!addProperty(rootNode, "version", "2")) + return false; + } + + // value node + auto valNode = addChild(rootNode, val.type); + if (valNode == NULL) + return false; + + if (!addProperty(valNode, "name", val.name)) + return false; + + if (!addProperty(valNode, "type", val.subType)) + return false; + + if (!addProperty(valNode, "password", val.password)) + return false; + + if (!addProperty(valNode, "exportable", val.exportable)) + return false; + + if (!addProperty(valNode, "backend", val.backend)) + return false; + + // data node + auto dataNode = xmlNewTextChild(valNode, + NULL, + BAD_CAST val.format.c_str(), + BAD_CAST val.data.c_str()); + if (dataNode == NULL) + return false; + + if (!addProperty(dataNode, "IV", val.iv)) + return false; + + if (!addProperty(dataNode, "tag", val.tag)) + return false; + + // accessor nodes + for (auto& accessor : val.accessors) { + auto accNode = addChild(valNode, "Permission"); + if (accNode == NULL) + return false; + + if (!addProperty(accNode, "accessor", accessor)) + return false; + } + + if (0 >= xmlSaveFormatFile(xmlFile.empty() ? "-" : xmlFile.c_str(), lib.doc, 1)) { + std::cerr << "xmlSaveFile() failed" << std::endl; + return false; + } + return true; +} + +int main(int argc, char* argv[]) +{ + std::string xmlFile, keyFile, dataFile; + Buffer key, data, iv, tag; + InitialValue val; + + int idx = 0; + int c; + while ((c = ::getopt_long(argc, argv, "x:k:n:d:t:s:p:ea:b:h", OPTS, &idx)) != -1) { + switch (c) { + case 'x': + xmlFile = optarg; + break; + case 'k': + keyFile = optarg; + break; + case 'n': + val.name = optarg; + break; + case 'd': + dataFile = optarg; + break; + case 't': + val.type = optarg; + break; + case 's': + val.subType = optarg; + break; + case 'p': + val.password = optarg; + break; + case 'e': + val.exportable = "true"; + break; + case 'a': + { + std::string tmp = optarg; + size_t pos = 0; + size_t found = 0; + while ((found = tmp.find(',', pos)) != std::string::npos) { + if (found != pos) + val.accessors.insert(tmp.substr(pos, found - pos)); + pos = found + 1; + } + if (pos < tmp.size()) + val.accessors.insert(tmp.substr(pos)); + break; + } + case 'b': + val.backend = optarg; + break; + case 'h': + usage(); + return EXIT_SUCCESS; + case '?': + case ':': + default: + usage(); + return EXIT_FAILURE; + } + } + + if (val.name.empty() || dataFile.empty() || val.type.empty()) { + usage(); + return EXIT_FAILURE; + } + + if (TYPES.find(val.type) == TYPES.end()) { + usage(); + return EXIT_FAILURE; + } + + if (val.type == KEY && (val.subType.empty() || SUBTYPES.find(val.subType) == SUBTYPES.end())) { + usage(); + return EXIT_FAILURE; + } + + if (!val.backend.empty() && BACKENDS.find(val.backend) == BACKENDS.end()) { + usage(); + return EXIT_FAILURE; + } + + data = readFile(dataFile); + if (data.empty()) { + std::cerr << "Empty data file " << dataFile << std::endl; + return EXIT_FAILURE; + } + + key = readFile(keyFile); + + val.format = FORMAT.at(val.type).plain; + if (!keyFile.empty()) { + if (key.size() != 32) { + std::cerr << "Invalid key size " << std::endl; + return EXIT_FAILURE; + } + + Buffer output; + if (!encrypt(data, key, output, iv, tag)) + return EXIT_FAILURE; + + val.data = base64(output); + if (val.data.empty()) + return EXIT_FAILURE; + + val.iv = base64(iv); + if (val.iv.empty()) + return EXIT_FAILURE; + + val.tag = base64(tag); + if (val.tag.empty()) + return EXIT_FAILURE; + + val.format = FORMAT.at(val.type).encrypted; + } else { + val.data = base64(data); + } + + if (!addInitialValue(xmlFile, val)) + return EXIT_FAILURE; + + return EXIT_SUCCESS; +} -- 2.7.4 From 7d81f2d157e4f2f2d1aae5f1e327a1bb073da82b Mon Sep 17 00:00:00 2001 From: Krzysztof Jackiewicz Date: Fri, 5 Oct 2018 16:17:44 +0200 Subject: [PATCH 16/16] Overwrite existing initial values Delete any existing values of given name before saving new one. Change-Id: I4cf23efad7cff6ef453f1ed7e4bfcda76d2fdc69 --- src/manager/initial-values/InitialValueHandler.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/manager/initial-values/InitialValueHandler.cpp b/src/manager/initial-values/InitialValueHandler.cpp index 6ca335a..ef06c1a 100644 --- a/src/manager/initial-values/InitialValueHandler.cpp +++ b/src/manager/initial-values/InitialValueHandler.cpp @@ -78,6 +78,9 @@ void InitialValueHandler::End() // save data Policy policy(m_password, m_exportable, m_backend); + m_db_logic.removeData(Credentials(CKMLogic::SYSTEM_DB_UID, CLIENT_ID_SYSTEM), + 0, m_name, CLIENT_ID_SYSTEM); + int ec = m_db_logic.importInitialData(m_name, Crypto::Data(getDataType(), m_bufferHandler->getData()), m_bufferHandler->getEncryptionParams(), -- 2.7.4