<?xml version="1.0" encoding="UTF-8"?>
-<InitialValues version="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="initial_values.xsd ">
+<InitialValues version="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="initial_values.xsd">
<Key name="key1" type="RSA_PUB" password="123">
<PEM>
-----BEGIN PUBLIC KEY-----
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<DeviceKey version="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="sw_key.xsd ">
+ <RSAPrivateKey>
+ <DER>
+ MIIEpAIBAAKCAQEAyJjUHY2pJJUBRBCrlerrgcS7aBiWlY3594dufu3m4qy48b9hsw1R/AHSNUPU
+ 11vzQ+kUcXkEZOby5SHRHBAXIJ1dLbTPtRwsVwgf1nmc/ZGGV/XOrOaKi7nSKgYHaglPgc9dLPuu
+ osRHs/EdIWh3o59MdY6rA6y+QTJrQm3axRKdT7unX3kFS3SsId02GWBkLtrw+yQVtvhCYlY/n2/T
+ uZBJpZN7vT2it0rJS4fQkfjcjAi8f/isZLrfUgDqxIDSWVbVyjlQOphIO+K3ABjev3ZbJMWl+w10
+ pV0nbmF8lviEYft9mhERS9kUdQwzy3KIgyjyt+ewQG6hjyMJ/5y5KwIDAQABAoIBAQC3S06nIoZn
+ su/RLhpbhqljjkxgNfeC+JRsJghFW0UZ4xGrdGDlp0o+p7tYiH63uoFykEvp09a8DHvt+xSEO/+m
+ AaTe2tTgfLnXXMkaxU06Nfs37JfJTW9TdZwgYhnsPk20I7LUI7XTbN7IAY3ItRh9HlZTJOYHGZVP
+ Ja70qES6xUOTaVOvKIbB2W9XeiMX6cNoHTLM9rl1I8bA13Er0M0acKRtF4Rfw4z43nJKzORCYKm3
+ mA3zqtQja7z+zdQBib34RHZiKgvuJDqg89p7FTLT9z+lbXONH+K/3MldaYG1O8mtgt4zv6onH199
+ QBOrww158Z6keH3tBz+xsrClfIpBAoGBAPkar4ugZYLRgyuythby3uHrlMBNajmJf2gFwngvfUgO
+ JS45fLN2AIDrA5VYUiT8cFjVFfzEiu1xa33Juy8rfHlQuY8yOIVDnbdGJvOBYsrvlyYWY+9jEydd
+ cLctQKquACLb3jNYbrC9m8cBBcSZelRAVSF4O1k8HdlcdV7IIVyjAoGBAM4mY5PNLr3I/pyyNizw
+ 7cUmHdblU+sScwFdC/KDwfG5WOI3WorTLutD4EiEA3yQIDStuVJLiray4Pu+bqhUPAJumpRrpQJ4
+ PCPxr/M98FhXvMmDWzGu/xK/6hLP5g1Ngp6qvVygnYNBkyqMzfM0rUAxQLS3qmocWk2xBKDEnjHZ
+ AoGBAJkWgVO52yiuQYKVbbpkv/zvnpcf/GwnyBjRkVXzOXcS2l6yDaTsnBqeU7FweespCJJPQhf5
+ YbfSwFCprVOr0e9sYN1T69BaYY7EmiOEHIbC/4z0ra3soVTL4/1u3hMGpCbIIKJFcqFDpXyDcFwG
+ RluIvci37yFEBMQUQj1hmL8pAoGAJBHtfG/7TLO9cRdxiT2CrOs1b2Ni4o+w1b09GOra5XujxLkg
+ u4el/v46YRXQMlxZdj4rXe3f0IXN/d5dKFDMyzQlEfEfxyXYiAWC3tGomxyG6M92BmRzNwmjYDVG
+ MG+ueiqvxWRJCy1PHbPTWUmPQtsbUkOMqtJZLpzZjXO5pkkCgYA9uyQ8os9yfjALc1VDZ4HtGxaC
+ Uq8zy0jJEJxchRn1JUNHop/skaRA65x613lWDygfNCuakozjP5x+GA5WEIuxIE8V7JPac1zpEZW4
+ 5nwmxoR1l3HUDT8kRYkLzMIo55PpLG9arNLwH9mSRh/taG8020aGg3nFSNCJNDs12x/9RA==
+ </DER>
+ </RSAPrivateKey>
+</DeviceKey>
<xsd:element name="Base64"
type="EncodingRawType" maxOccurs="1" minOccurs="1">
</xsd:element>
+ <xsd:element name="EncryptedBase64"
+ type="EncodingRawType" maxOccurs="1" minOccurs="1">
+ </xsd:element>
</xsd:choice>
<xsd:element name="Permission" type="PermissionType" maxOccurs="unbounded" minOccurs="0"></xsd:element>
</xsd:sequence>
<xsd:attribute name="accessor" type="xsd:string"></xsd:attribute>
</xsd:complexType>
-</xsd:schema>
\ No newline at end of file
+</xsd:schema>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
+ <xsd:element name="DeviceKey" type="DeviceKeyType"></xsd:element>
+
+ <xsd:complexType name="DeviceKeyType">
+ <xsd:sequence maxOccurs="1" minOccurs="1">
+ <xsd:choice maxOccurs="1" minOccurs="1">
+ <xsd:element name="RSAPrivateKey" type="RSAPrivateKeyType"
+ maxOccurs="1" minOccurs="1">
+ </xsd:element>
+ </xsd:choice>
+ </xsd:sequence>
+ <xsd:attribute name="version" type="xsd:int" use="required"></xsd:attribute>
+ </xsd:complexType>
+
+ <xsd:complexType name="RSAPrivateKeyType">
+ <xsd:sequence maxOccurs="1" minOccurs="1">
+ <xsd:choice maxOccurs="1" minOccurs="1">
+ <xsd:element name="PEM"
+ type="EncodingPemType" maxOccurs="1" minOccurs="1">
+ </xsd:element>
+ <xsd:element name="DER"
+ type="EncodingDerType" maxOccurs="1" minOccurs="1">
+ </xsd:element>
+ <xsd:element name="Base64"
+ type="EncodingRawType" maxOccurs="1" minOccurs="1">
+ </xsd:element>
+ </xsd:choice>
+ </xsd:sequence>
+ </xsd:complexType>
+
+ <xsd:simpleType name="EncodingDerType">
+ <xsd:restriction base="xsd:string"></xsd:restriction>
+ </xsd:simpleType>
+ <xsd:simpleType name="EncodingPemType">
+ <xsd:restriction base="xsd:string"></xsd:restriction>
+ </xsd:simpleType>
+ <xsd:simpleType name="EncodingRawType">
+ <xsd:restriction base="xsd:string"></xsd:restriction>
+ </xsd:simpleType>
+</xsd:schema>
ln -s ../central-key-manager-api-control.socket %{buildroot}%{_unitdir}/sockets.target.wants/central-key-manager-api-control.socket
ln -s ../central-key-manager-api-storage.socket %{buildroot}%{_unitdir}/sockets.target.wants/central-key-manager-api-storage.socket
ln -s ../central-key-manager-api-ocsp.socket %{buildroot}%{_unitdir}/sockets.target.wants/central-key-manager-api-ocsp.socket
+ln -s ../central-key-manager-api-encryption.socket %{buildroot}%{_unitdir}/sockets.target.wants/central-key-manager-api-encryption.socket
%clean
rm -rf %{buildroot}
%{_unitdir}/central-key-manager-api-storage.socket
%{_unitdir}/sockets.target.wants/central-key-manager-api-ocsp.socket
%{_unitdir}/central-key-manager-api-ocsp.socket
+%{_unitdir}/sockets.target.wants/central-key-manager-api-encryption.socket
+%{_unitdir}/central-key-manager-api-encryption.socket
%{_datadir}/license/%{name}
%{_datadir}/ckm/scripts/*.sql
%{_datadir}/
${KEY_MANAGER_PATH}/service/db-crypto.cpp
${KEY_MANAGER_PATH}/service/ocsp-service.cpp
${KEY_MANAGER_PATH}/service/ocsp-logic.cpp
+ ${KEY_MANAGER_PATH}/service/encryption-service.cpp
+ ${KEY_MANAGER_PATH}/service/encryption-logic.cpp
${KEY_MANAGER_PATH}/initial-values/parser.cpp
${KEY_MANAGER_PATH}/initial-values/BufferHandler.cpp
${KEY_MANAGER_PATH}/initial-values/CertHandler.cpp
});
}
-int ManagerImpl::encrypt(const CryptoAlgorithm &algo,
- const Alias &keyAlias,
- const Password &password,
- const RawBuffer& plain,
- RawBuffer& encrypted)
+int ManagerImpl::crypt(EncryptionCommand command,
+ const CryptoAlgorithm &algo,
+ const Alias &keyAlias,
+ const Password &password,
+ const RawBuffer& input,
+ RawBuffer& output)
{
int my_counter = ++m_counter;
MessageBuffer recv;
AliasSupport helper(keyAlias);
CryptoAlgorithmSerializable cas(algo);
- auto send = MessageBuffer::Serialize(static_cast<int>(EncryptionCommand::ENCRYPT),
+ auto send = MessageBuffer::Serialize(static_cast<int>(command),
my_counter,
cas,
helper.getName(),
helper.getLabel(),
password,
- plain);
+ input);
int retCode = m_encryptionConnection.processRequest(send.Pop(), recv);
if (CKM_API_SUCCESS != retCode)
int command;
int counter;
- recv.Deserialize(command, counter, encrypted);
+ recv.Deserialize(command, counter, retCode, output);
if (my_counter != counter) {
return CKM_API_ERROR_UNKNOWN;
});
}
+int ManagerImpl::encrypt(const CryptoAlgorithm &algo,
+ const Alias &keyAlias,
+ const Password &password,
+ const RawBuffer& plain,
+ RawBuffer& encrypted)
+{
+ return crypt(EncryptionCommand::ENCRYPT, algo, keyAlias, password, plain, encrypted);
+}
+
int ManagerImpl::decrypt(const CryptoAlgorithm &algo,
const Alias &keyAlias,
const Password &password,
const RawBuffer& encrypted,
RawBuffer& decrypted)
{
- int my_counter = ++m_counter;
-
- return try_catch([&] {
- MessageBuffer recv;
- AliasSupport helper(keyAlias);
- CryptoAlgorithmSerializable cas(algo);
- auto send = MessageBuffer::Serialize(static_cast<int>(EncryptionCommand::DECRYPT),
- my_counter,
- cas,
- helper.getName(),
- helper.getLabel(),
- password,
- encrypted);
-
- int retCode = m_encryptionConnection.processRequest(send.Pop(), recv);
- if (CKM_API_SUCCESS != retCode)
- return retCode;
-
- int command;
- int counter;
- recv.Deserialize(command, counter, decrypted);
-
- if (my_counter != counter) {
- return CKM_API_ERROR_UNKNOWN;
- }
-
- return retCode;
- });
+ return crypt(EncryptionCommand::DECRYPT, algo, keyAlias, password, encrypted, decrypted);
}
ManagerShPtr Manager::create() {
const Policy &policyPrivateKey,
const Policy &policyPublicKey);
+ int crypt(EncryptionCommand command,
+ const CryptoAlgorithm &algo,
+ const Alias &keyAlias,
+ const Password &password,
+ const RawBuffer& input,
+ RawBuffer& output);
+
int m_counter;
CKM::ServiceConnection m_storageConnection;
CKM::ServiceConnection m_ocspConnection;
virtual ~GKey () {}
};
+typedef std::unique_ptr<GKey> GKeyUPtr;
typedef std::shared_ptr<GKey> GKeyShPtr;
} // namespace Crypto
class GStore {
public:
- virtual GKeyShPtr getKey(const Token &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
+ virtual GKeyUPtr getKey(const Token &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
virtual TokenPair generateAKey(const CryptoAlgorithm &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
virtual Token generateSKey(const CryptoAlgorithm &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
virtual Token import(DataType, const RawBuffer &) { ThrowErr(Exc::Crypto::OperationNotSupported); }
#include <sw-backend/store.h>
#include <sw-backend/internals.h>
+namespace {
+
+template <typename T, typename ...Args>
+std::unique_ptr<T> make_unique(Args&& ...args) {
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+} // namespace anonymous
+
namespace CKM {
namespace Crypto {
namespace SW {
Internals::initialize();
}
-GKeyShPtr Store::getKey(const Token &token) {
+GKeyUPtr Store::getKey(const Token &token) {
if (token.backendId != m_backendId) {
ThrowErr(Exc::Crypto::WrongBackend, "Decider choose wrong backend!");
}
if (token.dataType.isKeyPrivate() || token.dataType.isKeyPublic()) {
- return std::make_shared<AKey>(token.data, token.dataType);
+ return make_unique<AKey>(token.data, token.dataType);
}
if (token.dataType == DataType(DataType::KEY_AES)) {
- return std::make_shared<SKey>(token.data, token.dataType);
+ return make_unique<SKey>(token.data, token.dataType);
}
if (token.dataType.isCertificate()) {
- return std::make_shared<Cert>(token.data, token.dataType);
+ return make_unique<Cert>(token.data, token.dataType);
}
ThrowErr(Exc::Crypto::KeyNotSupported,
public:
explicit Store(CryptoBackend backendId);
- virtual GKeyShPtr getKey(const Token &token);
+ virtual GKeyUPtr getKey(const Token &token);
virtual TokenPair generateAKey(const CryptoAlgorithm &);
virtual Token generateSKey(const CryptoAlgorithm &);
virtual Token import(DataType dataType, const RawBuffer &buffer);
: GStore(backendId)
{}
-GKeyShPtr Store::getKey(const Token &) {
+GKeyUPtr Store::getKey(const Token &) {
ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!");
}
public:
explicit Store(CryptoBackend backendId);
- virtual GKeyShPtr getKey(const Token &token);
+ virtual GKeyUPtr getKey(const Token &token);
virtual TokenPair generateAKey(const CryptoAlgorithm &);
virtual Token import(DataType dataType, const RawBuffer &buffer);
virtual void destroy(const Token &){}
}
// Sends message of type M to all registered listeners
- void SendMessage(const M& msg)
+ // Returns the number of listeners called
+ size_t SendMessage(const M& msg) const
{
- for(auto it : m_listeners)
+ size_t num = 0;
+ for(auto& it : m_listeners) {
it(msg);
+ num++;
+ }
+ return num;
}
protected:
MessageManager() {}
}
// M message type
+ // Sending a message calls an unknown listener callback on the receiving side. It may throw.
template <typename M>
- void SendMessage(const M& msg)
+ size_t SendMessage(const M& msg) const
{
- MessageManager<M>::SendMessage(msg);
+ return MessageManager<M>::SendMessage(msg);
}
};
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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 credentials.h
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#pragma once
+
+#include <sys/types.h>
+#include <ckm/ckm-type.h>
+
+namespace CKM {
+
+struct Credentials {
+ Credentials() : clientUid(0) {}
+ Credentials(uid_t socketUid, const Label & socketLabel)
+ : clientUid(socketUid), smackLabel(socketLabel) {}
+ uid_t clientUid;
+ Label smackLabel;
+};
+
+} // namespace CKM
#include <generic-event.h>
#include <dpl/raw-buffer.h>
#include <ckm/ckm-type.h>
+#include <credentials.h>
+#include <service-messages.h>
extern "C" {
struct msghdr;
typedef int InterfaceID;
-struct Credentials {
- Credentials() : clientUid(0) {}
- Credentials(uid_t socketUid, const Label & socketLabel)
- : clientUid(socketUid), smackLabel(socketLabel) {}
- uid_t clientUid;
- Label smackLabel;
-};
-
struct ConnectionID {
int sock; // This is decriptor used for connection
int counter; // Unique handler per socket
virtual void SetSocketManager(GenericSocketManager *manager) {
m_serviceManager = manager;
}
+ virtual void SetCommManager(CommMgr *manager) {
+ m_commMgr = manager;
+ }
virtual ServiceDescriptionVector GetServiceDescription() = 0;
virtual void Event(const AcceptEvent &event) = 0;
virtual void Start() = 0;
virtual void Stop() = 0;
- GenericSocketService() : m_serviceManager(NULL) {}
+ GenericSocketService() : m_serviceManager(NULL), m_commMgr(NULL) {}
virtual ~GenericSocketService(){}
protected:
GenericSocketManager *m_serviceManager;
+ CommMgr *m_commMgr;
};
struct GenericSocketManager {
#include <ckm-service.h>
#include <ocsp-service.h>
+#include <encryption-service.h>
#include <key-provider.h>
#include <file-system.h>
REGISTER_SOCKET_SERVICE(manager, CKM::CKMService);
REGISTER_SOCKET_SERVICE(manager, CKM::OCSPService);
+ REGISTER_SOCKET_SERVICE(manager, CKM::EncryptionService);
manager.MainLoop();
}
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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 message-service.h
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#pragma once
+
+#include <mutex>
+#include <list>
+#include <utility>
+#include <thread-service.h>
+#include <noncopyable.h>
+#include <dpl/log/log.h>
+
+namespace CKM {
+
+/*
+ * MessageService framework is a wrapper for inter service communication with use of
+ * CommunicationManager. It allows registering a service as a listener in CommunicationManager and
+ * provides thread safe message handling. The message received from communication manager in
+ * SENDER THREAD is passed to RECEIVER THREAD. The RECEIVER THREAD is notified with
+ * ServiceThread::CreateEvent which in turn calls provided callback in this thread.
+ */
+
+template <typename ...Msgs>
+class MessageService;
+
+
+// aggregating template
+template <typename Msg, typename ...Msgs>
+class MessageService<Msg, Msgs...> : public MessageService<Msg>, public MessageService<Msgs...>
+{
+protected:
+ // RECEIVER THREAD
+ template <typename Mgr>
+ void Register(Mgr& mgr) {
+ MessageService<Msg>::Register(mgr);
+ MessageService<Msgs...>::Register(mgr);
+ }
+ // RECEIVER THREAD
+ void CheckMessages() {
+ MessageService<Msg>::CheckMessages();
+ MessageService<Msgs...>::CheckMessages();
+ }
+};
+
+
+// single Message type (Msg) handler
+template <typename Msg>
+class MessageService<Msg>
+{
+public:
+ MessageService() {}
+ virtual ~MessageService() {}
+ NONCOPYABLE(MessageService);
+
+protected:
+ // RECEIVER THREAD: register as a listener of Msg
+ template <typename Mgr>
+ void Register(Mgr& mgr);
+
+ // SENDER THREAD: notify about new message
+ virtual void Notify() = 0;
+
+ // RECEIVER THREAD: check if there are new messages and process each of them
+ void CheckMessages();
+
+ // RECEIVER THREAD: process single message
+ virtual void ProcessMessage(Msg msg) = 0;
+
+private:
+ // SENDER THREAD: add message to the list
+ void AddMessage(const Msg& msg);
+
+ std::mutex m_messagesMutex;
+ std::list<Msg> m_messages;
+};
+
+template <typename Msg>
+template <typename Mgr>
+void MessageService<Msg>::Register(Mgr& mgr)
+{
+ mgr.Register<Msg>([this](const Msg& msg) { this->AddMessage(msg); });
+}
+
+template <typename Msg>
+void MessageService<Msg>::AddMessage(const Msg& msg)
+{
+ m_messagesMutex.lock();
+ m_messages.push_back(msg);
+ m_messagesMutex.unlock();
+ Notify(); // notify about added message
+}
+
+template <typename Msg>
+void MessageService<Msg>::CheckMessages()
+{
+ while(true) {
+ m_messagesMutex.lock();
+ if (m_messages.empty()) {
+ m_messagesMutex.unlock();
+ break;
+ }
+ // move out the first message
+ Msg message = std::move(m_messages.front());
+ m_messages.pop_front();
+ m_messagesMutex.unlock();
+
+ try {
+ ProcessMessage(std::move(message));
+ } catch(...) {
+ LogError("Uncaught exception in ProcessMessage");
+ }
+ }
+}
+
+
+// thread based service with messages support
+template <typename ...Msgs>
+class ThreadMessageService : public ThreadService, public MessageService<Msgs...>
+{
+public:
+ ThreadMessageService() {}
+ virtual ~ThreadMessageService() {}
+ NONCOPYABLE(ThreadMessageService);
+
+ // RECEIVER THREAD: register as a listener of all supported messages
+ template <typename Mgr>
+ void Register(Mgr& mgr) {
+ MessageService<Msgs...>::Register(mgr);
+ }
+
+private:
+ // SENDER THREAD: adds callback to RECEIVER THREAD event queue and wakes it
+ virtual void Notify() {
+ CreateEvent([this]() { this->CheckMessages(); });
+ }
+
+ // RECEIVER THREAD
+ void CheckMessages() {
+ MessageService<Msgs...>::CheckMessages();
+ }
+};
+
+} /* namespace CKM */
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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 service-messages.h
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#pragma once
+
+#include <memory>
+
+#include <credentials.h>
+#include <ckm/ckm-type.h>
+#include <protocols.h>
+#include <ckm/ckm-error.h>
+#include <communication-manager.h>
+#include <generic-backend/gkey.h>
+
+namespace CKM {
+
+// inter-service communication message base class
+struct MsgBase
+{
+ explicit MsgBase(int id) : id(id) {}
+ virtual ~MsgBase() {}
+
+ int id;
+};
+
+// 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)
+ {}
+ Credentials cred;
+ Name name;
+ Label label;
+ Password password;
+};
+
+// key response
+struct MsgKeyResponse : public MsgBase
+{
+ MsgKeyResponse(int id, const Crypto::GKeyShPtr& key, int errorCode = CKM_API_SUCCESS) :
+ MsgBase(id),
+ key(key),
+ error(errorCode)
+ {}
+ Crypto::GKeyShPtr key;
+ int error;
+};
+
+typedef CommunicationManager<MsgKeyRequest, MsgKeyResponse> CommMgr;
+
+} /* namespace CKM */
void Start() {}
void Stop() {}
- void Event(const AcceptEvent &event) { (void)event; }
- void Event(const WriteEvent &event) { (void)event; }
- void Event(const ReadEvent &event) { (void)event; }
- void Event(const CloseEvent &event) { (void)event; }
+ void Event(const AcceptEvent &) {}
+ void Event(const WriteEvent &) {}
+ void Event(const ReadEvent &) {}
+ void Event(const CloseEvent &) {}
};
struct SignalService : public GenericSocketService {
void Start() {}
void Stop() {}
- void Event(const AcceptEvent &event) { (void)event; } // not supported
- void Event(const WriteEvent &event) { (void)event; } // not supported
- void Event(const CloseEvent &event) { (void)event; } // not supported
+ void Event(const AcceptEvent &) {} // not supported
+ void Event(const WriteEvent &) {} // not supported
+ void Event(const CloseEvent &) {} // not supported
void Event(const ReadEvent &event) {
LogDebug("Get signal information");
void SocketManager::RegisterSocketService(GenericSocketService *service) {
service->SetSocketManager(this);
+ service->SetCommManager(&m_commMgr);
auto serviceVector = service->GetServiceDescription();
Try {
for (auto iter = serviceVector.begin(); iter != serviceVector.end(); ++iter)
#include <dpl/exception.h>
#include <generic-socket-manager.h>
+#include <service-messages.h>
namespace CKM {
int m_notifyMe[2];
int m_counter;
std::priority_queue<Timeout> m_timeoutQueue;
+ CommMgr m_commMgr;
};
} // namespace CKM
protected:
virtual bool ProcessOne(const ConnectionID &conn,
ConnectionInfo &info) = 0;
-private:
+
template <typename E>
void ThreadEvent(const E& event) {
CreateEvent([this, event]() { this->Handle(event); });
}
+private:
void Handle(const AcceptEvent &event);
void Handle(const WriteEvent &event);
handle.database.deleteKey(appSmackLabel);
}
}
- } catch (const KeyProvider::Exception::PassWordError &e) {
- LogError("Incorrect Password " << e.GetMessage());
- retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("Error in KeyProvider " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
} catch (const Exc::Exception &e) {
retCode = e.error();
} catch (const CKM::Exception &e) {
try
{
retCode = changeUserPasswordHelper(user, oldPassword, newPassword);
- } catch (const KeyProvider::Exception::PassWordError &e) {
- LogError("Incorrect Password " << e.GetMessage());
- retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("Error in KeyProvider " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
} catch (const Exc::Exception &e) {
retCode = e.error();
} catch (const CKM::Exception &e) {
{
retCode = saveDataHelper(cred, name, label, dataType, binaryData, policy);
}
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("KeyProvider failed with message: " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
} catch (const DB::Crypto::Exception::InternalError &e) {
LogError("DB::Crypto failed with message: " << e.GetMessage());
retCode = CKM_API_ERROR_DB_ERROR;
return retCode;
}
+int CKMLogic::getKeyForService(
+ const Credentials &cred,
+ const Name &name,
+ const Label &label,
+ const Password &pass,
+ Crypto::GKeyShPtr &key)
+{
+ DB::Row row;
+ try {
+ // Key is for internal service use. It won't be exported to the client
+ int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, label, pass, row);
+ if (retCode == CKM_API_SUCCESS)
+ key = m_decider.getStore(row).getKey(row);
+ return retCode;
+ } catch (const DB::Crypto::Exception::Base &e) {
+ LogError("DB::Crypto failed with message: " << e.GetMessage());
+ return CKM_API_ERROR_DB_ERROR;
+ } catch (const Exc::Exception &e) {
+ return e.error();
+ } catch (const CKM::Exception &e) {
+ LogError("CKM::Exception: " << e.GetMessage());
+ return CKM_API_ERROR_SERVER_ERROR;
+ }
+}
+
RawBuffer CKMLogic::saveData(
const Credentials &cred,
int commandId,
int retCode = CKM_API_ERROR_UNKNOWN;
try {
retCode = saveDataHelper(cred, name, label, pkcs, keyPolicy, certPolicy);
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("KeyProvider failed with message: " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
+ } catch (const Exc::Exception &e) {
+ retCode = e.error();
} catch (const DB::Crypto::Exception::InternalError &e) {
LogError("DB::Crypto failed with message: " << e.GetMessage());
retCode = CKM_API_ERROR_DB_ERROR;
try {
retCode = readDataHelper(true, cred, dataType, name, label, password, row);
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("KeyProvider failed with error: " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
} catch (const DB::Crypto::Exception::Base &e) {
LogError("DB::Crypto failed with message: " << e.GetMessage());
retCode = CKM_API_ERROR_DB_ERROR;
// prepare response
if(retCode == CKM_API_SUCCESS)
output = PKCS12Serializable(privKey, cert, caChain);
-
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("KeyProvider failed with error: " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
} catch (const DB::Crypto::Exception::Base &e) {
LogError("DB::Crypto failed with message: " << e.GetMessage());
retCode = CKM_API_ERROR_DB_ERROR;
if(retCode == CKM_API_SUCCESS) {
signature = m_decider.getStore(row).getKey(row)->sign(cryptoAlg, message);
}
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("KeyProvider failed with message: " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
} catch (const DB::Crypto::Exception::Base &e) {
LogError("DB::Crypto failed with message: " << e.GetMessage());
retCode = CKM_API_ERROR_DB_ERROR;
}
} catch (const Exc::Exception &e) {
retCode = e.error();
- } catch (const KeyProvider::Exception::Base &e) {
- LogError("KeyProvider failed with error: " << e.GetMessage());
- retCode = CKM_API_ERROR_SERVER_ERROR;
} catch (const DB::Crypto::Exception::Base &e) {
LogError("DB::Crypto failed with message: " << e.GetMessage());
retCode = CKM_API_ERROR_DB_ERROR;
#include <access-control.h>
#include <certificate-impl.h>
#include <sys/types.h>
+#include <generic-backend/gkey.h>
#include <platform/decider.h>
DataType dataType,
const PolicySerializable &policy);
+ int getKeyForService(const Credentials &cred,
+ const Name &name,
+ const Label &label,
+ const Password& pass,
+ Crypto::GKeyShPtr& key);
+
private:
// select private/system database depending on asking uid and owner label.
};
}
+void CKMService::SetCommManager(CommMgr *manager)
+{
+ ThreadService::SetCommManager(manager);
+ Register(*manager);
+}
+
bool CKMService::ProcessOne(
const ConnectionID &conn,
ConnectionInfo &info)
}
}
+void CKMService::ProcessMessage(MsgKeyRequest msg)
+{
+ Crypto::GKeyShPtr key;
+ int ret = m_logic->getKeyForService(msg.cred,
+ msg.name,
+ msg.label,
+ msg.password,
+ key);
+ MsgKeyResponse kResp(msg.id, key, ret);
+ try {
+ if (!m_commMgr->SendMessage(kResp))
+ LogError("No listener found"); // can't do much more
+ } catch (...) {
+ LogError("Uncaught exception in SendMessage. Check listeners.");
+ }
+}
+
} // namespace CKM
*/
#pragma once
-#include <thread-service.h>
+#include <mutex>
+#include <message-service.h>
#include <message-buffer.h>
#include <dpl/exception.h>
class CKMLogic;
-class CKMService : public CKM::ThreadService
+class CKMService : public ThreadMessageService<MsgKeyRequest>
{
public:
CKMService();
ServiceDescriptionVector GetServiceDescription();
private:
+ virtual void SetCommManager(CommMgr *manager);
+
class Exception {
public:
DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
Credentials &cred,
MessageBuffer &buffer);
+ virtual void ProcessMessage(MsgKeyRequest msg);
+
CKMLogic *m_logic;
};
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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 crypto-request.h
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#pragma once
+
+#include <generic-socket-manager.h>
+#include <protocols.h>
+#include <ckm/ckm-type.h>
+
+namespace CKM {
+
+struct CryptoRequest
+{
+ ConnectionID conn;
+ Credentials cred;
+ EncryptionCommand command;
+ int msgId;
+ CryptoAlgorithmSerializable cas;
+ Name name;
+ Label label;
+ Password password;
+ RawBuffer input;
+};
+
+} /* namespace CKM */
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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-logic.cpp
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#include <encryption-logic.h>
+#include <ckm/ckm-error.h>
+#include <dpl/log/log.h>
+
+namespace CKM {
+
+void EncryptionLogic::Crypt(const CryptoRequest& request)
+{
+ // check arguments
+ if(request.input.empty()) {
+ LogError("No input data");
+ m_service.RespondToClient(request, CKM_API_ERROR_INPUT_PARAM);
+ return;
+ }
+
+ // store request in the map
+ auto ret = m_requests.insert(std::make_pair(request.msgId, request));
+ if (!ret.second) {
+ LogError("Request with id " << request.msgId << " already exists");
+ m_service.RespondToClient(request, CKM_API_ERROR_INPUT_PARAM);
+ return;
+ }
+
+ // request key
+ try {
+ m_service.RequestKey(request);
+ } catch (...) {
+ LogError("Key request failed");
+ m_requests.erase(request.msgId);
+ m_service.RespondToClient(request, CKM_API_ERROR_SERVER_ERROR);
+ }
+}
+
+void EncryptionLogic::KeyRetrieved(MsgKeyResponse response)
+{
+ auto it = m_requests.find(response.id);
+ if (it == m_requests.end()) {
+ LogError("No matching request found"); // nothing we can do
+ return;
+ }
+ CryptoRequest req = std::move(it->second);
+ m_requests.erase(it);
+
+ if (response.error != CKM_API_SUCCESS) {
+ LogError("Attempt to retrieve key failed with error: " << response.error);
+ m_service.RespondToClient(req, response.error);
+ return;
+ }
+
+ if (!response.key) {
+ LogError("Retrieved key is empty");
+ m_service.RespondToClient(req, CKM_API_ERROR_SERVER_ERROR);
+ return;
+ }
+
+ // encrypt/decrypt
+ try {
+ RawBuffer output;
+ if (req.command == EncryptionCommand::ENCRYPT)
+ output = response.key->encrypt(req.cas, req.input);
+ else
+ output = response.key->decrypt(req.cas, req.input);
+ m_service.RespondToClient(req, CKM_API_SUCCESS, output);
+ } catch (const Exc::Exception& ex) {
+ m_service.RespondToClient(req, ex.error());
+ } catch (...) {
+ LogError("Uncaught exception from encrypt/decrypt.");
+ m_service.RespondToClient(req, CKM_API_ERROR_SERVER_ERROR);
+ }
+}
+
+} /* namespace CKM */
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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-logic.h
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#pragma once
+
+#include <map>
+#include <ckm/ckm-type.h>
+#include <generic-socket-manager.h>
+#include <protocols.h>
+#include <iencryption-service.h>
+#include <crypto-request.h>
+
+namespace CKM {
+
+class EncryptionLogic
+{
+public:
+ EncryptionLogic(IEncryptionService& service) : m_service(service) {}
+ virtual ~EncryptionLogic() {}
+
+ void Crypt(const CryptoRequest& request);
+ void KeyRetrieved(MsgKeyResponse response);
+private:
+ IEncryptionService& m_service;
+
+ std::map<int, CryptoRequest> m_requests;
+};
+
+} /* namespace CKM */
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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-service.cpp
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#include <stdexcept>
+#include <utility>
+#include <encryption-service.h>
+#include <protocols.h>
+#include <dpl/log/log.h>
+#include <dpl/serialization.h>
+#include <crypto-request.h>
+
+namespace {
+const CKM::InterfaceID SOCKET_ID_ENCRYPTION = 0;
+} // namespace anonymous
+
+namespace CKM {
+
+EncryptionService::EncryptionService() : m_logic(*this)
+{
+}
+
+EncryptionService::~EncryptionService()
+{
+}
+
+void EncryptionService::RespondToClient(const CryptoRequest& request,
+ int retCode,
+ const RawBuffer& data)
+{
+ try {
+ RawBuffer response = MessageBuffer::Serialize(
+ static_cast<int>(request.command), request.msgId, retCode, data).Pop();
+ m_serviceManager->Write(request.conn, response);
+ } catch (...) {
+ LogError("Failed to send response to the client");
+ }
+}
+
+void EncryptionService::RequestKey(const CryptoRequest& request)
+{
+ MsgKeyRequest kReq(request.msgId, request.cred, request.name, request.label, request.password);
+ if (!m_commMgr->SendMessage(kReq))
+ throw std::runtime_error("No listener found"); // TODO
+}
+
+GenericSocketService::ServiceDescriptionVector EncryptionService::GetServiceDescription()
+{
+ return ServiceDescriptionVector {
+ {SERVICE_SOCKET_ENCRYPTION, "key-manager::api-encryption", SOCKET_ID_ENCRYPTION}
+ };
+}
+
+void EncryptionService::Start() {
+ Create();
+}
+
+void EncryptionService::Stop() {
+ Join();
+}
+
+void EncryptionService::SetCommManager(CommMgr *manager)
+{
+ ThreadService::SetCommManager(manager);
+ Register(*manager);
+}
+
+bool EncryptionService::ProcessOne(
+ const ConnectionID &conn,
+ ConnectionInfo &info)
+{
+ LogDebug ("process One");
+ try {
+ if (!info.buffer.Ready())
+ return false;
+
+ ProcessEncryption(conn, info.credentials, info.buffer);
+ return true;
+ } catch (MessageBuffer::Exception::Base) {
+ LogError("Broken protocol. Closing socket.");
+ } catch (const std::exception &e) {
+ LogError("Std exception:: " << e.what());
+ } catch (...) {
+ LogError("Unknown exception. Closing socket.");
+ }
+
+ m_serviceManager->Close(conn);
+ return false;
+}
+
+void EncryptionService::ProcessMessage(MsgKeyResponse msg)
+{
+ m_logic.KeyRetrieved(std::move(msg));
+}
+
+void EncryptionService::ProcessEncryption(const ConnectionID &conn,
+ const Credentials &cred,
+ MessageBuffer &buffer)
+{
+ int tmpCmd = 0;
+ CryptoRequest req;
+
+ buffer.Deserialize(tmpCmd, req.msgId, req.cas, req.name, req.label, req.password, req.input);
+ req.command = static_cast<EncryptionCommand>(tmpCmd);
+ if (req.command != EncryptionCommand::ENCRYPT && req.command != EncryptionCommand::DECRYPT)
+ throw std::runtime_error("Unsupported command: " + tmpCmd);
+
+ req.conn = conn;
+ req.cred = cred;
+ m_logic.Crypt(req);
+}
+
+} /* namespace CKM */
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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-service.h
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#pragma once
+
+#include <message-service.h>
+#include <noncopyable.h>
+#include <iencryption-service.h>
+#include <encryption-logic.h>
+#include <service-messages.h>
+
+namespace CKM {
+
+class EncryptionService : public ThreadMessageService<MsgKeyResponse>, public IEncryptionService
+{
+public:
+ EncryptionService();
+ virtual ~EncryptionService();
+ NONCOPYABLE(EncryptionService);
+
+ // from ThreadService
+ ServiceDescriptionVector GetServiceDescription();
+
+ void Start();
+ void Stop();
+
+private:
+ virtual void SetCommManager(CommMgr *manager);
+
+ bool ProcessOne(const ConnectionID &conn, ConnectionInfo &info);
+ void ProcessMessage(MsgKeyResponse msg);
+ void ProcessEncryption(const ConnectionID &conn,
+ const Credentials &cred,
+ MessageBuffer &buffer);
+
+ // from IEncryptionService
+ virtual void RespondToClient(const CryptoRequest& request,
+ int retCode,
+ const RawBuffer& data = RawBuffer());
+ virtual void RequestKey(const CryptoRequest& request);
+
+ EncryptionLogic m_logic;
+};
+
+} /* namespace CKM */
--- /dev/null
+/*
+ * Copyright (c) 2000 - 2015 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 iencryption-service.h
+ * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version 1.0
+ */
+
+#pragma once
+
+#include <generic-socket-manager.h>
+#include <ckm/ckm-type.h>
+#include <generic-backend/gkey.h>
+#include <protocols.h>
+#include <crypto-request.h>
+
+namespace CKM {
+
+class IEncryptionService {
+public:
+ virtual void RespondToClient(const CryptoRequest& request,
+ int retCode,
+ const RawBuffer& data = RawBuffer()) = 0;
+ virtual void RequestKey(const CryptoRequest& request) = 0;
+};
+
+} // namespace CKM
+
+
+#include <exception.h>
#include <key-provider.h>
#include <dpl/log/log.h>
{
// overwrite key
char *ptr = reinterpret_cast<char*>(keyAndInfo);
- for (size_t size = 0; size < sizeof(KeyAndInfo); ++size)
- ptr[size] = 0;
+ memset(ptr, 0, sizeof(KeyAndInfo));
// verification
for (size_t size = 0; size < sizeof(KeyAndInfo); ++size) {
- if (0 != ptr[size]) {
- delete keyAndInfo;
- ThrowMsg(Exception::Base, "KeyAndInfo in KeyAndInfoContainer "
- "was not destroyed!");
+ if (ptr[size]) {
+ LogError("Write momory error! Memory used by key was not owerwritten.");
}
}
delete keyAndInfo;
, m_isInitialized(true)
{
if (!m_isInitialized) {
- ThrowMsg(Exception::InitFailed, "Object not initialized!. Should not happened");
+ ThrowErr(Exc::InternalError, "Object not initialized!. Should not happened");
}
if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
LogError("input size:" << domainKEKInWrapForm.size()
<< " Expected: " << sizeof(WrappedKeyAndInfo));
- ThrowMsg(Exception::InputParamError, "buffer doesn't have proper size to store WrappedKeyAndInfo in KeyProvider Constructor");
+ ThrowErr(Exc::InternalError, "buffer doesn't have proper size to store WrappedKeyAndInfo in KeyProvider Constructor");
}
WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer(domainKEKInWrapForm.data());
PKEK1)) {
delete[] concat_user_pass;
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
}
delete[] concat_user_pass;
wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv,
m_kmcDKEK->getKeyAndInfo().key))) {
- ThrowMsg(Exception::PassWordError, "VerifyDomainKEK failed in KeyProvider Constructor");
+ ThrowErr(Exc::AuthenticationFailed, "VerifyDomainKEK failed in KeyProvider Constructor");
}
m_kmcDKEK->setKeyInfo(&(wkmcDKEK.getWrappedKeyAndInfo().keyInfo));
RawBuffer KeyProvider::getPureDomainKEK()
{
if (!m_isInitialized) {
- ThrowMsg(Exception::InitFailed, "Object not initialized!");
+ ThrowErr(Exc::InternalError, "Object not initialized!");
}
// TODO secure
RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
{
if (!m_isInitialized) {
- ThrowMsg(Exception::InitFailed, "Object not initialized!");
+ ThrowErr(Exc::InternalError, "Object not initialized!");
}
WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer();
PKEK1)) {
delete[] concat_user_pass;
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
}
delete[] concat_user_pass;
wkmcDKEK.getWrappedKeyAndInfo().wrappedKey,
wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag))) {
- ThrowMsg(Exception::InitFailed, "WrapDKEK Failed in KeyProvider::getDomainKEK");
+ ThrowErr(Exc::InternalError, "WrapDKEK Failed in KeyProvider::getDomainKEK");
}
wkmcDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);
RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
{
if (!m_isInitialized) {
- ThrowMsg(Exception::InitFailed, "Object not initialized!");
+ ThrowErr(Exc::InternalError, "Object not initialized!");
}
if (DEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)){
LogError("input size:" << DEKInWrapForm.size()
<< " Expected: " << sizeof(WrappedKeyAndInfo));
- ThrowMsg(Exception::InputParamError,
+ ThrowErr(Exc::InternalError,
"buffer doesn't have proper size to store "
"WrappedKeyAndInfo in KeyProvider::getPureDEK");
}
MAX_KEY_SIZE,
PKEK2)) {
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
}
if (0 > (keyLength = decryptAes256Gcm(
wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv,
kmcDEK.getKeyAndInfo().key))) {
- ThrowMsg(Exception::UnwrapFailed,
+ ThrowErr(Exc::InternalError,
"UnwrapDEK Failed in KeyProvider::getPureDEK");
}
RawBuffer KeyProvider::generateDEK(const std::string &smackLabel)
{
if (!m_isInitialized) {
- ThrowMsg(Exception::InitFailed,
- "Object not initialized!");
+ ThrowErr(Exc::InternalError, "Object not initialized!");
}
WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer();
if (!RAND_bytes(key, m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength) ||
!RAND_bytes(wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE)) {
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
}
if (!PKCS5_PBKDF2_HMAC_SHA1(
MAX_KEY_SIZE,
PKEK2)) {
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
}
int wrappedKeyLength;
wkmcDEK.getWrappedKeyAndInfo().wrappedKey,
wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag))) {
- ThrowMsg(Exception::GenFailed,
- "GenerateDEK Failed in KeyProvider::generateDEK");
+ ThrowErr(Exc::InternalError, "GenerateDEK Failed in KeyProvider::generateDEK");
}
wkmcDEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);
if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
LogError("input size:" << domainKEKInWrapForm.size()
<< " Expected: " << sizeof(WrappedKeyAndInfo));
- ThrowMsg(Exception::InputParamError,
+ ThrowErr(Exc::InternalError,
"buffer doesn't have proper size to store "
"WrappedKeyAndInfo in KeyProvider::reencrypt");
}
PKEK1)) {
delete[] concat_user_pass;
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
}
delete[] concat_user_pass;
wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.iv,
kmcDKEK.getKeyAndInfo().key))) {
- ThrowMsg(Exception::PassWordError,
- "Incorrect Old Password ");
+ ThrowErr(Exc::AuthenticationFailed, "Incorrect Old Password ");
}
kmcDKEK.setKeyInfo(&(wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo));
PKEK1)) {
delete[] concat_user_pass;
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
}
delete[] concat_user_pass;
wkmcNewDKEK.getWrappedKeyAndInfo().wrappedKey,
wkmcNewDKEK.getWrappedKeyAndInfo().keyInfo.tag))) {
- ThrowMsg(Exception::UnwrapFailed,
- "UpdateDomainKEK in KeyProvider::reencrypt Failed");
+ ThrowErr(Exc::InternalError, "UpdateDomainKEK in KeyProvider::reencrypt Failed");
}
wkmcNewDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);
if (!RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt, MAX_SALT_SIZE) ||
!RAND_bytes(key, MAX_KEY_SIZE) ||
!RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE))
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
int wrappedKeyLength;
char *concat_user_pass = NULL;
PKEK1)) {
delete[] concat_user_pass;
- ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINED_ERROR");
+ ThrowErr(Exc::InternalError, "OPENSSL_ENGINED_ERROR");
}
delete[] concat_user_pass;
wkmcDKEK.getWrappedKeyAndInfo().wrappedKey,
wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag))) {
- ThrowMsg(Exception::GenFailed,
+ ThrowErr(Exc::InternalError,
"GenerateDomainKEK Failed in KeyProvider::generateDomainKEK");
}
#include <memory>
#include <ckm/ckm-type.h>
-#include <dpl/exception.h>
#ifndef SUCCESS
#define SUCCESS 0
class KeyAndInfoContainer{
public:
- class Exception{
- public:
- DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
- };
KeyAndInfoContainer();
KeyAndInfoContainer(const unsigned char*);
KeyAndInfo& getKeyAndInfo();
// This is internal api so all functions should throw exception on errors.
class KeyProvider {
public:
- class Exception {
- public:
- DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
- DECLARE_EXCEPTION_TYPE(Base, InitFailed)
- DECLARE_EXCEPTION_TYPE(Base, GenFailed)
- DECLARE_EXCEPTION_TYPE(Base, WrapFailed)
- DECLARE_EXCEPTION_TYPE(Base, UnwrapFailed)
- DECLARE_EXCEPTION_TYPE(Base, PassWordError)
- DECLARE_EXCEPTION_TYPE(Base, InputParamError)
- DECLARE_EXCEPTION_TYPE(Base, OpensslEngineError)
- };
-
// To store in std containers
KeyProvider();
// In constructor you must check if SKMM is initialized. On error -> exception
${CMAKE_SOURCE_DIR}/systemd/central-key-manager-api-control.socket
${CMAKE_SOURCE_DIR}/systemd/central-key-manager-api-storage.socket
${CMAKE_SOURCE_DIR}/systemd/central-key-manager-api-ocsp.socket
+ ${CMAKE_SOURCE_DIR}/systemd/central-key-manager-api-encryption.socket
DESTINATION
${SYSTEMD_UNIT_DIR}
)
--- /dev/null
+[Socket]
+ListenStream=/tmp/.central-key-manager-api-encryption.sock
+SocketMode=0777
+SmackLabelIPIn=key-manager::api-encryption
+SmackLabelIPOut=@
+
+Service=central-key-manager.service
+
+[Unit]
+Wants=central-key-manager.target
+Before=central-key-manager.target
+
+[Install]
+WantedBy=sockets.target
Sockets=central-key-manager-api-storage.socket
Sockets=central-key-manager-api-control.socket
Sockets=central-key-manager-api-ocsp.socket
+Sockets=central-key-manager-api-encryption.socket
EnvironmentFile=-@SYSTEMD_ENV_FILE@
[Install]
#include <dpl/log/log.h>
#include <log-setup.h>
+#include <exception.h>
+
struct TestConfig {
TestConfig() {
boost::unit_test::unit_test_log.set_threshold_level( boost::unit_test::log_test_units);
struct KeyProviderLib {
KeyProviderLib() {
- Try {
+ try {
CKM::KeyProvider::initializeLibrary();
isLibInitialized = true;
- }
- Catch (CKM::Exception) {
+ } catch (const CKM::Exc::Exception &) {
std::cout << "Library initialization failed!" << std::endl;
}
}
~KeyProviderLib() {
- Try { CKM::KeyProvider::closeLibrary(); }
- Catch (CKM::Exception) {
+ try {
+ CKM::KeyProvider::closeLibrary();
+ } catch (const CKM::Exc::Exception &) {
std::cout << "Library deinitialization failed!" << std::endl;
}
}
#define BOOST_TEST_MODULE KEY_MANAGER_TEST
#include <boost/test/unit_test.hpp>
+#include <exception.h>
#include <key-provider.h>
#include <test_common.h>
#include <iostream>
BOOST_REQUIRE_NO_THROW(rb_test =
CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
BOOST_REQUIRE_THROW(keyProvider = CKM::KeyProvider(rb_test, INCORRECT_PASSWORD),
- CKM::KeyProvider::Exception::PassWordError);
+ CKM::Exc::AuthenticationFailed);
BOOST_REQUIRE_MESSAGE(!keyProvider.isInitialized(),
"KeyProvider not created, but initialized");
}
BOOST_REQUIRE_NO_THROW(rb_test =
CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
BOOST_REQUIRE_THROW((rb_test = CKM::KeyProvider::reencrypt(rb_test, INCORRECT_PASSWORD,
- NEW_PASSWORD)), CKM::KeyProvider::Exception::PassWordError);
+ NEW_PASSWORD)), CKM::Exc::AuthenticationFailed);
}
BOOST_AUTO_TEST_CASE(KeyGetPureDEK_after_reencrypt){
BOOST_AUTO_TEST_CASE(TMM_0010_NoListener) {
CKM::CommunicationManager<MessageA> mgr;
- //int reci = 0;
- mgr.SendMessage(MessageA(22));
+ BOOST_REQUIRE_MESSAGE(0 == mgr.SendMessage(MessageA(22)), "There should be no listener.");
}
BOOST_AUTO_TEST_CASE(TMM_0020_Basic) {
CKM::CommunicationManager<MessageA> mgr;
int received = 0;
mgr.Register<MessageA>([&](const MessageA& msg){ received = msg.i; });
- mgr.SendMessage(MessageA(4));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(4)), "No listener found");
BOOST_REQUIRE_MESSAGE(received != 0, "Message not received");
BOOST_REQUIRE_MESSAGE(received == 4, "Wrong message received i=" << received);
}
char recc = 0;
mgr.Register<MessageA>([&](const MessageA& msg){ reci = msg.i; });
mgr.Register<MessageB>([&](const MessageB& msg){ recc = msg.c; });
- mgr.SendMessage(MessageB('c'));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageB('c')), "No listener found");
BOOST_REQUIRE_MESSAGE(reci == 0, "Unexpected message received");
BOOST_REQUIRE_MESSAGE(recc != 0, "Message not received");
BOOST_REQUIRE_MESSAGE(recc == 'c', "Wrong message received c=" << recc);
- mgr.SendMessage(MessageA(42));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(42)), "No listener found");
BOOST_REQUIRE_MESSAGE(reci!= 0, "Message not received");
BOOST_REQUIRE_MESSAGE(reci == 42, "Wrong message received i=" << reci);
BOOST_REQUIRE_MESSAGE(recc == 'c', "Previous message overwritten c=" << recc);
mgr.Register<MessageC>([&](const MessageC& msg){ l.Handle(msg); });
mgr.Register<MessageA>([&](const MessageA& msg){ l.Handle(msg); });
- mgr.SendMessage(MessageC("lorem ipsum"));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageC("lorem ipsum")), "No listener found");
BOOST_REQUIRE_MESSAGE(l.i == 0, "Unexpected message received");
BOOST_REQUIRE_MESSAGE(!l.str.empty(), "Message not received");
BOOST_REQUIRE_MESSAGE(l.str == "lorem ipsum", "Wrong message received c=" << l.str);
- mgr.SendMessage(MessageA(3));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(3)), "No listener found");
BOOST_REQUIRE_MESSAGE(l.i!= 0, "Message not received");
BOOST_REQUIRE_MESSAGE(l.i == 3, "Wrong message received i=" << l.i);
BOOST_REQUIRE_MESSAGE(l.str == "lorem ipsum", "Previous message overwritten str=" << l.str);
called[1] = true;
});
- mgr.SendMessage(MessageA(5));
+ BOOST_REQUIRE_MESSAGE(2 == mgr.SendMessage(MessageA(5)), "No listener found");
BOOST_REQUIRE_MESSAGE(called[0], "First listener not called");
BOOST_REQUIRE_MESSAGE(called[1], "Second listener not called");
}
switch(message_dist(generator))
{
case 0:
- mgr.SendMessage(MessageA(42));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageA(42)), "No listener found");
a--;
break;
case 1:
- mgr.SendMessage(MessageB('c'));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageB('c')), "No listener found");
b--;
break;
case 2:
- mgr.SendMessage(MessageC("lorem ipsum"));
+ BOOST_REQUIRE_MESSAGE(1 == mgr.SendMessage(MessageC("lorem ipsum")), "No listener found");
c--;
break;
default: