Merge "allow all clients to access storage socket and ocsp socket" into tizen
authorDongsun Lee <ds73.lee@samsung.com>
Sat, 27 Jun 2015 07:12:53 +0000 (00:12 -0700)
committerGerrit Code Review <gerrit@review.vlan103.tizen.org>
Sat, 27 Jun 2015 07:12:53 +0000 (00:12 -0700)
41 files changed:
doc/example.xml
doc/example_device_key.xml [new file with mode: 0644]
doc/initial_values.xsd
doc/sw_key.xsd [new file with mode: 0644]
packaging/key-manager.spec
src/CMakeLists.txt
src/manager/client/client-manager-impl.cpp
src/manager/client/client-manager-impl.h
src/manager/crypto/generic-backend/gkey.h
src/manager/crypto/generic-backend/gstore.h
src/manager/crypto/sw-backend/store.cpp
src/manager/crypto/sw-backend/store.h
src/manager/crypto/tz-backend/store.cpp
src/manager/crypto/tz-backend/store.h
src/manager/main/communication-manager.h
src/manager/main/credentials.h [new file with mode: 0644]
src/manager/main/generic-socket-manager.h
src/manager/main/key-manager-main.cpp
src/manager/main/message-service.h [new file with mode: 0644]
src/manager/main/service-messages.h [new file with mode: 0644]
src/manager/main/socket-manager.cpp
src/manager/main/socket-manager.h
src/manager/main/thread-service.h
src/manager/service/ckm-logic.cpp
src/manager/service/ckm-logic.h
src/manager/service/ckm-service.cpp
src/manager/service/ckm-service.h
src/manager/service/crypto-request.h [new file with mode: 0644]
src/manager/service/encryption-logic.cpp [new file with mode: 0644]
src/manager/service/encryption-logic.h [new file with mode: 0644]
src/manager/service/encryption-service.cpp [new file with mode: 0644]
src/manager/service/encryption-service.h [new file with mode: 0644]
src/manager/service/iencryption-service.h [new file with mode: 0644]
src/manager/service/key-provider.cpp
src/manager/service/key-provider.h
systemd/CMakeLists.txt
systemd/central-key-manager-api-encryption.socket [new file with mode: 0644]
systemd/central-key-manager.service.in
tests/main.cpp
tests/test-key-provider.cpp
tests/test_comm-manager.cpp

index c5d2874..7b07961 100644 (file)
@@ -1,5 +1,5 @@
 <?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-----
diff --git a/doc/example_device_key.xml b/doc/example_device_key.xml
new file mode 100644 (file)
index 0000000..e191221
--- /dev/null
@@ -0,0 +1,28 @@
+<?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>
index 69068df..c28c33c 100644 (file)
@@ -52,6 +52,9 @@
                                                <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>
diff --git a/doc/sw_key.xsd b/doc/sw_key.xsd
new file mode 100644 (file)
index 0000000..d4434b4
--- /dev/null
@@ -0,0 +1,41 @@
+<?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>
index 9d32beb..f6d52d8 100644 (file)
@@ -153,6 +153,7 @@ ln -s ../central-key-manager-listener.service %{buildroot}%{_unitdir}/multi-user
 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}
@@ -222,6 +223,8 @@ fi
 %{_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}/
index 1460a53..fd79979 100644 (file)
@@ -34,6 +34,8 @@ SET(KEY_MANAGER_SOURCES
     ${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
index 76a5e57..ca9d250 100644 (file)
@@ -763,11 +763,12 @@ int ManagerImpl::setPermission(const Alias &alias,
     });
 }
 
-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;
 
@@ -775,13 +776,13 @@ int ManagerImpl::encrypt(const CryptoAlgorithm &algo,
         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)
@@ -789,7 +790,7 @@ int ManagerImpl::encrypt(const CryptoAlgorithm &algo,
 
         int command;
         int counter;
-        recv.Deserialize(command, counter, encrypted);
+        recv.Deserialize(command, counter, retCode, output);
 
         if (my_counter != counter) {
             return CKM_API_ERROR_UNKNOWN;
@@ -799,40 +800,22 @@ int ManagerImpl::encrypt(const CryptoAlgorithm &algo,
     });
 }
 
+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() {
index fce5992..e9df170 100644 (file)
@@ -153,6 +153,13 @@ protected:
         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;
index f153f3e..b06926d 100644 (file)
@@ -56,6 +56,7 @@ public:
     virtual ~GKey () {}
 };
 
+typedef std::unique_ptr<GKey> GKeyUPtr;
 typedef std::shared_ptr<GKey> GKeyShPtr;
 
 } // namespace Crypto
index 13c7d26..2c8aca7 100644 (file)
@@ -33,7 +33,7 @@ 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); }
index 9f18575..8888ea9 100644 (file)
 #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 {
@@ -36,21 +45,21 @@ Store::Store(CryptoBackend backendId)
     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,
index 09350e8..cb23155 100644 (file)
@@ -31,7 +31,7 @@ class Store : public GStore {
 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);
index 100ca6f..11ac0b0 100644 (file)
@@ -30,7 +30,7 @@ Store::Store(CryptoBackend backendId)
   : GStore(backendId)
 {}
 
-GKeyShPtr Store::getKey(const Token &) {
+GKeyUPtr Store::getKey(const Token &) {
     ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!");
 }
 
index bbfb34e..ee5d24b 100644 (file)
@@ -31,7 +31,7 @@ class Store : public GStore {
 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 &){}
index 898d483..1637a07 100644 (file)
@@ -44,10 +44,15 @@ public:
     }
 
     // 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() {}
@@ -82,10 +87,11 @@ public:
     }
 
     // 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);
     }
 };
 
diff --git a/src/manager/main/credentials.h b/src/manager/main/credentials.h
new file mode 100644 (file)
index 0000000..e54f5df
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ *  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
index c9d5eda..bec21c6 100644 (file)
@@ -35,6 +35,8 @@
 #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;
@@ -44,14 +46,6 @@ namespace CKM {
 
 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
@@ -107,6 +101,9 @@ struct GenericSocketService {
     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;
@@ -117,10 +114,11 @@ struct GenericSocketService {
     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 {
index 71c76e7..d1e486e 100644 (file)
@@ -34,6 +34,7 @@
 
 #include <ckm-service.h>
 #include <ocsp-service.h>
+#include <encryption-service.h>
 
 #include <key-provider.h>
 #include <file-system.h>
@@ -100,6 +101,7 @@ int main(void) {
 
             REGISTER_SOCKET_SERVICE(manager, CKM::CKMService);
             REGISTER_SOCKET_SERVICE(manager, CKM::OCSPService);
+            REGISTER_SOCKET_SERVICE(manager, CKM::EncryptionService);
 
             manager.MainLoop();
         }
diff --git a/src/manager/main/message-service.h b/src/manager/main/message-service.h
new file mode 100644 (file)
index 0000000..65512c0
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ *  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 */
diff --git a/src/manager/main/service-messages.h b/src/manager/main/service-messages.h
new file mode 100644 (file)
index 0000000..f23711f
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ *  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 */
index 4a5e147..44a7d3c 100644 (file)
@@ -94,10 +94,10 @@ struct DummyService : public GenericSocketService {
     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 {
@@ -118,9 +118,9 @@ 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");
@@ -564,6 +564,7 @@ void SocketManager::CreateDomainSocket(
 
 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)
index 978dbee..5dbffdc 100644 (file)
@@ -35,6 +35,7 @@
 #include <dpl/exception.h>
 
 #include <generic-socket-manager.h>
+#include <service-messages.h>
 
 namespace CKM {
 
@@ -119,6 +120,7 @@ protected:
     int m_notifyMe[2];
     int m_counter;
     std::priority_queue<Timeout> m_timeoutQueue;
+    CommMgr m_commMgr;
 };
 
 } // namespace CKM
index 2a4cadb..e8f0ac6 100644 (file)
@@ -43,11 +43,12 @@ public:
 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);
index a2c3e45..a173cd7 100644 (file)
@@ -162,12 +162,6 @@ int CKMLogic::unlockDatabase(uid_t user, const Password & password)
                 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) {
@@ -283,12 +277,6 @@ RawBuffer CKMLogic::changeUserPassword(
     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) {
@@ -500,9 +488,6 @@ int CKMLogic::verifyAndSaveDataHelper(
         {
             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;
@@ -518,6 +503,31 @@ int CKMLogic::verifyAndSaveDataHelper(
     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,
@@ -592,9 +602,8 @@ RawBuffer CKMLogic::savePKCS12(
     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;
@@ -876,9 +885,6 @@ RawBuffer CKMLogic::getData(
 
     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;
@@ -964,10 +970,6 @@ RawBuffer CKMLogic::getPKCS12(
         // 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;
@@ -1470,9 +1472,6 @@ RawBuffer CKMLogic::createSignature(
         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;
@@ -1523,9 +1522,6 @@ RawBuffer CKMLogic::verifySignature(
         }
     } 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;
index afc90be..b6dc1eb 100644 (file)
@@ -35,6 +35,7 @@
 #include <access-control.h>
 #include <certificate-impl.h>
 #include <sys/types.h>
+#include <generic-backend/gkey.h>
 
 #include <platform/decider.h>
 
@@ -201,6 +202,12 @@ public:
         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.
index 3a21a64..3321fd5 100644 (file)
@@ -59,6 +59,12 @@ GenericSocketService::ServiceDescriptionVector CKMService::GetServiceDescription
     };
 }
 
+void CKMService::SetCommManager(CommMgr *manager)
+{
+    ThreadService::SetCommManager(manager);
+    Register(*manager);
+}
+
 bool CKMService::ProcessOne(
     const ConnectionID &conn,
     ConnectionInfo &info)
@@ -386,5 +392,22 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer)
     }
 }
 
+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
 
index b8b6c55..5bc7230 100644 (file)
@@ -21,7 +21,8 @@
  */
 #pragma once
 
-#include <thread-service.h>
+#include <mutex>
+#include <message-service.h>
 #include <message-buffer.h>
 #include <dpl/exception.h>
 
@@ -29,7 +30,7 @@ namespace CKM {
 
 class CKMLogic;
 
-class CKMService : public CKM::ThreadService
+class CKMService : public ThreadMessageService<MsgKeyRequest>
 {
 public:
     CKMService();
@@ -46,6 +47,8 @@ public:
     ServiceDescriptionVector GetServiceDescription();
 
 private:
+    virtual void SetCommManager(CommMgr *manager);
+
     class Exception {
     public:
         DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
@@ -63,6 +66,8 @@ private:
         Credentials &cred,
         MessageBuffer &buffer);
 
+    virtual void ProcessMessage(MsgKeyRequest msg);
+
     CKMLogic *m_logic;
 };
 
diff --git a/src/manager/service/crypto-request.h b/src/manager/service/crypto-request.h
new file mode 100644 (file)
index 0000000..d8acf2b
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ *  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 */
diff --git a/src/manager/service/encryption-logic.cpp b/src/manager/service/encryption-logic.cpp
new file mode 100644 (file)
index 0000000..a2bad2b
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ *  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 */
diff --git a/src/manager/service/encryption-logic.h b/src/manager/service/encryption-logic.h
new file mode 100644 (file)
index 0000000..8f941dd
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ *  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 */
diff --git a/src/manager/service/encryption-service.cpp b/src/manager/service/encryption-service.cpp
new file mode 100644 (file)
index 0000000..f08dbfa
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ *  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 */
diff --git a/src/manager/service/encryption-service.h b/src/manager/service/encryption-service.h
new file mode 100644 (file)
index 0000000..73140b7
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ *  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 */
diff --git a/src/manager/service/iencryption-service.h b/src/manager/service/iencryption-service.h
new file mode 100644 (file)
index 0000000..2c1d906
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *  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
+
+
index 48db9c0..23ca201 100644 (file)
@@ -1,3 +1,4 @@
+#include <exception.h>
 #include <key-provider.h>
 #include <dpl/log/log.h>
 
@@ -100,14 +101,11 @@ KeyAndInfoContainer::~KeyAndInfoContainer()
 {
     // 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;
@@ -127,12 +125,12 @@ KeyProvider::KeyProvider(
     , 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());
@@ -154,7 +152,7 @@ KeyProvider::KeyProvider(
         PKEK1)) {
 
         delete[] concat_user_pass;
-        ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+        ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
     }
 
     delete[] concat_user_pass;
@@ -169,7 +167,7 @@ KeyProvider::KeyProvider(
         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));
@@ -205,7 +203,7 @@ bool KeyProvider::isInitialized()
 RawBuffer KeyProvider::getPureDomainKEK()
 {
     if (!m_isInitialized) {
-        ThrowMsg(Exception::InitFailed, "Object not initialized!");
+        ThrowErr(Exc::InternalError, "Object not initialized!");
     }
 
     // TODO secure
@@ -215,7 +213,7 @@ RawBuffer KeyProvider::getPureDomainKEK()
 RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
 {
     if (!m_isInitialized) {
-        ThrowMsg(Exception::InitFailed, "Object not initialized!");
+        ThrowErr(Exc::InternalError, "Object not initialized!");
     }
 
     WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer();
@@ -237,7 +235,7 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
         PKEK1)) {
 
         delete[] concat_user_pass;
-        ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+        ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
     }
 
     delete[] concat_user_pass;
@@ -254,7 +252,7 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
         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);
@@ -267,13 +265,13 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
 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");
     }
@@ -293,7 +291,7 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
         MAX_KEY_SIZE,
         PKEK2)) {
 
-        ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+        ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
     }
 
     if (0 > (keyLength = decryptAes256Gcm(
@@ -304,7 +302,7 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
         wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv,
         kmcDEK.getKeyAndInfo().key))) {
 
-        ThrowMsg(Exception::UnwrapFailed,
+        ThrowErr(Exc::InternalError,
             "UnwrapDEK Failed in KeyProvider::getPureDEK");
     }
 
@@ -319,8 +317,7 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
 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();
@@ -336,7 +333,7 @@ RawBuffer KeyProvider::generateDEK(const std::string &smackLabel)
     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(
@@ -348,7 +345,7 @@ RawBuffer KeyProvider::generateDEK(const std::string &smackLabel)
         MAX_KEY_SIZE,
         PKEK2)) {
 
-        ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+        ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
     }
 
     int wrappedKeyLength;
@@ -361,8 +358,7 @@ RawBuffer KeyProvider::generateDEK(const std::string &smackLabel)
         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);
@@ -381,7 +377,7 @@ RawBuffer KeyProvider::reencrypt(
     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");
     }
@@ -409,7 +405,7 @@ RawBuffer KeyProvider::reencrypt(
         PKEK1)) {
 
         delete[] concat_user_pass;
-        ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+        ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
     }
     delete[] concat_user_pass;
 
@@ -421,8 +417,7 @@ RawBuffer KeyProvider::reencrypt(
         wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.iv,
         kmcDKEK.getKeyAndInfo().key))) {
 
-        ThrowMsg(Exception::PassWordError,
-            "Incorrect Old Password ");
+        ThrowErr(Exc::AuthenticationFailed, "Incorrect Old Password ");
     }
 
     kmcDKEK.setKeyInfo(&(wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo));
@@ -442,7 +437,7 @@ RawBuffer KeyProvider::reencrypt(
         PKEK1)) {
 
         delete[] concat_user_pass;
-        ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINE_ERROR");
+        ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
     }
 
     delete[] concat_user_pass;
@@ -458,8 +453,7 @@ RawBuffer KeyProvider::reencrypt(
         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);
@@ -479,7 +473,7 @@ RawBuffer KeyProvider::generateDomainKEK(
     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;
@@ -494,7 +488,7 @@ RawBuffer KeyProvider::generateDomainKEK(
         PKEK1)) {
 
         delete[] concat_user_pass;
-        ThrowMsg(Exception::OpensslEngineError, "OPENSSL_ENGINED_ERROR");
+        ThrowErr(Exc::InternalError, "OPENSSL_ENGINED_ERROR");
     }
 
     delete[] concat_user_pass;
@@ -507,7 +501,7 @@ RawBuffer KeyProvider::generateDomainKEK(
         wkmcDKEK.getWrappedKeyAndInfo().wrappedKey,
         wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag))) {
 
-        ThrowMsg(Exception::GenFailed,
+        ThrowErr(Exc::InternalError,
             "GenerateDomainKEK Failed in KeyProvider::generateDomainKEK");
     }
 
index a386652..918a622 100644 (file)
@@ -9,7 +9,6 @@
 #include <memory>
 
 #include <ckm/ckm-type.h>
-#include <dpl/exception.h>
 
 #ifndef SUCCESS
 #define SUCCESS               0
@@ -82,10 +81,6 @@ private:
 
 class KeyAndInfoContainer{
 public:
-    class Exception{
-    public:
-        DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
-    };
     KeyAndInfoContainer();
     KeyAndInfoContainer(const unsigned char*);
     KeyAndInfo& getKeyAndInfo();
@@ -100,18 +95,6 @@ private:
 // 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
index f9005e7..cda16ec 100644 (file)
@@ -8,6 +8,7 @@ INSTALL(FILES
     ${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}
 )
diff --git a/systemd/central-key-manager-api-encryption.socket b/systemd/central-key-manager-api-encryption.socket
new file mode 100644 (file)
index 0000000..21e8e81
--- /dev/null
@@ -0,0 +1,14 @@
+[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
index 469db7a..0159131 100644 (file)
@@ -8,6 +8,7 @@ ExecStart=/usr/bin/key-manager
 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]
index 0a47fd8..efaf1be 100644 (file)
@@ -28,6 +28,8 @@
 #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);
@@ -42,17 +44,17 @@ bool isLibInitialized = false;
 
 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;
         }
     }
index 433e8ec..92f7e07 100644 (file)
@@ -1,5 +1,6 @@
 #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>
@@ -36,7 +37,7 @@ BOOST_AUTO_TEST_CASE(KeyDomainKekInvalidPassword){
     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");
 }
@@ -114,7 +115,7 @@ BOOST_AUTO_TEST_CASE(KeyReencrypt_incorrect_password){
     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){
index ec9ccaf..facd20b 100644 (file)
@@ -63,15 +63,14 @@ BOOST_AUTO_TEST_SUITE(MESSAGE_MANAGER_TEST)
 
 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);
 }
@@ -82,12 +81,12 @@ BOOST_AUTO_TEST_CASE(TMM_0030_MultipleMessages) {
     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);
@@ -99,12 +98,12 @@ BOOST_AUTO_TEST_CASE(TMM_0040_Listener) {
     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);
@@ -124,7 +123,7 @@ BOOST_AUTO_TEST_CASE(TMM_0050_2Listeners) {
         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");
 }
@@ -159,15 +158,15 @@ BOOST_AUTO_TEST_CASE(TMM_0060_Stress) {
             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: