Change RawBuffer into SafeBuffer.
authorBartlomiej Grzelewski <b.grzelewski@samsung.com>
Thu, 17 Jul 2014 12:27:47 +0000 (14:27 +0200)
committerBartlomiej Grzelewski <b.grzelewski@samsung.com>
Fri, 12 Sep 2014 12:59:06 +0000 (14:59 +0200)
Change-Id: Iccf37f75713c7b573dcd6858fed3b9e530c2c936

51 files changed:
src/include/ckm/ckm-type.h
src/manager/client/client-certificate.cpp [new file with mode: 0644]
src/manager/client/client-common.cpp
src/manager/client/client-common.h
src/manager/client/client-key.cpp [new file with mode: 0644]
src/manager/client/client-manager-impl.cpp
src/manager/client/client-manager-impl.h
src/manager/client/client-manager.cpp [new file with mode: 0644]
src/manager/common/base64.cpp
src/manager/common/base64.h
src/manager/common/buffer-conversion.h [new file with mode: 0644]
src/manager/common/certificate-impl.cpp
src/manager/common/certificate-impl.h
src/manager/common/crypto.h
src/manager/common/digest.cpp
src/manager/common/digest.h
src/manager/common/generic-key.cpp
src/manager/common/generic-key.h
src/manager/common/message-buffer.cpp
src/manager/common/message-buffer.h
src/manager/common/safe-buffer.h
src/manager/dpl/core/include/dpl/serialization.h
src/manager/dpl/db/include/dpl/db/sql_connection.h
src/manager/dpl/db/src/sql_connection.cpp
src/manager/main/generic-socket-manager.h
src/manager/main/key-manager-util.cpp
src/manager/main/key-manager-util.h
src/manager/main/socket-manager.cpp
src/manager/main/socket-manager.h
src/manager/service/CryptoService.cpp
src/manager/service/CryptoService.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-logic.cpp
src/manager/service/crypto-logic.h
src/manager/service/db-crypto.cpp
src/manager/service/db-crypto.h
src/manager/service/db-row.h
src/manager/service/file-system.cpp
src/manager/service/file-system.h
src/manager/service/key-provider.h
src/manager/service/ocsp-logic.cpp
src/manager/service/ocsp-logic.h
src/manager/service/ocsp-service.cpp
tests/test-key-provider.cpp
tests/test_common.cpp
tests/test_common.h
tests/test_db_crypto.cpp
tests/test_sql.cpp

index 8eb14db..90d59b0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *  Copyright (c) 2014 Samsung Electronics Co.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
diff --git a/src/manager/client/client-certificate.cpp b/src/manager/client/client-certificate.cpp
new file mode 100644 (file)
index 0000000..187c772
--- /dev/null
@@ -0,0 +1,67 @@
+/* Copyright (c) 2000 - 2013 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        client-certificate.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Certificate class implementation.
+ */
+
+#include <ckm/ckm-manager.h>
+
+#include <buffer-conversion.h>
+#include <certificate-impl.h>
+
+namespace CKM {
+
+Certificate::Certificate(){}
+
+Certificate::Certificate(const RawBuffer &rawData, DataFormat format)
+  : m_impl(new CertificateImpl(toSafeBuffer(rawData), format))
+{}
+
+Certificate::Certificate(const Certificate &second) {
+    m_impl = second.m_impl;
+}
+
+Certificate& Certificate::operator=(const Certificate &second) {
+    m_impl = second.m_impl;
+    return *this;
+}
+
+bool Certificate::empty() const {
+    if (m_impl)
+        return m_impl->empty();
+    return true;
+}
+
+RawBuffer Certificate::getDER() const {
+    if (m_impl)
+        return toRawBuffer(m_impl->getDER());
+    return RawBuffer();
+}
+
+void* Certificate::getX509() const {
+    if (m_impl)
+        return m_impl->getX509();
+    return NULL;
+}
+
+CertificateImpl* Certificate::getImpl() const {
+    return m_impl.get();
+}
+
+} // namespace CKM
+
index 1679923..3c137cb 100644 (file)
@@ -166,7 +166,7 @@ private:
 namespace CKM {
 
 
-int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv) {
+int sendToServer(char const * const interface, const SafeBuffer &send, MessageBuffer &recv) {
     int ret;
     SockRAII sock;
     ssize_t done = 0;
@@ -208,7 +208,7 @@ int sendToServer(char const * const interface, const RawBuffer &send, MessageBuf
             return CKM_API_ERROR_SOCKET;
         }
 
-        RawBuffer raw(buffer, buffer+temp);
+        SafeBuffer raw(buffer, buffer+temp);
         recv.Push(raw);
     } while(!recv.Ready());
     return CKM_API_SUCCESS;
index b8eddd4..93a1ce3 100644 (file)
@@ -39,7 +39,7 @@ extern "C" {
 
 namespace CKM {
 
-int sendToServer(char const * const interface, const RawBuffer &send, MessageBuffer &recv);
+int sendToServer(char const * const interface, const SafeBuffer &send, MessageBuffer &recv);
 
 /*
  * Decorator function that performs frequently repeated exception handling in
diff --git a/src/manager/client/client-key.cpp b/src/manager/client/client-key.cpp
new file mode 100644 (file)
index 0000000..269667e
--- /dev/null
@@ -0,0 +1,81 @@
+/* Copyright (c) 2000 - 2013 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        client-key.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Key - api implementation.
+ */
+#include <ckm/ckm-type.h>
+#include <ckm/ckm-manager.h>
+
+#include <dpl/log/log.h>
+
+#include <buffer-conversion.h>
+
+#include <generic-key.h>
+
+namespace CKM {
+
+Key::Key()
+  : m_impl(NULL)
+{}
+
+Key::Key(
+    const RawBuffer &rawData,
+    const std::string &password,
+    KeyType type)
+{
+    (void)type;
+    m_impl.reset(new GenericKey(toSafeBuffer(rawData), password));
+}
+
+Key::Key(const Key &second) {
+    m_impl = second.m_impl;
+}
+
+Key& Key::operator=(const Key &second) {
+    m_impl = second.m_impl;
+    return *this;
+}
+
+Key::~Key(){}
+
+bool Key::empty() const {
+    if (m_impl)
+        return m_impl->empty();
+    return true;
+}
+
+KeyType Key::getType() const {
+    if (m_impl)
+        return m_impl->getType();
+    return KeyType::KEY_NONE;
+}
+
+RawBuffer Key::getDER() const {
+    if (m_impl)
+        return toRawBuffer(m_impl->getDER());
+    return RawBuffer();
+}
+
+GenericKey* Key::getImpl() const {
+    if (m_impl)
+        return m_impl.get();
+    return NULL;
+};
+
+} // namespace CKM
+
index ffd08ab..b393d5f 100644 (file)
@@ -25,6 +25,7 @@
 
 #include <client-manager-impl.h>
 #include <client-common.h>
+#include <buffer-conversion.h>
 #include <message-buffer.h>
 #include <protocols.h>
 #include <generic-key.h>
@@ -59,7 +60,7 @@ ManagerImpl::ManagerImpl()
 int ManagerImpl::saveBinaryData(
     const Alias &alias,
     DBDataType dataType,
-    const RawBuffer &rawData,
+    const SafeBuffer &rawData,
     const Policy &policy)
 {
     m_counter++;
@@ -104,7 +105,7 @@ int ManagerImpl::saveBinaryData(
 int ManagerImpl::saveKey(const Alias &alias, const KeyShPtr &key, const Policy &policy) {
     if (key.get() == NULL)
         return CKM_API_ERROR_INPUT_PARAM;
-    return saveBinaryData(alias, toDBDataType(key->getType()), key->getDER(), policy);
+    return saveBinaryData(alias, toDBDataType(key->getType()), toSafeBuffer(key->getDER()), policy);
 }
 
 int ManagerImpl::saveCertificate(
@@ -114,13 +115,13 @@ int ManagerImpl::saveCertificate(
 {
     if (cert.get() == NULL)
         return CKM_API_ERROR_INPUT_PARAM;
-    return saveBinaryData(alias, DBDataType::CERTIFICATE, cert->getDER(), policy);
+    return saveBinaryData(alias, DBDataType::CERTIFICATE, toSafeBuffer(cert->getDER()), policy);
 }
 
 int ManagerImpl::saveData(const Alias &alias, const RawBuffer &rawData, const Policy &policy) {
     if (!policy.extractable)
         return CKM_API_ERROR_INPUT_PARAM;
-    return saveBinaryData(alias, DBDataType::BINARY_DATA, rawData, policy);
+    return saveBinaryData(alias, DBDataType::BINARY_DATA, toSafeBuffer(rawData), policy);
 }
 
 int ManagerImpl::removeBinaryData(const Alias &alias, DBDataType dataType)
@@ -177,7 +178,7 @@ int ManagerImpl::getBinaryData(
     DBDataType sendDataType,
     const std::string &password,
     DBDataType &recvDataType,
-    RawBuffer &rawData)
+    SafeBuffer &rawData)
 {
     return try_catch([&] {
         if (alias.empty())
@@ -219,7 +220,7 @@ int ManagerImpl::getBinaryData(
 
 int ManagerImpl::getKey(const Alias &alias, const std::string &password, KeyShPtr &key) {
     DBDataType recvDataType;
-    RawBuffer rawData;
+    SafeBuffer rawData;
 
     int retCode = getBinaryData(
         alias,
@@ -246,7 +247,7 @@ int ManagerImpl::getKey(const Alias &alias, const std::string &password, KeyShPt
 int ManagerImpl::getCertificate(const Alias &alias, const std::string &password, CertificateShPtr &cert)
 {
     DBDataType recvDataType;
-    RawBuffer rawData;
+    SafeBuffer rawData;
 
     int retCode = getBinaryData(
         alias,
@@ -274,13 +275,16 @@ int ManagerImpl::getCertificate(const Alias &alias, const std::string &password,
 int ManagerImpl::getData(const Alias &alias, const std::string &password, RawBuffer &rawData)
 {
     DBDataType recvDataType;
+    SafeBuffer safeData;
 
     int retCode = getBinaryData(
         alias,
         DBDataType::BINARY_DATA,
         password,
         recvDataType,
-        rawData);
+        safeData);
+
+    rawData = toRawBuffer(safeData);
 
     if (retCode != CKM_API_SUCCESS)
         return retCode;
@@ -451,7 +455,7 @@ int getCertChain(
 
         int retCommand;
         int retCounter;
-        RawBufferVector rawBufferVector;
+        SafeBufferVector rawBufferVector;
 
         Deserialization::Deserialize(recv, retCommand);
         Deserialization::Deserialize(recv, retCounter);
@@ -483,10 +487,10 @@ int ManagerImpl::getCertificateChain(
     const CertificateShPtrVector &untrustedCertificates,
     CertificateShPtrVector &certificateChainVector)
 {
-    RawBufferVector rawBufferVector;
+    SafeBufferVector rawBufferVector;
 
     for (auto &e: untrustedCertificates) {
-        rawBufferVector.push_back(e->getDER());
+        rawBufferVector.push_back(toSafeBuffer(e->getDER()));
     }
 
     return getCertChain(
@@ -527,7 +531,7 @@ int ManagerImpl::createSignature(
         Serialization::Serialize(send, my_counter);
         Serialization::Serialize(send, privateKeyAlias);
         Serialization::Serialize(send, password);
-        Serialization::Serialize(send, message);
+        Serialization::Serialize(send, toSafeBuffer(message));
         Serialization::Serialize(send, static_cast<int>(hash));
         Serialization::Serialize(send, static_cast<int>(padding));
 
@@ -542,11 +546,14 @@ int ManagerImpl::createSignature(
 
         int command;
         int counter;
+        SafeBuffer safeData;
 
         Deserialization::Deserialize(recv, command);
         Deserialization::Deserialize(recv, counter);
         Deserialization::Deserialize(recv, retCode);
-        Deserialization::Deserialize(recv, signature);
+        Deserialization::Deserialize(recv, safeData);
+
+        signature = toRawBuffer(safeData);
 
         if ((command != static_cast<int>(LogicCommand::CREATE_SIGNATURE))
             || (counter != my_counter))
@@ -575,8 +582,8 @@ int ManagerImpl::verifySignature(
         Serialization::Serialize(send, my_counter);
         Serialization::Serialize(send, publicKeyOrCertAlias);
         Serialization::Serialize(send, password);
-        Serialization::Serialize(send, message);
-        Serialization::Serialize(send, signature);
+        Serialization::Serialize(send, toSafeBuffer(message));
+        Serialization::Serialize(send, toSafeBuffer(signature));
         Serialization::Serialize(send, static_cast<int>(hash));
         Serialization::Serialize(send, static_cast<int>(padding));
 
@@ -612,9 +619,9 @@ int ManagerImpl::ocspCheck(const CertificateShPtrVector &certChain, int &ocspSta
         int my_counter = ++m_counter;
         MessageBuffer send, recv;
 
-        RawBufferVector rawCertChain;
+        SafeBufferVector rawCertChain;
         for (auto &e: certChain) {
-            rawCertChain.push_back(e->getDER());
+            rawCertChain.push_back(toSafeBuffer(e->getDER()));
         }
 
         Serialization::Serialize(send, my_counter);
index 9e8d638..dfec4b1 100644 (file)
@@ -21,6 +21,7 @@
 #pragma once
 
 #include <protocols.h>
+#include <safe-buffer.h>
 
 #include <ckm/ckm-type.h>
 #include <ckm/ckm-key.h>
@@ -94,7 +95,7 @@ protected:
     int saveBinaryData(
         const Alias &alias,
         DBDataType dataType,
-        const RawBuffer &rawData,
+        const SafeBuffer &rawData,
         const Policy &policy);
 
     int removeBinaryData(
@@ -106,7 +107,7 @@ protected:
         DBDataType sendDataType,
         const std::string &password,
         DBDataType &recvDataType,
-        RawBuffer &rawData);
+        SafeBuffer &rawData);
 
     int getBinaryDataAliasVector(
         DBDataType sendDataType,
diff --git a/src/manager/client/client-manager.cpp b/src/manager/client/client-manager.cpp
new file mode 100644 (file)
index 0000000..e1cc443
--- /dev/null
@@ -0,0 +1,157 @@
+/* Copyright (c) 2000 - 2013 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        client-manager.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Client Manager implementation.
+ */
+#include <ckm/ckm-manager.h>
+
+#include <safe-buffer.h>
+#include <buffer-conversion.h>
+#include <client-manager-impl.h>
+
+namespace CKM {
+
+Manager::Manager()
+  : m_impl(new ManagerImpl)
+{}
+
+Manager::~Manager(){}
+
+int Manager::saveKey(const Alias &alias, const Key &key, const Policy &policy) {
+    return m_impl->saveKey(alias, key, policy);
+}
+
+int Manager::removeKey(const Alias &alias) {
+    return m_impl->removeKey(alias);
+}
+
+int Manager::getKey(const Alias &alias, const std::string &password, Key &key) {
+    return m_impl->getKey(alias, password, key);
+}
+
+int Manager::saveCertificate(const Alias &alias, const Certificate &cert, const Policy &policy) {
+    if (cert.empty() || alias.empty())
+        return CKM_API_ERROR_INPUT_PARAM;
+    return m_impl->saveCertificate(alias, cert, policy);
+}
+
+int Manager::removeCertificate(const Alias &alias) {
+    if (alias.empty())
+        return CKM_API_ERROR_INPUT_PARAM;
+    return m_impl->removeCertificate(alias);
+}
+
+int Manager::getCertificate(const Alias &alias, const std::string &password, Certificate &cert) {
+    return m_impl->getCertificate(alias, password, cert);
+}
+
+int Manager::saveData(const Alias &alias, const RawBuffer &data, const Policy &policy) {
+    return m_impl->saveData(alias, toSafeBuffer(data), policy);
+}
+
+int Manager::removeData(const Alias &alias) {
+    return m_impl->removeData(alias);
+}
+
+int Manager::getData(const Alias &alias, const std::string &password, RawBuffer &data) {
+    SafeBuffer safeBuffer;
+    int status = m_impl->getData(alias, password, safeBuffer);
+    data = toRawBuffer(safeBuffer);
+    return status;
+}
+
+int Manager::getKeyAliasVector(AliasVector &av) {
+    return m_impl->getKeyAliasVector(av);
+}
+
+int Manager::getCertificateAliasVector(AliasVector &av) {
+    return m_impl->getCertificateAliasVector(av);
+}
+
+int Manager::getDataAliasVector(AliasVector &av) {
+    return m_impl->getDataAliasVector(av);
+}
+
+int Manager::createKeyPairRSA(
+    const int size,              // size in bits [1024, 2048, 4096]
+    const Alias &privateKeyAlias,
+    const Alias &publicKeyAlias,
+    const Policy &policyPrivateKey,
+    const Policy &policyPublicKey)
+{
+    return m_impl->createKeyPairRSA(size, privateKeyAlias, publicKeyAlias, policyPrivateKey, policyPublicKey);
+}
+
+int Manager::createKeyPairECDSA(
+    ElipticCurve type,
+    const Alias &privateKeyAlias,
+    const Alias &publicKeyAlias,
+    const Policy &policyPrivateKey,
+    const Policy &policyPublicKey) 
+{
+    return m_impl->createKeyPairECDSA(type, privateKeyAlias, publicKeyAlias, policyPrivateKey, policyPublicKey);
+}
+
+int Manager::getCertificateChain(
+    const Certificate &certificate,
+    const CertificateVector &untrustedCertificates,
+    CertificateVector &certificateChainVector)
+{
+    return m_impl->getCertificateChain(certificate, untrustedCertificates, certificateChainVector);
+}
+
+int Manager::getCertificateChain(
+    const Certificate &certificate,
+    const AliasVector &untrustedCertificates,
+    CertificateVector &certificateChainVector)
+{
+    return m_impl->getCertificateChain(certificate, untrustedCertificates, certificateChainVector);
+}
+
+int Manager::createSignature(
+    const Alias &privateKeyAlias,
+    const std::string &password,           // password for private_key
+    const RawBuffer &message,
+    const HashAlgorithm hash,
+    const RSAPaddingAlgorithm padding,
+    RawBuffer &signature)
+{
+    SafeBuffer safeBuffer;
+    int status = m_impl->createSignature(privateKeyAlias, password, toSafeBuffer(message), hash, padding, safeBuffer);
+    signature = toRawBuffer(safeBuffer);
+    return status;
+}
+
+int Manager::verifySignature(
+    const Alias &publicKeyOrCertAlias,
+    const std::string &password,           // password for public_key (optional)
+    const RawBuffer &message,
+    const RawBuffer &signature,
+    const HashAlgorithm hash,
+    const RSAPaddingAlgorithm padding)
+{
+    return m_impl->verifySignature(publicKeyOrCertAlias, password, toSafeBuffer(message), toSafeBuffer(signature), hash, padding);
+}
+
+int Manager::ocspCheck(const CertificateVector &certificateChainVector, int &ocspStatus)
+{
+    return m_impl->ocspCheck(certificateChainVector, ocspStatus);
+}
+
+} // namespace CKM
+
index 1be549b..9ca17b9 100644 (file)
@@ -34,7 +34,7 @@ Base64Encoder::Base64Encoder() :
 {
 }
 
-void Base64Encoder::append(const RawBuffer &data)
+void Base64Encoder::append(const SafeBuffer &data)
 {
     if (m_finalized) {
         LogWarning("Already finalized.");
@@ -57,7 +57,7 @@ void Base64Encoder::finalize()
     BIO_flush(m_b64);
 }
 
-RawBuffer Base64Encoder::get()
+SafeBuffer Base64Encoder::get()
 {
     if (!m_finalized) {
         LogWarning("Not finalized");
@@ -71,9 +71,9 @@ RawBuffer Base64Encoder::get()
     }
 
     if (bptr->length > 0) {
-        return RawBuffer(bptr->data, bptr->data + bptr->length);
+        return SafeBuffer(bptr->data, bptr->data + bptr->length);
     }
-    return RawBuffer();
+    return SafeBuffer();
 }
 
 void Base64Encoder::reset()
@@ -101,7 +101,7 @@ Base64Decoder::Base64Decoder() :
 {
 }
 
-void Base64Decoder::append(const RawBuffer &data)
+void Base64Decoder::append(const SafeBuffer &data)
 {
     if (m_finalized) {
         LogWarning("Already finalized.");
@@ -144,7 +144,7 @@ bool Base64Decoder::finalize()
     BIO *b64, *bmem;
     size_t len = m_input.size();
 
-    RawBuffer buffer(len);
+    SafeBuffer buffer(len);
 
     if (!buffer.data()) {
         LogError("Error in malloc.");
@@ -158,7 +158,7 @@ bool Base64Decoder::finalize()
         ThrowMsg(Exception::InternalError, "Couldn't create BIO object.");
     }
     BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
-    RawBuffer tmp(m_input);
+    SafeBuffer tmp(m_input);
     m_input.clear();
 
     bmem = BIO_new_mem_buf(tmp.data(), len);
@@ -193,7 +193,7 @@ bool Base64Decoder::finalize()
     return status;
 }
 
-RawBuffer Base64Decoder::get() const
+SafeBuffer Base64Decoder::get() const
 {
     if (!m_finalized) {
         LogWarning("Not finalized.");
index 70169cb..fd48349 100644 (file)
@@ -19,8 +19,7 @@
 #include <string>
 #include <dpl/noncopyable.h>
 #include <dpl/exception.h>
-
-#include <ckm/ckm-type.h>
+#include <safe-buffer.h>
 
 struct bio_st;
 typedef bio_st BIO;
@@ -39,9 +38,9 @@ class Base64Encoder : public CKM::Noncopyable
         DECLARE_EXCEPTION_TYPE(Base, AlreadyFinalized)
     };
     Base64Encoder();
-    void append(const RawBuffer &data);
+    void append(const SafeBuffer &data);
     void finalize();
-    RawBuffer get();
+    SafeBuffer get();
     void reset();
     ~Base64Encoder();
 
@@ -63,22 +62,22 @@ class Base64Decoder : public CKM::Noncopyable
         DECLARE_EXCEPTION_TYPE(Base, AlreadyFinalized)
     };
     Base64Decoder();
-    void append(const RawBuffer &data);
+    void append(const SafeBuffer &data);
 
     /*
      *  Function will return false when BIO_read fails
      *  (for example: when string was not in base64 format).
      */
     bool finalize();
-    RawBuffer get() const;
+    SafeBuffer get() const;
     void reset();
     ~Base64Decoder()
     {
     }
 
   private:
-    RawBuffer m_input;
-    RawBuffer m_output;
+    SafeBuffer m_input;
+    SafeBuffer m_output;
     bool m_finalized;
 };
 } // namespace CKM
diff --git a/src/manager/common/buffer-conversion.h b/src/manager/common/buffer-conversion.h
new file mode 100644 (file)
index 0000000..ba97d4d
--- /dev/null
@@ -0,0 +1,23 @@
+#pragma once
+
+#include <string.h>
+
+#include <ckm/ckm-type.h>
+#include <safe-buffer.h>
+
+namespace CKM {
+
+inline RawBuffer toRawBuffer(const SafeBuffer &safe) {
+    RawBuffer output(safe.size());
+    memcpy(output.data(), safe.data(), safe.size());
+    return output;
+}
+
+inline SafeBuffer toSafeBuffer(const RawBuffer &raw) {
+    SafeBuffer output(raw.size());
+    memcpy(output.data(), raw.data(), raw.size());
+    return output;
+}
+
+} // namespace CKM
+
index 10d818a..ef20d4f 100644 (file)
@@ -24,6 +24,7 @@
 
 #include <dpl/log/log.h>
 
+#include <buffer-conversion.h>
 #include <generic-key.h>
 #include <certificate-impl.h>
 #include <base64.h>
@@ -35,7 +36,47 @@ CertificateImpl::CertificateImpl(const RawBuffer &der, DataFormat format)
 {
     int size;
     const unsigned char *ptr;
-    RawBuffer tmp;
+    SafeBuffer tmp;
+
+    LogDebug("Certificate to parse. Size: " << der.size());
+
+    if (DataFormat::FORM_DER_BASE64 == format) {
+        Base64Decoder base64;
+        base64.reset();
+        base64.append(toSafeBuffer(der));
+        base64.finalize();
+        tmp = base64.get();
+        ptr = reinterpret_cast<const unsigned char*>(tmp.data());
+        size = static_cast<int>(tmp.size());
+        m_x509 = d2i_X509(NULL, &ptr, size);
+    } else if (DataFormat::FORM_DER == format) {
+        ptr = reinterpret_cast<const unsigned char*>(der.data());
+        size = static_cast<int>(der.size());
+        m_x509 = d2i_X509(NULL, &ptr, size);
+    } else if (DataFormat::FORM_PEM == format) {
+        BIO *buff = BIO_new(BIO_s_mem());
+        BIO_write(buff, der.data(), der.size());
+        m_x509 = PEM_read_bio_X509(buff, NULL, NULL, NULL);
+        BIO_free_all(buff);
+    } else {
+        // TODO
+        LogError("Unknown certificate format");
+    }
+
+    if (!m_x509) {
+        // TODO
+        LogError("Certificate could not be parsed.");
+//        ThrowMsg(Exception::OpensslInternalError,
+//          "Internal Openssl error in d2i_X509 function.");
+    }
+}
+
+CertificateImpl::CertificateImpl(const SafeBuffer &der, DataFormat format)
+  : m_x509(NULL)
+{
+    int size;
+    const unsigned char *ptr;
+    SafeBuffer tmp;
 
     LogDebug("Certificate to parse. Size: " << der.size());
 
@@ -121,6 +162,21 @@ RawBuffer CertificateImpl::getDER(void) const {
     return output;
 }
 
+SafeBuffer CertificateImpl::getDERSB(void) const {
+    unsigned char *rawDer = NULL;
+    int size = i2d_X509(m_x509, &rawDer);
+    if (!rawDer || size <= 0) {
+        LogError("i2d_X509 failed");
+        return SafeBuffer();
+    }
+
+    SafeBuffer output(
+        reinterpret_cast<char*>(rawDer),
+        reinterpret_cast<char*>(rawDer) + size);
+    OPENSSL_free(rawDer);
+    return output;
+}
+
 bool CertificateImpl::empty() const {
     return m_x509 == NULL;
 }
index 4dc6fc1..fb20b0e 100644 (file)
@@ -34,6 +34,7 @@ class CertificateImpl : public Certificate {
 public:
     CertificateImpl(){}
     CertificateImpl(X509* x509);
+    CertificateImpl(const SafeBuffer &data, DataFormat format);
     CertificateImpl(const RawBuffer &data, DataFormat format);
     CertificateImpl(const CertificateImpl &);
     CertificateImpl(CertificateImpl &&);
@@ -44,6 +45,8 @@ public:
     virtual bool empty() const;
     virtual X509* getX509() const;
 
+    SafeBuffer getDERSB() const;
+
     GenericKey::EvpShPtr getEvpShPtr() const;
     GenericKey getGenericKey() const;
 
index 82122c4..7103250 100644 (file)
 
 #include <openssl/evp.h>
 
-#include <vector>
+#include <safe-buffer.h>
 
 namespace CKM {
 
-typedef std::vector<unsigned char> RawBuffer;
-
 namespace Crypto {
 
 class Exception
@@ -123,8 +121,8 @@ public:                                                               \
     {}                                                                \
 }
 
-DEFINE_CIPHER(AesCbcEncryption, RawBuffer, EVP_aes_256_cbc(), true);
-DEFINE_CIPHER(AesCbcDecryption, RawBuffer, EVP_aes_256_cbc(), false);
+DEFINE_CIPHER(AesCbcEncryption, SafeBuffer, EVP_aes_256_cbc(), true);
+DEFINE_CIPHER(AesCbcDecryption, SafeBuffer, EVP_aes_256_cbc(), false);
 
 #undef DEFINE_CIPHER
 
index 0bec6fc..9e4847f 100644 (file)
@@ -61,7 +61,7 @@ void Digest::reset()
     m_initialized = true;
 }
 
-void Digest::append(const RawBuffer &data, std::size_t len)
+void Digest::append(const SafeBuffer &data, std::size_t len)
 {
     int ret = -1;
 
@@ -82,7 +82,7 @@ void Digest::append(const RawBuffer &data, std::size_t len)
     }
 }
 
-RawBuffer Digest::finalize()
+SafeBuffer Digest::finalize()
 {
     int ret = -1;
     unsigned int dlen;
@@ -104,12 +104,12 @@ RawBuffer Digest::finalize()
     return m_digest;
 }
 
-RawBuffer Digest::get()
+SafeBuffer Digest::get()
 {
     if (m_finalized)
         return m_digest;
     else
-        return RawBuffer();
+        return SafeBuffer();
 }
 
 unsigned int Digest::length()
index e890329..bd3fc11 100644 (file)
@@ -16,6 +16,7 @@
 
 #pragma once
 
+#include <safe-buffer.h>
 #include <dpl/noncopyable.h>
 #include <dpl/exception.h>
 #include <ckm/ckm-type.h>
@@ -41,16 +42,16 @@ class Digest : public CKM::Noncopyable
         };
         Digest();
         ~Digest();
-        void append(const RawBuffer &data, std::size_t len = 0);
-        RawBuffer finalize(void);
-        RawBuffer get(void);
+        void append(const SafeBuffer &data, std::size_t len = 0);
+        SafeBuffer finalize(void);
+        SafeBuffer get(void);
         void reset(void);
         unsigned int length(void);
 
     private:
         EVP_MD_CTX *m_ctx;
         const EVP_MD *m_md;
-        RawBuffer m_digest;
+        SafeBuffer m_digest;
         bool m_initialized;
         bool m_finalized;
 };
index f9b6b1e..368dcb9 100644 (file)
 
 #include <ckm/ckm-type.h>
 #include <generic-key.h>
+#include <buffer-conversion.h>
 
 namespace CKM {
 namespace {
 
-//void printDER(const RawBuffer &key) {
+//void printDER(const SafeBuffer &key) {
 //    std::stringstream ss;
 //    for (auto &e : key) {
 //        ss << std::hex << " " << (int)e;
@@ -64,31 +65,31 @@ int passcb(char *buff, int size, int rwflag, void *userdata) {
 
 typedef int(*I2D_CONV)(BIO*, EVP_PKEY*);
 
-CKM::RawBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) {
+CKM::SafeBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) {
     BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all);
 
     if (NULL == pkey) {
         LogDebug("You are trying to read empty key!");
-        return RawBuffer();
+        return SafeBuffer();
     }
 
     if (NULL == bio.get()) {
         LogError("Error in memory allocation! Function: BIO_new.");
-        return RawBuffer();
+        return SafeBuffer();
     }
 
     if (1 != fun(bio.get(), pkey)) {
         LogError("Error in conversion EVP_PKEY to der");
-        return RawBuffer();
+        return SafeBuffer();
     }
 
-    CKM::RawBuffer output(8196);
+    CKM::SafeBuffer output(8196);
 
     int size = BIO_read(bio.get(), output.data(), output.size());
 
     if (size <= 0) {
         LogError("Error in BIO_read: " << size);
-        return RawBuffer();
+        return SafeBuffer();
     }
 
     output.resize(size);
@@ -107,7 +108,7 @@ GenericKey::GenericKey(const GenericKey &second) {
     m_type = second.m_type;
 }
 
-GenericKey::GenericKey(const RawBuffer &buf, const std::string &pass)
+GenericKey::GenericKey(const SafeBuffer &buf, const std::string &pass)
   : m_pkey(NULL, EVP_PKEY_free)
   , m_type(KeyType::KEY_NONE)
 {
@@ -196,35 +197,29 @@ KeyType GenericKey::getType() const {
     return m_type;
 }
 
-RawBuffer GenericKey::getDERPRV() const {
+SafeBuffer GenericKey::getDERPRV() const {
     return i2d(i2d_PrivateKey_bio, m_pkey.get());
 }
 
-RawBuffer GenericKey::getDERPUB() const {
+SafeBuffer GenericKey::getDERPUB() const {
     return i2d(i2d_PUBKEY_bio, m_pkey.get());
 }
 
-RawBuffer GenericKey::getDER() const {
+SafeBuffer GenericKey::getDERSB() const {
     if (m_type == KeyType::KEY_ECDSA_PRIVATE || m_type == KeyType::KEY_RSA_PRIVATE) {
         return getDERPRV();
     } else if (m_type == KeyType::KEY_RSA_PUBLIC || m_type == KeyType::KEY_ECDSA_PUBLIC) {
         return getDERPUB();
     }
-    return RawBuffer();
-
-//    RawBuffer output;
-//    if (m_type == KeyType::KEY_ECDSA_PRIVATE || m_type == KeyType::KEY_RSA_PRIVATE) {
-//        output = getDERPRV();
-//    } else if (m_type == KeyType::KEY_RSA_PUBLIC || m_type == KeyType::KEY_ECDSA_PUBLIC) {
-//        output = getDERPUB();
-//    } 
-//    LogError("Key::getDER");
-//    printDER(output);
-//    return output;
+    return SafeBuffer();
+}
+
+RawBuffer GenericKey::getDER() const {
+    return toRawBuffer(getDERSB());
 }
 
 KeyShPtr Key::create(const RawBuffer &raw, const std::string &password) {
-    KeyShPtr output(new GenericKey(raw, password));
+    KeyShPtr output(new GenericKey(toSafeBuffer(raw), password));
     if (output->empty())
         output.reset();
     return output;
index 69526c0..4f1cd5b 100644 (file)
@@ -22,6 +22,8 @@
 
 #include <memory>
 
+#include <safe-buffer.h>
+
 #include <ckm/ckm-type.h>
 #include <ckm/ckm-key.h>
 #include <openssl/evp.h>
@@ -34,14 +36,17 @@ public:
 
     GenericKey();
     GenericKey(const GenericKey &second);
-    GenericKey(const RawBuffer& buffer, const std::string &pass = std::string());
+    GenericKey(const SafeBuffer& buffer, const std::string &pass = std::string());
     GenericKey(EvpShPtr pkey, KeyType type);
 
     virtual KeyType getType() const;
     virtual RawBuffer getDER() const;
-    virtual RawBuffer getDERPUB() const;
-    virtual RawBuffer getDERPRV() const;
-    virtual EvpShPtr getEvpShPtr() const;
+
+    SafeBuffer getDERSB() const;
+    SafeBuffer getDERPUB() const;
+    SafeBuffer getDERPRV() const;
+    EvpShPtr getEvpShPtr() const;
+
     virtual ElipticCurve getCurve() const {
         // TODO
         return ElipticCurve::prime192v1;
index bfecf37..d756f34 100644 (file)
 
 namespace CKM {
 
-void MessageBuffer::Push(const RawBuffer &data) {
+void MessageBuffer::Push(const SafeBuffer &data) {
     m_buffer.AppendCopy(&data[0], data.size());
 }
 
-RawBuffer MessageBuffer::Pop() {
+SafeBuffer MessageBuffer::Pop() {
     size_t size = m_buffer.Size();
-    RawBuffer buffer;
+    SafeBuffer buffer;
     buffer.resize(size + sizeof(size_t));
     memcpy(&buffer[0], &size, sizeof(size_t));
     m_buffer.FlattenConsume(&buffer[sizeof(size_t)], size);
index e19a07b..47f3326 100644 (file)
@@ -26,7 +26,7 @@
 #ifndef _CENT_KEY_MNG_SOCKET_BUFFER_
 #define _CENT_KEY_MNG_SOCKET_BUFFER_
 
-#include <vector>
+#include <safe-buffer.h>
 
 #include <dpl/binary_queue.h>
 #include <dpl/exception.h>
@@ -34,8 +34,6 @@
 
 namespace CKM {
 
-typedef std::vector<unsigned char> RawBuffer;
-
 class MessageBuffer : public CKM::IStream {
 public:
     class Exception
@@ -49,9 +47,9 @@ public:
       : m_bytesLeft(0)
     {}
 
-    void Push(const RawBuffer &data);
+    void Push(const SafeBuffer &data);
 
-    RawBuffer Pop();
+    SafeBuffer Pop();
 
     bool Ready();
 
index fb754dc..720012d 100644 (file)
@@ -24,6 +24,8 @@
 
 #include <string.h>
 
+#include <vector>
+
 #include <boost/container/vector.hpp>
 
 namespace CKM {
@@ -68,7 +70,7 @@ constexpr bool operator!= (const erase_on_dealloc<T>&, const erase_on_dealloc<U>
  *  template <typename T>
  *  using SafeBuffer = std::vector<T, erase_on_dealloc<T>>;
  *
- *  typedef SafeBuffer<unsigned char> RawBuffer
+ *  typedef SafeBuffer<unsigned char> SafeBuffer
  *
  * when gcc 4.7/4.8 is available. Also replace boost::vector with std::vector
  * in other parts of code
@@ -80,6 +82,7 @@ struct SafeBufferT {
 
 // used to pass password and raw key data
 typedef SafeBufferT<unsigned char>::Type SafeBuffer;
+typedef std::vector<SafeBuffer> SafeBufferVector;
 
 } // namespace CKM
 
index 58773ed..5c120f3 100644 (file)
@@ -28,6 +28,8 @@
 #include <map>
 #include <memory>
 
+#include <safe-buffer.h>
+
 namespace CKM {
 // Abstract data stream buffer
 class IStream
@@ -212,6 +214,19 @@ struct Serialization {
     {
         Serialize(stream, *p);
     }
+
+    static void Serialize(IStream& stream, const SafeBuffer& vec)
+    {
+        int length = vec.size();
+        stream.Write(sizeof(length), &length);
+        stream.Write(length, vec.data());
+    }
+
+    static void Serialize(IStream& stream, const SafeBuffer* const vec)
+    {
+        Serialize(stream, *vec);
+    }
+
 }; // struct Serialization
 
 struct Deserialization {
@@ -393,6 +408,21 @@ struct Deserialization {
         map = new std::map<K, T>;
         Deserialize(stream, *map);
     }
+
+    static void Deserialize(IStream& stream, SafeBuffer& vec)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        vec.resize(length);
+        stream.Read(length, vec.data());
+    }
+
+    static void Deserialize(IStream& stream, SafeBuffer*& vec)
+    {
+        vec = new SafeBuffer;
+        Deserialize(stream, *vec);
+    }
+
 }; // struct Deserialization
 } // namespace CKM
 
index ee90cc4..561879b 100644 (file)
@@ -35,6 +35,8 @@
 #include <stdint.h>
 #include <vector>
 
+#include <safe-buffer.h>
+
 namespace CKM {
 namespace DB {
 /**
@@ -165,8 +167,7 @@ class SqlConnection
          * @param position Index of argument to bind value to
          * @param value Value to bind
          */
-        void BindBlob(ArgumentIndex position,
-                const std::vector<unsigned char> &value);
+        void BindBlob(ArgumentIndex position, const SafeBuffer &value);
 
         /**
          * Bind optional int to the prepared statement argument.
@@ -248,7 +249,7 @@ class SqlConnection
          * @param value Value to bind
          */
         void BindBlob(ArgumentIndex position,
-                const boost::optional<std::vector<unsigned char>> &value);
+                const boost::optional<SafeBuffer> &value);
 
         /**
          * Execute the prepared statement and/or move
@@ -331,7 +332,7 @@ class SqlConnection
          *
          * @throw Exception::InvalidColumn
          */
-        std::vector<unsigned char> GetColumnBlob(ColumnIndex column);
+        SafeBuffer GetColumnBlob(ColumnIndex column);
 
         /**
          * Get optional integer value from column in current row.
@@ -394,8 +395,7 @@ class SqlConnection
          *
          * @throw Exception::InvalidColumn
          */
-        boost::optional<std::vector<unsigned char>>
-            GetColumnOptionalBlob(ColumnIndex column);
+        boost::optional<SafeBuffer> GetColumnOptionalBlob(ColumnIndex column);
     };
 
     // Move on copy constructor. No copy semantics
@@ -492,7 +492,7 @@ class SqlConnection
      *
      * @param rawPass password given in raw binary format
      */
-    void SetKey(const std::vector<unsigned char> &rawPass);
+    void SetKey(const SafeBuffer &rawPass);
 
     /**
      * ResetKey is used for changing key used for database encryption.
@@ -506,8 +506,8 @@ class SqlConnection
      * @param rawPassNew new password for encryption in raw binary format
      *
      */
-    void ResetKey(const std::vector<unsigned char> &rawPassOld,
-                  const std::vector<unsigned char> &rawPassNew);
+    void ResetKey(const SafeBuffer &rawPassOld,
+                  const SafeBuffer &rawPassNew);
 
     /**
      * Execute SQL command without result
index 7d92157..edd9aab 100644 (file)
@@ -35,6 +35,8 @@
 #include <cstdarg>
 #include <memory>
 
+#include <safe-buffer.h>
+
 namespace CKM {
 namespace DB {
 namespace // anonymous
@@ -231,7 +233,7 @@ void SqlConnection::DataCommand::BindString(
 
 void SqlConnection::DataCommand::BindBlob(
     SqlConnection::ArgumentIndex position,
-    const std::vector<unsigned char> &raw)
+    const SafeBuffer &raw)
 {
     if (raw.size() == 0) {
         BindNull(position);
@@ -343,7 +345,7 @@ void SqlConnection::DataCommand::BindString(
 
 void SqlConnection::DataCommand::BindBlob(
     SqlConnection::ArgumentIndex position,
-    const boost::optional<std::vector<unsigned char>> &value)
+    const boost::optional<SafeBuffer> &value)
 {
     if (!!value) {
         BindBlob(position, *value);
@@ -512,7 +514,7 @@ std::string SqlConnection::DataCommand::GetColumnString(
     return std::string(value);
 }
 
-std::vector<unsigned char> SqlConnection::DataCommand::GetColumnBlob(
+SafeBuffer SqlConnection::DataCommand::GetColumnBlob(
     SqlConnection::ColumnIndex column)
 {
     LogPedantic("SQL data command get column blog: [" << column << "]");
@@ -522,13 +524,13 @@ std::vector<unsigned char> SqlConnection::DataCommand::GetColumnBlob(
             sqlcipher3_column_blob(m_stmt, column));
 
     if (value == NULL) {
-        return std::vector<unsigned char>();
+        return SafeBuffer();
     }
 
     int length = sqlcipher3_column_bytes(m_stmt, column);
     LogPedantic("Got blob of length: " << length);
 
-    return std::vector<unsigned char>(value, value + length);
+    return SafeBuffer(value, value + length);
 }
 
 boost::optional<int> SqlConnection::DataCommand::GetColumnOptionalInteger(
@@ -645,14 +647,14 @@ boost::optional<String> SqlConnection::DataCommand::GetColumnOptionalString(
     return boost::optional<String>(s);
 }
 
-boost::optional<std::vector<unsigned char>> SqlConnection::DataCommand::GetColumnOptionalBlob(
+boost::optional<SafeBuffer> SqlConnection::DataCommand::GetColumnOptionalBlob(
     SqlConnection::ColumnIndex column)
 {
     LogPedantic("SQL data command get column blog: [" << column << "]");
     CheckColumnIndex(column);
 
     if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) {
-        return boost::optional<std::vector<unsigned char>>();
+        return boost::optional<SafeBuffer>();
     }
     const unsigned char *value = reinterpret_cast<const unsigned char*>(
             sqlcipher3_column_blob(m_stmt, column));
@@ -660,8 +662,8 @@ boost::optional<std::vector<unsigned char>> SqlConnection::DataCommand::GetColum
     int length = sqlcipher3_column_bytes(m_stmt, column);
     LogPedantic("Got blob of length: " << length);
 
-    std::vector<unsigned char> temp(value, value + length);
-    return boost::optional<std::vector<unsigned char>>(temp);
+    SafeBuffer temp(value, value + length);
+    return boost::optional<SafeBuffer>(temp);
 }
 
 void SqlConnection::Connect(const std::string &address,
@@ -698,12 +700,12 @@ const std::size_t SQLCIPHER_RAW_DATA_SIZE = 32;
 
 void rawToHexString(TransitoryString& str,
                     std::size_t offset,
-                    const std::vector<unsigned char> &raw) {
+                    const SafeBuffer &raw) {
     for (std::size_t i = 0; i < raw.size(); i++)
         sprintf(&str[offset + i*2], "%02X", raw[i]);
 }
 
-TransitoryString createHexPass(const std::vector<unsigned char> &rawPass){
+TransitoryString createHexPass(const SafeBuffer &rawPass){
     TransitoryString pass = TransitoryString('0', SQLCIPHER_RAW_PREFIX.length() +
                                              //We are required to pass 64byte
                                              //long hex password made out of
@@ -720,7 +722,7 @@ TransitoryString createHexPass(const std::vector<unsigned char> &rawPass){
 
 }
 
-void SqlConnection::SetKey(const std::vector<unsigned char> &rawPass){
+void SqlConnection::SetKey(const SafeBuffer &rawPass){
     if (m_connection == NULL) {
         LogPedantic("Cannot set key. No connection to DB!");
         return;
@@ -742,8 +744,9 @@ void SqlConnection::SetKey(const std::vector<unsigned char> &rawPass){
     m_isKeySet = true;
 };
 
-void SqlConnection::ResetKey(const std::vector<unsigned char> &rawPassOld,
-                             const std::vector<unsigned char> &rawPassNew) {
+void SqlConnection::ResetKey(const SafeBuffer &rawPassOld,
+                             const SafeBuffer &rawPassNew)
+{
     if (m_connection == NULL) {
         LogPedantic("Cannot reset key. No connection to DB!");
         return;
index c9be9ac..d24c397 100644 (file)
@@ -31,6 +31,8 @@
 
 #include <sys/types.h>
 
+#include <safe-buffer.h>
+
 #include <dpl/exception.h>
 
 #include <generic-event.h>
@@ -56,8 +58,6 @@ struct ConnectionID {
     }
 };
 
-typedef std::vector<unsigned char> RawBuffer;
-
 struct GenericSocketManager;
 
 struct GenericSocketService {
@@ -96,7 +96,7 @@ struct GenericSocketService {
 
     struct ReadEvent : public GenericEvent {
         ConnectionID connectionID;
-        RawBuffer rawBuffer;
+        SafeBuffer rawBuffer;
     };
 
     struct CloseEvent : public GenericEvent {
@@ -123,7 +123,7 @@ struct GenericSocketManager {
     virtual void MainLoop() = 0;
     virtual void RegisterSocketService(GenericSocketService *ptr) = 0;
     virtual void Close(ConnectionID connectionID) = 0;
-    virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer) = 0;
+    virtual void Write(ConnectionID connectionID, const SafeBuffer &rawBuffer) = 0;
     virtual ~GenericSocketManager(){}
 };
 
index 04f424d..3fb3fa4 100644 (file)
@@ -117,14 +117,14 @@ char *read_exe_path_from_proc(pid_t pid)
     return exe;
 }
 
-void rawBufferToX509(X509 **ppCert, RawBuffer rawCert) {
+void rawBufferToX509(X509 **ppCert, SafeBuffer rawCert) {
   BIO *bio = BIO_new(BIO_s_mem());
   BIO_write(bio, rawCert.data(), rawCert.size());
   d2i_X509_bio(bio, ppCert);
   BIO_free_all(bio);
 }
 
-void x509ToRawBuffer(RawBuffer &buf, X509 *cert) {
+void x509ToSafeBuffer(SafeBuffer &buf, X509 *cert) {
   int len = i2d_X509(cert, NULL);
   unsigned char tmpBuff[len];
   unsigned char *p = tmpBuff;
index b43b3fa..f0ceb93 100644 (file)
@@ -22,6 +22,7 @@
 #ifndef CENT_KEY_MNG_UTIL_H
 #define CENT_KEY_MNG_UTIL_H
 
+#include <safe-buffer.h>
 #include <sys/types.h>
 #include <ckm/ckm-type.h>
 #include <openssl/x509v3.h>
@@ -33,8 +34,8 @@ namespace CKM {
 int util_smack_label_is_valid(const char *smack_label);
 char *read_exe_path_from_proc(pid_t pid);
 
-void rawBufferToX509(X509 **ppCert, RawBuffer rawCert);
-void x509ToRawBuffer(RawBuffer &buf, X509 *cert);
+void rawBufferToX509(X509 **ppCert, SafeBuffer rawCert);
+void x509ToSafeBuffer(SafeBuffer &buf, X509 *cert);
 
 STACK_OF(X509) *loadSystemCerts( const char * dirpath);
 X509 *loadCert(const char *file);
index 73e90e4..42559b8 100644 (file)
@@ -582,7 +582,7 @@ void SocketManager::Close(ConnectionID connectionID) {
     NotifyMe();
 }
 
-void SocketManager::Write(ConnectionID connectionID, const RawBuffer &rawBuffer) {
+void SocketManager::Write(ConnectionID connectionID, const SafeBuffer &rawBuffer) {
     WriteBuffer buffer;
     buffer.connectionID = connectionID;
     buffer.rawBuffer = rawBuffer;
index 978dbee..922567d 100644 (file)
@@ -52,7 +52,7 @@ public:
 
     virtual void RegisterSocketService(GenericSocketService *service);
     virtual void Close(ConnectionID connectionID);
-    virtual void Write(ConnectionID connectionID, const RawBuffer &rawBuffer);
+    virtual void Write(ConnectionID connectionID, const SafeBuffer &rawBuffer);
 
 protected:
     void CreateDomainSocket(
@@ -79,7 +79,7 @@ protected:
         InterfaceID interfaceID;
         GenericSocketService *service;
         time_t timeout;
-        RawBuffer rawBuffer;
+        SafeBuffer rawBuffer;
         int counter;
 
         SocketDescription()
@@ -97,7 +97,7 @@ protected:
 
     struct WriteBuffer {
         ConnectionID connectionID;
-        RawBuffer rawBuffer;
+        SafeBuffer rawBuffer;
     };
 
     struct Timeout {
index 39908a3..4d73ce1 100644 (file)
@@ -274,15 +274,15 @@ int CryptoService::createKeyPairECDSA(ElipticCurve type,
 }
 
 int CryptoService::createSignature(const GenericKey &privateKey,
-               const RawBuffer &message,
+               const SafeBuffer &message,
                const HashAlgorithm hashAlgo,
                const RSAPaddingAlgorithm padAlgo,
-               RawBuffer &signature)
+               SafeBuffer &signature)
 {
        EVP_MD_CTX *mdctx = NULL;
        EVP_PKEY_CTX *pctx = NULL;
        int rsa_padding = NOT_DEFINED;
-       RawBuffer data;
+       SafeBuffer data;
        const EVP_MD *md_algo = NULL;
 
        // check the parameters of functions
@@ -403,8 +403,8 @@ int CryptoService::createSignature(const GenericKey &privateKey,
 }
 
 int CryptoService::verifySignature(const GenericKey &publicKey,
-               const RawBuffer &message,
-               const RawBuffer &signature,
+               const SafeBuffer &message,
+               const SafeBuffer &signature,
                const HashAlgorithm hashAlgo,
                const RSAPaddingAlgorithm padAlgo)
 {
@@ -515,7 +515,7 @@ int CryptoService::verifyCertificateChain(const CertificateImpl &certificate,
 
        X509 *cert = X509_new();
        X509 *tempCert;
-       rawBufferToX509(&cert, certificate.getDER());
+       rawBufferToX509(&cert, certificate.getDERSB());
 
        std::vector<X509 *> trustedCerts;
        std::vector<X509 *> userTrustedCerts;
@@ -557,7 +557,7 @@ int CryptoService::verifyCertificateChain(const CertificateImpl &certificate,
                                LogError("Error in X509_new function");
                                ThrowMsg(CryptoService::Exception::opensslError, "Error in X509_new function");
                        }
-                       rawBufferToX509(&tempCert, userTrustedCertificates[i].getDER());
+                       rawBufferToX509(&tempCert, userTrustedCertificates[i].getDERSB());
                        userTrustedCerts.push_back(tempCert);
                }
 
@@ -566,16 +566,16 @@ int CryptoService::verifyCertificateChain(const CertificateImpl &certificate,
                                LogError("Error in X509_new function");
                                ThrowMsg(CryptoService::Exception::opensslError, "Error in X509_new function");
                        }
-                       rawBufferToX509(&tempCert, untrustedCertificates[i].getDER());
+                       rawBufferToX509(&tempCert, untrustedCertificates[i].getDERSB());
                        untrustedChain.push_back(tempCert);
                }
 
                std::vector<X509 *> chain = verifyCertChain(cert, trustedCerts, userTrustedCerts, untrustedChain);
 
-               RawBuffer tmpBuf;
+               SafeBuffer tmpBuf;
                for(unsigned int i=0;i<chain.size();i++) {
-                       x509ToRawBuffer(tmpBuf, chain[i]);
-                       CertificateImpl tmpCertImpl((const RawBuffer)tmpBuf, DataFormat::FORM_DER);
+                       x509ToSafeBuffer(tmpBuf, chain[i]);
+                       CertificateImpl tmpCertImpl((const SafeBuffer)tmpBuf, DataFormat::FORM_DER);
                        certificateChainVector.push_back(tmpCertImpl);
                }
        } Catch(CryptoService::Exception::opensslError) {
index 22e92fe..04b8bb8 100644 (file)
@@ -61,14 +61,14 @@ class CryptoService {
                                         GenericKey &createdPublicKey);  // returned value
 
      int createSignature(const GenericKey &privateKey,
-                         const RawBuffer &message,
+                         const SafeBuffer &message,
                          const HashAlgorithm hashAlgo,
                          const RSAPaddingAlgorithm padAlgo,
-                         RawBuffer &signature);
+                         SafeBuffer &signature);
 
      int verifySignature(const GenericKey &publicKey,
-                         const RawBuffer &message,
-                         const RawBuffer &signature,
+                         const SafeBuffer &message,
+                         const SafeBuffer &signature,
                          const HashAlgorithm hashAlgo,
                          const RSAPaddingAlgorithm padAlgo);
 
index 948411f..3a58269 100755 (executable)
@@ -50,7 +50,7 @@ CKMLogic::CKMLogic()
 
 CKMLogic::~CKMLogic(){}
 
-RawBuffer CKMLogic::unlockUserKey(uid_t user, const std::string &password) {
+SafeBuffer CKMLogic::unlockUserKey(uid_t user, const std::string &password) {
     // TODO try catch for all errors that should be supported by error code
     int retCode = CKM_API_SUCCESS;
 
@@ -67,7 +67,7 @@ RawBuffer CKMLogic::unlockUserKey(uid_t user, const std::string &password) {
 
             handle.keyProvider = KeyProvider(wrappedDomainKEK, password);
 
-            RawBuffer key = handle.keyProvider.getPureDomainKEK();
+            SafeBuffer key = handle.keyProvider.getPureDomainKEK();
             handle.database = DBCrypto(fs.getDBPath(), key);
             handle.crypto = CryptoLogic();
             // TODO wipe key
@@ -91,7 +91,7 @@ RawBuffer CKMLogic::unlockUserKey(uid_t user, const std::string &password) {
     return response.Pop();
 }
 
-RawBuffer CKMLogic::lockUserKey(uid_t user) {
+SafeBuffer CKMLogic::lockUserKey(uid_t user) {
     int retCode = CKM_API_SUCCESS;
     // TODO try catch for all errors that should be supported by error code
     m_userDataMap.erase(user);
@@ -101,7 +101,7 @@ RawBuffer CKMLogic::lockUserKey(uid_t user) {
     return response.Pop();
 }
 
-RawBuffer CKMLogic::removeUserData(uid_t user) {
+SafeBuffer CKMLogic::removeUserData(uid_t user) {
     int retCode = CKM_API_SUCCESS;
     // TODO try catch for all errors that should be supported by error code
     m_userDataMap.erase(user);
@@ -114,7 +114,7 @@ RawBuffer CKMLogic::removeUserData(uid_t user) {
     return response.Pop();
 }
 
-RawBuffer CKMLogic::changeUserPassword(
+SafeBuffer CKMLogic::changeUserPassword(
     uid_t user,
     const std::string &oldPassword,
     const std::string &newPassword)
@@ -145,7 +145,7 @@ RawBuffer CKMLogic::changeUserPassword(
     return response.Pop();
 }
 
-RawBuffer CKMLogic::resetUserPassword(
+SafeBuffer CKMLogic::resetUserPassword(
     uid_t user,
     const std::string &newPassword)
 {
@@ -168,7 +168,7 @@ int CKMLogic::saveDataHelper(
     Credentials &cred,
     DBDataType dataType,
     const Alias &alias,
-    const RawBuffer &key,
+    const SafeBuffer &key,
     const PolicySerializable &policy)
 {
     if (0 == m_userDataMap.count(cred.uid))
@@ -176,12 +176,12 @@ int CKMLogic::saveDataHelper(
 
     DBRow row = { alias, cred.smackLabel, policy.restricted,
          policy.extractable, dataType, DBCMAlgType::NONE,
-         0, RawBuffer(), static_cast<int>(key.size()), key };
+         0, SafeBuffer(), static_cast<int>(key.size()), key };
 
     auto &handler = m_userDataMap[cred.uid];
     DBCrypto::Transaction transaction(&handler.database);
     if (!handler.crypto.haveKey(cred.smackLabel)) {
-        RawBuffer key;
+        SafeBuffer key;
         auto key_optional = handler.database.getKey(cred.smackLabel);
         if(!key_optional) {
             LogDebug("No Key in database found. Generating new one for label: "
@@ -202,12 +202,12 @@ int CKMLogic::saveDataHelper(
     return CKM_API_SUCCESS;
 }
 
-RawBuffer CKMLogic::saveData(
+SafeBuffer CKMLogic::saveData(
     Credentials &cred,
     int commandId,
     DBDataType dataType,
     const Alias &alias,
-    const RawBuffer &key,
+    const SafeBuffer &key,
     const PolicySerializable &policy)
 {
     int retCode = CKM_API_SUCCESS;
@@ -240,7 +240,7 @@ RawBuffer CKMLogic::saveData(
     return response.Pop();
 }
 
-RawBuffer CKMLogic::removeData(
+SafeBuffer CKMLogic::removeData(
     Credentials &cred,
     int commandId,
     DBDataType dataType,
@@ -320,7 +320,7 @@ int CKMLogic::getDataHelper(
     }
 
     if (!handler.crypto.haveKey(row.smackLabel)) {
-        RawBuffer key;
+        SafeBuffer key;
         auto key_optional = handler.database.getKey(row.smackLabel);
         if(!key_optional) {
             LogError("No key for given label in database");
@@ -335,7 +335,7 @@ int CKMLogic::getDataHelper(
     return CKM_API_SUCCESS;
 }
 
-RawBuffer CKMLogic::getData(
+SafeBuffer CKMLogic::getData(
     Credentials &cred,
     int commandId,
     DBDataType dataType,
@@ -372,7 +372,7 @@ RawBuffer CKMLogic::getData(
     return response.Pop();
 }
 
-RawBuffer CKMLogic::getDataList(
+SafeBuffer CKMLogic::getDataList(
     Credentials &cred,
     int commandId,
     DBDataType dataType)
@@ -431,7 +431,7 @@ int CKMLogic::createKeyPairRSAHelper(
     retCode = saveDataHelper(cred,
                             toDBDataType(prv.getType()),
                             aliasPrivate,
-                            prv.getDER(),
+                            prv.getDERSB(),
                             policyPrivate);
 
     if (CKM_API_SUCCESS != retCode)
@@ -440,7 +440,7 @@ int CKMLogic::createKeyPairRSAHelper(
     retCode = saveDataHelper(cred,
                             toDBDataType(pub.getType()),
                             aliasPublic,
-                            pub.getDER(),
+                            pub.getDERSB(),
                             policyPublic);
 
     if (CKM_API_SUCCESS != retCode)
@@ -451,7 +451,7 @@ int CKMLogic::createKeyPairRSAHelper(
     return retCode;
 }
 
-RawBuffer CKMLogic::createKeyPairRSA(
+SafeBuffer CKMLogic::createKeyPairRSA(
     Credentials &cred,
     int commandId,
     int size,
@@ -520,7 +520,7 @@ int CKMLogic::createKeyPairECDSAHelper(
     retCode = saveDataHelper(cred,
                             toDBDataType(prv.getType()),
                             aliasPrivate,
-                            prv.getDER(),
+                            prv.getDERSB(),
                             policyPrivate);
 
     if (CKM_API_SUCCESS != retCode)
@@ -529,7 +529,7 @@ int CKMLogic::createKeyPairECDSAHelper(
     retCode = saveDataHelper(cred,
                             toDBDataType(pub.getType()),
                             aliasPublic,
-                            pub.getDER(),
+                            pub.getDERSB(),
                             policyPublic);
 
     if (CKM_API_SUCCESS != retCode)
@@ -540,7 +540,7 @@ int CKMLogic::createKeyPairECDSAHelper(
     return retCode;
 }
 
-RawBuffer CKMLogic::createKeyPairECDSA(
+SafeBuffer CKMLogic::createKeyPairECDSA(
     Credentials &cred,
     int commandId,
     int type,
@@ -581,18 +581,18 @@ RawBuffer CKMLogic::createKeyPairECDSA(
     return response.Pop();
 }
 
-RawBuffer CKMLogic::getCertificateChain(
+SafeBuffer CKMLogic::getCertificateChain(
     Credentials &cred,
     int commandId,
-    const RawBuffer &certificate,
-    const RawBufferVector &untrustedRawCertVector)
+    const SafeBuffer &certificate,
+    const SafeBufferVector &untrustedRawCertVector)
 {
     (void)cred;
 
     CertificateImpl cert(certificate, DataFormat::FORM_DER);
     CertificateImplVector untrustedCertVector;
     CertificateImplVector chainVector;
-    RawBufferVector chainRawVector;
+    SafeBufferVector chainRawVector;
 
     for (auto &e: untrustedRawCertVector)
         untrustedCertVector.push_back(CertificateImpl(e, DataFormat::FORM_DER));
@@ -603,7 +603,7 @@ RawBuffer CKMLogic::getCertificateChain(
 
     if (retCode == CKM_API_SUCCESS) {
         for (auto &e : chainVector)
-            chainRawVector.push_back(e.getDER());
+            chainRawVector.push_back(e.getDERSB());
     }
 
     MessageBuffer response;
@@ -614,14 +614,14 @@ RawBuffer CKMLogic::getCertificateChain(
     return response.Pop();
 }
 
-RawBuffer CKMLogic::getCertificateChain(
+SafeBuffer CKMLogic::getCertificateChain(
     Credentials &cred,
     int commandId,
-    const RawBuffer &certificate,
+    const SafeBuffer &certificate,
     const AliasVector &aliasVector)
 {
     int retCode = CKM_API_SUCCESS;
-    RawBufferVector chainRawVector;
+    SafeBufferVector chainRawVector;
     try {
         CertificateImpl cert(certificate, DataFormat::FORM_DER);
         CertificateImplVector untrustedCertVector;
@@ -648,7 +648,7 @@ RawBuffer CKMLogic::getCertificateChain(
             goto senderror;
 
         for (auto &i: chainVector)
-            chainRawVector.push_back(i.getDER());
+            chainRawVector.push_back(i.getDERSB());
 
     } catch (const CryptoLogic::Exception::Base &e) {
         LogError("DBCyptorModule failed with message: " << e.GetMessage());
@@ -669,18 +669,18 @@ senderror:
     return response.Pop();
 }
 
-RawBuffer CKMLogic::createSignature(
+SafeBuffer CKMLogic::createSignature(
         Credentials &cred,
         int commandId,
         const Alias &privateKeyAlias,
         const std::string &password,           // password for private_key
-        const RawBuffer &message,
+        const SafeBuffer &message,
         const HashAlgorithm hash,
         const RSAPaddingAlgorithm padding)
 {
     DBRow row;
     CryptoService cs;
-    RawBuffer signature;
+    SafeBuffer signature;
 
     int retCode = CKM_API_SUCCESS;
 
@@ -720,13 +720,13 @@ RawBuffer CKMLogic::createSignature(
     return response.Pop();
 }
 
-RawBuffer CKMLogic::verifySignature(
+SafeBuffer CKMLogic::verifySignature(
         Credentials &cred,
         int commandId,
         const Alias &publicKeyOrCertAlias,
         const std::string &password,           // password for public_key (optional)
-        const RawBuffer &message,
-        const RawBuffer &signature,
+        const SafeBuffer &message,
+        const SafeBuffer &signature,
         const HashAlgorithm hash,
         const RSAPaddingAlgorithm padding)
 {
index 661a6a7..c42a478 100644 (file)
@@ -50,48 +50,48 @@ public:
     CKMLogic& operator=(CKMLogic &&) = delete;
     virtual ~CKMLogic();
 
-    RawBuffer unlockUserKey(uid_t user, const std::string &password);
+    SafeBuffer unlockUserKey(uid_t user, const std::string &password);
 
-    RawBuffer lockUserKey(uid_t user);
+    SafeBuffer lockUserKey(uid_t user);
 
-    RawBuffer removeUserData(uid_t user);
+    SafeBuffer removeUserData(uid_t user);
 
-    RawBuffer changeUserPassword(
+    SafeBuffer changeUserPassword(
         uid_t user,
         const std::string &oldPassword,
         const std::string &newPassword);
 
-    RawBuffer resetUserPassword(
+    SafeBuffer resetUserPassword(
         uid_t user,
         const std::string &newPassword);
 
-    RawBuffer saveData(
+    SafeBuffer saveData(
         Credentials &cred,
         int commandId,
         DBDataType dataType,
         const Alias &alias,
-        const RawBuffer &key,
+        const SafeBuffer &key,
         const PolicySerializable &policy);
 
-    RawBuffer removeData(
+    SafeBuffer removeData(
         Credentials &cred,
         int commandId,
         DBDataType dataType,
         const Alias &alias);
 
-    RawBuffer getData(
+    SafeBuffer getData(
         Credentials &cred,
         int commandId,
         DBDataType dataType,
         const Alias &alias,
         const std::string &password);
 
-    RawBuffer getDataList(
+    SafeBuffer getDataList(
         Credentials &cred,
         int commandId,
         DBDataType dataType);
 
-    RawBuffer createKeyPairRSA(
+    SafeBuffer createKeyPairRSA(
         Credentials &cred,
         int commandId,
         int size,
@@ -100,7 +100,7 @@ public:
         const PolicySerializable &policyPrivate,
         const PolicySerializable &policyPublic);
 
-    RawBuffer createKeyPairECDSA(
+    SafeBuffer createKeyPairECDSA(
         Credentials &cred,
         int commandId,
         int type,
@@ -109,34 +109,34 @@ public:
         const PolicySerializable &policyPrivate,
         const PolicySerializable &policyPublic);
 
-    RawBuffer getCertificateChain(
+    SafeBuffer getCertificateChain(
         Credentials &cred,
         int commandId,
-        const RawBuffer &certificate,
-        const RawBufferVector &untrustedCertificates);
+        const SafeBuffer &certificate,
+        const SafeBufferVector &untrustedCertificates);
 
-    RawBuffer getCertificateChain(
+    SafeBuffer getCertificateChain(
         Credentials &cred,
         int commandId,
-        const RawBuffer &certificate,
+        const SafeBuffer &certificate,
         const AliasVector &aliasVector);
 
-    RawBuffer  createSignature(
+    SafeBuffer  createSignature(
         Credentials &cred,
         int commandId,
         const Alias &privateKeyAlias,
         const std::string &password,           // password for private_key
-        const RawBuffer &message,
+        const SafeBuffer &message,
         const HashAlgorithm hash,
         const RSAPaddingAlgorithm padding);
 
-    RawBuffer verifySignature(
+    SafeBuffer verifySignature(
         Credentials &cred,
         int commandId,
         const Alias &publicKeyOrCertAlias,
         const std::string &password,           // password for public_key (optional)
-        const RawBuffer &message,
-        const RawBuffer &signature,
+        const SafeBuffer &message,
+        const SafeBuffer &signature,
         const HashAlgorithm hash,
         const RSAPaddingAlgorithm padding);
 
@@ -146,7 +146,7 @@ private:
         Credentials &cred,
         DBDataType dataType,
         const Alias &alias,
-        const RawBuffer &key,
+        const SafeBuffer &key,
         const PolicySerializable &policy);
 
     int getDataHelper(
index 39f8339..441f767 100644 (file)
@@ -77,7 +77,7 @@ bool CKMService::processOne(
     ConnectionInfo &info)
 {
     LogDebug ("process One");
-    RawBuffer response;
+    SafeBuffer response;
 
     Try {
         if (!info.buffer.Ready())
@@ -103,7 +103,7 @@ bool CKMService::processOne(
     return false;
 }
 
-RawBuffer CKMService::processControl(MessageBuffer &buffer) {
+SafeBuffer CKMService::processControl(MessageBuffer &buffer) {
     int command;
     uid_t user;
     ControlCommand cc;
@@ -137,7 +137,7 @@ RawBuffer CKMService::processControl(MessageBuffer &buffer) {
     }
 }
 
-RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
+SafeBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
     int command;
     int commandId;
     int tmpDataType;
@@ -152,7 +152,7 @@ RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
     switch(static_cast<LogicCommand>(command)) {
         case LogicCommand::SAVE:
         {
-            RawBuffer rawData;
+            SafeBuffer rawData;
             PolicySerializable policy;
             Deserialization::Deserialize(buffer, tmpDataType);
             Deserialization::Deserialize(buffer, alias);
@@ -241,8 +241,8 @@ RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
         }
         case LogicCommand::GET_CHAIN_CERT:
         {
-            RawBuffer certificate;
-            RawBufferVector rawBufferVector;
+            SafeBuffer certificate;
+            SafeBufferVector rawBufferVector;
             Deserialization::Deserialize(buffer, certificate);
             Deserialization::Deserialize(buffer, rawBufferVector);
             return m_logic->getCertificateChain(
@@ -253,7 +253,7 @@ RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
         }
         case LogicCommand::GET_CHAIN_ALIAS:
         {
-            RawBuffer certificate;
+            SafeBuffer certificate;
             AliasVector aliasVector;
             Deserialization::Deserialize(buffer, certificate);
             Deserialization::Deserialize(buffer, aliasVector);
@@ -267,7 +267,7 @@ RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
         {
             Alias privateKeyAlias;
             std::string password;        // password for private_key
-            RawBuffer message;
+            SafeBuffer message;
             int padding, hash;
             Deserialization::Deserialize(buffer, privateKeyAlias);
             Deserialization::Deserialize(buffer, password);
@@ -288,8 +288,8 @@ RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
         {
             Alias publicKeyOrCertAlias;
             std::string password;           // password for public_key (optional)
-            RawBuffer message;
-            RawBuffer signature;
+            SafeBuffer message;
+            SafeBuffer signature;
             //HashAlgorithm hash;
             //RSAPaddingAlgorithm padding;
             int padding, hash;
index f305a05..09011dd 100644 (file)
@@ -58,10 +58,10 @@ private:
         const ConnectionID &conn,
         ConnectionInfo &info);
 
-    RawBuffer processControl(
+    SafeBuffer processControl(
         MessageBuffer &buffer);
 
-    RawBuffer processStorage(
+    SafeBuffer processStorage(
         Credentials &cred,
         MessageBuffer &buffer);
 
index 4b71210..a9d8d63 100644 (file)
@@ -60,7 +60,7 @@ bool CryptoLogic::haveKey(const std::string &smackLabel)
 }
 
 void CryptoLogic::pushKey(const std::string &smackLabel,
-                            const RawBuffer &applicationKey)
+                            const SafeBuffer &applicationKey)
 {
     if (smackLabel.length() == 0) {
         ThrowMsg(Exception::InternalError, "Empty smack label.");
@@ -75,9 +75,9 @@ void CryptoLogic::pushKey(const std::string &smackLabel,
     m_keyMap[smackLabel] = applicationKey;
 }
 
-std::size_t CryptoLogic::insertDigest(RawBuffer &data, const int dataSize)
+std::size_t CryptoLogic::insertDigest(SafeBuffer &data, const int dataSize)
 {
-    RawBuffer digest;
+    SafeBuffer digest;
 
     try {
         Digest dig;
@@ -92,7 +92,7 @@ std::size_t CryptoLogic::insertDigest(RawBuffer &data, const int dataSize)
     return digest.size();
 }
 
-void CryptoLogic::removeDigest(RawBuffer &data, RawBuffer &digest)
+void CryptoLogic::removeDigest(SafeBuffer &data, SafeBuffer &digest)
 {
     unsigned int dlen = Digest().length();
 
@@ -105,36 +105,36 @@ void CryptoLogic::removeDigest(RawBuffer &data, RawBuffer &digest)
     data.erase(data.begin(), data.begin() + dlen);
 }
 
-RawBuffer CryptoLogic::encryptData(
-    const RawBuffer &data,
-    const RawBuffer &key,
-    const RawBuffer &iv) const
+SafeBuffer CryptoLogic::encryptData(
+    const SafeBuffer &data,
+    const SafeBuffer &key,
+    const SafeBuffer &iv) const
 {
     Crypto::Cipher::AesCbcEncryption enc(key, iv);
-    RawBuffer result = enc.Append(data);
-    RawBuffer tmp = enc.Finalize();
+    SafeBuffer result = enc.Append(data);
+    SafeBuffer tmp = enc.Finalize();
     std::copy(tmp.begin(), tmp.end(), std::back_inserter(result));
     return result;
 }
 
-RawBuffer CryptoLogic::decryptData(
-    const RawBuffer &data,
-    const RawBuffer &key,
-    const RawBuffer &iv) const
+SafeBuffer CryptoLogic::decryptData(
+    const SafeBuffer &data,
+    const SafeBuffer &key,
+    const SafeBuffer &iv) const
 {
     Crypto::Cipher::AesCbcDecryption dec(key, iv);
-    RawBuffer result = dec.Append(data);
-    RawBuffer tmp = dec.Finalize();
+    SafeBuffer result = dec.Append(data);
+    SafeBuffer tmp = dec.Finalize();
     std::copy(tmp.begin(), tmp.end(), std::back_inserter(result));
     return result;
 }
 
-RawBuffer CryptoLogic::passwordToKey(
+SafeBuffer CryptoLogic::passwordToKey(
     const std::string &password,
-    const RawBuffer &salt,
+    const SafeBuffer &salt,
     size_t keySize) const
 {
-    RawBuffer result(keySize);
+    SafeBuffer result(keySize);
 
     if (1 != PKCS5_PBKDF2_HMAC_SHA1(
                 password.c_str(),
@@ -150,8 +150,8 @@ RawBuffer CryptoLogic::passwordToKey(
     return result;
 }
 
-RawBuffer CryptoLogic::generateRandIV() const {
-    RawBuffer civ(EVP_MAX_IV_LENGTH);
+SafeBuffer CryptoLogic::generateRandIV() const {
+    SafeBuffer civ(EVP_MAX_IV_LENGTH);
 
     if (1 != RAND_bytes(civ.data(), civ.size())) {
         ThrowMsg(Exception::InternalError,
@@ -165,9 +165,9 @@ void CryptoLogic::encryptRow(const std::string &password, DBRow &row)
 {
     try {
         DBRow crow = row;
-        RawBuffer key;
-        RawBuffer result1;
-        RawBuffer result2;
+        SafeBuffer key;
+        SafeBuffer result1;
+        SafeBuffer result2;
 
         crow.algorithmType = DBCMAlgType::AES_CBC_256;
 
@@ -217,8 +217,8 @@ void CryptoLogic::decryptRow(const std::string &password, DBRow &row)
 {
     try {
         DBRow crow = row;
-        RawBuffer key;
-        RawBuffer digest, dataDigest;
+        SafeBuffer key;
+        SafeBuffer digest, dataDigest;
 
         if (row.algorithmType != DBCMAlgType::AES_CBC_256) {
             ThrowMsg(Exception::DecryptDBRowError, "Invalid algorithm type.");
@@ -278,10 +278,10 @@ void CryptoLogic::decryptRow(const std::string &password, DBRow &row)
     }
 }
 
-void CryptoLogic::encBase64(RawBuffer &data)
+void CryptoLogic::encBase64(SafeBuffer &data)
 {
     Base64Encoder benc;
-    RawBuffer encdata;
+    SafeBuffer encdata;
 
     benc.append(data);
     benc.finalize();
@@ -294,10 +294,10 @@ void CryptoLogic::encBase64(RawBuffer &data)
     data = std::move(encdata);
 }
 
-void CryptoLogic::decBase64(RawBuffer &data)
+void CryptoLogic::decBase64(SafeBuffer &data)
 {
     Base64Decoder bdec;
-    RawBuffer decdata;
+    SafeBuffer decdata;
 
     bdec.reset();
     bdec.append(data);
@@ -315,7 +315,7 @@ void CryptoLogic::decBase64(RawBuffer &data)
     data = std::move(decdata);
 }
 
-bool CryptoLogic::equalDigests(RawBuffer &dig1, RawBuffer &dig2)
+bool CryptoLogic::equalDigests(SafeBuffer &dig1, SafeBuffer &dig2)
 {
     unsigned int dlen = Digest().length();
 
index 00eed7f..12aa0e1 100644 (file)
@@ -53,35 +53,35 @@ public:
 
     bool haveKey(const std::string &smackLabel);
     void pushKey(const std::string &smackLabel,
-                 const RawBuffer &applicationKey);
+                 const SafeBuffer &applicationKey);
 
 private:
        static const int ENCR_BASE64 =   1 << 0;
        static const int ENCR_APPKEY =   1 << 1;
        static const int ENCR_PASSWORD = 1 << 2;
 
-       std::map<std::string, RawBuffer> m_keyMap;
+       std::map<std::string, SafeBuffer> m_keyMap;
 
-    RawBuffer generateRandIV() const;
-    RawBuffer passwordToKey(const std::string &password,
-                            const RawBuffer &salt,
+    SafeBuffer generateRandIV() const;
+    SafeBuffer passwordToKey(const std::string &password,
+                            const SafeBuffer &salt,
                             size_t keySize) const;
 
-    RawBuffer encryptData(
-        const RawBuffer &data,
-        const RawBuffer &key,
-        const RawBuffer &iv) const;
+    SafeBuffer encryptData(
+        const SafeBuffer &data,
+        const SafeBuffer &key,
+        const SafeBuffer &iv) const;
 
-    RawBuffer decryptData(
-        const RawBuffer &data,
-        const RawBuffer &key,
-        const RawBuffer &iv) const;
+    SafeBuffer decryptData(
+        const SafeBuffer &data,
+        const SafeBuffer &key,
+        const SafeBuffer &iv) const;
 
-    void decBase64(RawBuffer &data);
-    void encBase64(RawBuffer &data);
-    bool equalDigests(RawBuffer &dig1, RawBuffer &dig2);
-    std::size_t insertDigest(RawBuffer &data, const int dataSize);
-    void removeDigest(RawBuffer &data, RawBuffer &digest);
+    void decBase64(SafeBuffer &data);
+    void encBase64(SafeBuffer &data);
+    bool equalDigests(SafeBuffer &dig1, SafeBuffer &dig2);
+    std::size_t insertDigest(SafeBuffer &data, const int dataSize);
+    void removeDigest(SafeBuffer &data, SafeBuffer &digest);
 };
 
 } // namespace CKM
index daced42..984d5af 100644 (file)
@@ -25,6 +25,8 @@
 #include <dpl/log/log.h>
 #include <ckm/ckm-error.h>
 
+#include <buffer-conversion.h>
+
 #pragma GCC diagnostic push
 #pragma GCC diagnostic warning "-Wdeprecated-declarations"
 
@@ -125,7 +127,7 @@ namespace {
 namespace CKM {
 using namespace DB;
     DBCrypto::DBCrypto(const std::string& path,
-                         const RawBuffer &rawPass) {
+                         const SafeBuffer &rawPass) {
         m_connection = NULL;
         m_inUserTransaction = false;
         Try {
@@ -434,7 +436,7 @@ using namespace DB;
 
     void DBCrypto::saveKey(
             const std::string& label,
-            const RawBuffer &key)
+            const SafeBuffer &key)
     {
         Try {
             Transaction transaction(this);
@@ -454,7 +456,7 @@ using namespace DB;
                 "Couldn't save key for label " << label);
     }
 
-    DBCrypto::RawBufferOptional DBCrypto::getKey(
+    DBCrypto::SafeBufferOptional DBCrypto::getKey(
             const std::string& label)
     {
         Try {
@@ -465,11 +467,11 @@ using namespace DB;
 
             if (selectCommand->Step()) {
                 transaction.commit();
-                return RawBufferOptional(
+                return SafeBufferOptional(
                         selectCommand->GetColumnBlob(0));
             } else {
                 transaction.commit();
-                return RawBufferOptional();
+                return SafeBufferOptional();
             }
 
         } Catch (SqlConnection::Exception::InvalidColumn) {
index 9ff5c10..5a72c57 100644 (file)
@@ -39,7 +39,7 @@ namespace CKM {
     class DBCrypto {
          public:
             typedef boost::optional<DBRow> DBRowOptional;
-            typedef boost::optional<RawBuffer> RawBufferOptional;
+            typedef boost::optional<SafeBuffer> SafeBufferOptional;
             class Exception
             {
               public:
@@ -53,7 +53,7 @@ namespace CKM {
                 m_inUserTransaction(false)
               {};
             //user name instead of path?
-            DBCrypto(const std::string &path, const RawBuffer &rawPass);
+            DBCrypto(const std::string &path, const SafeBuffer &rawPass);
             DBCrypto(const DBCrypto &other) = delete;
             DBCrypto(DBCrypto &&other);
 
@@ -81,8 +81,8 @@ namespace CKM {
                     const Alias& alias,
                     const std::string &label);
 
-            void saveKey(const std::string& label, const RawBuffer &key);
-            RawBufferOptional getKey(
+            void saveKey(const std::string& label, const SafeBuffer &key);
+            SafeBufferOptional getKey(
                     const std::string& label);
             void deleteKey(const std::string& label);
 
index 0a03e25..1de73a0 100644 (file)
@@ -2,6 +2,8 @@
 
 #include <string>
 
+#include <safe-buffer.h>
+
 #include <ckm/ckm-type.h>
 #include <protocols.h>
 
@@ -14,9 +16,9 @@ namespace CKM {
         DBDataType dataType;        // cert/key/data
         DBCMAlgType algorithmType;  // Algorithm type used for row data encryption
         int encryptionScheme;       // for example: (ENCR_BASE64 | ENCR_PASSWORD)
-        RawBuffer iv;               // encoded in base64
+        SafeBuffer iv;               // encoded in base64
         int dataSize;               // size of information without hash and padding
-        RawBuffer data;
+        SafeBuffer data;
     };
 } // namespace CKM
 
index 940e4b9..47a3b7e 100644 (file)
@@ -28,6 +28,9 @@
 #include <sstream>
 #include <fstream>
 
+#include <safe-buffer.h>
+#include <buffer-conversion.h>
+
 #include <dpl/log/log.h>
 
 #include <file-system.h>
@@ -59,15 +62,15 @@ std::string FileSystem::getDKEKPath() const {
     return ss.str();
 }
 
-RawBuffer FileSystem::getDomainKEK() const
+SafeBuffer FileSystem::getDomainKEK() const
 {
     std::ifstream is(getDKEKPath());
     std::istreambuf_iterator<char> begin(is),end;
     RawBuffer buffer(begin, end);
-    return buffer;
+    return toSafeBuffer(buffer);
 }
 
-bool FileSystem::saveDomainKEK(const RawBuffer &buffer) const
+bool FileSystem::saveDomainKEK(const SafeBuffer &buffer) const
 {
     std::ofstream os(getDKEKPath(), std::ios::out | std::ofstream::binary);
     std::copy(buffer.begin(), buffer.end(), std::ostreambuf_iterator<char>(os));
index 197cc96..847aa5e 100644 (file)
@@ -31,8 +31,8 @@ public:
     FileSystem(uid_t uid);
 
     std::string getDBPath() const;
-    RawBuffer getDomainKEK() const;
-    bool saveDomainKEK(const RawBuffer &buffer) const;
+    SafeBuffer getDomainKEK() const;
+    bool saveDomainKEK(const SafeBuffer &buffer) const;
     int removeUserData() const;
 
     static int init();
index 3c8285c..77f5a3e 100644 (file)
@@ -1,5 +1,7 @@
 #pragma once
 
+#include <safe-buffer.h>
+
 #include <ckm-key-provider.h>
 #include <ckm/ckm-type.h>
 #include <dpl/exception.h>
@@ -52,7 +54,7 @@ public:
        // if (keyInWrapForm.size() != sizeof(WrappedKeyMaterial))
        //       throw exception; // buffer does not have proper size to store WrappedKeyMaterial
        // WrappedKeyMaterial *wkm = static_cast<WrappedKeyMaterial>(keyInWrapForm.data());
-       KeyProvider(const RawBuffer &domainKEKInWrapForm, const std::string &password);
+       KeyProvider(const SafeBuffer &domainKEKInWrapForm, const std::string &password);
 
        KeyProvider(KeyProvider &&);
        KeyProvider(const KeyProvider &) = delete;
@@ -62,31 +64,31 @@ public:
        bool isInitialized();
 
        // Returns Key used to decrypt database.
-       RawBuffer getPureDomainKEK();
+       SafeBuffer getPureDomainKEK();
 
        // Returns Key in form used to store key in file
-       // Requied by Control::resetPassword(const RawBuffer &newPassword);
+       // Requied by Control::resetPassword(const SafeBuffer &newPassword);
        // This api should be used only on Tizen 2.2.1
-       RawBuffer getWrappedDomainKEK(const std::string &password);
+       SafeBuffer getWrappedDomainKEK(const std::string &password);
 
        // EncryptedKey key extracted from database. Used to encrypt application data.
        // This key will be used to decrypt/encrypt data in ROW
-       RawBuffer getPureDEK(const RawBuffer &DEKInWrapForm);
+       SafeBuffer getPureDEK(const SafeBuffer &DEKInWrapForm);
 
        // Returns WRAPPED DEK. This will be written to datbase.
        // This key will be used to encrypt all application information.
        // All application are identified by smackLabel.
-       RawBuffer generateDEK(const std::string &smackLabel);
+       SafeBuffer generateDEK(const std::string &smackLabel);
 
        // used by change user password. On error -> exception
-       static RawBuffer reencrypt(
-               const RawBuffer &domainKEKInWrapForm,
+       static SafeBuffer reencrypt(
+               const SafeBuffer &domainKEKInWrapForm,
                const std::string &oldPass,
                const std::string &newPass);
 
        // First run of application for some user. DomainKEK was not created yet. We must create one.
        // This key will be used to encrypt user database.
-       static RawBuffer generateDomainKEK(const std::string &user, const std::string &userPassword);
+       static SafeBuffer generateDomainKEK(const std::string &user, const std::string &userPassword);
 
        // This will be called by framework at the begin of the program
        static int initializeLibrary();
index a12867f..814acb2 100644 (file)
@@ -31,7 +31,7 @@
 
 namespace CKM {
 
-RawBuffer OCSPLogic::ocspCheck(int commandId, const RawBufferVector &rawChain) {
+SafeBuffer OCSPLogic::ocspCheck(int commandId, const SafeBufferVector &rawChain) {
     CertificateImplVector certChain;
     OCSPModule ocsp;
     int retCode = CKM_API_SUCCESS;
index f0dcab4..dded072 100644 (file)
@@ -33,7 +33,7 @@ public:
     OCSPLogic& operator=(const OCSPLogic &) = delete;
     OCSPLogic& operator=(OCSPLogic &&) = delete;
 
-    RawBuffer ocspCheck(int commandId, const RawBufferVector &rawChain);
+    SafeBuffer ocspCheck(int commandId, const SafeBufferVector &rawChain);
     virtual ~OCSPLogic(){}
 };
 
index 4a3884a..3e7f0c2 100644 (file)
@@ -83,11 +83,11 @@ bool OCSPService::processOne(
         auto &buffer = info.buffer;
 
         int commandId;
-        RawBufferVector chainVector;
+        SafeBufferVector chainVector;
         Deserialization::Deserialize(buffer, commandId);
         Deserialization::Deserialize(buffer, chainVector);
 
-        RawBuffer response = m_logic->ocspCheck(commandId, chainVector);
+        SafeBuffer response = m_logic->ocspCheck(commandId, chainVector);
         m_serviceManager->Write(conn, response);
 
         return true;
index 04c0d9c..590907d 100644 (file)
@@ -41,7 +41,7 @@ BOOST_AUTO_TEST_CASE(KeyDomainKEK){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
     CKM::KeyProvider keyProvider;
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD));
@@ -53,7 +53,7 @@ BOOST_AUTO_TEST_CASE(KeyDomainKekInvalidPassword){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
     CKM::KeyProvider keyProvider;
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_THROW(keyProvider = CKM::KeyProvider(rb_test, INCORRECT_PASSWORD),
@@ -66,7 +66,7 @@ BOOST_AUTO_TEST_CASE(KeygetPureDomainKEK){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
     CKM::KeyProvider keyProvider;
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, std::string(PASSWORD)));
@@ -79,7 +79,7 @@ BOOST_AUTO_TEST_CASE(KeyGetWrappedDomainKEK){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
     CKM::KeyProvider keyProvider;
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD));
@@ -92,8 +92,8 @@ BOOST_AUTO_TEST_CASE(KeyGenerateDEK){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
     CKM::KeyProvider keyProvider;
-    CKM::RawBuffer rb_test;
-    CKM::RawBuffer rb_DEK1;
+    CKM::SafeBuffer rb_test;
+    CKM::SafeBuffer rb_DEK1;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD));
@@ -106,9 +106,9 @@ BOOST_AUTO_TEST_CASE(KeyGetPureDEK){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
     CKM::KeyProvider keyProvider;
-    CKM::RawBuffer rb_pureDEK1;
-    CKM::RawBuffer rb_DEK1;
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_pureDEK1;
+    CKM::SafeBuffer rb_DEK1;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD));
@@ -121,7 +121,7 @@ BOOST_AUTO_TEST_CASE(KeyGetPureDEK){
 BOOST_AUTO_TEST_CASE(KeyReencrypt){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_NO_THROW(CKM::KeyProvider::reencrypt(rb_test, PASSWORD,
@@ -131,7 +131,7 @@ BOOST_AUTO_TEST_CASE(KeyReencrypt){
 BOOST_AUTO_TEST_CASE(KeyReencrypt_incorrect_password){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_THROW((rb_test = CKM::KeyProvider::reencrypt(rb_test, INCORRECT_PASSWORD,
@@ -142,8 +142,8 @@ BOOST_AUTO_TEST_CASE(KeyGetPureDEK_after_reencrypt){
     BOOST_REQUIRE_MESSAGE(isLibInitialized,
             "Library is not initialized!");
     CKM::KeyProvider keyProvider;
-    CKM::RawBuffer rb_DEK1;
-    CKM::RawBuffer rb_test;
+    CKM::SafeBuffer rb_DEK1;
+    CKM::SafeBuffer rb_test;
     BOOST_REQUIRE_NO_THROW(rb_test =
             CKM::KeyProvider::generateDomainKEK(USERNAME_LONG, PASSWORD));
     BOOST_REQUIRE_NO_THROW(keyProvider = CKM::KeyProvider(rb_test, PASSWORD));
index 55feab3..999f608 100644 (file)
@@ -3,27 +3,18 @@
 
 using namespace CKM;
 
-RawBuffer createDefaultPass() {
-    RawBuffer raw;
+SafeBuffer createDefaultPass() {
+    SafeBuffer raw;
     for(unsigned char i =0; i < RAW_PASS_SIZE; i++)
         raw.push_back(i);
     return raw;
 }
 
-RawBuffer createBigBlob(std::size_t size) {
-    RawBuffer raw;
+SafeBuffer createBigBlob(std::size_t size) {
+    SafeBuffer raw;
     for(std::size_t i = 0; i < size; i++) {
         raw.push_back(static_cast<unsigned char>(i));
     }
     return raw;
 }
 
-//raw to hex string conversion from SqlConnection
-std::string rawToHexString(const std::vector<unsigned char> &raw) {
-    std::string dump(raw.size()*2, '0');
-    for(std::size_t i = 0; i < raw.size(); i++){
-        sprintf(&dump[2*i], "%02x", raw[i]);
-    }
-    return dump;
-}
-
index c4a5865..8f2b33e 100644 (file)
@@ -1,5 +1,6 @@
 #pragma once
 #include <string>
+#include <safe-buffer.h>
 #include <ckm/ckm-type.h>
 #include <boost/test/unit_test_log.hpp>
 #include <boost/test/results_reporter.hpp>
@@ -16,15 +17,22 @@ struct TestConfig {
 private:
 };
 
-CKM::RawBuffer createDefaultPass();
-CKM::RawBuffer createBigBlob(std::size_t size);
+CKM::SafeBuffer createDefaultPass();
+CKM::SafeBuffer createBigBlob(std::size_t size);
 
-const CKM::RawBuffer defaultPass = createDefaultPass();
+const CKM::SafeBuffer defaultPass = createDefaultPass();
 const std::string pattern =
     "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
 
 const std::size_t RAW_PASS_SIZE = 32;
 const std::size_t HEX_PASS_SIZE = RAW_PASS_SIZE * 2;
 
+template <class T>
+std::string rawToHexString(const T &raw) {
+    std::string dump(raw.size()*2, '0');
+    for(std::size_t i = 0; i < raw.size(); i++) {
+        sprintf(&dump[2*i], "%02x", static_cast<int>(raw[i]));
+    }
+    return dump;
+}
 
-std::string rawToHexString(const std::vector<unsigned char> &raw);
index 4933e6a..215e691 100644 (file)
@@ -90,7 +90,7 @@ BOOST_AUTO_TEST_CASE(DBtestSimple) {
     BOOST_REQUIRE_NO_THROW(db = DBCrypto(crypto_db, defaultPass));
 
     DBRow rowPattern = createDefaultRow();
-    rowPattern.data = RawBuffer(32, 1);
+    rowPattern.data = SafeBuffer(32, 1);
     rowPattern.dataSize = rowPattern.data.size();
 
     checkDBIntegrity(rowPattern, db);
@@ -112,7 +112,7 @@ BOOST_AUTO_TEST_CASE(DBtestGlobal) {
     BOOST_REQUIRE_NO_THROW(db = DBCrypto(crypto_db, defaultPass));
 
     DBRow rowPattern = createDefaultRow(restricted_global);
-    rowPattern.data = RawBuffer(1024, 2);
+    rowPattern.data = SafeBuffer(1024, 2);
     rowPattern.dataSize = rowPattern.data.size();
 
     BOOST_REQUIRE_NO_THROW(db.saveDBRow(rowPattern));
@@ -129,7 +129,7 @@ BOOST_AUTO_TEST_CASE(DBtestTransaction) {
     BOOST_REQUIRE_NO_THROW(db = DBCrypto(crypto_db, defaultPass));
 
     DBRow rowPattern = createDefaultRow(0);
-    rowPattern.data = RawBuffer(100, 20);
+    rowPattern.data = SafeBuffer(100, 20);
     rowPattern.dataSize = rowPattern.data.size();
     DBCrypto::Transaction transaction(&db);
 
index 984504c..d1f5f12 100644 (file)
@@ -25,7 +25,7 @@ const char *insert_table = "INSERT INTO t1(a,b) VALUES ("
                                        " 'two for the show');";
 const char *select_table = "SELECT * FROM t1";
 
-CKM::RawBuffer raw_password = createDefaultPass();
+CKM::SafeBuffer raw_password = createDefaultPass();
 
 BOOST_AUTO_TEST_SUITE(SQL_TEST)
 BOOST_AUTO_TEST_CASE(sqlTestConversion){
@@ -43,7 +43,7 @@ BOOST_AUTO_TEST_CASE(sqlTestSetKeyTooShort) {
     BOOST_CHECK(unlink(encrypt_me_not) == 0 || errno == ENOENT);
     SqlConnection connection(encrypt_me_not,
                                SqlConnection::Flag::CRW);
-    CKM::RawBuffer wrong_key(RAW_PASS_SIZE - 1, 1);
+    CKM::SafeBuffer wrong_key(RAW_PASS_SIZE - 1, 1);
     BOOST_REQUIRE_THROW(connection.SetKey(wrong_key),
             SqlConnection::Exception::InvalidArguments);
 }
@@ -53,7 +53,7 @@ BOOST_AUTO_TEST_CASE(sqlTestSetKeyTooLong) {
     BOOST_CHECK(unlink(encrypt_me_not) == 0 || errno == ENOENT);
     SqlConnection connection(encrypt_me_not,
                                SqlConnection::Flag::CRW);
-    CKM::RawBuffer wrong_key(RAW_PASS_SIZE + 1, 1);
+    CKM::SafeBuffer wrong_key(RAW_PASS_SIZE + 1, 1);
     BOOST_REQUIRE_THROW(connection.SetKey(wrong_key),
             SqlConnection::Exception::InvalidArguments);
 }
@@ -118,7 +118,7 @@ BOOST_AUTO_TEST_CASE(sqlTestConnectionEncryptedNegative) {
     {
         SqlConnection encrypting_you(encrypt_me,
                                      SqlConnection::Flag::RW);
-        CKM::RawBuffer wrong_password;
+        CKM::SafeBuffer wrong_password;
         for(std::size_t i = 0; i < RAW_PASS_SIZE; i++) {
             wrong_password.push_back(raw_password[i] + 1);
         }