/*
- * 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.
--- /dev/null
+/* 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
+
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;
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;
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
--- /dev/null
+/* 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
+
#include <client-manager-impl.h>
#include <client-common.h>
+#include <buffer-conversion.h>
#include <message-buffer.h>
#include <protocols.h>
#include <generic-key.h>
int ManagerImpl::saveBinaryData(
const Alias &alias,
DBDataType dataType,
- const RawBuffer &rawData,
+ const SafeBuffer &rawData,
const Policy &policy)
{
m_counter++;
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(
{
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)
DBDataType sendDataType,
const std::string &password,
DBDataType &recvDataType,
- RawBuffer &rawData)
+ SafeBuffer &rawData)
{
return try_catch([&] {
if (alias.empty())
int ManagerImpl::getKey(const Alias &alias, const std::string &password, KeyShPtr &key) {
DBDataType recvDataType;
- RawBuffer rawData;
+ SafeBuffer rawData;
int retCode = getBinaryData(
alias,
int ManagerImpl::getCertificate(const Alias &alias, const std::string &password, CertificateShPtr &cert)
{
DBDataType recvDataType;
- RawBuffer rawData;
+ SafeBuffer rawData;
int retCode = getBinaryData(
alias,
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;
int retCommand;
int retCounter;
- RawBufferVector rawBufferVector;
+ SafeBufferVector rawBufferVector;
Deserialization::Deserialize(recv, retCommand);
Deserialization::Deserialize(recv, retCounter);
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(
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));
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))
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));
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);
#pragma once
#include <protocols.h>
+#include <safe-buffer.h>
#include <ckm/ckm-type.h>
#include <ckm/ckm-key.h>
int saveBinaryData(
const Alias &alias,
DBDataType dataType,
- const RawBuffer &rawData,
+ const SafeBuffer &rawData,
const Policy &policy);
int removeBinaryData(
DBDataType sendDataType,
const std::string &password,
DBDataType &recvDataType,
- RawBuffer &rawData);
+ SafeBuffer &rawData);
int getBinaryDataAliasVector(
DBDataType sendDataType,
--- /dev/null
+/* 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
+
{
}
-void Base64Encoder::append(const RawBuffer &data)
+void Base64Encoder::append(const SafeBuffer &data)
{
if (m_finalized) {
LogWarning("Already finalized.");
BIO_flush(m_b64);
}
-RawBuffer Base64Encoder::get()
+SafeBuffer Base64Encoder::get()
{
if (!m_finalized) {
LogWarning("Not finalized");
}
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()
{
}
-void Base64Decoder::append(const RawBuffer &data)
+void Base64Decoder::append(const SafeBuffer &data)
{
if (m_finalized) {
LogWarning("Already finalized.");
BIO *b64, *bmem;
size_t len = m_input.size();
- RawBuffer buffer(len);
+ SafeBuffer buffer(len);
if (!buffer.data()) {
LogError("Error in malloc.");
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);
return status;
}
-RawBuffer Base64Decoder::get() const
+SafeBuffer Base64Decoder::get() const
{
if (!m_finalized) {
LogWarning("Not finalized.");
#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;
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();
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
--- /dev/null
+#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
+
#include <dpl/log/log.h>
+#include <buffer-conversion.h>
#include <generic-key.h>
#include <certificate-impl.h>
#include <base64.h>
{
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());
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;
}
public:
CertificateImpl(){}
CertificateImpl(X509* x509);
+ CertificateImpl(const SafeBuffer &data, DataFormat format);
CertificateImpl(const RawBuffer &data, DataFormat format);
CertificateImpl(const CertificateImpl &);
CertificateImpl(CertificateImpl &&);
virtual bool empty() const;
virtual X509* getX509() const;
+ SafeBuffer getDERSB() const;
+
GenericKey::EvpShPtr getEvpShPtr() const;
GenericKey getGenericKey() const;
#include <openssl/evp.h>
-#include <vector>
+#include <safe-buffer.h>
namespace CKM {
-typedef std::vector<unsigned char> RawBuffer;
-
namespace Crypto {
class Exception
{} \
}
-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
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;
}
}
-RawBuffer Digest::finalize()
+SafeBuffer Digest::finalize()
{
int ret = -1;
unsigned int dlen;
return m_digest;
}
-RawBuffer Digest::get()
+SafeBuffer Digest::get()
{
if (m_finalized)
return m_digest;
else
- return RawBuffer();
+ return SafeBuffer();
}
unsigned int Digest::length()
#pragma once
+#include <safe-buffer.h>
#include <dpl/noncopyable.h>
#include <dpl/exception.h>
#include <ckm/ckm-type.h>
};
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;
};
#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;
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);
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)
{
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;
#include <memory>
+#include <safe-buffer.h>
+
#include <ckm/ckm-type.h>
#include <ckm/ckm-key.h>
#include <openssl/evp.h>
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;
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);
#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>
namespace CKM {
-typedef std::vector<unsigned char> RawBuffer;
-
class MessageBuffer : public CKM::IStream {
public:
class Exception
: m_bytesLeft(0)
{}
- void Push(const RawBuffer &data);
+ void Push(const SafeBuffer &data);
- RawBuffer Pop();
+ SafeBuffer Pop();
bool Ready();
#include <string.h>
+#include <vector>
+
#include <boost/container/vector.hpp>
namespace CKM {
* 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
// used to pass password and raw key data
typedef SafeBufferT<unsigned char>::Type SafeBuffer;
+typedef std::vector<SafeBuffer> SafeBufferVector;
} // namespace CKM
#include <map>
#include <memory>
+#include <safe-buffer.h>
+
namespace CKM {
// Abstract data stream buffer
class IStream
{
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 {
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
#include <stdint.h>
#include <vector>
+#include <safe-buffer.h>
+
namespace CKM {
namespace DB {
/**
* @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.
* @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
*
* @throw Exception::InvalidColumn
*/
- std::vector<unsigned char> GetColumnBlob(ColumnIndex column);
+ SafeBuffer GetColumnBlob(ColumnIndex column);
/**
* Get optional integer value from column in current row.
*
* @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
*
* @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.
* @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
#include <cstdarg>
#include <memory>
+#include <safe-buffer.h>
+
namespace CKM {
namespace DB {
namespace // anonymous
void SqlConnection::DataCommand::BindBlob(
SqlConnection::ArgumentIndex position,
- const std::vector<unsigned char> &raw)
+ const SafeBuffer &raw)
{
if (raw.size() == 0) {
BindNull(position);
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);
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 << "]");
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(
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));
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,
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
}
-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;
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;
#include <sys/types.h>
+#include <safe-buffer.h>
+
#include <dpl/exception.h>
#include <generic-event.h>
}
};
-typedef std::vector<unsigned char> RawBuffer;
-
struct GenericSocketManager;
struct GenericSocketService {
struct ReadEvent : public GenericEvent {
ConnectionID connectionID;
- RawBuffer rawBuffer;
+ SafeBuffer rawBuffer;
};
struct CloseEvent : public GenericEvent {
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(){}
};
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;
#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>
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);
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;
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(
InterfaceID interfaceID;
GenericSocketService *service;
time_t timeout;
- RawBuffer rawBuffer;
+ SafeBuffer rawBuffer;
int counter;
SocketDescription()
struct WriteBuffer {
ConnectionID connectionID;
- RawBuffer rawBuffer;
+ SafeBuffer rawBuffer;
};
struct Timeout {
}
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
}
int CryptoService::verifySignature(const GenericKey &publicKey,
- const RawBuffer &message,
- const RawBuffer &signature,
+ const SafeBuffer &message,
+ const SafeBuffer &signature,
const HashAlgorithm hashAlgo,
const RSAPaddingAlgorithm padAlgo)
{
X509 *cert = X509_new();
X509 *tempCert;
- rawBufferToX509(&cert, certificate.getDER());
+ rawBufferToX509(&cert, certificate.getDERSB());
std::vector<X509 *> trustedCerts;
std::vector<X509 *> userTrustedCerts;
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);
}
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) {
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);
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;
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
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);
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);
return response.Pop();
}
-RawBuffer CKMLogic::changeUserPassword(
+SafeBuffer CKMLogic::changeUserPassword(
uid_t user,
const std::string &oldPassword,
const std::string &newPassword)
return response.Pop();
}
-RawBuffer CKMLogic::resetUserPassword(
+SafeBuffer CKMLogic::resetUserPassword(
uid_t user,
const std::string &newPassword)
{
Credentials &cred,
DBDataType dataType,
const Alias &alias,
- const RawBuffer &key,
+ const SafeBuffer &key,
const PolicySerializable &policy)
{
if (0 == m_userDataMap.count(cred.uid))
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: "
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;
return response.Pop();
}
-RawBuffer CKMLogic::removeData(
+SafeBuffer CKMLogic::removeData(
Credentials &cred,
int commandId,
DBDataType dataType,
}
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");
return CKM_API_SUCCESS;
}
-RawBuffer CKMLogic::getData(
+SafeBuffer CKMLogic::getData(
Credentials &cred,
int commandId,
DBDataType dataType,
return response.Pop();
}
-RawBuffer CKMLogic::getDataList(
+SafeBuffer CKMLogic::getDataList(
Credentials &cred,
int commandId,
DBDataType dataType)
retCode = saveDataHelper(cred,
toDBDataType(prv.getType()),
aliasPrivate,
- prv.getDER(),
+ prv.getDERSB(),
policyPrivate);
if (CKM_API_SUCCESS != retCode)
retCode = saveDataHelper(cred,
toDBDataType(pub.getType()),
aliasPublic,
- pub.getDER(),
+ pub.getDERSB(),
policyPublic);
if (CKM_API_SUCCESS != retCode)
return retCode;
}
-RawBuffer CKMLogic::createKeyPairRSA(
+SafeBuffer CKMLogic::createKeyPairRSA(
Credentials &cred,
int commandId,
int size,
retCode = saveDataHelper(cred,
toDBDataType(prv.getType()),
aliasPrivate,
- prv.getDER(),
+ prv.getDERSB(),
policyPrivate);
if (CKM_API_SUCCESS != retCode)
retCode = saveDataHelper(cred,
toDBDataType(pub.getType()),
aliasPublic,
- pub.getDER(),
+ pub.getDERSB(),
policyPublic);
if (CKM_API_SUCCESS != retCode)
return retCode;
}
-RawBuffer CKMLogic::createKeyPairECDSA(
+SafeBuffer CKMLogic::createKeyPairECDSA(
Credentials &cred,
int commandId,
int type,
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));
if (retCode == CKM_API_SUCCESS) {
for (auto &e : chainVector)
- chainRawVector.push_back(e.getDER());
+ chainRawVector.push_back(e.getDERSB());
}
MessageBuffer response;
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;
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());
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;
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)
{
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,
const PolicySerializable &policyPrivate,
const PolicySerializable &policyPublic);
- RawBuffer createKeyPairECDSA(
+ SafeBuffer createKeyPairECDSA(
Credentials &cred,
int commandId,
int type,
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);
Credentials &cred,
DBDataType dataType,
const Alias &alias,
- const RawBuffer &key,
+ const SafeBuffer &key,
const PolicySerializable &policy);
int getDataHelper(
ConnectionInfo &info)
{
LogDebug ("process One");
- RawBuffer response;
+ SafeBuffer response;
Try {
if (!info.buffer.Ready())
return false;
}
-RawBuffer CKMService::processControl(MessageBuffer &buffer) {
+SafeBuffer CKMService::processControl(MessageBuffer &buffer) {
int command;
uid_t user;
ControlCommand cc;
}
}
-RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
+SafeBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer){
int command;
int commandId;
int tmpDataType;
switch(static_cast<LogicCommand>(command)) {
case LogicCommand::SAVE:
{
- RawBuffer rawData;
+ SafeBuffer rawData;
PolicySerializable policy;
Deserialization::Deserialize(buffer, tmpDataType);
Deserialization::Deserialize(buffer, alias);
}
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(
}
case LogicCommand::GET_CHAIN_ALIAS:
{
- RawBuffer certificate;
+ SafeBuffer certificate;
AliasVector aliasVector;
Deserialization::Deserialize(buffer, certificate);
Deserialization::Deserialize(buffer, aliasVector);
{
Alias privateKeyAlias;
std::string password; // password for private_key
- RawBuffer message;
+ SafeBuffer message;
int padding, hash;
Deserialization::Deserialize(buffer, privateKeyAlias);
Deserialization::Deserialize(buffer, password);
{
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;
const ConnectionID &conn,
ConnectionInfo &info);
- RawBuffer processControl(
+ SafeBuffer processControl(
MessageBuffer &buffer);
- RawBuffer processStorage(
+ SafeBuffer processStorage(
Credentials &cred,
MessageBuffer &buffer);
}
void CryptoLogic::pushKey(const std::string &smackLabel,
- const RawBuffer &applicationKey)
+ const SafeBuffer &applicationKey)
{
if (smackLabel.length() == 0) {
ThrowMsg(Exception::InternalError, "Empty smack label.");
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;
return digest.size();
}
-void CryptoLogic::removeDigest(RawBuffer &data, RawBuffer &digest)
+void CryptoLogic::removeDigest(SafeBuffer &data, SafeBuffer &digest)
{
unsigned int dlen = Digest().length();
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(),
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,
{
try {
DBRow crow = row;
- RawBuffer key;
- RawBuffer result1;
- RawBuffer result2;
+ SafeBuffer key;
+ SafeBuffer result1;
+ SafeBuffer result2;
crow.algorithmType = DBCMAlgType::AES_CBC_256;
{
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.");
}
}
-void CryptoLogic::encBase64(RawBuffer &data)
+void CryptoLogic::encBase64(SafeBuffer &data)
{
Base64Encoder benc;
- RawBuffer encdata;
+ SafeBuffer encdata;
benc.append(data);
benc.finalize();
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);
data = std::move(decdata);
}
-bool CryptoLogic::equalDigests(RawBuffer &dig1, RawBuffer &dig2)
+bool CryptoLogic::equalDigests(SafeBuffer &dig1, SafeBuffer &dig2)
{
unsigned int dlen = Digest().length();
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
#include <dpl/log/log.h>
#include <ckm/ckm-error.h>
+#include <buffer-conversion.h>
+
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
namespace CKM {
using namespace DB;
DBCrypto::DBCrypto(const std::string& path,
- const RawBuffer &rawPass) {
+ const SafeBuffer &rawPass) {
m_connection = NULL;
m_inUserTransaction = false;
Try {
void DBCrypto::saveKey(
const std::string& label,
- const RawBuffer &key)
+ const SafeBuffer &key)
{
Try {
Transaction transaction(this);
"Couldn't save key for label " << label);
}
- DBCrypto::RawBufferOptional DBCrypto::getKey(
+ DBCrypto::SafeBufferOptional DBCrypto::getKey(
const std::string& label)
{
Try {
if (selectCommand->Step()) {
transaction.commit();
- return RawBufferOptional(
+ return SafeBufferOptional(
selectCommand->GetColumnBlob(0));
} else {
transaction.commit();
- return RawBufferOptional();
+ return SafeBufferOptional();
}
} Catch (SqlConnection::Exception::InvalidColumn) {
class DBCrypto {
public:
typedef boost::optional<DBRow> DBRowOptional;
- typedef boost::optional<RawBuffer> RawBufferOptional;
+ typedef boost::optional<SafeBuffer> SafeBufferOptional;
class Exception
{
public:
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);
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);
#include <string>
+#include <safe-buffer.h>
+
#include <ckm/ckm-type.h>
#include <protocols.h>
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
#include <sstream>
#include <fstream>
+#include <safe-buffer.h>
+#include <buffer-conversion.h>
+
#include <dpl/log/log.h>
#include <file-system.h>
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));
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();
#pragma once
+#include <safe-buffer.h>
+
#include <ckm-key-provider.h>
#include <ckm/ckm-type.h>
#include <dpl/exception.h>
// 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;
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();
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;
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(){}
};
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;
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));
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),
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)));
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));
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));
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));
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,
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,
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));
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;
-}
-
#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>
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);
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);
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));
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);
" '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){
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);
}
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);
}
{
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);
}