diff options
author | sangwan.kwon <sangwan.kwon@samsung.com> | 2015-12-10 13:49:43 +0900 |
---|---|---|
committer | sangwan.kwon <sangwan.kwon@samsung.com> | 2015-12-22 16:24:22 +0900 |
commit | fa221dbbd5ecc2b439932755c56a9e5ad2d7c23b (patch) | |
tree | 33824b7a92543eb0e5a26d5362b3d37d83932644 | |
parent | 37c8ad2ece096d99ee2699db4ace43192ef4d721 (diff) | |
download | key-manager-fa221dbbd5ecc2b439932755c56a9e5ad2d7c23b.tar.gz key-manager-fa221dbbd5ecc2b439932755c56a9e5ad2d7c23b.tar.bz2 key-manager-fa221dbbd5ecc2b439932755c56a9e5ad2d7c23b.zip |
Apply coding rule
covered Tizen C++ coding rule list
- [R06] : Do not unnecessarily use braces where a single statement will do.
- Exception: if one branch of a conditional statement is a single statement,
use braces in both branches.
- [M08] : Keywords have following space rules
- Put a space after (most) keywords
- example: if, switch, case, for, do, while
- Do not put a space after function like keywords
- example: sizeof, typeof, alignof, __attribute__
- [M09] : Operators have following space rules
- Put a space around(on each side of) most binary and ternary operators
- Example : = + -< > * / % | & ^ <= >= == != ? :
- Do not put a space after unary operators
- Example: & * + -~ !
- Unary "++" and unary "--" are allowed no space on one side
- Do not put a space around the "." and "->" structure member operators.
- Do not put a space after cast operator
- [M10] : Seperators have following space rules
- Put a space after closing brace when it has anything on the line.
- Exception : comma after closing brace '},‘
- Put a space after comma
- Do not put space inside parenthesis '(', ')‘
- Do not put space before open square bracket '[‘ and inside square bracket '[', ']‘
- [M12] : Functions have the opening brace at the beginning of the next line.
- [M13] : The open brace last on the line. The closing brace is empty on a line of its own
- Exception : else, whileshould follow close brace '}’
- [M14] : Open braces for enum, union and structgo on the same line
Change-Id: I6e59513ba121a25222e6e626792b3e115ebec1d3
Signed-off-by: sangwan.kwon <sangwan.kwon@samsung.com>
155 files changed, 2630 insertions, 2656 deletions
diff --git a/src/include/ckm/ckm-certificate.h b/src/include/ckm/ckm-certificate.h index f7ec2233..e864b4b5 100644..100755 --- a/src/include/ckm/ckm-certificate.h +++ b/src/include/ckm/ckm-certificate.h @@ -39,7 +39,6 @@ typedef std::shared_ptr<Certificate> CertificateShPtr; class KEY_MANAGER_API Certificate { public: - virtual bool empty() const = 0; // This function will return openssl struct X509*. @@ -47,7 +46,7 @@ public: // Memory will be freed in ~Certificate. virtual X509 *getX509() const = 0; virtual RawBuffer getDER() const = 0; - virtual ~Certificate(){} + virtual ~Certificate() {} static CertificateShPtr create(const RawBuffer &rawBuffer, DataFormat format); }; diff --git a/src/include/ckm/ckm-control.h b/src/include/ckm/ckm-control.h index 67250fe4..af0a3806 100644..100755 --- a/src/include/ckm/ckm-control.h +++ b/src/include/ckm/ckm-control.h @@ -34,8 +34,7 @@ class Control; typedef std::shared_ptr<Control> ControlShPtr; // used by login manager to unlock user data with global password -class KEY_MANAGER_API Control -{ +class KEY_MANAGER_API Control { public: // decrypt user key with password virtual int unlockUserKey(uid_t user, const Password &password) = 0; @@ -68,7 +67,7 @@ public: const Label &accessor, PermissionMask permissionMask) = 0; - virtual ~Control(){} + virtual ~Control() {} static ControlShPtr create(); }; diff --git a/src/include/ckm/ckm-key.h b/src/include/ckm/ckm-key.h index 02522cc0..9095d498 100644..100755 --- a/src/include/ckm/ckm-key.h +++ b/src/include/ckm/ckm-key.h @@ -34,7 +34,7 @@ public: virtual KeyType getType() const = 0; virtual int getSize() const = 0; virtual RawBuffer getDER() const = 0; - virtual ~Key(){} + virtual ~Key() {} static KeyShPtr create( const RawBuffer &rawBuffer, diff --git a/src/include/ckm/ckm-pkcs12.h b/src/include/ckm/ckm-pkcs12.h index c6e043cd..f00e5f69 100644..100755 --- a/src/include/ckm/ckm-pkcs12.h +++ b/src/include/ckm/ckm-pkcs12.h @@ -44,7 +44,7 @@ public: virtual bool empty() const = 0; - virtual ~PKCS12(){} + virtual ~PKCS12() {} static PKCS12ShPtr create(const RawBuffer &rawData, const Password &password = Password()); }; diff --git a/src/include/ckm/ckm-raw-buffer.h b/src/include/ckm/ckm-raw-buffer.h index 02c9d6b5..6ac4ab61 100644..100755 --- a/src/include/ckm/ckm-raw-buffer.h +++ b/src/include/ckm/ckm-raw-buffer.h @@ -29,8 +29,7 @@ namespace CKM { template <typename T> -struct std_erase_on_dealloc -{ +struct std_erase_on_dealloc { // MJK: if re-factoring, remember not to inherit from the std::allocator ! // MJK: to be replaced with much shorter version once std::allocator_traits // becomes supported in STL containers (i.e. list, vector and string) @@ -47,42 +46,48 @@ struct std_erase_on_dealloc template <typename U> std_erase_on_dealloc(const std_erase_on_dealloc<U>&) {} - T* allocate(std::size_t n) { + T* allocate(std::size_t n) + { return static_cast<T*>(::operator new(n*sizeof(T))); } - void deallocate(T* ptr, std::size_t n) { + void deallocate(T* ptr, std::size_t n) + { // clear the memory before deleting - memset(ptr, 0 ,n * sizeof(T)); + memset(ptr, 0 , n * sizeof(T)); ::operator delete(ptr); } template<typename _Tp1> - struct rebind - { + struct rebind { typedef std_erase_on_dealloc<_Tp1> other; }; - void construct(pointer p, const T& val) { + void construct(pointer p, const T& val) + { new (p) T(val); } - void destroy(pointer p) { + void destroy(pointer p) + { p->~T(); } - size_type max_size() const { + size_type max_size() const + { return size_type(-1); } }; template <typename T, typename U> -inline bool operator == (const std_erase_on_dealloc<T>&, const std_erase_on_dealloc<U>&) { +inline bool operator == (const std_erase_on_dealloc<T>&, const std_erase_on_dealloc<U>&) +{ return true; } template <typename T, typename U> -inline bool operator != (const std_erase_on_dealloc<T>& a, const std_erase_on_dealloc<U>& b) { +inline bool operator != (const std_erase_on_dealloc<T>& a, const std_erase_on_dealloc<U>& b) +{ return !(a == b); } diff --git a/src/include/ckm/ckm-type.h b/src/include/ckm/ckm-type.h index 5ce89b6a..352dc145 100644..100755 --- a/src/include/ckm/ckm-type.h +++ b/src/include/ckm/ckm-type.h @@ -75,7 +75,7 @@ struct Policy { : password(pass) , extractable(extract) {} - virtual ~Policy(){} + virtual ~Policy() {} Password password; // byte array used to encrypt data inside CKM bool extractable; // if true key may be extracted from storage }; @@ -197,7 +197,8 @@ protected: }; template <typename T> -bool CryptoAlgorithm::getParam(ParamName name, T& value) const { +bool CryptoAlgorithm::getParam(ParamName name, T& value) const +{ auto param = m_params.find(name); if (param == m_params.end()) return false; @@ -216,7 +217,8 @@ template <> bool CryptoAlgorithm::getParam(ParamName name, RawBuffer& value) const; template <typename T> -bool CryptoAlgorithm::setParam(ParamName name, const T& value) { +bool CryptoAlgorithm::setParam(ParamName name, const T& value) +{ if (name < ParamName::FIRST || name > ParamName::LAST) return false; m_params[name] = IntParam::create(static_cast<uint64_t>(value)); diff --git a/src/include/ckmc/ckmc-error.h b/src/include/ckmc/ckmc-error.h index abbea8d7..c7ac7ece 100644 --- a/src/include/ckmc/ckmc-error.h +++ b/src/include/ckmc/ckmc-error.h @@ -36,30 +36,30 @@ extern "C" { * @since_tizen 2.3 */ typedef enum { - CKMC_ERROR_NONE = TIZEN_ERROR_NONE, /**< Successful */ - CKMC_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER, /**< Invalid function parameter */ - CKMC_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY, /**< Out of memory */ - CKMC_ERROR_PERMISSION_DENIED = TIZEN_ERROR_PERMISSION_DENIED, /**< Permission denied */ - CKMC_ERROR_NOT_SUPPORTED = TIZEN_ERROR_NOT_SUPPORTED, /**< Device needed to run API is not supported*/ + CKMC_ERROR_NONE = TIZEN_ERROR_NONE, /**< Successful */ + CKMC_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER, /**< Invalid function parameter */ + CKMC_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY, /**< Out of memory */ + CKMC_ERROR_PERMISSION_DENIED = TIZEN_ERROR_PERMISSION_DENIED, /**< Permission denied */ + CKMC_ERROR_NOT_SUPPORTED = TIZEN_ERROR_NOT_SUPPORTED, /**< Device needed to run API is not supported*/ - CKMC_ERROR_SOCKET = TIZEN_ERROR_KEY_MANAGER | 0x01, /**< Socket error between client and Central Key Manager */ - CKMC_ERROR_BAD_REQUEST = TIZEN_ERROR_KEY_MANAGER | 0x02, /**< Invalid request from client */ - CKMC_ERROR_BAD_RESPONSE = TIZEN_ERROR_KEY_MANAGER | 0x03, /**< Invalid response from Central Key Manager */ - CKMC_ERROR_SEND_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x04, /**< Transmitting request failed */ - CKMC_ERROR_RECV_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x05, /**< Receiving response failed */ - CKMC_ERROR_AUTHENTICATION_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x06, /**< Authentication between client and manager failed */ - CKMC_ERROR_BUFFER_TOO_SMALL = TIZEN_ERROR_KEY_MANAGER | 0x07, /**< The output buffer size which is passed as parameter is too small */ - CKMC_ERROR_SERVER_ERROR = TIZEN_ERROR_KEY_MANAGER | 0x08, /**< Central Key Manager has been failed for some reason */ - CKMC_ERROR_DB_LOCKED = TIZEN_ERROR_KEY_MANAGER | 0x09, /**< The database was not unlocked - user did not login */ - CKMC_ERROR_DB_ERROR = TIZEN_ERROR_KEY_MANAGER | 0x0A, /**< An internal error inside the database */ - CKMC_ERROR_DB_ALIAS_EXISTS = TIZEN_ERROR_KEY_MANAGER | 0x0B, /**< Provided alias already exists in the database */ - CKMC_ERROR_DB_ALIAS_UNKNOWN = TIZEN_ERROR_KEY_MANAGER | 0x0C, /**< No data for given alias */ - CKMC_ERROR_VERIFICATION_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x0D, /**< CA certificate(s) were unknown and chain could not be created */ - CKMC_ERROR_INVALID_FORMAT = TIZEN_ERROR_KEY_MANAGER | 0x0E, /**< A provided file or binary has not a valid format */ - CKMC_ERROR_FILE_ACCESS_DENIED = TIZEN_ERROR_KEY_MANAGER | 0x0F, /**< A provided file doesn't exist or cannot be accessed in the file system */ - CKMC_ERROR_NOT_EXPORTABLE = TIZEN_ERROR_KEY_MANAGER | 0x10, /**< Key is not exportable. It could not be returned to client */ - CKMC_ERROR_FILE_SYSTEM = TIZEN_ERROR_KEY_MANAGER | 0x11, /**< Save key/certificate/pkcs12 failed because of file system error */ - CKMC_ERROR_UNKNOWN = TIZEN_ERROR_KEY_MANAGER | 0xFF, /**< The error with unknown reason */ + CKMC_ERROR_SOCKET = TIZEN_ERROR_KEY_MANAGER | 0x01, /**< Socket error between client and Central Key Manager */ + CKMC_ERROR_BAD_REQUEST = TIZEN_ERROR_KEY_MANAGER | 0x02, /**< Invalid request from client */ + CKMC_ERROR_BAD_RESPONSE = TIZEN_ERROR_KEY_MANAGER | 0x03, /**< Invalid response from Central Key Manager */ + CKMC_ERROR_SEND_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x04, /**< Transmitting request failed */ + CKMC_ERROR_RECV_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x05, /**< Receiving response failed */ + CKMC_ERROR_AUTHENTICATION_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x06, /**< Authentication between client and manager failed */ + CKMC_ERROR_BUFFER_TOO_SMALL = TIZEN_ERROR_KEY_MANAGER | 0x07, /**< The output buffer size which is passed as parameter is too small */ + CKMC_ERROR_SERVER_ERROR = TIZEN_ERROR_KEY_MANAGER | 0x08, /**< Central Key Manager has been failed for some reason */ + CKMC_ERROR_DB_LOCKED = TIZEN_ERROR_KEY_MANAGER | 0x09, /**< The database was not unlocked - user did not login */ + CKMC_ERROR_DB_ERROR = TIZEN_ERROR_KEY_MANAGER | 0x0A, /**< An internal error inside the database */ + CKMC_ERROR_DB_ALIAS_EXISTS = TIZEN_ERROR_KEY_MANAGER | 0x0B, /**< Provided alias already exists in the database */ + CKMC_ERROR_DB_ALIAS_UNKNOWN = TIZEN_ERROR_KEY_MANAGER | 0x0C, /**< No data for given alias */ + CKMC_ERROR_VERIFICATION_FAILED = TIZEN_ERROR_KEY_MANAGER | 0x0D, /**< CA certificate(s) were unknown and chain could not be created */ + CKMC_ERROR_INVALID_FORMAT = TIZEN_ERROR_KEY_MANAGER | 0x0E, /**< A provided file or binary has not a valid format */ + CKMC_ERROR_FILE_ACCESS_DENIED = TIZEN_ERROR_KEY_MANAGER | 0x0F, /**< A provided file doesn't exist or cannot be accessed in the file system */ + CKMC_ERROR_NOT_EXPORTABLE = TIZEN_ERROR_KEY_MANAGER | 0x10, /**< Key is not exportable. It could not be returned to client */ + CKMC_ERROR_FILE_SYSTEM = TIZEN_ERROR_KEY_MANAGER | 0x11, /**< Save key/certificate/pkcs12 failed because of file system error */ + CKMC_ERROR_UNKNOWN = TIZEN_ERROR_KEY_MANAGER | 0xFF, /**< The error with unknown reason */ } key_manager_error_e; /** diff --git a/src/include/ckmc/ckmc-type.h b/src/include/ckmc/ckmc-type.h index 997ed96f..4e02e99d 100644..100755 --- a/src/include/ckmc/ckmc-type.h +++ b/src/include/ckmc/ckmc-type.h @@ -111,11 +111,11 @@ typedef enum __ckmc_data_format { * @since_tizen 2.3 */ typedef enum __ckmc_ec_type { - CKMC_EC_PRIME192V1 = 0, /**< Elliptic curve domain "secp192r1" listed in "SEC 2" recommended + CKMC_EC_PRIME192V1 = 0, /**< Elliptic curve domain "secp192r1" listed in "SEC 2" recommended elliptic curve domain */ - CKMC_EC_PRIME256V1, /**< "SEC 2" recommended elliptic curve domain - secp256r1 */ - CKMC_EC_SECP384R1 /**< NIST curve P-384 (covers "secp384r1", the elliptic curve domain - listed in See SEC 2 */ + CKMC_EC_PRIME256V1, /**< "SEC 2" recommended elliptic curve domain - secp256r1 */ + CKMC_EC_SECP384R1 /**< NIST curve P-384(covers "secp384r1", the elliptic curve domain + listed in See SEC 2 */ } ckmc_ec_type_e; /** @@ -145,7 +145,7 @@ typedef enum __ckmc_rsa_padding_algo { * @brief Enumeration for database access rights. * @since_tizen 2.3 */ -typedef enum __ckmc_access_right{ +typedef enum __ckmc_access_right { CKMC_AR_READ = 0, /**< Access right for read*/ CKMC_AR_READ_REMOVE /**< Access right for read and remove*/ } ckmc_access_right_e; @@ -154,7 +154,7 @@ typedef enum __ckmc_access_right{ * @brief Enumeration for permissions to access/modify alias. * @since_tizen 2.4 */ -typedef enum __ckmc_permission{ +typedef enum __ckmc_permission { CKMC_PERMISSION_NONE = 0x00, /**< Clear permissions */ CKMC_PERMISSION_READ = 0x01, /**< Eead allowed */ CKMC_PERMISSION_REMOVE = 0x02 /**< Remove allowed */ diff --git a/src/listener/listener-daemon.cpp b/src/listener/listener-daemon.cpp index 4521bbd9..894d4282 100644 --- a/src/listener/listener-daemon.cpp +++ b/src/listener/listener-daemon.cpp @@ -68,7 +68,7 @@ void packageUninstalledEventCallback( if (eventType != PACKAGE_MANAGER_EVENT_TYPE_UNINSTALL || eventState != PACKAGE_MANAGER_EVENT_STATE_STARTED || package == NULL) - return; + return; SLOGD("PackageUninstalled Callback. Uninstalation of: %s", package); diff --git a/src/manager/client-async/async-request.h b/src/manager/client-async/async-request.h index 7c5330ab..18199fe3 100644 --- a/src/manager/client-async/async-request.h +++ b/src/manager/client-async/async-request.h @@ -30,8 +30,7 @@ namespace CKM { -struct AsyncRequest -{ +struct AsyncRequest { typedef std::map<int, AsyncRequest> Map; typedef std::queue<AsyncRequest, std::list<AsyncRequest> > Queue; diff --git a/src/manager/client-async/client-manager-async-impl.cpp b/src/manager/client-async/client-manager-async-impl.cpp index 269ef134..5024eaeb 100644 --- a/src/manager/client-async/client-manager-async-impl.cpp +++ b/src/manager/client-async/client-manager-async-impl.cpp @@ -28,7 +28,6 @@ #include <client-manager-async-impl.h> namespace CKM { - int ManagerAsync::Impl::m_counter = 0; ManagerAsync::Impl::Impl() @@ -117,7 +116,6 @@ void ManagerAsync::Impl::savePKCS12(const ManagerAsync::ObserverPtr& observer, PKCS12Serializable(*pkcs.get()), PolicySerializable(keyPolicy), PolicySerializable(certPolicy)); - }, [&observer](int error){ observer->ReceivedError(error); } ); } @@ -204,7 +202,7 @@ void ManagerAsync::Impl::createSignature(const ObserverPtr& observer, password, message, CryptoAlgorithmSerializable(cAlg)); - }, [&observer](int error) {observer->ReceivedError(error);}); + }, [&observer](int error) {observer->ReceivedError(error);} ); } void ManagerAsync::Impl::verifySignature(const ObserverPtr& observer, @@ -244,7 +242,7 @@ void ManagerAsync::Impl::ocspCheck(const ObserverPtr& observer, try_catch_async([&] { RawBufferVector rawCertChain; for (auto &e: certificateChainVector) { - if(!e || e->empty()) + if (!e || e->empty()) return observer->ReceivedError(CKM_API_ERROR_INPUT_PARAM); rawCertChain.push_back(e->getDER()); } @@ -308,8 +306,7 @@ void ManagerAsync::Impl::createKeyPair(const ManagerAsync::ObserverPtr& observer } // input type check CryptoAlgorithm keyGenAlgorithm; - switch(key_type) - { + switch (key_type) { case KeyType::KEY_RSA_PUBLIC: case KeyType::KEY_RSA_PRIVATE: keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::RSA_GEN); @@ -374,7 +371,7 @@ void ManagerAsync::Impl::createKeyAES(const ManagerAsync::ObserverPtr& observer, void ManagerAsync::Impl::observerCheck(const ManagerAsync::ObserverPtr& observer) { - if(!observer) + if (!observer) throw std::invalid_argument("Empty observer"); } diff --git a/src/manager/client-async/client-manager-async-impl.h b/src/manager/client-async/client-manager-async-impl.h index 21013fc5..6975c7c5 100644..100755 --- a/src/manager/client-async/client-manager-async-impl.h +++ b/src/manager/client-async/client-manager-async-impl.h @@ -149,7 +149,7 @@ public: untrusted, trusted, useSystemTrustedCertificates); - }, [&observer](int error){ observer->ReceivedError(error); } ); + }, [&observer](int error){ observer->ReceivedError(error);}); } void crypt( @@ -161,7 +161,6 @@ public: bool encryption); private: - template <typename... Args> void sendToStorage(const ManagerAsync::ObserverPtr& observer, const Args&... args) { diff --git a/src/manager/client-async/client-manager-async.cpp b/src/manager/client-async/client-manager-async.cpp index 92eb2073..935e9d30 100644 --- a/src/manager/client-async/client-manager-async.cpp +++ b/src/manager/client-async/client-manager-async.cpp @@ -28,9 +28,9 @@ namespace { RawBufferVector toRawBufferVector(const CertificateShPtrVector& certificates) { RawBufferVector rawBufferVector; - for (auto &e: certificates) { + for (auto &e: certificates) rawBufferVector.push_back(e->getDER()); - } + return rawBufferVector; } diff --git a/src/manager/client-async/connection-thread.cpp b/src/manager/client-async/connection-thread.cpp index ffb6d8d4..d816530b 100644 --- a/src/manager/client-async/connection-thread.cpp +++ b/src/manager/client-async/connection-thread.cpp @@ -44,7 +44,7 @@ ConnectionThread::Pipe::~Pipe() void ConnectionThread::Pipe::notify() { - if (-1 == TEMP_FAILURE_RETRY(write(m_pipe[1],"j",1))) + if (-1 == TEMP_FAILURE_RETRY(write(m_pipe[1], "j", 1))) ThrowMsg(PipeError, "Writing pipe failed " << GetErrnoString(errno)); } @@ -54,17 +54,20 @@ ConnectionThread::ConnectionThread() : { } -ConnectionThread::~ConnectionThread() { +ConnectionThread::~ConnectionThread() +{ m_join = true; m_pipe.notify(); m_thread.join(); } -void ConnectionThread::run() { +void ConnectionThread::run() +{ m_thread = std::thread(&ConnectionThread::threadLoop, this); } -void ConnectionThread::sendMessage(AsyncRequest&& req) { +void ConnectionThread::sendMessage(AsyncRequest&& req) +{ std::unique_lock<std::mutex> lock(m_mutex); m_waitingReqs.push(std::move(req)); lock.unlock(); @@ -93,7 +96,7 @@ void ConnectionThread::threadLoop() } // cleanup services - for(auto& it: m_services) + for (auto& it: m_services) it.second.serviceError(CKM_API_ERROR_UNKNOWN); m_services.clear(); @@ -102,7 +105,7 @@ void ConnectionThread::threadLoop() // remove waiting requests and notify about error std::unique_lock<std::mutex> lock(m_mutex); - while(!m_waitingReqs.empty()) { + while (!m_waitingReqs.empty()) { m_waitingReqs.front().observer->ReceivedError(CKM_API_ERROR_UNKNOWN); m_waitingReqs.pop(); } @@ -118,7 +121,7 @@ void ConnectionThread::readPipe(int pipe, short revents) if ((revents & POLLIN) == 0) ThrowMsg(PipeError, "Unexpected event: " << revents << "!=" << POLLIN); - if(1 != TEMP_FAILURE_RETRY(read(pipe,buffer, 1))) { + if (1 != TEMP_FAILURE_RETRY(read(pipe, buffer, 1))) { int err = errno; ThrowMsg(PipeError, "Failed to read pipe: " << GetErrnoString(err)); } @@ -132,7 +135,7 @@ Service& ConnectionThread::getService(const std::string& interface) // create new service, insert it and return return m_services.insert( - std::make_pair(interface,Service(m_descriptors, interface))).first->second; + std::make_pair(interface, Service(m_descriptors, interface))).first->second; } void ConnectionThread::newRequest(int pipe, short revents) @@ -142,7 +145,7 @@ void ConnectionThread::newRequest(int pipe, short revents) std::unique_lock<std::mutex> lock(m_mutex); // nothing to do? - if(m_waitingReqs.empty()) { + if (m_waitingReqs.empty()) { LogWarning("Empty request queue. Are we exiting?"); return; } diff --git a/src/manager/client-async/descriptor-set.cpp b/src/manager/client-async/descriptor-set.cpp index 8e36bed2..8767ceed 100644 --- a/src/manager/client-async/descriptor-set.cpp +++ b/src/manager/client-async/descriptor-set.cpp @@ -27,24 +27,28 @@ namespace CKM { -DescriptorSet::DescriptorSet() : m_dirty(true), m_fds(NULL) { +DescriptorSet::DescriptorSet() : m_dirty(true), m_fds(NULL) +{ } -DescriptorSet::~DescriptorSet() { +DescriptorSet::~DescriptorSet() +{ purge(); } -void DescriptorSet::purge() { - for(auto it:m_descriptors) +void DescriptorSet::purge() +{ + for (auto it:m_descriptors) close(it.first); m_descriptors.clear(); } -void DescriptorSet::add(int fd, short events, Callback&& callback) { +void DescriptorSet::add(int fd, short events, Callback&& callback) +{ // map operator[] requires empty DescriptorData constructor auto it = m_descriptors.find(fd); if (it == m_descriptors.end()) { - m_descriptors.insert(std::make_pair(fd,DescriptorData(events, std::move(callback)))); + m_descriptors.insert(std::make_pair(fd, DescriptorData(events, std::move(callback)))); } else { it->second.events = events; it->second.callback = std::move(callback); @@ -52,7 +56,8 @@ void DescriptorSet::add(int fd, short events, Callback&& callback) { m_dirty = true; } -void DescriptorSet::remove(int fd, bool close_fd) { +void DescriptorSet::remove(int fd, bool close_fd) +{ if (0 != m_descriptors.erase(fd)) { if (close_fd) close(fd); @@ -60,8 +65,9 @@ void DescriptorSet::remove(int fd, bool close_fd) { } } -void DescriptorSet::wait(int timeout_ms) { - if(!rebuildPollfd()) +void DescriptorSet::wait(int timeout_ms) +{ + if (!rebuildPollfd()) return; // wait @@ -76,7 +82,8 @@ void DescriptorSet::wait(int timeout_ms) { notify(ret); } -bool DescriptorSet::rebuildPollfd() { +bool DescriptorSet::rebuildPollfd() +{ if (m_dirty) { delete[] m_fds; m_fds = NULL; @@ -87,7 +94,7 @@ bool DescriptorSet::rebuildPollfd() { m_fds = new pollfd[m_descriptors.size()]; size_t idx = 0; - for(const auto& it : m_descriptors) { + for (const auto& it : m_descriptors) { m_fds[idx].fd = it.first; m_fds[idx].events = it.second.events; idx++; @@ -97,9 +104,10 @@ bool DescriptorSet::rebuildPollfd() { return true; } -void DescriptorSet::notify(int descCount) { +void DescriptorSet::notify(int descCount) +{ size_t size = m_descriptors.size(); - for(size_t idx = 0;idx < size;++idx) { + for (size_t idx = 0;idx < size;++idx) { const pollfd& pfd = m_fds[idx]; if (pfd.revents == 0) continue; diff --git a/src/manager/client-async/descriptor-set.h b/src/manager/client-async/descriptor-set.h index 7c70be18..0f8e2c10 100644 --- a/src/manager/client-async/descriptor-set.h +++ b/src/manager/client-async/descriptor-set.h @@ -29,8 +29,7 @@ namespace CKM { -class IDescriptorSet -{ +class IDescriptorSet { public: // int is for descriptor, short is for revents, typedef std::function<void(int, short)> Callback; @@ -46,8 +45,7 @@ protected: /** * @brief Wrapper for poll() */ -class DescriptorSet : public IDescriptorSet -{ +class DescriptorSet : public IDescriptorSet { public: DescriptorSet(); virtual ~DescriptorSet(); @@ -94,8 +92,7 @@ protected: bool rebuildPollfd(); void notify(int descCount); - struct DescriptorData - { + struct DescriptorData { DescriptorData(short e, Callback&& c) : events(e), callback(std::move(c)) {} short events; diff --git a/src/manager/client-async/service.cpp b/src/manager/client-async/service.cpp index 9725432c..40ab9ac3 100644 --- a/src/manager/client-async/service.cpp +++ b/src/manager/client-async/service.cpp @@ -45,7 +45,7 @@ Service::Service(IDescriptorSet& descriptors, const std::string& interface) : void Service::addRequest(AsyncRequest&& req) { - if(!m_socket) { + if (!m_socket) { m_socket.reset(new SockRAII()); int ret; if (CKM_API_SUCCESS != (ret = m_socket->connect(m_interface.c_str()))) { @@ -64,8 +64,7 @@ void Service::addRequest(AsyncRequest&& req) void Service::serviceError(int error) { - if (m_socket) - { + if (m_socket) { // stop listening on socket m_descriptors.remove(m_socket->get(), false); // close the socket @@ -73,13 +72,13 @@ void Service::serviceError(int error) } // notify observers waiting for response - for(const auto& it: m_responseMap) { + for (const auto& it: m_responseMap) it.second.observer->ReceivedError(error); - } + m_responseMap.clear(); // notify observers waiting for send - while(!m_sendQueue.empty()) { + while (!m_sendQueue.empty()) { m_sendQueue.front().observer->ReceivedError(error); m_sendQueue.pop(); } @@ -145,15 +144,15 @@ void Service::sendData() req.written += temp; // finished? -> move request to response map - if(req.written == req.buffer.size()) { + if (req.written == req.buffer.size()) { AsyncRequest finished = std::move(m_sendQueue.front()); m_sendQueue.pop(); // update poll flags if necessary - if(m_sendQueue.empty() || m_responseMap.empty()) + if (m_sendQueue.empty() || m_responseMap.empty()) watch((m_sendQueue.empty()? 0 : POLLOUT) | POLLIN); - m_responseMap.insert(std::make_pair(finished.id,finished)); + m_responseMap.insert(std::make_pair(finished.id, finished)); } } } @@ -162,7 +161,7 @@ void Service::receiveData() { char buffer[RECV_BUFFER_SIZE]; - ssize_t temp = TEMP_FAILURE_RETRY(::recv(m_socket->get(), buffer, RECV_BUFFER_SIZE,0)); + ssize_t temp = TEMP_FAILURE_RETRY(::recv(m_socket->get(), buffer, RECV_BUFFER_SIZE, 0)); if (-1 == temp) { int err = errno; LogError("Error in recv: " << GetErrnoString(err)); @@ -183,8 +182,7 @@ void Service::receiveData() m_responseBuffer->Push(raw); // parse while you can - while(m_responseBuffer->Ready()) - { + while (m_responseBuffer->Ready()) { std::unique_ptr<IReceiver> receiver; if (m_interface == SERVICE_SOCKET_CKM_STORAGE) receiver.reset(new StorageReceiver(*m_responseBuffer, m_responseMap)); diff --git a/src/manager/client-async/storage-receiver.cpp b/src/manager/client-async/storage-receiver.cpp index 15bee0bb..b8b59a19 100644 --- a/src/manager/client-async/storage-receiver.cpp +++ b/src/manager/client-async/storage-receiver.cpp @@ -149,8 +149,8 @@ void StorageReceiver::parseGetListCommand() } AliasVector aliasVector; - for(const auto &it : labelNameVector) - aliasVector.push_back( AliasSupport::merge(it.first, it.second) ); + for (const auto &it : labelNameVector) + aliasVector.push_back(AliasSupport::merge(it.first, it.second)); DataType type(dataType); diff --git a/src/manager/client-capi/ckmc-control.cpp b/src/manager/client-capi/ckmc-control.cpp index 8d28e6f4..ebc5c929 100644..100755 --- a/src/manager/client-capi/ckmc-control.cpp +++ b/src/manager/client-capi/ckmc-control.cpp @@ -79,12 +79,12 @@ int ckmc_reset_user_password(uid_t user, const char *newPassword) KEY_MANAGER_CAPI int ckmc_allow_access_by_adm(uid_t user, const char* owner, const char *alias, const char *accessor, ckmc_access_right_e granted) { - if(!owner || !alias) + if (!owner || !alias) return CKMC_ERROR_INVALID_PARAMETER; int ec, permissionMask; ec = access_to_permission_mask(granted, permissionMask); - if(ec != CKMC_ERROR_NONE) + if (ec != CKMC_ERROR_NONE) return ec; // if label given twice, service will return an error @@ -104,7 +104,7 @@ int ckmc_set_permission_by_adm(uid_t user, const char *alias, const char *access KEY_MANAGER_CAPI int ckmc_deny_access_by_adm(uid_t user, const char* owner, const char *alias, const char *accessor) { - if(!owner || !alias) + if (!owner || !alias) return CKMC_ERROR_INVALID_PARAMETER; // if label given twice, service will return an error diff --git a/src/manager/client-capi/ckmc-error.cpp b/src/manager/client-capi/ckmc-error.cpp index 8ea2591a..d606846d 100644 --- a/src/manager/client-capi/ckmc-error.cpp +++ b/src/manager/client-capi/ckmc-error.cpp @@ -26,6 +26,7 @@ #include <ckmc-type-converter.h> KEY_MANAGER_CAPI -const char * ckmc_error_to_string(int error) { - return CKM::ErrorToString(to_ckm_error(error)); +const char * ckmc_error_to_string(int error) +{ + return CKM::ErrorToString(to_ckm_error(error)); } diff --git a/src/manager/client-capi/ckmc-manager.cpp b/src/manager/client-capi/ckmc-manager.cpp index d668f512..6a62e0ba 100644..100755 --- a/src/manager/client-capi/ckmc-manager.cpp +++ b/src/manager/client-capi/ckmc-manager.cpp @@ -31,22 +31,20 @@ #include <iostream> #include <string.h> -namespace -{ +namespace { const CKM::CertificateShPtrVector EMPTY_CERT_VECTOR; const CKM::AliasVector EMPTY_ALIAS_VECTOR; CKM::Password _tostring(const char *str) { - if(str == NULL) + if (str == NULL) return CKM::Password(); return CKM::Password(str); } CKM::KeyShPtr _toCkmKey(const ckmc_key_s *key) { - if(key) - { + if (key) { CKM::RawBuffer buffer(key->raw_key, key->raw_key + key->key_size); return CKM::Key::create(buffer, _tostring(key->password)); } @@ -55,8 +53,7 @@ CKM::KeyShPtr _toCkmKey(const ckmc_key_s *key) CKM::CertificateShPtr _toCkmCertificate(const ckmc_cert_s *cert) { - if(cert) - { + if (cert) { CKM::RawBuffer buffer(cert->raw_cert, cert->raw_cert + cert->cert_size); CKM::DataFormat dataFormat = static_cast<CKM::DataFormat>(static_cast<int>(cert->data_format)); return CKM::Certificate::create(buffer, dataFormat); @@ -68,8 +65,7 @@ CKM::CertificateShPtrVector _toCkmCertificateVector(const ckmc_cert_list_s *list { CKM::CertificateShPtrVector certs; ckmc_cert_list_s *current = const_cast<ckmc_cert_list_s *>(list); - while (current != NULL) - { + while (current != NULL) { if (current->cert != NULL) certs.push_back(_toCkmCertificate(current->cert)); current = current->next; @@ -81,8 +77,7 @@ CKM::AliasVector _toCkmAliasVector(const ckmc_alias_list_s *list) { CKM::AliasVector aliases; ckmc_alias_list_s *current = const_cast<ckmc_alias_list_s *>(list); - while (current != NULL) - { + while (current != NULL) { if (current->alias != NULL) aliases.push_back(CKM::Alias(current->alias)); current = current->next; @@ -95,21 +90,21 @@ ckmc_cert_list_s *_toNewCkmCertList(const CKM::CertificateShPtrVector &certVecto int ret; ckmc_cert_list_s *start = NULL; ckmc_cert_list_s *plist = NULL; - for(const auto &e : certVector) { + for (const auto &e : certVector) { CKM::RawBuffer rawBuffer = e->getDER(); ckmc_cert_s *pcert = NULL; ret = ckmc_cert_new(rawBuffer.data(), rawBuffer.size(), CKMC_FORM_DER, &pcert); - if(pcert == NULL) { + if (pcert == NULL) { ckmc_cert_list_all_free(start); return NULL; } - if(plist == NULL) { + if (plist == NULL) { ret = ckmc_cert_list_new(pcert, &plist); start = plist; // save the pointer of the first element - }else { + } else { ret = ckmc_cert_list_add(plist, pcert, &plist); } - if(ret != CKMC_ERROR_NONE) { + if (ret != CKMC_ERROR_NONE) { ckmc_cert_list_all_free(start); return NULL; } @@ -130,7 +125,7 @@ int _cryptoOperation(cryptoFn operation, const ckmc_raw_buffer_s in, ckmc_raw_buffer_s **ppout) { - if(!params || !key_alias || !ppout) + if (!params || !key_alias || !ppout) return CKMC_ERROR_INVALID_PARAMETER; // params @@ -178,29 +173,28 @@ int ckmc_save_key(const char *alias, const ckmc_key_s key, const ckmc_policy_s p return try_catch_enclosure([&]()->int { CKM::ManagerShPtr mgr = CKM::Manager::create(); - if(alias == NULL) { + if (alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } + CKM::Alias ckmAlias(alias); - if(key.raw_key == NULL || key.key_size <= 0) { + if (key.raw_key == NULL || key.key_size <= 0) return CKMC_ERROR_INVALID_PARAMETER; - } + CKM::RawBuffer buffer(key.raw_key, key.raw_key + key.key_size); CKM::KeyShPtr ckmKey; - if(key.key_type == CKMC_KEY_AES) - { - if(key.password) + if (key.key_type == CKMC_KEY_AES) { + if (key.password) return CKMC_ERROR_INVALID_PARAMETER; ckmKey = CKM::Key::createAES(buffer); - } - else + } else { ckmKey = CKM::Key::create(buffer, _tostring(key.password)); - if(ckmKey.get() == NULL) { - return CKMC_ERROR_INVALID_FORMAT; } + if (ckmKey.get() == NULL) + return CKMC_ERROR_INVALID_FORMAT; + CKM::Policy storePolicy(_tostring(policy.password), policy.extractable); int ret = mgr->saveKey(ckmAlias, ckmKey, storePolicy); @@ -222,19 +216,17 @@ int ckmc_get_key(const char *alias, const char *password, ckmc_key_s **key) int ret; CKM::KeyShPtr ckmKey; - if(alias == NULL || key == NULL) { + if (alias == NULL || key == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::ManagerShPtr mgr = CKM::Manager::create(); - if( (ret = mgr->getKey(alias, _tostring(password), ckmKey)) != CKM_API_SUCCESS) { + if ((ret = mgr->getKey(alias, _tostring(password), ckmKey)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } CKM::RawBuffer buffer = ckmKey->getDER(); ckmc_key_type_e keyType = static_cast<ckmc_key_type_e>(static_cast<int>(ckmKey->getType())); - ret = ckmc_key_new( buffer.data(), buffer.size(), keyType, NULL, key); + ret = ckmc_key_new(buffer.data(), buffer.size(), keyType, NULL, key); return to_ckmc_error(ret); }); @@ -246,16 +238,14 @@ int ckmc_get_key_alias_list(ckmc_alias_list_s** alias_list) return try_catch_enclosure([&]()->int { int ret; - if (alias_list == NULL) { + if (alias_list == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::AliasVector aliasVector; CKM::ManagerShPtr mgr = CKM::Manager::create(); - if ((ret = mgr->getKeyAliasVector(aliasVector)) != CKM_API_SUCCESS) { + if ((ret = mgr->getKeyAliasVector(aliasVector)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } ckmc_alias_list_s *plist = NULL; @@ -276,9 +266,8 @@ int ckmc_get_key_alias_list(ckmc_alias_list_s** alias_list) } } - if(plist == NULL) { // if the alias_list size is zero + if (plist == NULL) // if the alias_list size is zero return CKMC_ERROR_DB_ALIAS_UNKNOWN; - } return CKMC_ERROR_NONE; }); @@ -288,18 +277,17 @@ KEY_MANAGER_CAPI int ckmc_save_cert(const char *alias, const ckmc_cert_s cert, const ckmc_policy_s policy) { return try_catch_enclosure([&]()->int { - if(alias == NULL) { + if (alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } + CKM::Alias ckmAlias(alias); - if(cert.raw_cert == NULL || cert.cert_size <= 0) { + if (cert.raw_cert == NULL || cert.cert_size <= 0) return CKMC_ERROR_INVALID_PARAMETER; - } + CKM::CertificateShPtr ckmCert = _toCkmCertificate(&cert); - if(ckmCert.get() == NULL) { + if (ckmCert.get() == NULL) return CKMC_ERROR_INVALID_FORMAT; - } CKM::Policy storePolicy(_tostring(policy.password), policy.extractable); @@ -323,38 +311,35 @@ int ckmc_get_cert(const char *alias, const char *password, ckmc_cert_s **cert) CKM::CertificateShPtr ckmCert; int ret; - if(alias == NULL || cert == NULL) { + if (alias == NULL || cert == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::ManagerShPtr mgr = CKM::Manager::create(); - if( (ret = mgr->getCertificate(alias, _tostring(password), ckmCert)) != CKM_API_SUCCESS) { + if ((ret = mgr->getCertificate(alias, _tostring(password), ckmCert)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } CKM::RawBuffer buffer = ckmCert->getDER(); - ret = ckmc_cert_new( buffer.data(), buffer.size(), CKMC_FORM_DER, cert); + ret = ckmc_cert_new(buffer.data(), buffer.size(), CKMC_FORM_DER, cert); return ret; }); } KEY_MANAGER_CAPI -int ckmc_get_cert_alias_list(ckmc_alias_list_s** alias_list) { +int ckmc_get_cert_alias_list(ckmc_alias_list_s** alias_list) +{ return try_catch_enclosure([&]()->int { int ret; - if (alias_list == NULL) { + if (alias_list == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } *alias_list = NULL; CKM::AliasVector aliasVector; CKM::ManagerShPtr mgr = CKM::Manager::create(); - if ((ret = mgr->getCertificateAliasVector(aliasVector)) != CKM_API_SUCCESS) { + if ((ret = mgr->getCertificateAliasVector(aliasVector)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } ckmc_alias_list_s *plist = NULL; @@ -375,9 +360,8 @@ int ckmc_get_cert_alias_list(ckmc_alias_list_s** alias_list) { } } - if(plist == NULL) { // if the alias_list size is zero + if (plist == NULL) // if the alias_list size is zero return CKMC_ERROR_DB_ALIAS_UNKNOWN; - } return CKMC_ERROR_NONE; }); @@ -391,9 +375,9 @@ int ckmc_save_pkcs12(const char *alias, const ckmc_pkcs12_s *ppkcs, const ckmc_p CKM::CertificateShPtr cert; CKM::CertificateShPtrVector ca_cert_list; - if(alias==NULL || ppkcs==NULL) { + if (alias == NULL || ppkcs == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } + CKM::Alias ckmAlias(alias); private_key = _toCkmKey(ppkcs->priv_key); cert = _toCkmCertificate(ppkcs->cert); @@ -422,9 +406,8 @@ int ckmc_get_pkcs12(const char *alias, const char *key_password, const char *cer ckmc_cert_s *cert = NULL; ckmc_cert_list_s *ca_cert_list = 0; - if(!alias || !pkcs12) { + if (!alias || !pkcs12) return CKMC_ERROR_INVALID_PARAMETER; - } if (key_password) keyPass = key_password; @@ -434,29 +417,26 @@ int ckmc_get_pkcs12(const char *alias, const char *key_password, const char *cer auto mgr = CKM::Manager::create(); - if((ret = mgr->getPKCS12(alias, keyPass, certPass, pkcs)) != CKM_API_SUCCESS) { + if ((ret = mgr->getPKCS12(alias, keyPass, certPass, pkcs)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } - if(!pkcs) + if (!pkcs) return CKMC_ERROR_BAD_RESPONSE; auto pkcsKey = pkcs->getKey(); - if(pkcsKey) - { + if (pkcsKey) { CKM::RawBuffer buffer = pkcsKey->getDER(); ckmc_key_type_e keyType = static_cast<ckmc_key_type_e>(pkcsKey->getType()); ret = ckmc_key_new(buffer.data(), buffer.size(), keyType, NULL, &private_key); - if(ret != CKMC_ERROR_NONE) + if (ret != CKMC_ERROR_NONE) return ret; } auto pkcsCert = pkcs->getCertificate(); - if(pkcsCert) - { + if (pkcsCert) { CKM::RawBuffer buffer = pkcsCert->getDER(); ret = ckmc_cert_new(buffer.data(), buffer.size(), CKMC_FORM_DER, &cert); - if(ret != CKMC_ERROR_NONE) { + if (ret != CKMC_ERROR_NONE) { ckmc_key_free(private_key); return ret; } @@ -465,8 +445,7 @@ int ckmc_get_pkcs12(const char *alias, const char *key_password, const char *cer ca_cert_list = _toNewCkmCertList(pkcs->getCaCertificateShPtrVector()); ret = ckmc_pkcs12_new(private_key, cert, ca_cert_list, pkcs12); - if(ret != CKMC_ERROR_NONE) - { + if (ret != CKMC_ERROR_NONE) { ckmc_key_free(private_key); ckmc_cert_free(cert); ckmc_cert_list_free(ca_cert_list); @@ -480,14 +459,14 @@ KEY_MANAGER_CAPI int ckmc_save_data(const char *alias, ckmc_raw_buffer_s data, const ckmc_policy_s policy) { return try_catch_enclosure([&]()->int { - if(alias == NULL) { + if (alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } + CKM::Alias ckmAlias(alias); - if(data.data == NULL || data.size <= 0) { + if (data.data == NULL || data.size <= 0) return CKMC_ERROR_INVALID_PARAMETER; - } + CKM::RawBuffer buffer(data.data, data.data + data.size); CKM::Policy storePolicy(_tostring(policy.password), policy.extractable); @@ -512,14 +491,12 @@ int ckmc_get_data(const char *alias, const char *password, ckmc_raw_buffer_s **d CKM::RawBuffer ckmBuff; int ret; - if(alias == NULL || data == NULL) { + if (alias == NULL || data == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::ManagerShPtr mgr = CKM::Manager::create(); - if( (ret = mgr->getData(alias, _tostring(password), ckmBuff)) != CKM_API_SUCCESS) { + if ((ret = mgr->getData(alias, _tostring(password), ckmBuff)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } ret = ckmc_buffer_new(ckmBuff.data(), ckmBuff.size(), data); @@ -528,21 +505,20 @@ int ckmc_get_data(const char *alias, const char *password, ckmc_raw_buffer_s **d } KEY_MANAGER_CAPI -int ckmc_get_data_alias_list(ckmc_alias_list_s** alias_list){ +int ckmc_get_data_alias_list(ckmc_alias_list_s** alias_list) +{ return try_catch_enclosure([&]()->int { int ret; - if(alias_list == NULL) { + if (alias_list == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } *alias_list = NULL; CKM::AliasVector aliasVector; CKM::ManagerShPtr mgr = CKM::Manager::create(); - if( (ret = mgr->getDataAliasVector(aliasVector)) != CKM_API_SUCCESS) { + if ((ret = mgr->getDataAliasVector(aliasVector)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } ckmc_alias_list_s *plist = NULL; @@ -563,9 +539,8 @@ int ckmc_get_data_alias_list(ckmc_alias_list_s** alias_list){ } } - if(plist == NULL) { // if the alias_list size is zero + if (plist == NULL) // if the alias_list size is zero return CKMC_ERROR_DB_ALIAS_UNKNOWN; - } return CKMC_ERROR_NONE; }); @@ -582,9 +557,8 @@ int ckmc_create_key_pair_rsa(const size_t size, int ret; CKM::ManagerShPtr mgr = CKM::Manager::create(); - if(private_key_alias == NULL || public_key_alias == NULL) { + if (private_key_alias == NULL || public_key_alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::Alias ckmPrivakeKeyAlias(private_key_alias); CKM::Alias ckmPublicKeyAlias(public_key_alias); @@ -607,9 +581,8 @@ int ckmc_create_key_pair_dsa(const size_t size, int ret; CKM::ManagerShPtr mgr = CKM::Manager::create(); - if(private_key_alias == NULL || public_key_alias == NULL) { + if (private_key_alias == NULL || public_key_alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::Alias ckmPrivakeKeyAlias(private_key_alias); CKM::Alias ckmPublicKeyAlias(public_key_alias); @@ -631,9 +604,8 @@ int ckmc_create_key_pair_ecdsa(const ckmc_ec_type_e type, return try_catch_enclosure([&]()->int { CKM::ManagerShPtr mgr = CKM::Manager::create(); - if(private_key_alias == NULL || public_key_alias == NULL) { + if (private_key_alias == NULL || public_key_alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::ElipticCurve ckmType = static_cast<CKM::ElipticCurve>(static_cast<int>(type)); CKM::Alias ckmPrivakeKeyAlias(private_key_alias); @@ -654,7 +626,7 @@ int ckmc_create_key_aes(size_t size, return try_catch_enclosure([&]()->int { CKM::ManagerShPtr mgr = CKM::Manager::create(); - if(key_alias == NULL) + if (key_alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; CKM::Alias ckmKeyAlias(key_alias); @@ -678,26 +650,24 @@ int ckmc_create_signature(const char *private_key_alias, CKM::ManagerShPtr mgr = CKM::Manager::create(); CKM::RawBuffer ckmSignature; - if(private_key_alias == NULL || signature == NULL) { + if (private_key_alias == NULL || signature == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::Alias ckmPrivakeKeyAlias(private_key_alias); CKM::RawBuffer ckmMessage(message.data, message.data + message.size); CKM::HashAlgorithm ckmHashAlgo = static_cast<CKM::HashAlgorithm>(static_cast<int>(hash)); CKM::RSAPaddingAlgorithm ckmPadding = static_cast<CKM::RSAPaddingAlgorithm>(static_cast<int>(padding)); - if( (ret = mgr->createSignature( + if ((ret = mgr->createSignature( ckmPrivakeKeyAlias, _tostring(password), ckmMessage, ckmHashAlgo, ckmPadding, - ckmSignature)) != CKM_API_SUCCESS) { + ckmSignature)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } - ret = ckmc_buffer_new( ckmSignature.data(), ckmSignature.size(), signature); + ret = ckmc_buffer_new(ckmSignature.data(), ckmSignature.size(), signature); return ret; }); @@ -715,9 +685,8 @@ int ckmc_verify_signature(const char *public_key_alias, int ret; CKM::ManagerShPtr mgr = CKM::Manager::create(); - if(public_key_alias == NULL) { + if (public_key_alias == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::Alias ckmPublicKeyAlias(public_key_alias); CKM::RawBuffer ckmMessage(message.data, message.data + message.size); @@ -725,15 +694,14 @@ int ckmc_verify_signature(const char *public_key_alias, CKM::HashAlgorithm ckmHashAlgo = static_cast<CKM::HashAlgorithm>(static_cast<int>(hash)); CKM::RSAPaddingAlgorithm ckmPadding = static_cast<CKM::RSAPaddingAlgorithm>(static_cast<int>(padding)); - if( (ret = mgr->verifySignature( + if ((ret = mgr->verifySignature( ckmPublicKeyAlias, _tostring(password), ckmMessage, ckmSignature, ckmHashAlgo, - ckmPadding)) != CKM_API_SUCCESS) { + ckmPadding)) != CKM_API_SUCCESS) return to_ckmc_error(ret); - } return CKMC_ERROR_NONE; }); @@ -747,18 +715,16 @@ int ckmc_get_cert_chain(const ckmc_cert_s *cert, const ckmc_cert_list_s *untrust CKM::ManagerShPtr mgr = CKM::Manager::create(); CKM::CertificateShPtrVector ckmCertChain; - if(cert == NULL || cert->raw_cert == NULL || cert->cert_size <= 0 || cert_chain_list == NULL) { + if (cert == NULL || cert->raw_cert == NULL || cert->cert_size <= 0 || cert_chain_list == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::CertificateShPtr ckmCert = _toCkmCertificate(cert); CKM::CertificateShPtrVector ckmUntrustedCerts = _toCkmCertificateVector(untrustedcerts); ret = mgr->getCertificateChain(ckmCert, ckmUntrustedCerts, EMPTY_CERT_VECTOR, true, ckmCertChain); - if( ret != CKM_API_SUCCESS) { + if (ret != CKM_API_SUCCESS) return to_ckmc_error(ret); - } *cert_chain_list = _toNewCkmCertList(ckmCertChain); @@ -775,21 +741,18 @@ int ckmc_get_cert_chain_with_alias(const ckmc_cert_s *cert, const ckmc_alias_lis CKM::CertificateShPtrVector ckmCertChain; - if(cert == NULL || cert->raw_cert == NULL || cert->cert_size <= 0 || cert_chain_list == NULL) { + if (cert == NULL || cert->raw_cert == NULL || cert->cert_size <= 0 || cert_chain_list == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::CertificateShPtr ckmCert = _toCkmCertificate(cert); - if(ckmCert.get() == NULL) { + if (ckmCert.get() == NULL) return CKMC_ERROR_INVALID_FORMAT; - } CKM::AliasVector ckmUntrustedAliases = _toCkmAliasVector(untrustedcerts); ret = mgr->getCertificateChain(ckmCert, ckmUntrustedAliases, EMPTY_ALIAS_VECTOR, true, ckmCertChain); - if( ret != CKM_API_SUCCESS) { + if (ret != CKM_API_SUCCESS) return to_ckmc_error(ret); - } *cert_chain_list = _toNewCkmCertList(ckmCertChain); @@ -809,22 +772,19 @@ int ckmc_get_cert_chain_with_trustedcert(const ckmc_cert_s* cert, CKM::ManagerShPtr mgr = CKM::Manager::create(); CKM::CertificateShPtrVector ckm_cert_chain; - if(cert == NULL || cert->raw_cert == NULL || cert->cert_size <= 0 || ppcert_chain_list == NULL) { + if (cert == NULL || cert->raw_cert == NULL || cert->cert_size <= 0 || ppcert_chain_list == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::CertificateShPtr ckm_cert = _toCkmCertificate(cert); - if(ckm_cert.get() == NULL) { + if (ckm_cert.get() == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } CKM::CertificateShPtrVector ckm_untrusted = _toCkmCertificateVector(untrustedcerts); CKM::CertificateShPtrVector ckm_trusted = _toCkmCertificateVector(trustedcerts); ret = mgr->getCertificateChain(ckm_cert, ckm_untrusted, ckm_trusted, sys_certs, ckm_cert_chain); - if( ret != CKM_API_SUCCESS) { + if (ret != CKM_API_SUCCESS) return to_ckmc_error(ret); - } *ppcert_chain_list = _toNewCkmCertList(ckm_cert_chain); @@ -840,9 +800,8 @@ int ckmc_ocsp_check(const ckmc_cert_list_s *pcert_chain_list, ckmc_ocsp_status_e || pcert_chain_list->cert == NULL || pcert_chain_list->cert->raw_cert == NULL || pcert_chain_list->cert->cert_size <= 0 - || ocsp_status == NULL) { + || ocsp_status == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } int tmpOcspStatus = -1; CKM::ManagerShPtr mgr = CKM::Manager::create(); @@ -860,7 +819,7 @@ int ckmc_allow_access(const char *alias, const char *accessor, ckmc_access_right return try_catch_enclosure([&]()->int { int ec, permissionMask; ec = access_to_permission_mask(granted, permissionMask); - if(ec != CKMC_ERROR_NONE) + if (ec != CKMC_ERROR_NONE) return ec; return ckmc_set_permission(alias, accessor, permissionMask); @@ -895,7 +854,7 @@ KEY_MANAGER_CAPI int ckmc_remove_alias(const char *alias) { return try_catch_enclosure([&]()->int { - if(!alias) + if (!alias) return CKMC_ERROR_INVALID_PARAMETER; CKM::ManagerShPtr mgr = CKM::Manager::create(); diff --git a/src/manager/client-capi/ckmc-type-converter.cpp b/src/manager/client-capi/ckmc-type-converter.cpp index b85c8852..8a27cfb1 100644..100755 --- a/src/manager/client-capi/ckmc-type-converter.cpp +++ b/src/manager/client-capi/ckmc-type-converter.cpp @@ -23,8 +23,9 @@ #include <ckmc/ckmc-type.h> #include <ckmc-type-converter.h> -int to_ckm_error(int ckmc_error) { - switch(ckmc_error) { +int to_ckm_error(int ckmc_error) +{ + switch (ckmc_error) { case CKMC_ERROR_NONE: return CKM_API_SUCCESS; case CKMC_ERROR_SOCKET: return CKM_API_ERROR_SOCKET; case CKMC_ERROR_BAD_REQUEST: return CKM_API_ERROR_BAD_REQUEST; @@ -52,8 +53,9 @@ int to_ckm_error(int ckmc_error) { return CKMC_ERROR_UNKNOWN; } -int to_ckmc_error(int ckm_error) { - switch(ckm_error) { +int to_ckmc_error(int ckm_error) +{ + switch (ckm_error) { case CKM_API_SUCCESS: return CKMC_ERROR_NONE; case CKM_API_ERROR_SOCKET: return CKMC_ERROR_SOCKET; case CKM_API_ERROR_BAD_REQUEST: return CKMC_ERROR_BAD_REQUEST; @@ -81,8 +83,9 @@ int to_ckmc_error(int ckm_error) { return CKMC_ERROR_UNKNOWN; } -ckmc_ocsp_status_e to_ckmc_ocsp_status(int ckm_ocsp_status) { - switch(ckm_ocsp_status) { +ckmc_ocsp_status_e to_ckmc_ocsp_status(int ckm_ocsp_status) +{ + switch (ckm_ocsp_status) { case CKM_API_OCSP_STATUS_GOOD: return CKMC_OCSP_STATUS_GOOD; case CKM_API_OCSP_STATUS_UNSUPPORTED: return CKMC_OCSP_ERROR_UNSUPPORTED; case CKM_API_OCSP_STATUS_REVOKED: return CKMC_OCSP_STATUS_REVOKED; @@ -97,8 +100,7 @@ ckmc_ocsp_status_e to_ckmc_ocsp_status(int ckm_ocsp_status) { int access_to_permission_mask(ckmc_access_right_e ar, int & permissionMask) { - switch(ar) - { + switch (ar) { case CKMC_AR_READ: permissionMask = CKMC_PERMISSION_READ; break; diff --git a/src/manager/client-capi/ckmc-type.cpp b/src/manager/client-capi/ckmc-type.cpp index a5de9f24..4db37f86 100644..100755 --- a/src/manager/client-capi/ckmc-type.cpp +++ b/src/manager/client-capi/ckmc-type.cpp @@ -44,9 +44,8 @@ const size_t DEFAULT_KEY_LEN_BITS = 4096; int _ckmc_load_cert_from_x509(X509 *xCert, ckmc_cert_s **cert) { - if(xCert == NULL) { + if (xCert == NULL) return CKMC_ERROR_INVALID_FORMAT; - } BIO *bcert = BIO_new(BIO_s_mem()); @@ -55,9 +54,9 @@ int _ckmc_load_cert_from_x509(X509 *xCert, ckmc_cert_s **cert) CKM::RawBuffer output(8196); int size = BIO_read(bcert, output.data(), output.size()); BIO_free_all(bcert); - if (size <= 0) { + if (size <= 0) return CKMC_ERROR_INVALID_FORMAT; - } + output.resize(size); return ckmc_cert_new(output.data(), output.size(), CKMC_FORM_DER, cert); @@ -75,16 +74,15 @@ int ckmc_key_new(unsigned char *raw_key, size_t key_size, ckmc_key_type_e key_ty { ckmc_key_s *pkey; - if(raw_key == NULL || key_size == 0 || ppkey == NULL) { + if (raw_key == NULL || key_size == 0 || ppkey == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } pkey = static_cast<ckmc_key_s*>(malloc(sizeof(ckmc_key_s))); - if(pkey == NULL) { + if (pkey == NULL) return CKMC_ERROR_OUT_OF_MEMORY; - } + pkey->raw_key = reinterpret_cast<unsigned char*>(malloc(key_size)); - if(pkey->raw_key == NULL) { + if (pkey->raw_key == NULL) { free(pkey); return CKMC_ERROR_OUT_OF_MEMORY; } @@ -93,16 +91,16 @@ int ckmc_key_new(unsigned char *raw_key, size_t key_size, ckmc_key_type_e key_ty pkey->key_size = key_size; pkey->key_type = key_type; - if(password != NULL) { + if (password != NULL) { pkey->password = reinterpret_cast<char*>(malloc(strlen(password) +1)); - if(pkey->password == NULL) { + if (pkey->password == NULL) { free(pkey->raw_key); free(pkey); return CKMC_ERROR_OUT_OF_MEMORY; } memset(pkey->password, 0, strlen(password) +1); strncpy(pkey->password, password, strlen(password)); - }else { + } else { pkey->password = NULL; } @@ -114,12 +112,12 @@ int ckmc_key_new(unsigned char *raw_key, size_t key_size, ckmc_key_type_e key_ty KEY_MANAGER_CAPI void ckmc_key_free(ckmc_key_s *key) { - if(key == NULL) + if (key == NULL) return; - if(key->password != NULL) + if (key->password != NULL) free(key->password); - if(key->raw_key != NULL) { + if (key->raw_key != NULL) { memset(key->raw_key, 0, key->key_size); free(key->raw_key); } @@ -128,20 +126,19 @@ void ckmc_key_free(ckmc_key_s *key) } KEY_MANAGER_CAPI -int ckmc_buffer_new(unsigned char *data, size_t size,ckmc_raw_buffer_s **ppbuffer) +int ckmc_buffer_new(unsigned char *data, size_t size, ckmc_raw_buffer_s **ppbuffer) { ckmc_raw_buffer_s *pbuff; - if(data == NULL || size == 0 || ppbuffer == NULL) { + if (data == NULL || size == 0 || ppbuffer == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } pbuff = static_cast<ckmc_raw_buffer_s*>(malloc(sizeof(ckmc_raw_buffer_s))); - if(pbuff == NULL) + if (pbuff == NULL) return CKMC_ERROR_OUT_OF_MEMORY; pbuff->data = reinterpret_cast<unsigned char*>(malloc(size)); - if(pbuff->data == NULL) { + if (pbuff->data == NULL) { free(pbuff); return CKMC_ERROR_OUT_OF_MEMORY; } @@ -156,10 +153,10 @@ int ckmc_buffer_new(unsigned char *data, size_t size,ckmc_raw_buffer_s **ppbuffe KEY_MANAGER_CAPI void ckmc_buffer_free(ckmc_raw_buffer_s *buffer) { - if(buffer == NULL) + if (buffer == NULL) return; - if(buffer->data != NULL) { + if (buffer->data != NULL) { memset(buffer->data, 0, buffer->size); free(buffer->data); } @@ -171,16 +168,15 @@ int ckmc_cert_new(unsigned char *raw_cert, size_t cert_size, ckmc_data_format_e { ckmc_cert_s *pcert; - if(raw_cert == NULL || cert_size == 0 || ppcert == NULL) { + if (raw_cert == NULL || cert_size == 0 || ppcert == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } pcert = static_cast<ckmc_cert_s*>(malloc(sizeof(ckmc_cert_s))); - if(pcert == NULL) { + if (pcert == NULL) return CKMC_ERROR_OUT_OF_MEMORY; - } + pcert->raw_cert = reinterpret_cast<unsigned char*>(malloc(cert_size)); - if(pcert->raw_cert == NULL) { + if (pcert->raw_cert == NULL) { free(pcert); return CKMC_ERROR_OUT_OF_MEMORY; } @@ -199,32 +195,31 @@ int ckmc_load_cert_from_file(const char *file_path, ckmc_cert_s **cert) CKM::initOpenSslOnce(); FILE *fp = fopen(file_path, "r"); - if(fp == NULL) + if (fp == NULL) return CKMC_ERROR_FILE_ACCESS_DENIED; X509 *pcert = NULL; - if(!(pcert = d2i_X509_fp(fp, NULL))) { + if (!(pcert = d2i_X509_fp(fp, NULL))) { fseek(fp, 0, SEEK_SET); pcert = PEM_read_X509(fp, NULL, NULL, NULL); } fclose(fp); - if(pcert == NULL) { + if (pcert == NULL) return CKMC_ERROR_INVALID_FORMAT; - } int ret = _ckmc_load_cert_from_x509(pcert, cert); - if(ret != CKMC_ERROR_NONE) { + if (ret != CKMC_ERROR_NONE) X509_free(pcert); - } + return ret; } KEY_MANAGER_CAPI void ckmc_cert_free(ckmc_cert_s *cert) { - if(cert == NULL) + if (cert == NULL) return; - if(cert->raw_cert != NULL) { + if (cert->raw_cert != NULL) { memset(cert->raw_cert, 0, cert->cert_size); free(cert->raw_cert); } @@ -237,15 +232,14 @@ int ckmc_pkcs12_new(ckmc_key_s *private_key, ckmc_cert_s *cert, { ckmc_pkcs12_s *pkcs12; - if(!pkcs12_bundle || - (private_key==NULL && cert==NULL && (ca_cert_list==NULL || ca_cert_list->cert==NULL))) { + if (!pkcs12_bundle || + (private_key == NULL && cert == NULL && (ca_cert_list == NULL || ca_cert_list->cert == NULL))) return CKMC_ERROR_INVALID_PARAMETER; - } pkcs12 = static_cast<ckmc_pkcs12_s*>(malloc(sizeof(ckmc_pkcs12_s))); - if(pkcs12 == NULL) { + if (pkcs12 == NULL) return CKMC_ERROR_OUT_OF_MEMORY; - } + // ownership is transferred into pkcs12 - mentioned in the docs pkcs12->priv_key = private_key; pkcs12->cert = cert; @@ -267,12 +261,14 @@ int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ck STACK_OF(X509)* ca; int ret; + public: ckmc_key_s *retPrivateKey; ckmc_cert_s *retCkmCert; ckmc_cert_list_s *retCaCertList; - Pkcs12Converter(){ + Pkcs12Converter() + { fp_in = NULL; p12 = NULL; pkey = NULL; @@ -283,59 +279,61 @@ int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ck retCkmCert = NULL; retCaCertList = NULL; }; - ~Pkcs12Converter(){ - if(fp_in != NULL) + ~Pkcs12Converter() + { + if (fp_in != NULL) fclose(fp_in); - if(p12 != NULL) + if (p12 != NULL) PKCS12_free(p12); - if(x509Cert != NULL) + if (x509Cert != NULL) X509_free(x509Cert); - if(pkey != NULL) + if (pkey != NULL) EVP_PKEY_free(pkey); - if(ca != NULL) + if (ca != NULL) sk_X509_pop_free(ca, X509_free); - if(ret != CKMC_ERROR_NONE) { - if(retPrivateKey != NULL){ + if (ret != CKMC_ERROR_NONE) { + if (retPrivateKey != NULL) { ckmc_key_free(retPrivateKey); retPrivateKey = NULL; } - if(retCkmCert != NULL) { + if (retCkmCert != NULL) { ckmc_cert_free(retCkmCert); retCkmCert = NULL; } - if(retCaCertList != NULL) { + if (retCaCertList != NULL) { ckmc_cert_list_all_free(retCaCertList); retCaCertList = NULL; } } }; - int parsePkcs12(const char *filePath, const char *pass) { + int parsePkcs12(const char *filePath, const char *pass) + { fp_in = NULL; - if(!(fp_in = fopen(filePath, "rb"))) { + if (!(fp_in = fopen(filePath, "rb"))) return CKMC_ERROR_FILE_ACCESS_DENIED; - } - if(!(p12 = d2i_PKCS12_fp(fp_in, NULL))) { + if (!(p12 = d2i_PKCS12_fp(fp_in, NULL))) return CKMC_ERROR_INVALID_FORMAT; - } /* parse PKCS#12 certificate */ - if((ret = PKCS12_parse(p12, pass, &pkey, &x509Cert, &ca)) != 1) { + if ((ret = PKCS12_parse(p12, pass, &pkey, &x509Cert, &ca)) != 1) return CKMC_ERROR_INVALID_FORMAT; - } + return CKMC_ERROR_NONE; } - int toCkmCert() { - if( (ret =_ckmc_load_cert_from_x509(x509Cert,&retCkmCert)) != CKMC_ERROR_NONE) { + int toCkmCert() + { + if ((ret = _ckmc_load_cert_from_x509(x509Cert, &retCkmCert)) != CKMC_ERROR_NONE) return ret; - } + return CKMC_ERROR_NONE; } - int toCkmKey() { + int toCkmKey() + { BIO *bkey = BIO_new(BIO_s_mem()); i2d_PrivateKey_bio(bkey, pkey); @@ -343,14 +341,14 @@ int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ck CKM::RawBuffer output(8196); int size = BIO_read(bkey, output.data(), output.size()); BIO_free_all(bkey); - if (size <= 0) { + if (size <= 0) return CKMC_ERROR_INVALID_FORMAT; - } + output.resize(size); int type = EVP_PKEY_type(pkey->type); ckmc_key_type_e key_type = CKMC_KEY_NONE; - switch(type) { + switch (type) { case EVP_PKEY_RSA : key_type = CKMC_KEY_RSA_PRIVATE; break; @@ -361,31 +359,31 @@ int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ck key_type = CKMC_KEY_ECDSA_PRIVATE; break; } - if(key_type == CKMC_KEY_NONE) { + if (key_type == CKMC_KEY_NONE) return CKMC_ERROR_INVALID_FORMAT; - } char *nullPassword = NULL; return ckmc_key_new(output.data(), size, key_type, nullPassword, &retPrivateKey); } - int toCaCkmCertList() { + int toCaCkmCertList() + { int tmpRet; X509* popedCert = NULL; ckmc_cert_s *popedCkmCert = NULL; ckmc_cert_list_s *tmpCertList = NULL; - while((popedCert = sk_X509_pop(ca)) != NULL) { - if( (tmpRet =_ckmc_load_cert_from_x509(popedCert, &popedCkmCert)) != CKMC_ERROR_NONE) { + while ((popedCert = sk_X509_pop(ca)) != NULL) { + if ((tmpRet =_ckmc_load_cert_from_x509(popedCert, &popedCkmCert)) != CKMC_ERROR_NONE) return CKMC_ERROR_OUT_OF_MEMORY; - } - if(tmpCertList == NULL) { // first + + if (tmpCertList == NULL) { // first tmpRet = ckmc_cert_list_new(popedCkmCert, &tmpCertList); retCaCertList = tmpCertList; - }else { + } else { tmpRet = ckmc_cert_list_add(tmpCertList, popedCkmCert, &tmpCertList); } - if(tmpRet != CKMC_ERROR_NONE) { + if (tmpRet != CKMC_ERROR_NONE) { ckmc_cert_list_all_free(retCaCertList); retCaCertList = NULL; return tmpRet; @@ -393,7 +391,6 @@ int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ck } return CKMC_ERROR_NONE; } - }; CKM::initOpenSslOnce(); @@ -401,18 +398,17 @@ int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ck int ret = CKMC_ERROR_NONE; Pkcs12Converter converter; - if((ret = converter.parsePkcs12(file_path, passphrase)) != CKMC_ERROR_NONE) { + if ((ret = converter.parsePkcs12(file_path, passphrase)) != CKMC_ERROR_NONE) return ret; - } - if((ret = converter.toCkmCert()) != CKMC_ERROR_NONE) { + + if ((ret = converter.toCkmCert()) != CKMC_ERROR_NONE) return ret; - } - if((ret = converter.toCkmKey()) != CKMC_ERROR_NONE) { + + if ((ret = converter.toCkmKey()) != CKMC_ERROR_NONE) return ret; - } - if((ret = converter.toCaCkmCertList()) != CKMC_ERROR_NONE) { + + if ((ret = converter.toCaCkmCertList()) != CKMC_ERROR_NONE) return ret; - } *private_key = converter.retPrivateKey; *ckmcert = converter.retCkmCert; @@ -429,16 +425,15 @@ int ckmc_pkcs12_load(const char *file_path, const char *passphrase, ckmc_pkcs12_ ckmc_cert_s *cert = 0; ckmc_cert_list_s *ca_cert_list = 0; - if(!file_path || !pkcs12_bundle) + if (!file_path || !pkcs12_bundle) return CKMC_ERROR_INVALID_PARAMETER; ec = ckmc_load_from_pkcs12_file(file_path, passphrase, &private_key, &cert, &ca_cert_list); - if(ec != CKMC_ERROR_NONE) + if (ec != CKMC_ERROR_NONE) return ec; ec = ckmc_pkcs12_new(private_key, cert, ca_cert_list, pkcs12_bundle); - if(ec != CKMC_ERROR_NONE) - { + if (ec != CKMC_ERROR_NONE) { ckmc_key_free(private_key); ckmc_cert_free(cert); ckmc_cert_list_free(ca_cert_list); @@ -451,7 +446,7 @@ int ckmc_pkcs12_load(const char *file_path, const char *passphrase, ckmc_pkcs12_ KEY_MANAGER_CAPI void ckmc_pkcs12_free(ckmc_pkcs12_s *pkcs12) { - if(pkcs12 == NULL) + if (pkcs12 == NULL) return; ckmc_key_free(pkcs12->priv_key); @@ -472,21 +467,19 @@ int ckmc_alias_list_add(ckmc_alias_list_s *previous, char *alias, ckmc_alias_lis { ckmc_alias_list_s *plist; - if(alias == NULL || pplast == NULL) { + if (alias == NULL || pplast == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } plist = static_cast<ckmc_alias_list_s*>(malloc(sizeof(ckmc_alias_list_s))); - if(plist == NULL) { + if (plist == NULL) return CKMC_ERROR_OUT_OF_MEMORY; - } plist->alias = alias; plist->next = NULL; - if(previous != NULL) { + if (previous != NULL) previous->next = plist; - } + *pplast = plist; return CKMC_ERROR_NONE; @@ -527,20 +520,18 @@ int ckmc_cert_list_add(ckmc_cert_list_s *previous, ckmc_cert_s *cert, ckmc_cert_ { ckmc_cert_list_s *plist; - if(cert == NULL || pplast == NULL) { + if (cert == NULL || pplast == NULL) return CKMC_ERROR_INVALID_PARAMETER; - } plist = static_cast<ckmc_cert_list_s*>(malloc(sizeof(ckmc_cert_list_s))); - if(plist == NULL) { + if (plist == NULL) return CKMC_ERROR_OUT_OF_MEMORY; - } + plist->cert = cert; plist->next = NULL; - if(previous != NULL) { + if (previous != NULL) previous->next = plist; - } *pplast = plist; @@ -634,7 +625,7 @@ int ckmc_param_list_get_buffer(ckmc_param_list_h params, const CKM::CryptoAlgorithm* algo = reinterpret_cast<const CKM::CryptoAlgorithm*>(params); CKM::RawBuffer value; - if (!algo->getParam(static_cast<CKM::ParamName>(name),value)) + if (!algo->getParam(static_cast<CKM::ParamName>(name), value)) return CKMC_ERROR_INVALID_PARAMETER; return ckmc_buffer_new(value.data(), value.size(), ppbuffer); diff --git a/src/manager/client/client-common.cpp b/src/manager/client/client-common.cpp index 10d5de19..5aca5c52 100644 --- a/src/manager/client/client-common.cpp +++ b/src/manager/client/client-common.cpp @@ -83,7 +83,8 @@ int SockRAII::connect(const char * interface) return CKM_API_SUCCESS; } -int SockRAII::connectWrapper(int sock, const char *interface) { +int SockRAII::connectWrapper(int sock, const char *interface) +{ int flags; // we need to be sure that socket is in blocking mode @@ -108,8 +109,7 @@ int SockRAII::connectWrapper(int sock, const char *interface) { int retval = TEMP_FAILURE_RETRY(::connect(sock, (struct sockaddr*)&clientAddr, SUN_LEN(&clientAddr))); // we don't need to support EINPROGRESS because the socket is in blocking mode - if(-1 == retval) - { + if (-1 == retval) { if (errno == EACCES) { LogError("Access denied to interface: " << interface); return CKM_API_ERROR_ACCESS_DENIED; @@ -127,11 +127,13 @@ int SockRAII::connectWrapper(int sock, const char *interface) { return CKM_API_SUCCESS; } -bool SockRAII::isConnected() const { +bool SockRAII::isConnected() const +{ return (m_sock > -1); } -void SockRAII::disconnect() { +void SockRAII::disconnect() +{ if (isConnected()) close(m_sock); m_sock = -1; @@ -144,32 +146,28 @@ int SockRAII::waitForSocket(int event, int timeout) desc[0].fd = m_sock; desc[0].events = event; - while((-1 == (retval = poll(desc, 1, timeout))) && (errno == EINTR)) { + while ((-1 == (retval = poll(desc, 1, timeout))) && (errno == EINTR)) { timeout >>= 1; errno = 0; } - if (0 == retval) { + if (0 == retval) LogDebug("Poll timeout"); - } else if(-1 == retval) { + else if (-1 == retval) LogError("Error in poll: " << CKM::GetErrnoString(errno)); - } + return retval; } -int SockRAII::get() const { +int SockRAII::get() const +{ return m_sock; } -} // namespace anonymous - -namespace CKM { - AliasSupport::AliasSupport(const Alias &alias) { std::size_t separator_pos = alias.rfind(CKM::LABEL_NAME_SEPARATOR); - if(separator_pos == Alias::npos) - { + if (separator_pos == Alias::npos) { m_label.clear(); m_name = alias; } else { @@ -180,7 +178,7 @@ AliasSupport::AliasSupport(const Alias &alias) Alias AliasSupport::merge(const Label &label, const Name &name) { - if(label.empty()) + if (label.empty()) return name; std::stringstream output; @@ -188,20 +186,24 @@ Alias AliasSupport::merge(const Label &label, const Name &name) return output.str(); } -const Name & AliasSupport::getName() const { +const Name & AliasSupport::getName() const +{ return m_name; } -const Label & AliasSupport::getLabel() const { +const Label & AliasSupport::getLabel() const +{ return m_label; } -bool AliasSupport::isLabelEmpty() const { +bool AliasSupport::isLabelEmpty() const +{ return m_label.empty(); } -ServiceConnection::ServiceConnection(const char *service_interface) { - if(service_interface) +ServiceConnection::ServiceConnection(const char *service_interface) +{ + if (service_interface) m_serviceInterface = std::string(service_interface); } @@ -210,7 +212,7 @@ int ServiceConnection::processRequest( CKM::MessageBuffer &recv_buf) { int ec; - if(CKM_API_SUCCESS != (ec = send(send_buf))) + if (CKM_API_SUCCESS != (ec = send(send_buf))) return ec; return receive(recv_buf); @@ -262,8 +264,7 @@ int ServiceConnection::send(const CKM::RawBuffer &send_buf) int ServiceConnection::receive(CKM::MessageBuffer &recv_buf) { - if (!m_socket.isConnected()) - { + if (!m_socket.isConnected()) { LogError("Not connected!"); return CKM_API_ERROR_SOCKET; } @@ -271,9 +272,8 @@ int ServiceConnection::receive(CKM::MessageBuffer &recv_buf) int ec = CKM_API_SUCCESS; const size_t c_recv_buf_len = 2048; char buffer[c_recv_buf_len]; - do - { - if( 0 >= m_socket.waitForSocket(POLLIN, POLL_TIMEOUT)) { + do { + if (0 >= m_socket.waitForSocket(POLLIN, POLL_TIMEOUT)) { LogError("Error in WaitForSocket."); ec = CKM_API_ERROR_SOCKET; break; @@ -283,7 +283,7 @@ int ServiceConnection::receive(CKM::MessageBuffer &recv_buf) buffer, sizeof(buffer), 0)); - if(-1 == temp) { + if (-1 == temp) { LogError("Error in read: " << CKM::GetErrnoString(errno)); ec = CKM_API_ERROR_SOCKET; break; @@ -297,10 +297,9 @@ int ServiceConnection::receive(CKM::MessageBuffer &recv_buf) CKM::RawBuffer raw(buffer, buffer+temp); recv_buf.Push(raw); - } - while(!recv_buf.Ready()); + } while (!recv_buf.Ready()); - if(ec != CKM_API_SUCCESS) + if (ec != CKM_API_SUCCESS) m_socket.disconnect(); return ec; @@ -327,7 +326,8 @@ int try_catch(const std::function<int()>& func) return retval; } -void try_catch_async(const std::function<void()>& func, const std::function<void(int)>& error) +void try_catch_async(const std::function<void()>& func, + const std::function<void(int)>& error) { try { func(); @@ -348,15 +348,14 @@ void try_catch_async(const std::function<void()>& func, const std::function<void } // namespace CKM -static void init_lib(void) __attribute__ ((constructor)); +static void init_lib(void) __attribute__((constructor)); static void init_lib(void) { CKM::SetupClientLogSystem(); } -static void fini_lib(void) __attribute__ ((destructor)); +static void fini_lib(void) __attribute__((destructor)); static void fini_lib(void) { - } diff --git a/src/manager/client/client-common.h b/src/manager/client/client-common.h index 4d173a7d..ac391dda 100644 --- a/src/manager/client/client-common.h +++ b/src/manager/client/client-common.h @@ -42,8 +42,7 @@ extern "C" { namespace CKM { -class AliasSupport -{ +class AliasSupport { public: AliasSupport(const Alias &alias); @@ -52,6 +51,7 @@ class AliasSupport bool isLabelEmpty() const; static Alias merge(const Label &label, const Name &alias); + private: Name m_name; Label m_label; @@ -89,6 +89,7 @@ class ServiceConnection { int receive(CKM::MessageBuffer &recv_buf); virtual ~ServiceConnection(); + protected: int prepareConnection(); diff --git a/src/manager/client/client-control.cpp b/src/manager/client/client-control.cpp index 37cbf666..62db1487 100644 --- a/src/manager/client/client-control.cpp +++ b/src/manager/client/client-control.cpp @@ -38,11 +38,11 @@ public: ControlImpl& operator=(const ControlImpl &) = delete; ControlImpl& operator=(ControlImpl &&) = delete; - virtual int unlockUserKey(uid_t user, const Password &password) { + virtual int unlockUserKey(uid_t user, const Password &password) + { return try_catch([&] { - if((int)user < 0) { + if ((int)user < 0) return CKM_API_ERROR_INPUT_PARAM; - } MessageBuffer recv; auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::UNLOCK_USER_KEY), @@ -59,11 +59,11 @@ public: }); } - virtual int lockUserKey(uid_t user) { + virtual int lockUserKey(uid_t user) + { return try_catch([&] { - if((int)user < 0) { + if ((int)user < 0) return CKM_API_ERROR_INPUT_PARAM; - } MessageBuffer recv; auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::LOCK_USER_KEY), user); @@ -78,11 +78,11 @@ public: }); } - virtual int removeUserData(uid_t user) { + virtual int removeUserData(uid_t user) + { return try_catch([&] { - if((int)user < 0) { + if ((int)user < 0) return CKM_API_ERROR_INPUT_PARAM; - } MessageBuffer recv; auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::REMOVE_USER_DATA), user); @@ -97,11 +97,11 @@ public: }); } - virtual int changeUserPassword(uid_t user, const Password &oldPassword, const Password &newPassword) { + virtual int changeUserPassword(uid_t user, const Password &oldPassword, const Password &newPassword) + { return try_catch([&] { - if((int)user < 0) { + if ((int)user < 0) return CKM_API_ERROR_INPUT_PARAM; - } MessageBuffer recv; auto send = MessageBuffer::Serialize( @@ -120,11 +120,11 @@ public: }); } - virtual int resetUserPassword(uid_t user, const Password &newPassword) { + virtual int resetUserPassword(uid_t user, const Password &newPassword) + { return try_catch([&] { - if((int)user < 0) { + if ((int)user < 0) return CKM_API_ERROR_INPUT_PARAM; - } MessageBuffer recv; auto send = MessageBuffer::Serialize( @@ -142,11 +142,11 @@ public: }); } - virtual int removeApplicationData(const Label &smackLabel) { + virtual int removeApplicationData(const Label &smackLabel) + { return try_catch([&] { - if (smackLabel.empty()) { + if (smackLabel.empty()) return CKM_API_ERROR_INPUT_PARAM; - } MessageBuffer recv; auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::REMOVE_APP_DATA), smackLabel); @@ -161,7 +161,8 @@ public: }); } - virtual int updateCCMode() { + virtual int updateCCMode() + { return try_catch([&] { MessageBuffer recv; auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::UPDATE_CC_MODE)); @@ -203,12 +204,16 @@ public: }); } - virtual ~ControlImpl(){} + virtual ~ControlImpl() + { + } + private: CKM::ServiceConnection m_controlConnection; }; -ControlShPtr Control::create() { +ControlShPtr Control::create() +{ try { return std::make_shared<ControlImpl>(); } catch (const std::bad_alloc &) { diff --git a/src/manager/client/client-error.cpp b/src/manager/client/client-error.cpp index 94b228d4..fc018e34 100644 --- a/src/manager/client/client-error.cpp +++ b/src/manager/client/client-error.cpp @@ -24,9 +24,11 @@ #define ERRORDESCRIBE(name) case name: return #name namespace CKM { -__attribute__ ((visibility ("default"))) -const char * ErrorToString(int error) { - switch(error) { +__attribute__((visibility("default"))) + +const char * ErrorToString(int error) +{ + switch (error) { ERRORDESCRIBE(CKM_API_SUCCESS); ERRORDESCRIBE(CKM_API_ERROR_SOCKET); ERRORDESCRIBE(CKM_API_ERROR_BAD_REQUEST); diff --git a/src/manager/client/client-manager-impl.cpp b/src/manager/client/client-manager-impl.cpp index d6a464e4..17b79b7a 100644 --- a/src/manager/client/client-manager-impl.cpp +++ b/src/manager/client/client-manager-impl.cpp @@ -47,7 +47,6 @@ int getCertChain( CertificateShPtrVector &certificateChainVector) { return try_catch([&] { - MessageBuffer recv; auto send = MessageBuffer::Serialize(static_cast<int>(command), counter, @@ -65,13 +64,11 @@ int getCertChain( RawBufferVector rawBufferVector; recv.Deserialize(retCommand, retCounter, retCode, rawBufferVector); - if ((counter != retCounter) || (static_cast<int>(command) != retCommand)) { + if ((counter != retCounter) || (static_cast<int>(command) != retCommand)) return CKM_API_ERROR_UNKNOWN; - } - if (retCode != CKM_API_SUCCESS) { + if (retCode != CKM_API_SUCCESS) return retCode; - } for (auto &e: rawBufferVector) { CertificateShPtr cert(new CertificateImpl(e, DataFormat::FORM_DER)); @@ -134,12 +131,13 @@ int Manager::Impl::saveBinaryData( }); } -int Manager::Impl::saveKey(const Alias &alias, const KeyShPtr &key, const Policy &policy) { +int Manager::Impl::saveKey(const Alias &alias, const KeyShPtr &key, const Policy &policy) +{ if (key.get() == NULL) return CKM_API_ERROR_INPUT_PARAM; Try { return saveBinaryData(alias, DataType(key->getType()), key->getDER(), policy); - } Catch (DataType::Exception::Base) { + } Catch(DataType::Exception::Base) { LogError("Error in key conversion. Could not convert KeyType::NONE to DBDataType!"); } return CKM_API_ERROR_INPUT_PARAM; @@ -155,7 +153,8 @@ int Manager::Impl::saveCertificate( return saveBinaryData(alias, DataType::CERTIFICATE, cert->getDER(), policy); } -int Manager::Impl::saveData(const Alias &alias, const RawBuffer &rawData, const Policy &policy) { +int Manager::Impl::saveData(const Alias &alias, const RawBuffer &rawData, const Policy &policy) +{ if (!policy.extractable) return CKM_API_ERROR_INPUT_PARAM; return saveBinaryData(alias, DataType::BINARY_DATA, rawData, policy); @@ -168,7 +167,7 @@ int Manager::Impl::savePKCS12( const Policy &keyPolicy, const Policy &certPolicy) { - if (alias.empty() || pkcs.get()==NULL) + if (alias.empty() || pkcs.get() == NULL) return CKM_API_ERROR_INPUT_PARAM; int my_counter = ++m_counter; @@ -309,7 +308,8 @@ int Manager::Impl::getBinaryData( }); } -int Manager::Impl::getKey(const Alias &alias, const Password &password, KeyShPtr &key) { +int Manager::Impl::getKey(const Alias &alias, const Password &password, KeyShPtr &key) +{ DataType recvDataType; RawBuffer rawData; @@ -324,7 +324,7 @@ int Manager::Impl::getKey(const Alias &alias, const Password &password, KeyShPtr return retCode; KeyShPtr keyParsed; - if(DataType::KEY_AES == recvDataType) + if (DataType::KEY_AES == recvDataType) keyParsed = KeyShPtr(new KeyAESImpl(rawData)); else keyParsed = KeyShPtr(new KeyImpl(rawData)); @@ -406,28 +406,30 @@ int Manager::Impl::getBinaryDataAliasVector(DataType dataType, AliasVector &alia int tmpDataType; LabelNameVector labelNameVector; recv.Deserialize(command, counter, retCode, tmpDataType, labelNameVector); - if ((command != static_cast<int>(LogicCommand::GET_LIST)) || (counter != my_counter)) { + if ((command != static_cast<int>(LogicCommand::GET_LIST)) || (counter != my_counter)) return CKM_API_ERROR_UNKNOWN; - } - for(const auto &it : labelNameVector) - aliasVector.push_back( AliasSupport::merge(it.first, it.second) ); + for (const auto &it : labelNameVector) + aliasVector.push_back(AliasSupport::merge(it.first, it.second)); return retCode; }); } -int Manager::Impl::getKeyAliasVector(AliasVector &aliasVector) { +int Manager::Impl::getKeyAliasVector(AliasVector &aliasVector) +{ // in fact datatype has no meaning here - if not certificate or binary data // then manager decides to list all between DB_KEY_FIRST and DB_KEY_LAST return getBinaryDataAliasVector(DataType::DB_KEY_LAST, aliasVector); } -int Manager::Impl::getCertificateAliasVector(AliasVector &aliasVector) { +int Manager::Impl::getCertificateAliasVector(AliasVector &aliasVector) +{ return getBinaryDataAliasVector(DataType::CERTIFICATE, aliasVector); } -int Manager::Impl::getDataAliasVector(AliasVector &aliasVector) { +int Manager::Impl::getDataAliasVector(AliasVector &aliasVector) +{ return getBinaryDataAliasVector(DataType::BINARY_DATA, aliasVector); } @@ -470,7 +472,6 @@ int Manager::Impl::createKeyAES( int my_counter = ++m_counter; return try_catch([&] { - MessageBuffer recv; AliasSupport aliasHelper(keyAlias); auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES), @@ -487,9 +488,8 @@ int Manager::Impl::createKeyAES( int command; int counter; recv.Deserialize(command, counter, retCode); - if (counter != my_counter) { + if (counter != my_counter) return CKM_API_ERROR_UNKNOWN; - } return retCode; }); @@ -506,8 +506,7 @@ int Manager::Impl::createKeyPair( { // input type check CryptoAlgorithm keyGenAlgorithm; - switch(key_type) - { + switch (key_type) { case KeyType::KEY_RSA_PUBLIC: case KeyType::KEY_RSA_PRIVATE: keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::RSA_GEN); @@ -534,7 +533,6 @@ int Manager::Impl::createKeyPair( int my_counter = ++m_counter; return try_catch([&] { - MessageBuffer recv; AliasSupport privateHelper(privateKeyAlias); AliasSupport publicHelper(publicKeyAlias); @@ -555,9 +553,8 @@ int Manager::Impl::createKeyPair( int command; int counter; recv.Deserialize(command, counter, retCode); - if (counter != my_counter) { + if (counter != my_counter) return CKM_API_ERROR_UNKNOWN; - } return retCode; }); @@ -573,15 +570,14 @@ int Manager::Impl::getCertificateChain( RawBufferVector untrustedVector; RawBufferVector trustedVector; - if(!certificate || certificate->empty()) + if (!certificate || certificate->empty()) return CKM_API_ERROR_INPUT_PARAM; - for (auto &e: untrustedCertificates) { + for (auto &e: untrustedCertificates) untrustedVector.push_back(e->getDER()); - } - for (auto &e: trustedCertificates) { + + for (auto &e: trustedCertificates) trustedVector.push_back(e->getDER()); - } return getCertChain( m_storageConnection, @@ -604,7 +600,7 @@ int Manager::Impl::getCertificateChain( LabelNameVector untrustedVector; LabelNameVector trustedVector; - if(!certificate || certificate->empty()) + if (!certificate || certificate->empty()) return CKM_API_ERROR_INPUT_PARAM; for (auto &e: untrustedCertificates) { @@ -637,7 +633,6 @@ int Manager::Impl::createSignature( int my_counter = ++m_counter; return try_catch([&] { - MessageBuffer recv; AliasSupport helper(privateKeyAlias); auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_SIGNATURE), @@ -658,9 +653,7 @@ int Manager::Impl::createSignature( if ((command != static_cast<int>(LogicCommand::CREATE_SIGNATURE)) || (counter != my_counter)) - { return CKM_API_ERROR_UNKNOWN; - } return retCode; }); @@ -697,9 +690,7 @@ int Manager::Impl::verifySignature( if ((command != static_cast<int>(LogicCommand::VERIFY_SIGNATURE)) || (counter != my_counter)) - { return CKM_API_ERROR_UNKNOWN; - } return retCode; }); @@ -729,9 +720,8 @@ int Manager::Impl::ocspCheck(const CertificateShPtrVector &certChain, int &ocspS int counter; recv.Deserialize(counter, retCode, ocspStatus); - if (my_counter != counter) { + if (my_counter != counter) return CKM_API_ERROR_UNKNOWN; - } return retCode; }); @@ -761,9 +751,8 @@ int Manager::Impl::setPermission(const Alias &alias, int counter; recv.Deserialize(command, counter, retCode); - if (my_counter != counter) { + if (my_counter != counter) return CKM_API_ERROR_UNKNOWN; - } return retCode; }); @@ -798,9 +787,8 @@ int Manager::Impl::crypt(EncryptionCommand command, int counter; recv.Deserialize(retCommand, counter, retCode, output); - if (my_counter != counter || retCommand != static_cast<int>(command)) { + if (my_counter != counter || retCommand != static_cast<int>(command)) return CKM_API_ERROR_UNKNOWN; - } return retCode; }); diff --git a/src/manager/client/client-manager-impl.h b/src/manager/client/client-manager-impl.h index 29d381dd..98010f9e 100644..100755 --- a/src/manager/client/client-manager-impl.h +++ b/src/manager/client/client-manager-impl.h @@ -31,7 +31,7 @@ namespace CKM { class Manager::Impl { public: Impl(); - virtual ~Impl(){} + virtual ~Impl() {} int saveKey(const Alias &alias, const KeyShPtr &key, const Policy &policy); int getKey(const Alias &alias, const Password &password, KeyShPtr &key); diff --git a/src/manager/client/client-manager.cpp b/src/manager/client/client-manager.cpp index 275b545b..1e7c8eff 100644 --- a/src/manager/client/client-manager.cpp +++ b/src/manager/client/client-manager.cpp @@ -30,13 +30,15 @@ Manager::Manager() : m_impl(new Impl()) {} -Manager::~Manager(){} +Manager::~Manager() {} -int Manager::saveKey(const Alias &alias, const KeyShPtr &key, const Policy &policy) { +int Manager::saveKey(const Alias &alias, const KeyShPtr &key, const Policy &policy) +{ return m_impl->saveKey(alias, key, policy); } -int Manager::saveCertificate(const Alias &alias, const CertificateShPtr &cert, const Policy &policy) { +int Manager::saveCertificate(const Alias &alias, const CertificateShPtr &cert, const Policy &policy) +{ return m_impl->saveCertificate(alias, cert, policy); } @@ -49,15 +51,18 @@ int Manager::savePKCS12( return m_impl->savePKCS12(alias, pkcs, keyPolicy, certPolicy); } -int Manager::saveData(const Alias &alias, const RawBuffer &data, const Policy &policy) { +int Manager::saveData(const Alias &alias, const RawBuffer &data, const Policy &policy) +{ return m_impl->saveData(alias, data, policy); } -int Manager::removeAlias(const Alias &alias) { +int Manager::removeAlias(const Alias &alias) +{ return m_impl->removeAlias(alias); } -int Manager::getKey(const Alias &alias, const Password &password, KeyShPtr &key) { +int Manager::getKey(const Alias &alias, const Password &password, KeyShPtr &key) +{ return m_impl->getKey(alias, password, key); } @@ -69,11 +74,13 @@ int Manager::getCertificate( return m_impl->getCertificate(alias, password, certificate); } -int Manager::getData(const Alias &alias, const Password &password, RawBuffer &data) { +int Manager::getData(const Alias &alias, const Password &password, RawBuffer &data) +{ return m_impl->getData(alias, password, data); } -int Manager::getPKCS12(const Alias &alias, PKCS12ShPtr &pkcs) { +int Manager::getPKCS12(const Alias &alias, PKCS12ShPtr &pkcs) +{ return m_impl->getPKCS12(alias, pkcs); } @@ -86,15 +93,18 @@ int Manager::getPKCS12( return m_impl->getPKCS12(alias, keyPass, certPass, pkcs); } -int Manager::getKeyAliasVector(AliasVector &aliasVector) { +int Manager::getKeyAliasVector(AliasVector &aliasVector) +{ return m_impl->getKeyAliasVector(aliasVector); } -int Manager::getCertificateAliasVector(AliasVector &aliasVector) { +int Manager::getCertificateAliasVector(AliasVector &aliasVector) +{ return m_impl->getCertificateAliasVector(aliasVector); } -int Manager::getDataAliasVector(AliasVector &aliasVector) { +int Manager::getDataAliasVector(AliasVector &aliasVector) +{ return m_impl->getDataAliasVector(aliasVector); } @@ -204,7 +214,8 @@ int Manager::verifySignature( cAlg); } -int Manager::ocspCheck(const CertificateShPtrVector &certificateChainVector, int &ocspStatus) { +int Manager::ocspCheck(const CertificateShPtrVector &certificateChainVector, int &ocspStatus) +{ return m_impl->ocspCheck(certificateChainVector, ocspStatus); } @@ -236,7 +247,8 @@ int Manager::decrypt( return m_impl->decrypt(algo, keyAlias, password, encrypted, decrypted); } -ManagerShPtr Manager::create() { +ManagerShPtr Manager::create() +{ try { return std::make_shared<Manager>(); } catch (...) { diff --git a/src/manager/common/algo-param.cpp b/src/manager/common/algo-param.cpp index 54799e9a..9f8f4a65 100644 --- a/src/manager/common/algo-param.cpp +++ b/src/manager/common/algo-param.cpp @@ -22,8 +22,7 @@ #include <ckm/ckm-type.h> #include <cassert> -namespace CKM -{ +namespace CKM { bool CryptoAlgorithm::BufferParam::getBuffer(RawBuffer& buffer) const { diff --git a/src/manager/common/base64.cpp b/src/manager/common/base64.cpp index ad94d4b6..47ad1e9d 100644..100755 --- a/src/manager/common/base64.cpp +++ b/src/manager/common/base64.cpp @@ -41,9 +41,9 @@ void Base64Encoder::append(const RawBuffer &data) ThrowMsg(Exception::AlreadyFinalized, "Already finalized"); } - if (!m_b64) { + if (!m_b64) reset(); - } + BIO_write(m_b64, data.data(), data.size()); } @@ -70,9 +70,9 @@ RawBuffer Base64Encoder::get() ThrowMsg(Exception::InternalError, "Bio internal error"); } - if (bptr->length > 0) { + if (bptr->length > 0) return RawBuffer(bptr->data, bptr->data + bptr->length); - } + return RawBuffer(); } @@ -129,14 +129,13 @@ bool Base64Decoder::finalize() whiteCharacter), m_input.end()); - for (size_t i = 0; i<m_input.size(); ++i) { + for (size_t i = 0; i < m_input.size(); ++i) { if (isalnum(m_input[i]) || m_input[i] == '+' || m_input[i] == '/' || m_input[i] == '=') - { continue; - } + LogError("Base64 input contains illegal chars: " << m_input[i]); return false; } diff --git a/src/manager/common/base64.h b/src/manager/common/base64.h index 89e62852..8a69c626 100644 --- a/src/manager/common/base64.h +++ b/src/manager/common/base64.h @@ -28,13 +28,11 @@ typedef bio_st BIO; namespace CKM { -class COMMON_API Base64Encoder -{ +class COMMON_API Base64Encoder { public: NONCOPYABLE(Base64Encoder) - class Exception - { + class Exception { public: DECLARE_EXCEPTION_TYPE(CKM::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, InternalError) @@ -54,13 +52,11 @@ class COMMON_API Base64Encoder bool m_finalized; }; -class COMMON_API Base64Decoder -{ +class COMMON_API Base64Decoder { public: NONCOPYABLE(Base64Decoder) - class Exception - { + class Exception { public: DECLARE_EXCEPTION_TYPE(CKM::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, InternalError) diff --git a/src/manager/common/certificate-impl.cpp b/src/manager/common/certificate-impl.cpp index 0577958c..97cd4bd0 100644..100755 --- a/src/manager/common/certificate-impl.cpp +++ b/src/manager/common/certificate-impl.cpp @@ -65,8 +65,8 @@ CertificateImpl::CertificateImpl(const RawBuffer &der, DataFormat format) if (!m_x509) { // TODO LogError("Certificate could not be parsed."); -// ThrowMsg(Exception::OpensslInternalError, -// "Internal Openssl error in d2i_X509 function."); +// ThrowMsg(Exception::OpensslInternalError, +// "Internal Openssl error in d2i_X509 function."); } } @@ -78,20 +78,23 @@ CertificateImpl::CertificateImpl(X509 *x509, bool duplicate) m_x509 = x509; } -CertificateImpl::CertificateImpl(const CertificateImpl &second){ +CertificateImpl::CertificateImpl(const CertificateImpl &second) +{ m_x509 = X509_dup(second.m_x509); } -CertificateImpl::CertificateImpl(CertificateImpl &&second) { +CertificateImpl::CertificateImpl(CertificateImpl &&second) +{ m_x509 = second.m_x509; second.m_x509 = NULL; LogDebug("Certificate moved: " << (void*)m_x509); } -CertificateImpl& CertificateImpl::operator=(CertificateImpl &&second) { +CertificateImpl& CertificateImpl::operator=(CertificateImpl &&second) +{ if (this == &second) return *this; - if(m_x509) + if (m_x509) X509_free(m_x509); m_x509 = second.m_x509; second.m_x509 = NULL; @@ -99,20 +102,23 @@ CertificateImpl& CertificateImpl::operator=(CertificateImpl &&second) { return *this; } -CertificateImpl& CertificateImpl::operator=(const CertificateImpl &second) { +CertificateImpl& CertificateImpl::operator=(const CertificateImpl &second) +{ if (this == &second) return *this; - if(m_x509) + if (m_x509) X509_free(m_x509); m_x509 = X509_dup(second.m_x509); return *this; } -X509* CertificateImpl::getX509() const { +X509* CertificateImpl::getX509() const +{ return m_x509; } -RawBuffer CertificateImpl::getDER(void) const { +RawBuffer CertificateImpl::getDER(void) const +{ unsigned char *rawDer = NULL; int size = i2d_X509(m_x509, &rawDer); if (!rawDer || size <= 0) { @@ -127,18 +133,20 @@ RawBuffer CertificateImpl::getDER(void) const { return output; } -bool CertificateImpl::empty() const { +bool CertificateImpl::empty() const +{ return m_x509 == NULL; } -KeyImpl::EvpShPtr CertificateImpl::getEvpShPtr() const { +KeyImpl::EvpShPtr CertificateImpl::getEvpShPtr() const +{ return KeyImpl::EvpShPtr(X509_get_pubkey(m_x509), EVP_PKEY_free); } -KeyImpl CertificateImpl::getKeyImpl() const { +KeyImpl CertificateImpl::getKeyImpl() const +{ KeyImpl::EvpShPtr evp(X509_get_pubkey(m_x509), EVP_PKEY_free); - switch(EVP_PKEY_type(evp->type)) - { + switch (EVP_PKEY_type(evp->type)) { case EVP_PKEY_RSA: return KeyImpl(evp, KeyType::KEY_RSA_PUBLIC); case EVP_PKEY_DSA: @@ -152,7 +160,8 @@ KeyImpl CertificateImpl::getKeyImpl() const { return KeyImpl(); } -X509_NAME *getX509Name(X509 *x509, CertificateFieldId type) { +X509_NAME *getX509Name(X509 *x509, CertificateFieldId type) +{ if (!x509) return NULL; @@ -176,7 +185,8 @@ std::string CertificateImpl::getOneLine(CertificateFieldId type) const return std::string(buffer); } -std::string CertificateImpl::getField(CertificateFieldId type, int fieldNid) const { +std::string CertificateImpl::getField(CertificateFieldId type, int fieldNid) const +{ X509_NAME *subjectName = getX509Name(m_x509, type); X509_NAME_ENTRY *subjectEntry = NULL; @@ -188,17 +198,15 @@ std::string CertificateImpl::getField(CertificateFieldId type, int fieldNid) con for (int i = 0; i < entryCount; ++i) { subjectEntry = X509_NAME_get_entry(subjectName, i); - if (!subjectEntry) { + if (!subjectEntry) continue; - } int nid = OBJ_obj2nid( static_cast<ASN1_OBJECT*>( X509_NAME_ENTRY_get_object(subjectEntry))); - if (nid != fieldNid) { + if (nid != fieldNid) continue; - } ASN1_STRING* pASN1Str = subjectEntry->value; @@ -217,35 +225,43 @@ std::string CertificateImpl::getField(CertificateFieldId type, int fieldNid) con return std::string(); } -std::string CertificateImpl::getCommonName(CertificateFieldId type) const { +std::string CertificateImpl::getCommonName(CertificateFieldId type) const +{ return getField(type, NID_commonName); } -std::string CertificateImpl::getCountryName(CertificateFieldId type) const { +std::string CertificateImpl::getCountryName(CertificateFieldId type) const +{ return getField(type, NID_countryName); } -std::string CertificateImpl::getStateOrProvinceName(CertificateFieldId type) const { +std::string CertificateImpl::getStateOrProvinceName(CertificateFieldId type) const +{ return getField(type, NID_stateOrProvinceName); } -std::string CertificateImpl::getLocalityName(CertificateFieldId type) const { +std::string CertificateImpl::getLocalityName(CertificateFieldId type) const +{ return getField(type, NID_localityName); } -std::string CertificateImpl::getOrganizationName(CertificateFieldId type) const { +std::string CertificateImpl::getOrganizationName(CertificateFieldId type) const +{ return getField(type, NID_organizationName); } -std::string CertificateImpl::getOrganizationalUnitName(CertificateFieldId type) const { +std::string CertificateImpl::getOrganizationalUnitName(CertificateFieldId type) const +{ return getField(type, NID_organizationalUnitName); } -std::string CertificateImpl::getEmailAddres(CertificateFieldId type) const { +std::string CertificateImpl::getEmailAddres(CertificateFieldId type) const +{ return getField(type, NID_pkcs9_emailAddress); } -std::string CertificateImpl::getOCSPURL() const { +std::string CertificateImpl::getOCSPURL() const +{ if (!m_x509) return std::string(); @@ -259,12 +275,14 @@ std::string CertificateImpl::getOCSPURL() const { return result; } -CertificateImpl::~CertificateImpl() { - if(m_x509) +CertificateImpl::~CertificateImpl() +{ + if (m_x509) X509_free(m_x509); } -CertificateShPtr Certificate::create(const RawBuffer &rawBuffer, DataFormat format) { +CertificateShPtr Certificate::create(const RawBuffer &rawBuffer, DataFormat format) +{ try { CertificateShPtr output = std::make_shared<CertificateImpl>(rawBuffer, format); if (output->empty()) diff --git a/src/manager/common/certificate-impl.h b/src/manager/common/certificate-impl.h index e66f5eaa..106a19a6 100644 --- a/src/manager/common/certificate-impl.h +++ b/src/manager/common/certificate-impl.h @@ -60,6 +60,7 @@ public: std::string getOCSPURL() const; virtual ~CertificateImpl(); + protected: X509* m_x509; }; diff --git a/src/manager/common/connection-info.h b/src/manager/common/connection-info.h index b4d22f65..c0ea3ad3 100644 --- a/src/manager/common/connection-info.h +++ b/src/manager/common/connection-info.h @@ -30,8 +30,7 @@ #include <generic-socket-manager.h> #include <message-buffer.h> -namespace CKM -{ +namespace CKM { struct ConnectionInfo { InterfaceID interfaceID; MessageBuffer buffer; diff --git a/src/manager/common/crypto-init.cpp b/src/manager/common/crypto-init.cpp index 18d6d8c9..37fea8a0 100644..100755 --- a/src/manager/common/crypto-init.cpp +++ b/src/manager/common/crypto-init.cpp @@ -47,7 +47,7 @@ std::mutex* g_mutexes = NULL; void lockingCallback(int mode, int type, const char*, int) { - if(!g_mutexes) { + if (!g_mutexes) { LogError("Openssl mutexes do not exist"); return; } @@ -58,7 +58,8 @@ void lockingCallback(int mode, int type, const char*, int) g_mutexes[type].unlock(); } -unsigned long threadIdCallback() { +unsigned long threadIdCallback() +{ std::hash<std::thread::id> hasher; return hasher(std::this_thread::get_id()); } @@ -83,7 +84,8 @@ void opensslUninstallLocks() } // namespace anonymous -void initOpenSsl() { +void initOpenSsl() +{ // Loads all error strings (crypto and ssl) SSL_load_error_strings(); @@ -104,9 +106,8 @@ void initOpenSsl() { OPENSSL_config(NULL); // enable FIPS mode by default - if(0 == FIPS_mode_set(1)) { + if (0 == FIPS_mode_set(1)) LogWarning("Failed to set FIPS mode. Key-manager will be operated in non FIPS mode."); - } /* * Initialize entropy @@ -115,14 +116,14 @@ void initOpenSsl() { int ret = 0; std::ifstream ifile(DEV_HW_RANDOM_FILE); - if(ifile.is_open()) - ret= RAND_load_file(DEV_HW_RANDOM_FILE, RANDOM_BUFFER_LEN); + if (ifile.is_open()) + ret = RAND_load_file(DEV_HW_RANDOM_FILE, RANDOM_BUFFER_LEN); - if(ret != RANDOM_BUFFER_LEN ){ + if (ret != RANDOM_BUFFER_LEN) { LogWarning("Error in HW_RAND file load"); ret = RAND_load_file(DEV_URANDOM_FILE, RANDOM_BUFFER_LEN); - if(ret != RANDOM_BUFFER_LEN) + if (ret != RANDOM_BUFFER_LEN) LogError("Error in U_RAND_file_load"); } @@ -130,7 +131,8 @@ void initOpenSsl() { opensslInstallLocks(); } -void deinitOpenSsl() { +void deinitOpenSsl() +{ opensslUninstallLocks(); CONF_modules_unload(1); EVP_cleanup(); @@ -138,7 +140,8 @@ void deinitOpenSsl() { deinitOpenSslThread(); } -void deinitOpenSslThread() { +void deinitOpenSslThread() +{ CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); } @@ -151,19 +154,19 @@ void initOpenSslAndDetach(); typedef void(*initFnPtr)(); // has to be atomic as storing function pointer is not an atomic operation on armv7l -std::atomic<initFnPtr> initFn (&initOpenSslAndDetach); +std::atomic<initFnPtr> initFn(&initOpenSslAndDetach); void initEmpty() {} -void initOpenSslAndDetach() { +void initOpenSslAndDetach() +{ // DCLP std::lock_guard<std::mutex> lock(cryptoInitMutex); /* * We don't care about memory ordering here. Current thread will order it correctly and for * other threads only store matters. Also only one thread can be here at once because of lock. */ - if(initFn.load(std::memory_order_relaxed) != &initEmpty) - { + if (initFn.load(std::memory_order_relaxed) != &initEmpty) { initOpenSsl(); /* @@ -177,7 +180,8 @@ void initOpenSslAndDetach() { } // namespace anonymous -void initOpenSslOnce() { +void initOpenSslOnce() +{ /* * Synchronizes with store. Everything that happened before store in another thread will be * visible in this thread after load. diff --git a/src/manager/common/data-type.cpp b/src/manager/common/data-type.cpp index a7fcf636..35701bc7 100644..100755 --- a/src/manager/common/data-type.cpp +++ b/src/manager/common/data-type.cpp @@ -21,12 +21,12 @@ #include <data-type.h> -namespace CKM -{ +namespace CKM { -DataType::DataType() - : m_dataType(BINARY_DATA) -{} +DataType::DataType() : + m_dataType(BINARY_DATA) +{ +} DataType::DataType(Type data) : m_dataType(data) @@ -37,7 +37,7 @@ DataType::DataType(Type data) } DataType::DataType(KeyType key) { - switch(key) { + switch (key) { case KeyType::KEY_RSA_PUBLIC: m_dataType = DataType::KEY_RSA_PUBLIC; break; case KeyType::KEY_RSA_PRIVATE: m_dataType = DataType::KEY_RSA_PRIVATE; break; case KeyType::KEY_DSA_PUBLIC: m_dataType = DataType::KEY_DSA_PUBLIC; break; @@ -51,8 +51,9 @@ DataType::DataType(KeyType key) { } } -DataType::DataType(AlgoType algorithmType) { - switch(algorithmType) { +DataType::DataType(AlgoType algorithmType) +{ + switch (algorithmType) { case AlgoType::AES_CTR: case AlgoType::AES_CBC: case AlgoType::AES_GCM: @@ -72,19 +73,21 @@ DataType::DataType(AlgoType algorithmType) { } } -DataType::DataType(int data) - : m_dataType(static_cast<Type>(data)) +DataType::DataType(int data) : + m_dataType(static_cast<Type>(data)) { if (!isInRange(data)) ThrowMsg(Exception::OutOfRange, "Invalid conversion from int=" << data << " to DBDataType"); } -DataType::operator int () const { +DataType::operator int () const +{ return static_cast<int>(m_dataType); } -DataType::operator KeyType () const { - switch(m_dataType) { +DataType::operator KeyType () const +{ + switch (m_dataType) { case DataType::KEY_RSA_PUBLIC: return KeyType::KEY_RSA_PUBLIC; case DataType::KEY_RSA_PRIVATE: return KeyType::KEY_RSA_PRIVATE; case DataType::KEY_DSA_PUBLIC: return KeyType::KEY_DSA_PUBLIC; @@ -95,31 +98,36 @@ DataType::operator KeyType () const { default: ThrowMsg(Exception::OutOfRange, "Invalid conversion from DBDataType=" << static_cast<int>(m_dataType) << - " to KeyType" ); + " to KeyType"); } } -bool DataType::operator==(const DataType &second) const { +bool DataType::operator==(const DataType &second) const +{ return m_dataType == second.m_dataType; } -bool DataType::isKey() const { +bool DataType::isKey() const +{ if (DB_KEY_FIRST <= m_dataType && DB_KEY_LAST >= m_dataType) return true; return false; } -bool DataType::isSKey() const { +bool DataType::isSKey() const +{ return (KEY_AES == m_dataType); } -bool DataType::isChainCert() const { +bool DataType::isChainCert() const +{ if (DB_CHAIN_FIRST <= m_dataType && DB_CHAIN_LAST >= m_dataType) return true; return false; } -bool DataType::isKeyPrivate() const { +bool DataType::isKeyPrivate() const +{ switch (m_dataType) { case KEY_RSA_PRIVATE: case KEY_DSA_PRIVATE: @@ -130,7 +138,8 @@ bool DataType::isKeyPrivate() const { } } -bool DataType::isKeyPublic() const { +bool DataType::isKeyPublic() const +{ switch (m_dataType) { case KEY_RSA_PUBLIC: case KEY_DSA_PUBLIC: @@ -141,15 +150,18 @@ bool DataType::isKeyPublic() const { } } -bool DataType::isCertificate() const { +bool DataType::isCertificate() const +{ return m_dataType == CERTIFICATE; } -bool DataType::isBinaryData() const { +bool DataType::isBinaryData() const +{ return m_dataType == BINARY_DATA; } -bool DataType::isInRange(int data) { +bool DataType::isInRange(int data) +{ if (data < static_cast<int>(DB_FIRST)) return false; if (data > static_cast<int>(DB_LAST)) diff --git a/src/manager/common/data-type.h b/src/manager/common/data-type.h index b3026bb5..4cb7814e 100644 --- a/src/manager/common/data-type.h +++ b/src/manager/common/data-type.h @@ -96,7 +96,7 @@ public: static DataType getChainDatatype(unsigned int index); // it's not virtual for a reason! - ~DataType(){} + ~DataType() {} private: Type m_dataType; diff --git a/src/manager/common/exception.h b/src/manager/common/exception.h index 2c9ffe97..4b950f22 100644 --- a/src/manager/common/exception.h +++ b/src/manager/common/exception.h @@ -44,11 +44,13 @@ public: virtual ~Exception() noexcept {} - virtual const char *what(void) const noexcept { + virtual const char *what(void) const noexcept + { return m_message.c_str(); } - virtual std::string message(void) const { + virtual std::string message(void) const + { std::ostringstream msg; msg << "[" << m_path << ":" << m_line << " " << m_function << "()] " << m_message; return msg.str(); @@ -80,12 +82,14 @@ public: DefineException(const char *path, const char *function, int line, const Args&... args) : Exception(path, function, line, Stringify::Merge(args...)) { - Before(m_path, m_function, m_line, DefineException<Error,Stringify,Before,After>::error(), m_message); + Before(m_path, m_function, m_line, DefineException<Error, Stringify, Before, After>::error(), m_message); } - ~DefineException() noexcept { - After(m_path, m_function, m_line, DefineException<Error,Stringify,Before,After>::error(), m_message); + ~DefineException() noexcept + { + After(m_path, m_function, m_line, DefineException<Error, Stringify, Before, After>::error(), m_message); } - virtual int error(void) const { + virtual int error(void) const + { return Error; } }; diff --git a/src/manager/common/key-aes-impl.cpp b/src/manager/common/key-aes-impl.cpp index 10dba10a..b931f8f4 100644..100755 --- a/src/manager/common/key-aes-impl.cpp +++ b/src/manager/common/key-aes-impl.cpp @@ -27,35 +27,39 @@ namespace CKM { KeyAESImpl::KeyAESImpl(const RawBuffer &buf) : m_key(buf) { // buf stores bytes -> compare the bit sizes - switch(buf.size() * 8) - { - case 128: - case 192: - case 256: - break; + switch (buf.size() * 8) { + case 128: + case 192: + case 256: + break; - default: - throw std::invalid_argument("invalid AES key size"); + default: + throw std::invalid_argument("invalid AES key size"); } } -bool KeyAESImpl::empty() const { +bool KeyAESImpl::empty() const +{ return (getSize() == 0); } -KeyType KeyAESImpl::getType() const { +KeyType KeyAESImpl::getType() const +{ return KeyType::KEY_AES; } -RawBuffer KeyAESImpl::getDER() const { +RawBuffer KeyAESImpl::getDER() const +{ return m_key; } -int KeyAESImpl::getSize() const { +int KeyAESImpl::getSize() const +{ return m_key.size(); } -KeyShPtr Key::createAES(const RawBuffer &raw) { +KeyShPtr Key::createAES(const RawBuffer &raw) +{ try { KeyShPtr output = std::make_shared<KeyAESImpl>(raw); if (output->empty()) diff --git a/src/manager/common/key-impl.cpp b/src/manager/common/key-impl.cpp index a0349ef9..ab593fa3 100644..100755 --- a/src/manager/common/key-impl.cpp +++ b/src/manager/common/key-impl.cpp @@ -40,7 +40,8 @@ namespace { typedef std::unique_ptr<BIO, std::function<void(BIO*)>> BioUniquePtr; -int passcb(char *buff, int size, int rwflag, void *userdata) { +int passcb(char *buff, int size, int rwflag, void *userdata) +{ (void) rwflag; Password *ptr = static_cast<Password*>(userdata); if (ptr == NULL) @@ -55,7 +56,8 @@ 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::RawBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) +{ BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all); if (NULL == pkey) { @@ -91,16 +93,18 @@ CKM::RawBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) { KeyImpl::KeyImpl() : m_pkey(NULL, EVP_PKEY_free) , m_type(KeyType::KEY_NONE) -{} +{ +} -KeyImpl::KeyImpl(const KeyImpl &second) { +KeyImpl::KeyImpl(const KeyImpl &second) +{ m_pkey = second.m_pkey; m_type = second.m_type; } -KeyImpl::KeyImpl(const RawBuffer &buf, const Password &password) - : m_pkey(NULL, EVP_PKEY_free) - , m_type(KeyType::KEY_NONE) +KeyImpl::KeyImpl(const RawBuffer &buf, const Password &password) : + m_pkey(NULL, EVP_PKEY_free), + m_type(KeyType::KEY_NONE) { bool isPrivate = false; EVP_PKEY *pkey = NULL; @@ -147,8 +151,7 @@ KeyImpl::KeyImpl(const RawBuffer &buf, const Password &password) m_pkey.reset(pkey, EVP_PKEY_free); - switch(EVP_PKEY_type(pkey->type)) - { + switch (EVP_PKEY_type(pkey->type)) { case EVP_PKEY_RSA: m_type = isPrivate ? KeyType::KEY_RSA_PRIVATE : KeyType::KEY_RSA_PUBLIC; break; @@ -164,11 +167,12 @@ KeyImpl::KeyImpl(const RawBuffer &buf, const Password &password) LogDebug("KeyType is: " << (int)m_type << " isPrivate: " << isPrivate); } -KeyImpl::KeyImpl(EvpShPtr pkey, KeyType type) : m_pkey(pkey), m_type(type) +KeyImpl::KeyImpl(EvpShPtr pkey, KeyType type) : + m_pkey(pkey), + m_type(type) { int expected_type = EVP_PKEY_NONE; - switch(type) - { + switch (type) { case KeyType::KEY_RSA_PRIVATE: case KeyType::KEY_RSA_PUBLIC: expected_type = EVP_PKEY_RSA; @@ -195,36 +199,40 @@ KeyImpl::KeyImpl(EvpShPtr pkey, KeyType type) : m_pkey(pkey), m_type(type) // verify if actual key type matches the expected tpe int given_key_type = EVP_PKEY_type(pkey->type); - if(given_key_type==EVP_PKEY_NONE || expected_type!=given_key_type) - { + if (given_key_type == EVP_PKEY_NONE || expected_type != given_key_type) { m_pkey.reset(); m_type = KeyType::KEY_NONE; } } -bool KeyImpl::empty() const { +bool KeyImpl::empty() const +{ return m_pkey.get() == NULL; } -KeyImpl::EvpShPtr KeyImpl::getEvpShPtr() const { +KeyImpl::EvpShPtr KeyImpl::getEvpShPtr() const +{ return m_pkey; } -KeyType KeyImpl::getType() const { +KeyType KeyImpl::getType() const +{ return m_type; } -RawBuffer KeyImpl::getDERPRV() const { +RawBuffer KeyImpl::getDERPRV() const +{ return i2d(i2d_PrivateKey_bio, m_pkey.get()); } -RawBuffer KeyImpl::getDERPUB() const { +RawBuffer KeyImpl::getDERPUB() const +{ return i2d(i2d_PUBKEY_bio, m_pkey.get()); } -RawBuffer KeyImpl::getDER() const { - switch(m_type) - { +RawBuffer KeyImpl::getDER() const +{ + switch (m_type) { case KeyType::KEY_RSA_PRIVATE: case KeyType::KEY_DSA_PRIVATE: case KeyType::KEY_ECDSA_PRIVATE: @@ -241,7 +249,8 @@ RawBuffer KeyImpl::getDER() const { return RawBuffer(); } -KeyShPtr Key::create(const RawBuffer &raw, const Password &password) { +KeyShPtr Key::create(const RawBuffer &raw, const Password &password) +{ try { KeyShPtr output = std::make_shared<KeyImpl>(raw, password); if (output->empty()) diff --git a/src/manager/common/key-impl.h b/src/manager/common/key-impl.h index b40c586d..459405d5 100644 --- a/src/manager/common/key-impl.h +++ b/src/manager/common/key-impl.h @@ -43,17 +43,20 @@ public: virtual RawBuffer getDERPUB() const; virtual RawBuffer getDERPRV() const; virtual EvpShPtr getEvpShPtr() const; - virtual ElipticCurve getCurve() const { + virtual ElipticCurve getCurve() const + { // TODO return ElipticCurve::prime192v1; } - virtual int getSize() const { + virtual int getSize() const + { // TODO return 0; } virtual bool empty() const; - virtual ~KeyImpl(){} + virtual ~KeyImpl() {} + protected: EvpShPtr m_pkey; KeyType m_type; diff --git a/src/manager/common/log-setup.cpp b/src/manager/common/log-setup.cpp index ec994997..70207c0b 100644..100755 --- a/src/manager/common/log-setup.cpp +++ b/src/manager/common/log-setup.cpp @@ -38,8 +38,7 @@ bool logSystemReady = false; * Reads central-key-manager service environment file. This configuration may be later applied to * client so that it uses the same logging method. */ -class EnvFileParser -{ +class EnvFileParser { public: EnvFileParser(); virtual ~EnvFileParser() {} @@ -58,7 +57,7 @@ EnvFileParser::EnvFileParser() std::ifstream is(SYSTEMD_ENV_FILE); LogDebug("Reading env file: " SYSTEMD_ENV_FILE); - while(is.good()) { + while (is.good()) { std::string line; std::getline(is, line); @@ -66,8 +65,7 @@ EnvFileParser::EnvFileParser() if (0 == line.compare(0, PROVIDER_MATCH.size(), PROVIDER_MATCH)) { m_provider = line.substr(PROVIDER_MATCH.size()); LogDebug("Log provider: " << m_provider); - } - else if (0 == line.compare(0, LEVEL_MATCH.size(), LEVEL_MATCH)) { + } else if (0 == line.compare(0, LEVEL_MATCH.size(), LEVEL_MATCH)) { m_level = line.substr(LEVEL_MATCH.size()); LogDebug("Log level: " << m_level); } diff --git a/src/manager/common/message-buffer.cpp b/src/manager/common/message-buffer.cpp index bfecf372..166da553 100644 --- a/src/manager/common/message-buffer.cpp +++ b/src/manager/common/message-buffer.cpp @@ -29,11 +29,13 @@ namespace CKM { -void MessageBuffer::Push(const RawBuffer &data) { +void MessageBuffer::Push(const RawBuffer &data) +{ m_buffer.AppendCopy(&data[0], data.size()); } -RawBuffer MessageBuffer::Pop() { +RawBuffer MessageBuffer::Pop() +{ size_t size = m_buffer.Size(); RawBuffer buffer; buffer.resize(size + sizeof(size_t)); @@ -42,7 +44,8 @@ RawBuffer MessageBuffer::Pop() { return buffer; } -bool MessageBuffer::Ready() { +bool MessageBuffer::Ready() +{ CountBytesLeft(); if (m_bytesLeft == 0) return false; @@ -51,7 +54,8 @@ bool MessageBuffer::Ready() { return true; } -void MessageBuffer::Read(size_t num, void *bytes) { +void MessageBuffer::Read(size_t num, void *bytes) +{ CountBytesLeft(); if (num > m_bytesLeft) { LogDebug("Protocol broken. OutOfData. Asked for: " << num << " Ready: " << m_bytesLeft << " Buffer.size(): " << m_buffer.Size()); @@ -62,7 +66,8 @@ void MessageBuffer::Read(size_t num, void *bytes) { m_bytesLeft -= num; } -void MessageBuffer::Write(size_t num, const void *bytes) { +void MessageBuffer::Write(size_t num, const void *bytes) +{ m_buffer.AppendCopy(bytes, num); } diff --git a/src/manager/common/message-buffer.h b/src/manager/common/message-buffer.h index 798056ea..f519fc36 100644 --- a/src/manager/common/message-buffer.h +++ b/src/manager/common/message-buffer.h @@ -36,16 +36,16 @@ namespace CKM { class COMMON_API MessageBuffer : public CKM::IStream { public: - class Exception - { + class Exception { public: DECLARE_EXCEPTION_TYPE(CKM::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OutOfData) }; - MessageBuffer() - : m_bytesLeft(0) - {} + MessageBuffer() : + m_bytesLeft(0) + { + } MessageBuffer(MessageBuffer&&) = default; MessageBuffer& operator=(MessageBuffer&&) = default; @@ -62,7 +62,8 @@ public: // generic serialization template <typename... Args> - static MessageBuffer Serialize( const Args&... args) { + static MessageBuffer Serialize(const Args&... args) + { MessageBuffer buffer; Serializer<Args...>::Serialize(buffer, args...); return buffer; @@ -70,13 +71,14 @@ public: // generic deserialization template <typename... Args> - void Deserialize(Args&... args) { + void Deserialize(Args&... args) + { Deserializer<Args...>::Deserialize(*this, args...); } protected: - - inline void CountBytesLeft() { + inline void CountBytesLeft() + { if (m_bytesLeft > 0) return; // we already counted m_bytesLeft nothing to do diff --git a/src/manager/common/openssl_utils.h b/src/manager/common/openssl_utils.h index 47b966b2..83d2525e 100644 --- a/src/manager/common/openssl_utils.h +++ b/src/manager/common/openssl_utils.h @@ -31,13 +31,14 @@ namespace CKM typedef std::unique_ptr<X509_STORE_CTX, void(*)(X509_STORE_CTX*)> X509_STORE_CTX_PTR; typedef std::unique_ptr<STACK_OF(X509), void(*)(STACK_OF(X509)*)> X509_STACK_PTR; -inline X509_STACK_PTR create_x509_stack() { +inline X509_STACK_PTR create_x509_stack() +{ return X509_STACK_PTR(sk_X509_new_null(), [](STACK_OF(X509)* stack) { sk_X509_free(stack); }); } -inline X509_STORE_CTX_PTR create_x509_store_ctx() { - return X509_STORE_CTX_PTR(X509_STORE_CTX_new(),X509_STORE_CTX_free); +inline X509_STORE_CTX_PTR create_x509_store_ctx() +{ + return X509_STORE_CTX_PTR(X509_STORE_CTX_new(), X509_STORE_CTX_free); } } // namespace CKM - diff --git a/src/manager/common/pkcs12-impl.cpp b/src/manager/common/pkcs12-impl.cpp index 69146989..5a931d4b 100644..100755 --- a/src/manager/common/pkcs12-impl.cpp +++ b/src/manager/common/pkcs12-impl.cpp @@ -83,8 +83,7 @@ PKCS12Impl::PKCS12Impl(const RawBuffer &buffer, const Password &password) if (pkey) { KeyImpl::EvpShPtr ptr(pkey, EVP_PKEY_free); - switch(EVP_PKEY_type(pkey->type)) - { + switch (EVP_PKEY_type(pkey->type)) { case EVP_PKEY_RSA: m_pkey = std::make_shared<KeyImpl>(ptr, KeyType::KEY_RSA_PRIVATE); break; @@ -104,9 +103,8 @@ PKCS12Impl::PKCS12Impl(const RawBuffer &buffer, const Password &password) } } - if (cert) { + if (cert) m_cert = std::make_shared<CertificateImpl>(cert, false); - } if (ca) { while (sk_X509_num(ca) > 0) { @@ -118,31 +116,30 @@ PKCS12Impl::PKCS12Impl(const RawBuffer &buffer, const Password &password) } } -PKCS12Impl::PKCS12Impl(const PKCS12 &other) - : m_pkey(other.getKey()), - m_cert(other.getCertificate()), - m_ca(other.getCaCertificateShPtrVector()) +PKCS12Impl::PKCS12Impl(const PKCS12 &other) : + m_pkey(other.getKey()), + m_cert(other.getCertificate()), + m_ca(other.getCaCertificateShPtrVector()) { } -PKCS12Impl::PKCS12Impl(PKCS12Impl &&other) - : m_pkey(std::move(other.m_pkey)), - m_cert(std::move(other.m_cert)), - m_ca(std::move(other.m_ca)) +PKCS12Impl::PKCS12Impl(PKCS12Impl &&other) : + m_pkey(std::move(other.m_pkey)), + m_cert(std::move(other.m_cert)), + m_ca(std::move(other.m_ca)) { } -PKCS12Impl::PKCS12Impl(const PKCS12Impl &other) - : m_pkey(other.getKey()), - m_cert(other.getCertificate()), - m_ca(other.getCaCertificateShPtrVector()) +PKCS12Impl::PKCS12Impl(const PKCS12Impl &other) : + m_pkey(other.getKey()), + m_cert(other.getCertificate()), + m_ca(other.getCaCertificateShPtrVector()) { } PKCS12Impl& PKCS12Impl::operator=(const PKCS12Impl &other) { - if(this != &other) - { + if (this != &other) { m_pkey = other.getKey(); m_cert = other.getCertificate(); m_ca = other.getCaCertificateShPtrVector(); @@ -150,26 +147,32 @@ PKCS12Impl& PKCS12Impl::operator=(const PKCS12Impl &other) return *this; } -KeyShPtr PKCS12Impl::getKey() const { +KeyShPtr PKCS12Impl::getKey() const +{ return m_pkey; } -CertificateShPtr PKCS12Impl::getCertificate() const { +CertificateShPtr PKCS12Impl::getCertificate() const +{ return m_cert; } -CertificateShPtrVector PKCS12Impl::getCaCertificateShPtrVector() const { +CertificateShPtrVector PKCS12Impl::getCaCertificateShPtrVector() const +{ return m_ca; } -bool PKCS12Impl::empty() const { +bool PKCS12Impl::empty() const +{ return m_pkey.get() == NULL && m_cert.get() == NULL && m_ca.empty(); } PKCS12Impl::~PKCS12Impl() -{} +{ +} -PKCS12ShPtr PKCS12::create(const RawBuffer &rawBuffer, const Password &password) { +PKCS12ShPtr PKCS12::create(const RawBuffer &rawBuffer, const Password &password) +{ try { auto output = std::make_shared<PKCS12Impl>(rawBuffer, password); if (output->empty()) diff --git a/src/manager/common/protocols.cpp b/src/manager/common/protocols.cpp index 6f6c6c2d..d4d398d1 100644..100755 --- a/src/manager/common/protocols.cpp +++ b/src/manager/common/protocols.cpp @@ -37,17 +37,21 @@ char const * const SERVICE_SOCKET_ENCRYPTION = "/tmp/.central-key-manager-api-en char const * const LABEL_NAME_SEPARATOR = " "; char const * const OWNER_ID_SYSTEM = "/System"; -PKCS12Serializable::PKCS12Serializable() {} +PKCS12Serializable::PKCS12Serializable() +{ +} + PKCS12Serializable::PKCS12Serializable(const PKCS12 &pkcs) : PKCS12Impl(pkcs) -{} +{ +} PKCS12Serializable::PKCS12Serializable(IStream &stream) { // key size_t numKeys; Deserialization::Deserialize(stream, numKeys); - if(numKeys > 0) { + if (numKeys > 0) { int keyType; RawBuffer keyData; Deserialization::Deserialize(stream, keyType); @@ -58,7 +62,7 @@ PKCS12Serializable::PKCS12Serializable(IStream &stream) // cert size_t numCerts; Deserialization::Deserialize(stream, numCerts); - if(numCerts > 0) { + if (numCerts > 0) { RawBuffer certData; Deserialization::Deserialize(stream, certData); m_cert = CKM::Certificate::create(certData, DataFormat::FORM_DER); @@ -67,13 +71,13 @@ PKCS12Serializable::PKCS12Serializable(IStream &stream) // CA chain size_t num_CA; Deserialization::Deserialize(stream, num_CA); - for(size_t i=0; i<num_CA; i++) - { + for (size_t i=0; i < num_CA; i++) { RawBuffer CAcertData; Deserialization::Deserialize(stream, CAcertData); m_ca.push_back(CKM::Certificate::create(CAcertData, DataFormat::FORM_DER)); } } + PKCS12Serializable::PKCS12Serializable(const KeyShPtr &privKey, const CertificateShPtr &cert, const CertificateShPtrVector &chainCerts) { m_pkey = privKey; @@ -85,34 +89,36 @@ void PKCS12Serializable::Serialize(IStream &stream) const { // key Key *keyPtr = getKey().get(); - bool isAnyKeyPresent = (getKey().get()!=NULL); + bool isAnyKeyPresent = (getKey().get() != NULL); // logics if PKCS is correct or not is on the service side. // sending number of keys and certificates to allow proper parsing on the service side. // (what if no key or cert present? attempt to deserialize a not present key/cert would // throw an error and close the connection). Serialization::Serialize(stream, static_cast<size_t>(isAnyKeyPresent?1:0)); - if(keyPtr) { + if (keyPtr) { Serialization::Serialize(stream, DataType(keyPtr->getType())); Serialization::Serialize(stream, keyPtr->getDER()); } - bool isAnyCertPresent = (getCertificate().get()!=NULL); + bool isAnyCertPresent = (getCertificate().get() != NULL); Serialization::Serialize(stream, static_cast<size_t>(isAnyCertPresent?1:0)); - if(isAnyCertPresent) { + if (isAnyCertPresent) Serialization::Serialize(stream, getCertificate().get()->getDER()); - } // CA chain Serialization::Serialize(stream, getCaCertificateShPtrVector().size()); - for(auto it : getCaCertificateShPtrVector()) + for (auto it : getCaCertificateShPtrVector()) Serialization::Serialize(stream, it->getDER()); }; -CryptoAlgorithmSerializable::CryptoAlgorithmSerializable() {} +CryptoAlgorithmSerializable::CryptoAlgorithmSerializable() +{ +} + CryptoAlgorithmSerializable::CryptoAlgorithmSerializable(const CryptoAlgorithm &algo) : - CryptoAlgorithm(algo) + CryptoAlgorithm(algo) { } @@ -120,7 +126,7 @@ CryptoAlgorithmSerializable::CryptoAlgorithmSerializable(IStream &stream) { size_t plen = 0; Deserializer<size_t>::Deserialize(stream, plen); - while(plen) { + while (plen) { ParamName name; uint64_t integer; RawBuffer buffer; @@ -156,7 +162,7 @@ CryptoAlgorithmSerializable::CryptoAlgorithmSerializable(IStream &stream) void CryptoAlgorithmSerializable::Serialize(IStream &stream) const { Serializer<size_t>::Serialize(stream, m_params.size()); - for(const auto& it : m_params) { + for (const auto& it : m_params) { Serializer<int>::Serialize(stream, static_cast<int>(it.first)); uint64_t integer; RawBuffer buffer; @@ -167,7 +173,6 @@ void CryptoAlgorithmSerializable::Serialize(IStream &stream) const else ThrowMsg(UnsupportedParam, "Unsupported param type"); } - } } // namespace CKM diff --git a/src/manager/common/protocols.h b/src/manager/common/protocols.h index 63a92bdc..d2a9d05f 100644 --- a/src/manager/common/protocols.h +++ b/src/manager/common/protocols.h @@ -84,12 +84,18 @@ class IStream; struct COMMON_API PolicySerializable : public Policy, ISerializable { PolicySerializable() {}; - explicit PolicySerializable(const Policy &policy) : Policy(policy) {} - explicit PolicySerializable(IStream &stream) { + explicit PolicySerializable(const Policy &policy) : Policy(policy) + { + } + + explicit PolicySerializable(IStream &stream) + { Deserialization::Deserialize(stream, password); Deserialization::Deserialize(stream, extractable); } - void Serialize(IStream &stream) const { + + void Serialize(IStream &stream) const + { Serialization::Serialize(stream, password); Serialization::Serialize(stream, extractable); } diff --git a/src/manager/common/stringify.h b/src/manager/common/stringify.h index fbe2245c..60265c8b 100644 --- a/src/manager/common/stringify.h +++ b/src/manager/common/stringify.h @@ -33,12 +33,14 @@ template <> class StringifyBasic<false> { StringifyBasic() = delete; public: - static std::string Merge() { + static std::string Merge() + { return std::string(); } template <typename... Args> - static std::string Merge(const Args&...){ + static std::string Merge(const Args&...) + { return std::string(); } }; @@ -47,20 +49,26 @@ template <> class StringifyBasic<true> { StringifyBasic() = delete; - static void Concatenate(std::ostringstream&) {} + static void Concatenate(std::ostringstream&) + { + } template <typename t, typename... Args> - static void Concatenate(std::ostringstream& stream, const t& arg1, const Args&... args) { + static void Concatenate(std::ostringstream& stream, const t& arg1, const Args&... args) + { stream << arg1; Concatenate(stream, args...); } + public: - static std::string Merge() { + static std::string Merge() + { return std::string(); } template <typename T, typename... Args> - static std::string Merge(const T& arg1, const Args&... args) { + static std::string Merge(const T& arg1, const Args&... args) + { std::ostringstream stream; Concatenate(stream, arg1, args...); return stream.str(); diff --git a/src/manager/crypto/generic-backend/algo-validation.h b/src/manager/crypto/generic-backend/algo-validation.h index 69dd95d9..b51f23de 100644 --- a/src/manager/crypto/generic-backend/algo-validation.h +++ b/src/manager/crypto/generic-backend/algo-validation.h @@ -38,9 +38,9 @@ T unpack( ParamName paramName) { T result; - if (!alg.getParam(paramName, result)) { + if (!alg.getParam(paramName, result)) ThrowErr(Exc::Crypto::InputParam, "Wrong input param"); - } + return result; } @@ -63,10 +63,13 @@ struct Type { template <T First> struct Equals<First> { public: - static bool Check(const T& value) { + static bool Check(const T& value) + { return First == value; } - static void Why(std::ostringstream& os) { + + static void Why(std::ostringstream& os) + { os << "doesn't match " << static_cast<int>(First); } }; @@ -74,10 +77,13 @@ struct Type { template <T First, T ...Args> struct Equals<First, Args...> : public Equals<First>, public Equals<Args...> { public: - static bool Check(const T& value) { + static bool Check(const T& value) + { return Equals<First>::Check(value) || Equals<Args...>::Check(value); } - static void Why(std::ostringstream& os) { + + static void Why(std::ostringstream& os) + { Equals<First>::Why(os); os << ", "; Equals<Args...>::Why(os); @@ -118,7 +124,8 @@ struct BufferSizeGetter { ////////// ErrorHandlers ////////////// struct ThrowingHandler { - static void Handle(std::string message) { + static void Handle(std::string message) + { ThrowErr(Exc::Crypto::InputParam, message); } }; @@ -141,33 +148,39 @@ struct VBuilder; template <> struct VBuilder<> { -static ValidatorVector Build() { + static ValidatorVector Build() + { return ValidatorVector(); } }; template <typename First> struct VBuilder<First> { -static ValidatorVector Build() { + static ValidatorVector Build() + { ValidatorVector validators; Add(validators); return validators; } protected: - static void Add(ValidatorVector& validators) { + static void Add(ValidatorVector& validators) + { validators.emplace_back(new First); } }; template <typename First, typename ...Args> struct VBuilder<First, Args...> : public VBuilder<First>, public VBuilder<Args...> { - static ValidatorVector Build() { + static ValidatorVector Build() + { ValidatorVector validators; Add(validators); return validators; } + protected: - static void Add(ValidatorVector& validators) { + static void Add(ValidatorVector& validators) + { VBuilder<First>::Add(validators); VBuilder<Args...>::Add(validators); } @@ -191,12 +204,13 @@ template <ParamName Name, typename Getter = DefaultGetter<Type>, typename ErrorHandler = ThrowingHandler> struct ParamCheck : public ParamCheckBase { - void Check(const CryptoAlgorithm& ca) const { + void Check(const CryptoAlgorithm& ca) const + { Type value; std::ostringstream os; // check existence - if(!ca.getParam(Name,value)) { + if (!ca.getParam(Name, value)) { if (Mandatory) { os << "Mandatory parameter " << static_cast<int>(Name) << " doesn't exist"; ErrorHandler::Handle(os.str()); @@ -204,7 +218,7 @@ struct ParamCheck : public ParamCheckBase { return; } // validate - if(!Validator::Check(Getter::Get(value))) { + if (!Validator::Check(Getter::Get(value))) { os << "The "; Getter::What(os); os << " of param '" << static_cast<int>(Name) << "'="; diff --git a/src/manager/crypto/generic-backend/gobj.h b/src/manager/crypto/generic-backend/gobj.h index 1e6598f0..fc779fb8 100644 --- a/src/manager/crypto/generic-backend/gobj.h +++ b/src/manager/crypto/generic-backend/gobj.h @@ -32,29 +32,37 @@ namespace Crypto { class GObj { protected: - GObj(){} + GObj() {} + public: - virtual RawBuffer getBinary() const { + virtual RawBuffer getBinary() const + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual RawBuffer encrypt(const CryptoAlgorithm &, const RawBuffer &) { + virtual RawBuffer encrypt(const CryptoAlgorithm &, const RawBuffer &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &) { + virtual RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual RawBuffer sign(const CryptoAlgorithm &, const RawBuffer &) { + virtual RawBuffer sign(const CryptoAlgorithm &, const RawBuffer &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual int verify(const CryptoAlgorithm &, const RawBuffer &, const RawBuffer &) { + virtual int verify(const CryptoAlgorithm &, const RawBuffer &, const RawBuffer &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual ~GObj () {} + virtual ~GObj() + { + } }; typedef std::unique_ptr<GObj> GObjUPtr; diff --git a/src/manager/crypto/generic-backend/gstore.h b/src/manager/crypto/generic-backend/gstore.h index 6eee7a36..5ada1665 100644 --- a/src/manager/crypto/generic-backend/gstore.h +++ b/src/manager/crypto/generic-backend/gstore.h @@ -52,28 +52,37 @@ struct DataEncryption { class GStore { public: - virtual GObjUPtr getObject(const Token &, const Password &) { + virtual GObjUPtr getObject(const Token &, const Password &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual TokenPair generateAKey(const CryptoAlgorithm &, const Password &, const Password &) { + virtual TokenPair generateAKey(const CryptoAlgorithm &, const Password &, const Password &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual Token generateSKey(const CryptoAlgorithm &, const Password &) { + virtual Token generateSKey(const CryptoAlgorithm &, const Password &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual Token import(const Data &, const Password &) { + virtual Token import(const Data &, const Password &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual Token importEncrypted(const Data &, const Password &, const DataEncryption &) { + virtual Token importEncrypted(const Data &, const Password &, const DataEncryption &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } - virtual void destroy(const Token &) { + virtual void destroy(const Token &) + { ThrowErr(Exc::Crypto::OperationNotSupported); } virtual ~GStore() {} protected: - explicit GStore(CryptoBackend backendId) : m_backendId(backendId) {} + explicit GStore(CryptoBackend backendId) : + m_backendId(backendId) + { + } CryptoBackend m_backendId; }; diff --git a/src/manager/crypto/platform/decider.cpp b/src/manager/crypto/platform/decider.cpp index 2f73b1f5..6c6dc963 100644 --- a/src/manager/crypto/platform/decider.cpp +++ b/src/manager/crypto/platform/decider.cpp @@ -32,7 +32,8 @@ namespace CKM { namespace Crypto { namespace { -CryptoBackend chooseCryptoBackend(DataType dataType, bool exportable, bool encrypted) { +CryptoBackend chooseCryptoBackend(DataType dataType, bool exportable, bool encrypted) +{ // Only software backend supports device encyption key if (encrypted) return CryptoBackend::OpenSSL; @@ -61,13 +62,16 @@ CryptoBackend chooseCryptoBackend(DataType dataType, bool exportable, bool encry Decider::Decider() : m_swStore(new SW::Store(CryptoBackend::OpenSSL)) , m_tzStore(new TZ::Store(CryptoBackend::TrustZone)) -{} +{ +} -GStore& Decider::getStore(const Token &token) const { +GStore& Decider::getStore(const Token &token) const +{ return getStore(token.backendId); }; -GStore& Decider::getStore(CryptoBackend cryptoBackend) const { +GStore& Decider::getStore(CryptoBackend cryptoBackend) const +{ GStore *gStore = NULL; if (cryptoBackend == CryptoBackend::OpenSSL) gStore = m_swStore.get(); @@ -81,7 +85,8 @@ GStore& Decider::getStore(CryptoBackend cryptoBackend) const { "Backend not available. BackendId: ", (int)cryptoBackend); } -GStore& Decider::getStore(DataType data, bool exportable, bool encrypted) const { +GStore& Decider::getStore(DataType data, bool exportable, bool encrypted) const +{ return getStore(chooseCryptoBackend(data, exportable, encrypted)); } diff --git a/src/manager/crypto/platform/decider.h b/src/manager/crypto/platform/decider.h index 81ad3d09..5e48791e 100644 --- a/src/manager/crypto/platform/decider.h +++ b/src/manager/crypto/platform/decider.h @@ -38,7 +38,8 @@ public: GStore& getStore(const Token &token) const; GStore& getStore(DataType data, bool exportable, bool encrypted = false) const; - virtual ~Decider(){} + virtual ~Decider() {} + protected: GStore& getStore(CryptoBackend id) const; diff --git a/src/manager/crypto/sw-backend/crypto.h b/src/manager/crypto/sw-backend/crypto.h index d42d930b..ab3b17e4 100644 --- a/src/manager/crypto/sw-backend/crypto.h +++ b/src/manager/crypto/sw-backend/crypto.h @@ -48,16 +48,19 @@ struct Base { // Low level api. // Allows various cipher specific parameters to be determined and set. - int Control(int type, int arg, void *ptr) { + int Control(int type, int arg, void *ptr) + { return EVP_CIPHER_CTX_ctrl(m_ctx, type, arg, ptr); } virtual void AppendAAD(const T&) = 0; virtual T Append(const T&) = 0; virtual T Finalize() = 0; - virtual ~Base(){ + virtual ~Base() + { EVP_CIPHER_CTX_free(m_ctx); } + protected: EVP_CIPHER_CTX *m_ctx; }; @@ -69,46 +72,45 @@ public: EvpCipherWrapper(const EVP_CIPHER *type, const T &key, const T &iv, bool encryption) { - if (static_cast<int>(key.size()) != EVP_CIPHER_key_length(type)) { - ThrowErr(Exc::Crypto::InternalError, "Wrong key size! Expected: ", EVP_CIPHER_key_length(type) ," Get: ", key.size()); - } + if (static_cast<int>(key.size()) != EVP_CIPHER_key_length(type)) + ThrowErr(Exc::Crypto::InternalError, "Wrong key size! Expected: ", EVP_CIPHER_key_length(type), " Get: ", key.size()); - if (static_cast<int>(iv.size()) < EVP_CIPHER_iv_length(type)) { - ThrowErr(Exc::Crypto::InternalError, "Wrong iv size! Expected: ", EVP_CIPHER_iv_length(type) , " Get: ", iv.size()); - } + if (static_cast<int>(iv.size()) < EVP_CIPHER_iv_length(type)) + ThrowErr(Exc::Crypto::InternalError, "Wrong iv size! Expected: ", EVP_CIPHER_iv_length(type), " Get: ", iv.size()); - if (1 != EVP_CipherInit_ex(m_ctx, type, NULL, key.data(), iv.data(), encryption ? 1 : 0)) { + if (1 != EVP_CipherInit_ex(m_ctx, type, NULL, key.data(), iv.data(), encryption ? 1 : 0)) ThrowErr(Exc::Crypto::InternalError, "Failed in EVP_CipherInit"); - } EVP_CIPHER_CTX_set_padding(m_ctx, 1); } - void AppendAAD(const T& data) { + void AppendAAD(const T& data) + { static_assert(sizeof(typename T::value_type) == 1, "Unsupported type inside container."); int bytesLen; - if (1 != EVP_CipherUpdate(m_ctx, NULL, &bytesLen, data.data(), data.size())) { + if (1 != EVP_CipherUpdate(m_ctx, NULL, &bytesLen, data.data(), data.size())) ThrowErr(Exc::Crypto::InternalError, "AppendAAD(): Failed in EVP_CipherUpdate"); - } } - T Append(const T& data) { + T Append(const T& data) + { static_assert(sizeof(typename T::value_type) == 1, "Unsupported type inside container."); int bytesLen = static_cast<int>(data.size() + EVP_CIPHER_CTX_block_size(m_ctx)); T output(bytesLen); - if (1 != EVP_CipherUpdate(m_ctx, output.data(), &bytesLen, data.data(), data.size())) { + if (1 != EVP_CipherUpdate(m_ctx, output.data(), &bytesLen, data.data(), data.size())) ThrowErr(Exc::Crypto::InternalError, "Append(): Failed in EVP_CipherUpdate"); - } + output.resize(bytesLen); return output; } - T Finalize() { + T Finalize() + { int bytesLen = EVP_CIPHER_CTX_block_size(m_ctx); T output(bytesLen); - if (1 != EVP_CipherFinal_ex(m_ctx, output.data(), &bytesLen)) { + if (1 != EVP_CipherFinal_ex(m_ctx, output.data(), &bytesLen)) ThrowErr(Exc::Crypto::InternalError, "Failed in EVP_CipherFinal"); - } + output.resize(bytesLen); return output; } diff --git a/src/manager/crypto/sw-backend/internals.cpp b/src/manager/crypto/sw-backend/internals.cpp index 15775ec7..cabb094a 100644..100755 --- a/src/manager/crypto/sw-backend/internals.cpp +++ b/src/manager/crypto/sw-backend/internals.cpp @@ -62,28 +62,25 @@ typedef int(*I2D_CONV)(BIO*, EVP_PKEY*); const size_t DEFAULT_AES_GCM_TAG_LEN = 128; // tag length in bits according to W3C Crypto API const size_t DEFAULT_AES_IV_LEN = 16; // default iv size in bytes for AES -RawBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) { +RawBuffer i2d(I2D_CONV fun, EVP_PKEY* pkey) +{ BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all); - if (NULL == pkey) { + if (NULL == pkey) ThrowErr(Exc::Crypto::InternalError, "attempt to parse an empty key!"); - } - if (NULL == bio.get()) { + if (NULL == bio.get()) ThrowErr(Exc::Crypto::InternalError, "Error in memory allocation! Function: BIO_new."); - } - if (1 != fun(bio.get(), pkey)) { + if (1 != fun(bio.get(), pkey)) ThrowErr(Exc::Crypto::InternalError, "Error in conversion EVP_PKEY to DER"); - } RawBuffer output(8196); int size = BIO_read(bio.get(), output.data(), output.size()); - if (size <= 0) { + if (size <= 0) ThrowErr(Exc::Crypto::InternalError, "Error in BIO_read: ", size); - } output.resize(size); return output; @@ -189,7 +186,8 @@ typedef ParamCheck<ParamName::GEN_EC, ElipticCurve::secp384r1>> EcdsaEcCheck; typedef std::map<AlgoType, ValidatorVector> ValidatorMap; -ValidatorMap initValidators() { +ValidatorMap initValidators() +{ ValidatorMap validators; validators.emplace(AlgoType::RSA_SV, VBuilder<HashAlgoCheck, RsaPaddingCheck>::Build()); validators.emplace(AlgoType::RSA_SV, VBuilder<HashAlgoCheck, RsaPaddingCheck>::Build()); @@ -206,6 +204,7 @@ ValidatorMap initValidators() { validators.emplace(AlgoType::RSA_OAEP, VBuilder<RsaLabelCheck>::Build()); return validators; }; + ValidatorMap g_validators = initValidators(); template <typename TypeCheck> @@ -217,9 +216,9 @@ void validateParams(const CryptoAlgorithm& ca) AlgoType at = unpack<AlgoType>(ca, ParamName::ALGO_TYPE); try { - for(const auto& validator : g_validators.at(at)) + for (const auto& validator : g_validators.at(at)) validator->Check(ca); - } catch(const std::out_of_range&) { + } catch (const std::out_of_range&) { ThrowErr(Exc::Crypto::InputParam, "Unsupported algorithm ", static_cast<int>(at)); } } @@ -326,9 +325,10 @@ RawBuffer asymmetricHelper(int (*cryptoFn)(int, const unsigned char*, unsigned c } // anonymous namespace -const EVP_MD *getMdAlgo(const HashAlgorithm hashAlgo) { - const EVP_MD *md_algo=NULL; - switch(hashAlgo) { +const EVP_MD *getMdAlgo(const HashAlgorithm hashAlgo) +{ + const EVP_MD *md_algo = NULL; + switch (hashAlgo) { case HashAlgorithm::NONE: md_algo = NULL; break; @@ -350,9 +350,10 @@ const EVP_MD *getMdAlgo(const HashAlgorithm hashAlgo) { return md_algo; } -int getRsaPadding(const RSAPaddingAlgorithm padAlgo) { +int getRsaPadding(const RSAPaddingAlgorithm padAlgo) +{ int rsa_padding = -1; - switch(padAlgo) { + switch (padAlgo) { case RSAPaddingAlgorithm::NONE: rsa_padding = RSA_NO_PADDING; break; @@ -373,27 +374,22 @@ DataPair createKeyPairRSA(const int size) EvpPkeyUPtr pkey; // check the parameters of functions - if(size!=1024 && size!=2048 && size!=4096) { + if (size != 1024 && size != 2048 && size != 4096) ThrowErr(Exc::Crypto::InputParam, "Error in RSA input size"); - } EvpPkeyCtxUPtr ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL), EVP_PKEY_CTX_free); - if(!ctx) { + if (!ctx) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new_id function !!"); - } - if(EVP_PKEY_keygen_init(ctx.get()) <= 0) { + if (EVP_PKEY_keygen_init(ctx.get()) <= 0) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen_init function !!"); - } - if(EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), size) <= 0) { + if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), size) <= 0) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_keygen_bits function !!"); - } EVP_PKEY *pkeyTmp = NULL; - if(!EVP_PKEY_keygen(ctx.get(), &pkeyTmp)) { + if (!EVP_PKEY_keygen(ctx.get(), &pkeyTmp)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function !!"); - } pkey = EvpPkeyUPtr(pkeyTmp, EVP_PKEY_free); return std::make_pair<Data, Data>( @@ -408,46 +404,40 @@ DataPair createKeyPairDSA(const int size) EvpPkeyUPtr pparam; // check the parameters of functions - if(size!=1024 && size!=2048 && size!=3072 && size!=4096) { + if (size != 1024 && size != 2048 && size != 3072 && size != 4096) ThrowErr(Exc::Crypto::InputParam, "Error in DSA input size"); - } /* Create the context for generating the parameters */ EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, NULL), EVP_PKEY_CTX_free); - if(!pctx) { + if (!pctx) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new_id function"); - } - if(EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx.get())) { + if (EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx.get())) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen_init function"); - } - if(EVP_SUCCESS != EVP_PKEY_CTX_set_dsa_paramgen_bits(pctx.get(), size)) { + if (EVP_SUCCESS != EVP_PKEY_CTX_set_dsa_paramgen_bits(pctx.get(), size)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(", size, ") function"); - } /* Generate parameters */ EVP_PKEY *pparamTmp = NULL; - if(EVP_SUCCESS != EVP_PKEY_paramgen(pctx.get(), &pparamTmp)) { + if (EVP_SUCCESS != EVP_PKEY_paramgen(pctx.get(), &pparamTmp)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen function"); - } + pparam = EvpPkeyUPtr(pparamTmp, EVP_PKEY_free); // Start to generate key EvpPkeyCtxUPtr kctx(EVP_PKEY_CTX_new(pparam.get(), NULL), EVP_PKEY_CTX_free); - if(!kctx) { + if (!kctx) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function"); - } - if(EVP_SUCCESS != EVP_PKEY_keygen_init(kctx.get())) { + if (EVP_SUCCESS != EVP_PKEY_keygen_init(kctx.get())) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen_init function"); - } /* Generate the key */ EVP_PKEY *pkeyTmp = NULL; - if(!EVP_PKEY_keygen(kctx.get(), &pkeyTmp)) { + if (!EVP_PKEY_keygen(kctx.get(), &pkeyTmp)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function !!"); - } + pkey = EvpPkeyUPtr(pkeyTmp, EVP_PKEY_free); return std::make_pair<Data, Data>( @@ -461,7 +451,7 @@ DataPair createKeyPairECDSA(ElipticCurve type) EvpPkeyUPtr pkey; EvpPkeyUPtr pparam; - switch(type) { + switch (type) { case ElipticCurve::prime192v1: ecCurve = NID_X9_62_prime192v1; break; @@ -477,40 +467,35 @@ DataPair createKeyPairECDSA(ElipticCurve type) /* Create the context for generating the parameters */ EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL), EVP_PKEY_CTX_free); - if(!pctx) { + if (!pctx) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new_id function"); - } - if(EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx.get())) { + if (EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx.get())) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen_init function"); - } - if(EVP_SUCCESS != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx.get(), ecCurve)) { + if (EVP_SUCCESS != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx.get(), ecCurve)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_ec_paramgen_curve_nid function"); - } /* Generate parameters */ EVP_PKEY *pparamTmp = NULL; - if(EVP_SUCCESS != EVP_PKEY_paramgen(pctx.get(), &pparamTmp)) { + if (EVP_SUCCESS != EVP_PKEY_paramgen(pctx.get(), &pparamTmp)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_paramgen function"); - } + pparam = EvpPkeyUPtr(pparamTmp, EVP_PKEY_free); // Start to generate key EvpPkeyCtxUPtr kctx(EVP_PKEY_CTX_new(pparam.get(), NULL), EVP_PKEY_CTX_free); - if(!kctx) { + if (!kctx) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function"); - } - if(EVP_SUCCESS != EVP_PKEY_keygen_init(kctx.get())) { + if (EVP_SUCCESS != EVP_PKEY_keygen_init(kctx.get())) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen_init function"); - } /* Generate the key */ EVP_PKEY *pkeyTmp = NULL; - if(!EVP_PKEY_keygen(kctx.get(), &pkeyTmp)) { + if (!EVP_PKEY_keygen(kctx.get(), &pkeyTmp)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function !!"); - } + pkey = EvpPkeyUPtr(pkeyTmp, EVP_PKEY_free); return std::make_pair<Data, Data>( @@ -521,7 +506,7 @@ DataPair createKeyPairECDSA(ElipticCurve type) Data createKeyAES(const int sizeBits) { // check the parameters of functions - if(sizeBits!=128 && sizeBits!=192 && sizeBits!=256) { + if (sizeBits != 128 && sizeBits != 192 && sizeBits != 256) { LogError("Error in AES input size"); ThrowMsg(Exc::Crypto::InputParam, "Error in AES input size"); } @@ -541,16 +526,13 @@ DataPair generateAKey(const CryptoAlgorithm &algorithm) validateParams<IsAsymGeneration>(algorithm); AlgoType keyType = unpack<AlgoType>(algorithm, ParamName::ALGO_TYPE); - if(keyType == AlgoType::RSA_GEN || keyType == AlgoType::DSA_GEN) - { + if (keyType == AlgoType::RSA_GEN || keyType == AlgoType::DSA_GEN) { int keyLength = unpack<int>(algorithm, ParamName::GEN_KEY_LEN); - if(keyType == AlgoType::RSA_GEN) + if (keyType == AlgoType::RSA_GEN) return createKeyPairRSA(keyLength); else return createKeyPairDSA(keyLength); - } - else // AlgoType::ECDSA_GEN - { + } else { // AlgoType::ECDSA_GEN ElipticCurve ecType = unpack<ElipticCurve>(algorithm, ParamName::GEN_EC); return createKeyPairECDSA(ecType); } @@ -595,9 +577,9 @@ std::pair<RawBuffer, RawBuffer> encryptDataAesGcm( RawBuffer result = enc->Append(data); RawBuffer tmp = enc->Finalize(); std::copy(tmp.begin(), tmp.end(), std::back_inserter(result)); - if (0 == enc->Control(EVP_CTRL_GCM_GET_TAG, tagSize, tag.data())) { + if (0 == enc->Control(EVP_CTRL_GCM_GET_TAG, tagSize, tag.data())) ThrowErr(Exc::Crypto::InternalError, "Error in AES control function. Get tag failed."); - } + return std::make_pair(result, tag); } @@ -637,10 +619,9 @@ RawBuffer decryptDataAesGcm( EvpCipherPtr dec; selectCipher(AlgoType::AES_GCM, key.size(), false)(dec, key, iv); void *ptr = (void*)tag.data(); - if (0 == dec->Control(EVP_CTRL_GCM_SET_TAG, tag.size(), ptr)) { - ThrowErr(Exc::Crypto::InternalError, - "Error in AES control function. Set tag failed."); - } + if (0 == dec->Control(EVP_CTRL_GCM_SET_TAG, tag.size(), ptr)) + ThrowErr(Exc::Crypto::InternalError, "Error in AES control function. Set tag failed."); + if (!aad.empty()) dec->AppendAAD(aad); @@ -676,26 +657,25 @@ RawBuffer symmetricEncrypt(const RawBuffer &key, validateParams<IsSymEncryption>(alg); AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE); - switch(keyType) + switch (keyType) { + case AlgoType::AES_CBC: + case AlgoType::AES_CTR: + case AlgoType::AES_CFB: + return encryptDataAes(keyType, key, data, unpack<RawBuffer>(alg, ParamName::ED_IV)); + case AlgoType::AES_GCM: { - case AlgoType::AES_CBC: - case AlgoType::AES_CTR: - case AlgoType::AES_CFB: - return encryptDataAes(keyType, key, data, unpack<RawBuffer>(alg, ParamName::ED_IV)); - case AlgoType::AES_GCM: - { - int tagLenBits = DEFAULT_AES_GCM_TAG_LEN; - alg.getParam(ParamName::ED_TAG_LEN, tagLenBits); - RawBuffer aad; - alg.getParam(ParamName::ED_AAD, aad); - return encryptDataAesGcmPacked(key, - data, - unpack<RawBuffer>(alg, ParamName::ED_IV), - tagLenBits/8, - aad); - } - default: - break; + int tagLenBits = DEFAULT_AES_GCM_TAG_LEN; + alg.getParam(ParamName::ED_TAG_LEN, tagLenBits); + RawBuffer aad; + alg.getParam(ParamName::ED_AAD, aad); + return encryptDataAesGcmPacked(key, + data, + unpack<RawBuffer>(alg, ParamName::ED_IV), + tagLenBits/8, + aad); + } + default: + break; } ThrowErr(Exc::Crypto::OperationNotSupported, "symmetric enc: algorithm not recognized"); } @@ -707,26 +687,25 @@ RawBuffer symmetricDecrypt(const RawBuffer &key, validateParams<IsSymEncryption>(alg); AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE); - switch(keyType) + switch (keyType) { + case AlgoType::AES_CBC: + case AlgoType::AES_CTR: + case AlgoType::AES_CFB: + return decryptDataAes(keyType, key, data, unpack<RawBuffer>(alg, ParamName::ED_IV)); + case AlgoType::AES_GCM: { - case AlgoType::AES_CBC: - case AlgoType::AES_CTR: - case AlgoType::AES_CFB: - return decryptDataAes(keyType, key, data, unpack<RawBuffer>(alg, ParamName::ED_IV)); - case AlgoType::AES_GCM: - { - int tagLenBits = DEFAULT_AES_GCM_TAG_LEN; - alg.getParam(ParamName::ED_TAG_LEN, tagLenBits); - RawBuffer aad; - alg.getParam(ParamName::ED_AAD, aad); - return decryptDataAesGcmPacked(key, - data, - unpack<RawBuffer>(alg, ParamName::ED_IV), - tagLenBits/8, - aad); - } - default: - break; + int tagLenBits = DEFAULT_AES_GCM_TAG_LEN; + alg.getParam(ParamName::ED_TAG_LEN, tagLenBits); + RawBuffer aad; + alg.getParam(ParamName::ED_AAD, aad); + return decryptDataAesGcmPacked(key, + data, + unpack<RawBuffer>(alg, ParamName::ED_IV), + tagLenBits/8, + aad); + } + default: + break; } ThrowErr(Exc::Crypto::InputParam, "symmetric dec: algorithm not recognized"); } @@ -760,7 +739,7 @@ RawBuffer sign(EVP_PKEY *pkey, int rsa_padding = getRsaPadding(rsaPad); // -// if((privateKey.getType() != KeyType::KEY_RSA_PRIVATE) && +// if ((privateKey.getType() != KeyType::KEY_RSA_PRIVATE) && // (privateKey.getType() != KeyType::KEY_DSA_PRIVATE) && // (privateKey.getType() != KeyType::KEY_ECDSA_PRIVATE)) // { @@ -768,19 +747,17 @@ RawBuffer sign(EVP_PKEY *pkey, // ThrowErr(CryptoService::Exception::Crypto_internal, "Error in private key type"); // } // -// if(privateKey.getType()==KeyType::KEY_RSA_PRIVATE) { +// if (privateKey.getType()==KeyType::KEY_RSA_PRIVATE) { // rsa_padding = getRsaPadding(padAlgo); // } - if (NULL == pkey) { + if (NULL == pkey) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_keygen function"); - } - if(md_algo == NULL) { + if (md_algo == NULL) return signMessage(pkey, message, rsa_padding); - } - return digestSignMessage(pkey,message, md_algo, rsa_padding); + return digestSignMessage(pkey, message, md_algo, rsa_padding); } RawBuffer signMessage(EVP_PKEY *privKey, @@ -789,39 +766,33 @@ RawBuffer signMessage(EVP_PKEY *privKey, { EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new(privKey, NULL), EVP_PKEY_CTX_free); - if(!pctx.get()) { + if (!pctx.get()) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function"); - } - if(EVP_PKEY_sign_init(pctx.get()) != EVP_SUCCESS) { + if (EVP_PKEY_sign_init(pctx.get()) != EVP_SUCCESS) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_sign_init function"); - } /* Set padding algorithm */ - if(EVP_PKEY_type(privKey->type) == EVP_PKEY_RSA) { - if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx.get(), rsa_padding)) { + if (EVP_PKEY_type(privKey->type) == EVP_PKEY_RSA) + if (EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx.get(), rsa_padding)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function"); - } - } /* Finalize the Sign operation */ /* First call EVP_PKEY_sign with a NULL sig parameter to obtain the length of the * signature. Length is returned in slen */ size_t slen; - if(EVP_SUCCESS != EVP_PKEY_sign(pctx.get(), NULL, &slen, message.data(), message.size())) { + if (EVP_SUCCESS != EVP_PKEY_sign(pctx.get(), NULL, &slen, message.data(), message.size())) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_sign function"); - } /* Allocate memory for the signature based on size in slen */ RawBuffer sig(slen); - if(EVP_SUCCESS == EVP_PKEY_sign(pctx.get(), + if (EVP_SUCCESS == EVP_PKEY_sign(pctx.get(), sig.data(), &slen, message.data(), - message.size())) - { + message.size())) { // Set value to return RawData sig.resize(slen); return sig; @@ -840,41 +811,34 @@ RawBuffer digestSignMessage(EVP_PKEY *privKey, EVP_PKEY_CTX *pctx = NULL; // Create the Message Digest Context - if(!mdctx.get()) { + if (!mdctx.get()) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_MD_CTX_create function"); - } - if(EVP_SUCCESS != EVP_DigestSignInit(mdctx.get(), &pctx, md_algo, NULL, privKey)) { + if (EVP_SUCCESS != EVP_DigestSignInit(mdctx.get(), &pctx, md_algo, NULL, privKey)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignInit function"); - } /* Set padding algorithm */ - if(EVP_PKEY_type(privKey->type) == EVP_PKEY_RSA) { - if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx, rsa_padding)) { + if (EVP_PKEY_type(privKey->type) == EVP_PKEY_RSA) + if (EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx, rsa_padding)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function"); - } - } /* Call update with the message */ - if(EVP_SUCCESS != EVP_DigestSignUpdate(mdctx.get(), message.data(), message.size())) { + if (EVP_SUCCESS != EVP_DigestSignUpdate(mdctx.get(), message.data(), message.size())) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignUpdate function"); - } /* Finalize the DigestSign operation */ /* First call EVP_DigestSignFinal with a NULL sig parameter to obtain the length of the * signature. Length is returned in slen */ size_t slen; - if(EVP_SUCCESS != EVP_DigestSignFinal(mdctx.get(), NULL, &slen)) { + if (EVP_SUCCESS != EVP_DigestSignFinal(mdctx.get(), NULL, &slen)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignFinal function"); - } /* Allocate memory for the signature based on size in slen */ RawBuffer sig(slen); /* Obtain the signature */ - if(EVP_SUCCESS != EVP_DigestSignFinal(mdctx.get(), sig.data(), &slen)) { + if (EVP_SUCCESS != EVP_DigestSignFinal(mdctx.get(), sig.data(), &slen)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestSignFinal function"); - } // Set value to return RawData sig.resize(slen); @@ -900,7 +864,7 @@ int verify(EVP_PKEY *pkey, rsa_padding = getRsaPadding(rsaPad); // -// if((publicKey.getType() != KeyType::KEY_RSA_PUBLIC) && +// if ((publicKey.getType() != KeyType::KEY_RSA_PUBLIC) && // (publicKey.getType() != KeyType::KEY_DSA_PUBLIC) && // (publicKey.getType() != KeyType::KEY_ECDSA_PUBLIC)) // { @@ -908,18 +872,16 @@ int verify(EVP_PKEY *pkey, // ThrowErr(CryptoService::Exception::Crypto_internal, "Error in private key type"); // } // -// if(publicKey.getType()==KeyType::KEY_RSA_PUBLIC) { +// if (publicKey.getType()==KeyType::KEY_RSA_PUBLIC) { // rsa_padding = getRsaPadding(padAlgo); // } // auto shrPKey = publicKey.getEvpShPtr(); - if (NULL == pkey) { + if (NULL == pkey) ThrowErr(Exc::Crypto::InternalError, "Error in getEvpShPtr function"); - } - if (md_algo == NULL) { + if (md_algo == NULL) return verifyMessage(pkey, message, signature, rsa_padding); - } return digestVerifyMessage(pkey, message, signature, md_algo, rsa_padding); } @@ -931,24 +893,19 @@ int verifyMessage(EVP_PKEY *pubKey, { EvpPkeyCtxUPtr pctx(EVP_PKEY_CTX_new(pubKey, NULL), EVP_PKEY_CTX_free); - if(!pctx.get()) { + if (!pctx.get()) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_new function"); - } - if(EVP_PKEY_verify_init(pctx.get()) != EVP_SUCCESS) { + if (EVP_PKEY_verify_init(pctx.get()) != EVP_SUCCESS) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_verify_init function"); - } /* Set padding algorithm */ - if(EVP_PKEY_type(pubKey->type) == EVP_PKEY_RSA) { - if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx.get(), rsa_padding)) { + if (EVP_PKEY_type(pubKey->type) == EVP_PKEY_RSA) + if (EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx.get(), rsa_padding)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function"); - } - } - if(EVP_SUCCESS == EVP_PKEY_verify(pctx.get(), signature.data(), signature.size(), message.data(), message.size())) { + if (EVP_SUCCESS == EVP_PKEY_verify(pctx.get(), signature.data(), signature.size(), message.data(), message.size())) return CKM_API_SUCCESS; - } LogError("EVP_PKEY_verify Failed"); return CKM_API_ERROR_VERIFICATION_FAILED; @@ -964,27 +921,21 @@ int digestVerifyMessage(EVP_PKEY *pubKey, EVP_PKEY_CTX *pctx = NULL; /* Create the Message Digest Context */ - if(!mdctx.get()) { + if (!mdctx.get()) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_MD_CTX_create function"); - } - if(EVP_SUCCESS != EVP_DigestVerifyInit(mdctx.get(), &pctx, md_algo, NULL, pubKey)) { + if (EVP_SUCCESS != EVP_DigestVerifyInit(mdctx.get(), &pctx, md_algo, NULL, pubKey)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestVerifyInit function"); - } - if(EVP_PKEY_type(pubKey->type) == EVP_PKEY_RSA) { - if(EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx, rsa_padding)) { + if (EVP_PKEY_type(pubKey->type) == EVP_PKEY_RSA) + if (EVP_SUCCESS != EVP_PKEY_CTX_set_rsa_padding(pctx, rsa_padding)) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_PKEY_CTX_set_rsa_padding function"); - } - } - if(EVP_SUCCESS != EVP_DigestVerifyUpdate(mdctx.get(), message.data(), message.size()) ) { + if (EVP_SUCCESS != EVP_DigestVerifyUpdate(mdctx.get(), message.data(), message.size())) ThrowErr(Exc::Crypto::InternalError, "Error in EVP_DigestVerifyUpdate function"); - } - if(EVP_SUCCESS == EVP_DigestVerifyFinal(mdctx.get(), const_cast<unsigned char*>(signature.data()), signature.size()) ) { + if (EVP_SUCCESS == EVP_DigestVerifyFinal(mdctx.get(), const_cast<unsigned char*>(signature.data()), signature.size())) return CKM_API_SUCCESS; - } LogError("EVP_PKEY_verify Failed"); return CKM_API_ERROR_VERIFICATION_FAILED; @@ -994,14 +945,14 @@ bool verifyBinaryData(DataType dataType, const RawBuffer &buffer) { if (dataType.isSKey()) { switch (buffer.size()) { - default: - LogError("AES key have wrong size."); - return false; - case 128: - case 192: - case 256: - LogDebug("AES key verified."); - return true; + case 128: + case 192: + case 256: + LogDebug("AES key verified."); + return true; + default: + LogError("AES key have wrong size."); + return false; } } @@ -1033,8 +984,7 @@ bool verifyBinaryData(DataType dataType, const RawBuffer &buffer) return false; } - if (dataType.isCertificate() || dataType.isChainCert()) - { + if (dataType.isCertificate() || dataType.isChainCert()) { const unsigned char *ptr = reinterpret_cast<const unsigned char*>(buffer.data()); int size = static_cast<int>(buffer.size()); X509 *x509 = d2i_X509(NULL, &ptr, size); diff --git a/src/manager/crypto/sw-backend/internals.h b/src/manager/crypto/sw-backend/internals.h index b19dcfbf..275500ec 100644 --- a/src/manager/crypto/sw-backend/internals.h +++ b/src/manager/crypto/sw-backend/internals.h @@ -24,8 +24,8 @@ #include <openssl/evp.h> #include <sw-backend/obj.h> -#define EVP_SUCCESS 1 // DO NOTCHANGE THIS VALUE -#define EVP_FAIL 0 // DO NOTCHANGE THIS VALUE +#define EVP_SUCCESS 1 // DO NOTCHANGE THIS VALUE +#define EVP_FAIL 0 // DO NOTCHANGE THIS VALUE #define CKM_CRYPTO_INIT_SUCCESS 1 #define CKM_CRYPTO_CREATEKEY_SUCCESS 2 @@ -43,7 +43,7 @@ struct Data { RawBuffer buffer; }; -typedef std::pair<Data,Data> DataPair; +typedef std::pair<Data, Data> DataPair; DataPair createKeyPairRSA(const int size); DataPair createKeyPairDSA(const int size); @@ -53,26 +53,32 @@ Data createKeyAES(const int sizeBits); DataPair generateAKey(const CryptoAlgorithm &algorithm); Data generateSKey(const CryptoAlgorithm &algorithm); -RawBuffer symmetricEncrypt(const RawBuffer &key, - const CryptoAlgorithm &alg, - const RawBuffer &data); -RawBuffer symmetricDecrypt(const RawBuffer &key, - const CryptoAlgorithm &alg, - const RawBuffer &cipher); -RawBuffer asymmetricEncrypt(const EvpShPtr &key, - const CryptoAlgorithm &alg, - const RawBuffer &data); -RawBuffer asymmetricDecrypt(const EvpShPtr &key, - const CryptoAlgorithm &alg, - const RawBuffer &data); - -std::pair<RawBuffer, RawBuffer> encryptDataAesGcm(const RawBuffer &key, +RawBuffer symmetricEncrypt( + const RawBuffer &key, + const CryptoAlgorithm &alg, + const RawBuffer &data); +RawBuffer symmetricDecrypt( + const RawBuffer &key, + const CryptoAlgorithm &alg, + const RawBuffer &cipher); +RawBuffer asymmetricEncrypt( + const EvpShPtr &key, + const CryptoAlgorithm &alg, + const RawBuffer &data); +RawBuffer asymmetricDecrypt( + const EvpShPtr &key, + const CryptoAlgorithm &alg, + const RawBuffer &data); + +std::pair<RawBuffer, RawBuffer> encryptDataAesGcm( + const RawBuffer &key, const RawBuffer &data, const RawBuffer &iv, int tagSize, const RawBuffer &aad = RawBuffer()); -RawBuffer decryptDataAesGcm(const RawBuffer &key, +RawBuffer decryptDataAesGcm( + const RawBuffer &key, const RawBuffer &data, const RawBuffer &iv, const RawBuffer &tag, diff --git a/src/manager/crypto/sw-backend/obj.cpp b/src/manager/crypto/sw-backend/obj.cpp index 2a70736e..7364fa8d 100644..100755 --- a/src/manager/crypto/sw-backend/obj.cpp +++ b/src/manager/crypto/sw-backend/obj.cpp @@ -30,8 +30,8 @@ #include <sw-backend/obj.h> #include <sw-backend/internals.h> -#define EVP_SUCCESS 1 // DO NOTCHANGE THIS VALUE -#define EVP_FAIL 0 // DO NOTCHANGE THIS VALUE +#define EVP_SUCCESS 1 // DO NOTCHANGE THIS VALUE +#define EVP_FAIL 0 // DO NOTCHANGE THIS VALUE namespace CKM { namespace Crypto { @@ -39,8 +39,9 @@ namespace SW { namespace { -AlgoType key2algo(DataType type) { - switch(static_cast<int>(type)) { +AlgoType key2algo(DataType type) +{ + switch (static_cast<int>(type)) { case DataType::Type::KEY_RSA_PRIVATE: case DataType::Type::KEY_RSA_PUBLIC: return AlgoType::RSA_SV; @@ -77,15 +78,16 @@ RawBuffer AKey::sign( return Internals::sign(getEvpShPtr().get(), algWithType, message); } -int AKey::verify(const CryptoAlgorithm &alg, const RawBuffer &message, const RawBuffer &sign) { +int AKey::verify(const CryptoAlgorithm &alg, const RawBuffer &message, const RawBuffer &sign) +{ CryptoAlgorithm algWithType(alg); EVP_PKEY* evp = getEvpShPtr().get(); AlgoType type; // setup algorithm type basing on evp key type if it doesn't exist - if(!algWithType.getParam(ParamName::ALGO_TYPE, type)) { + if (!algWithType.getParam(ParamName::ALGO_TYPE, type)) { int subType = EVP_PKEY_type(evp->type); - switch(subType) { + switch (subType) { case EVP_PKEY_RSA: type = AlgoType::RSA_SV; break; case EVP_PKEY_DSA: @@ -110,7 +112,8 @@ RawBuffer AKey::decrypt(const CryptoAlgorithm &alg, const RawBuffer &data) return Internals::asymmetricDecrypt(getEvpShPtr(), alg, data); } -EvpShPtr AKey::getEvpShPtr() { +EvpShPtr AKey::getEvpShPtr() +{ if (m_evp) return m_evp; @@ -133,15 +136,15 @@ EvpShPtr AKey::getEvpShPtr() { LogDebug("Trying d2i_PUBKEY_bio Status: " << (void*)pkey); } - if (!pkey) { + if (!pkey) ThrowErr(Exc::Crypto::InternalError, "Failed to parse key"); - } m_evp.reset(pkey, EVP_PKEY_free); return m_evp; } -EvpShPtr Cert::getEvpShPtr() { +EvpShPtr Cert::getEvpShPtr() +{ if (m_evp) return m_evp; @@ -150,9 +153,8 @@ EvpShPtr Cert::getEvpShPtr() { X509 *x509 = d2i_X509(NULL, &ptr, size); - if (!x509) { + if (!x509) ThrowErr(Exc::Crypto::InternalError, "Failed to parse certificate."); - } m_evp.reset(X509_get_pubkey(x509), EVP_PKEY_free); X509_free(x509); @@ -162,4 +164,3 @@ EvpShPtr Cert::getEvpShPtr() { } // namespace SW } // namespace Crypto } // namespace CKM - diff --git a/src/manager/crypto/sw-backend/obj.h b/src/manager/crypto/sw-backend/obj.h index f8c3cfee..082664a2 100644 --- a/src/manager/crypto/sw-backend/obj.h +++ b/src/manager/crypto/sw-backend/obj.h @@ -30,7 +30,7 @@ namespace CKM { namespace Crypto { namespace SW { -typedef std::unique_ptr<EVP_PKEY_CTX,std::function<void(EVP_PKEY_CTX*)>> ContextUPtr; +typedef std::unique_ptr<EVP_PKEY_CTX, std::function<void(EVP_PKEY_CTX*)>> ContextUPtr; typedef std::shared_ptr<EVP_PKEY> EvpShPtr; class BData : public GObj { @@ -38,7 +38,8 @@ public: BData(RawBuffer buffer, DataType keyType) : m_raw(std::move(buffer)) , m_type(keyType) - {} + { + } virtual RawBuffer getBinary() const { return m_raw; } protected: @@ -49,7 +50,8 @@ protected: class SKey : public BData { public: SKey(RawBuffer buffer, DataType keyType) : BData(std::move(buffer), keyType) - {} + { + } virtual RawBuffer encrypt(const CryptoAlgorithm &, const RawBuffer &); virtual RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &); @@ -58,12 +60,14 @@ public: class AKey : public BData { public: AKey(RawBuffer buffer, DataType dataType) : BData(std::move(buffer), dataType) - {} + { + } virtual RawBuffer sign(const CryptoAlgorithm &alg, const RawBuffer &message); virtual int verify(const CryptoAlgorithm &alg, const RawBuffer &message, const RawBuffer &sign); virtual RawBuffer encrypt(const CryptoAlgorithm &, const RawBuffer &); virtual RawBuffer decrypt(const CryptoAlgorithm &, const RawBuffer &); - virtual ~AKey(){} + virtual ~AKey() {} + protected: virtual EvpShPtr getEvpShPtr(); @@ -74,8 +78,9 @@ class Cert : public AKey { public: Cert(RawBuffer buffer, DataType dataType) : AKey(std::move(buffer), dataType) - {} - virtual ~Cert(){} + { + } + virtual ~Cert() {} protected: virtual EvpShPtr getEvpShPtr(); }; diff --git a/src/manager/crypto/sw-backend/store.cpp b/src/manager/crypto/sw-backend/store.cpp index 2605f4d0..b0fdb618 100644..100755 --- a/src/manager/crypto/sw-backend/store.cpp +++ b/src/manager/crypto/sw-backend/store.cpp @@ -49,11 +49,13 @@ enum EncryptionScheme { }; template <typename T, typename ...Args> -std::unique_ptr<T> make_unique(Args&& ...args) { +std::unique_ptr<T> make_unique(Args&& ...args) +{ return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } -RawBuffer generateRandIV() { +RawBuffer generateRandIV() +{ RawBuffer civ(EVP_MAX_IV_LENGTH); if (1 != RAND_bytes(civ.data(), civ.size())) @@ -73,9 +75,7 @@ RawBuffer passwordToKey(const Password &password, const RawBuffer &salt, size_t ITERATIONS, result.size(), result.data())) - { ThrowErr(Exc::InternalError, "PCKS5_PKKDF2_HMAC_SHA1 failed."); - } return result; } @@ -156,43 +156,36 @@ Store::Store(CryptoBackend backendId) // get the device key if present InitialValues::SWKeyFile keyFile(DEVICE_KEY_SW_FILE); int rc = keyFile.Validate(DEVICE_KEY_XSD); - if(rc == XML::Parser::PARSE_SUCCESS) - { + if (rc == XML::Parser::PARSE_SUCCESS) { rc = keyFile.Parse(); - if(rc == XML::Parser::PARSE_SUCCESS) + if (rc == XML::Parser::PARSE_SUCCESS) m_deviceKey = keyFile.getPrivKey(); else - { // do nothing, bypass encrypted elements LogWarning("invalid SW key file: " << DEVICE_KEY_SW_FILE << ", parsing code: " << rc); - } - } - else + } else { LogWarning("invalid SW key file: " << DEVICE_KEY_SW_FILE << ", validation code: " << rc); + } } -GObjUPtr Store::getObject(const Token &token, const Password &pass) { - if (token.backendId != m_backendId) { +GObjUPtr Store::getObject(const Token &token, const Password &pass) +{ + if (token.backendId != m_backendId) ThrowErr(Exc::Crypto::WrongBackend, "Decider choose wrong backend!"); - } RawBuffer data = unpack(token.data, pass); - if (token.dataType.isKeyPrivate() || token.dataType.isKeyPublic()) { + if (token.dataType.isKeyPrivate() || token.dataType.isKeyPublic()) return make_unique<AKey>(data, token.dataType); - } - if (token.dataType == DataType(DataType::KEY_AES)) { + if (token.dataType == DataType(DataType::KEY_AES)) return make_unique<SKey>(data, token.dataType); - } - if (token.dataType.isCertificate() || token.dataType.isChainCert()) { + if (token.dataType.isCertificate() || token.dataType.isChainCert()) return make_unique<Cert>(data, token.dataType); - } - if (token.dataType.isBinaryData()) { + if (token.dataType.isBinaryData()) return make_unique<BData>(data, token.dataType); - } ThrowErr(Exc::Crypto::DataTypeNotSupported, "This type of data is not supported by openssl backend: ", (int)token.dataType); @@ -203,7 +196,7 @@ TokenPair Store::generateAKey(const CryptoAlgorithm &algorithm, const Password &pubPass) { Internals::DataPair ret = Internals::generateAKey(algorithm); - return std::make_pair<Token,Token>( + return std::make_pair<Token, Token>( Token(m_backendId, ret.first.type, pack(ret.first.buffer, prvPass)), Token(m_backendId, ret.second.type, pack(ret.second.buffer, pubPass))); } @@ -214,12 +207,14 @@ Token Store::generateSKey(const CryptoAlgorithm &algorithm, const Password &pass return Token(m_backendId, ret.type, pack(ret.buffer, pass)); } -Token Store::import(const Data &data, const Password &pass) { +Token Store::import(const Data &data, const Password &pass) +{ return Token(m_backendId, data.type, pack(data.data, pass)); } -Token Store::importEncrypted(const Data &data, const Password &pass, const DataEncryption &enc) { - if(!m_deviceKey) +Token Store::importEncrypted(const Data &data, const Password &pass, const DataEncryption &enc) +{ + if (!m_deviceKey) ThrowErr(Exc::Crypto::InternalError, "No device key present"); // decrypt the AES key using device key diff --git a/src/manager/crypto/sw-backend/store.h b/src/manager/crypto/sw-backend/store.h index 860e3938..a29f30c0 100644 --- a/src/manager/crypto/sw-backend/store.h +++ b/src/manager/crypto/sw-backend/store.h @@ -36,7 +36,7 @@ public: virtual Token generateSKey(const CryptoAlgorithm &, const Password &); virtual Token import(const Data &data, const Password &); virtual Token importEncrypted(const Data &, const Password &, const DataEncryption &); - virtual void destroy(const Token &){} + virtual void destroy(const Token &) {} private: Crypto::GObjShPtr m_deviceKey; diff --git a/src/manager/crypto/tz-backend/obj.h b/src/manager/crypto/tz-backend/obj.h index 60e3a610..d8ca54a3 100644 --- a/src/manager/crypto/tz-backend/obj.h +++ b/src/manager/crypto/tz-backend/obj.h @@ -28,15 +28,17 @@ namespace TZ { class SKey : public GObj { public: - SKey(){} - virtual ~SKey(){} + SKey() {} + virtual ~SKey() {} + protected: }; class AKey : public GObj { public: - AKey(){} - virtual ~AKey(){} + AKey() {} + virtual ~AKey() {} + protected: }; diff --git a/src/manager/crypto/tz-backend/store.cpp b/src/manager/crypto/tz-backend/store.cpp index 4dd2b219..8fd12f1f 100644 --- a/src/manager/crypto/tz-backend/store.cpp +++ b/src/manager/crypto/tz-backend/store.cpp @@ -26,23 +26,28 @@ namespace CKM { namespace Crypto { namespace TZ { -Store::Store(CryptoBackend backendId) - : GStore(backendId) -{} +Store::Store(CryptoBackend backendId) : + GStore(backendId) +{ +} -GObjUPtr Store::getObject(const Token &, const Password &) { +GObjUPtr Store::getObject(const Token &, const Password &) +{ ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!"); } -TokenPair Store::generateAKey(const CryptoAlgorithm &, const Password &, const Password &) { +TokenPair Store::generateAKey(const CryptoAlgorithm &, const Password &, const Password &) +{ ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!"); } -Token Store::import(const Data &, const Password &) { +Token Store::import(const Data &, const Password &) +{ ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!"); } -Token Store::importEncrypted(const Data &, const Password &, const DataEncryption &) { +Token Store::importEncrypted(const Data &, const Password &, const DataEncryption &) +{ ThrowErr(Exc::Crypto::OperationNotSupported, "Trust zone backend is not implemented!"); } diff --git a/src/manager/dpl/core/include/dpl/binary_queue.h b/src/manager/dpl/core/include/dpl/binary_queue.h index 1bb43e37..e8f1a33f 100644 --- a/src/manager/dpl/core/include/dpl/binary_queue.h +++ b/src/manager/dpl/core/include/dpl/binary_queue.h @@ -41,13 +41,11 @@ typedef std::auto_ptr<BinaryQueue> BinaryQueueAutoPtr; * * @todo Add optimized implementation for FlattenConsume */ -class COMMON_API BinaryQueue +class COMMON_API BinaryQueue { // : public AbstractInputOutput -{ - public: - class Exception - { - public: +public: + class Exception { + public: DECLARE_EXCEPTION_TYPE(CKM::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OutOfData) }; @@ -58,9 +56,8 @@ class COMMON_API BinaryQueue size_t bufferSize, void *userParam); - class BucketVisitor - { - public: + class BucketVisitor { + public: /** * Destructor */ @@ -76,9 +73,8 @@ class COMMON_API BinaryQueue virtual void OnVisitBucket(const void *buffer, size_t bufferSize) = 0; }; - private: - struct Bucket - { +private: + struct Bucket { NONCOPYABLE(Bucket); const void *buffer; @@ -102,12 +98,11 @@ class COMMON_API BinaryQueue static void DeleteBucket(Bucket *bucket); - class BucketVisitorCall - { - private: + class BucketVisitorCall { + private: BucketVisitor *m_visitor; - public: + public: BucketVisitorCall(BucketVisitor *visitor); virtual ~BucketVisitorCall(); diff --git a/src/manager/dpl/core/include/dpl/exception.h b/src/manager/dpl/core/include/dpl/exception.h index 9aab85b1..7bc7ad30 100644 --- a/src/manager/dpl/core/include/dpl/exception.h +++ b/src/manager/dpl/core/include/dpl/exception.h @@ -48,9 +48,8 @@ class COMMON_API Exception static void AddRef(Exception* exception) { - if (!m_exceptionCount) { + if (!m_exceptionCount) m_terminateHandler = std::set_terminate(&TerminateHandler); - } ++m_exceptionCount; m_lastException = exception; @@ -58,9 +57,8 @@ class COMMON_API Exception static void UnRef(Exception* e) { - if (m_lastException == e) { + if (m_lastException == e) m_lastException = NULL; - } --m_exceptionCount; @@ -126,11 +124,10 @@ class COMMON_API Exception Exception(const Exception &other) { // Deep copy - if (other.m_reason != NULL) { + if (other.m_reason != NULL) m_reason = new Exception(*other.m_reason); - } else { + else m_reason = NULL; - } m_message = other.m_message; m_path = other.m_path; @@ -144,16 +141,14 @@ class COMMON_API Exception const Exception &operator =(const Exception &other) { - if (this == &other) { + if (this == &other) return *this; - } // Deep copy - if (other.m_reason != NULL) { + if (other.m_reason != NULL) m_reason = new Exception(*other.m_reason); - } else { + else m_reason = NULL; - } m_message = other.m_message; m_path = other.m_path; @@ -207,18 +202,16 @@ class COMMON_API Exception void Dump() const { // Show reason first - if (m_reason != NULL) { + if (m_reason != NULL) m_reason->Dump(); - } // Afterward, dump exception const char *file = strchr(m_path.c_str(), '/'); - if (file == NULL) { + if (file == NULL) file = m_path.c_str(); - } else { + else ++file; - } printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", file, m_line, @@ -230,17 +223,15 @@ class COMMON_API Exception std::string DumpToString() const { std::string ret; - if (m_reason != NULL) { + if (m_reason != NULL) ret = m_reason->DumpToString(); - } const char *file = strchr(m_path.c_str(), '/'); - if (file == NULL) { + if (file == NULL) file = m_path.c_str(); - } else { + else ++file; - } char buf[1024]; snprintf(buf, @@ -296,8 +287,7 @@ class COMMON_API Exception throw ClassName(__FILE__, __FUNCTION__, __LINE__) #define ThrowMsg(ClassName, Message) \ - do \ - { \ + do { \ std::ostringstream dplLoggingStream; \ dplLoggingStream << Message; \ throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str()); \ diff --git a/src/manager/dpl/core/include/dpl/fstream_accessors.h b/src/manager/dpl/core/include/dpl/fstream_accessors.h index b1aa17c6..e5850354 100644 --- a/src/manager/dpl/core/include/dpl/fstream_accessors.h +++ b/src/manager/dpl/core/include/dpl/fstream_accessors.h @@ -38,7 +38,8 @@ template<typename T> class FstreamAccessors : T::__filebuf_type { typedef FstreamAccessors<T> MyType; public: - static int GetFd(T &strm) { + static int GetFd(T &strm) + { return static_cast<MyType *>(strm.rdbuf())->_M_file.fd(); } }; diff --git a/src/manager/dpl/core/include/dpl/scoped_ptr.h b/src/manager/dpl/core/include/dpl/scoped_ptr.h index 37e5f90a..d39b0324 100644 --- a/src/manager/dpl/core/include/dpl/scoped_ptr.h +++ b/src/manager/dpl/core/include/dpl/scoped_ptr.h @@ -27,7 +27,8 @@ namespace CKM { struct free_deleter{ - void operator()(char *p) { + void operator()(char *p) + { free(p); } }; diff --git a/src/manager/dpl/core/include/dpl/serialization.h b/src/manager/dpl/core/include/dpl/serialization.h index 581fedd9..9f616808 100644 --- a/src/manager/dpl/core/include/dpl/serialization.h +++ b/src/manager/dpl/core/include/dpl/serialization.h @@ -32,8 +32,7 @@ namespace CKM { // Abstract data stream buffer -class IStream -{ +class IStream { public: virtual void Read(size_t num, void * bytes) = 0; virtual void Write(size_t num, const void * bytes) = 0; @@ -41,8 +40,7 @@ class IStream }; // Serializable interface -class ISerializable -{ +class ISerializable { public: /* ISerializable(){}; * ISerializable(IStream&){}; */ @@ -137,7 +135,7 @@ struct Serialization { // std::string template <typename T, typename R, typename A> - static void Serialize(IStream& stream, const std::basic_string<T,R,A>& str) + static void Serialize(IStream& stream, const std::basic_string<T, R, A>& str) { int length = str.size(); stream.Write(sizeof(length), &length); @@ -145,7 +143,7 @@ struct Serialization { } template<typename T, typename R, typename A> - static void Serialize(IStream& stream, const std::basic_string<T,R,A>* const str) + static void Serialize(IStream& stream, const std::basic_string<T, R, A>* const str) { int length = str->size(); stream.Write(sizeof(length), &length); @@ -162,9 +160,7 @@ struct Serialization { stream.Write(sizeof(length), &length); for (typename std::list<T>::const_iterator list_iter = list.begin(); list_iter != list.end(); list_iter++) - { Serialize(stream, *list_iter); - } } template <typename T> static void Serialize(IStream& stream, const std::list<T>* const list) @@ -194,9 +190,7 @@ struct Serialization { int length = vec.size(); stream.Write(sizeof(length), &length); for (const auto &i : vec) - { Serialize(stream, i); - } } template <typename T, typename A> static void Serialize(IStream& stream, const std::vector<T, A>* const vec) @@ -241,7 +235,6 @@ struct Serialization { { Serialize(stream, *p); } - }; // struct Serialization struct Deserialization { @@ -339,23 +332,23 @@ struct Deserialization { } template <typename T, typename R, typename A> - static void Deserialize(IStream& stream, std::basic_string<T,R,A>& str) + static void Deserialize(IStream& stream, std::basic_string<T, R, A>& str) { int length; stream.Read(sizeof(length), &length); std::vector<T> buf(length); stream.Read(length*sizeof(T), buf.data()); - str = std::basic_string<T,R,A>(buf.data(), buf.data()+length); + str = std::basic_string<T, R, A>(buf.data(), buf.data() + length); } template <typename T, typename R, typename A> - static void Deserialize(IStream& stream, std::basic_string<T,R,A>*& str) + static void Deserialize(IStream& stream, std::basic_string<T, R, A>*& str) { int length; stream.Read(sizeof(length), &length); std::vector<T> buf(length); stream.Read(length*sizeof(T), buf.data()); - str = new std::basic_string<T,R,A>(buf.data(), buf.data()+length); + str = new std::basic_string<T, R, A>(buf.data(), buf.data() + length); } // STL templates @@ -392,13 +385,13 @@ struct Deserialization { template <typename A> static void Deserialize(IStream& stream, std::vector<unsigned char, A>*& vec) { - vec = new std::vector<unsigned char,A>; + vec = new std::vector<unsigned char, A>; Deserialize(stream, *vec); } // std::vector template <typename T, typename A> - static void Deserialize(IStream& stream, std::vector<T,A>& vec) + static void Deserialize(IStream& stream, std::vector<T, A>& vec) { int length; stream.Read(sizeof(length), &length); @@ -409,9 +402,9 @@ struct Deserialization { } } template <typename T, typename A> - static void Deserialize(IStream& stream, std::vector<T,A>*& vec) + static void Deserialize(IStream& stream, std::vector<T, A>*& vec) { - vec = new std::vector<T,A>; + vec = new std::vector<T, A>; Deserialize(stream, *vec); } @@ -457,7 +450,8 @@ struct Serializer; template <typename First, typename... Args> struct Serializer<First, Args...> : public Serializer<Args...> { - static void Serialize(IStream& stream, const First& f, const Args&... args) { + static void Serialize(IStream& stream, const First& f, const Args&... args) + { Serialization::Serialize(stream, f); Serializer<Args...>::Serialize(stream, args...); } @@ -466,7 +460,8 @@ struct Serializer<First, Args...> : public Serializer<Args...> { // end of recursion template <> struct Serializer<> { - static void Serialize(IStream&) { + static void Serialize(IStream&) + { return; } }; @@ -477,7 +472,8 @@ struct Deserializer; template <typename First, typename... Args> struct Deserializer<First, Args...> : public Deserializer<Args...> { - static void Deserialize(IStream& stream, First& f, Args&... args) { + static void Deserialize(IStream& stream, First& f, Args&... args) + { Deserialization::Deserialize(stream, f); Deserializer<Args...>::Deserialize(stream, args...); } @@ -486,7 +482,8 @@ struct Deserializer<First, Args...> : public Deserializer<Args...> { // end of recursion template <> struct Deserializer<> { - static void Deserialize(IStream&) { + static void Deserialize(IStream&) + { return; } }; diff --git a/src/manager/dpl/core/src/assert.cpp b/src/manager/dpl/core/src/assert.cpp index 43898bd9..38ed526d 100644 --- a/src/manager/dpl/core/src/assert.cpp +++ b/src/manager/dpl/core/src/assert.cpp @@ -33,20 +33,17 @@ void AssertProc(const char *condition, const char *function) { #define INTERNAL_LOG(message) \ - do \ - { \ + do { \ std::ostringstream platformLog; \ platformLog << message; \ CKM::Log::LogSystemSingleton::Instance().Log( \ CKM::Log::AbstractLogProvider::LogLevel::Pedantic, \ platformLog.str().c_str(), \ __FILE__, __LINE__, __FUNCTION__); \ - } \ - while (0) + } while (0) // Try to log failed assertion to log system - Try - { + Try { INTERNAL_LOG( "################################################################################"); INTERNAL_LOG( diff --git a/src/manager/dpl/core/src/binary_queue.cpp b/src/manager/dpl/core/src/binary_queue.cpp index 5a3c42eb..8d3a232f 100644 --- a/src/manager/dpl/core/src/binary_queue.cpp +++ b/src/manager/dpl/core/src/binary_queue.cpp @@ -59,9 +59,8 @@ void BinaryQueue::AppendCopyFrom(const BinaryQueue &other) // To speed things up, always copy as one bucket void *bufferCopy = malloc(other.m_size); - if (bufferCopy == NULL) { + if (bufferCopy == NULL) throw std::bad_alloc(); - } try { other.Flatten(bufferCopy, other.m_size); @@ -108,9 +107,8 @@ void BinaryQueue::AppendCopy(const void* buffer, size_t bufferSize) void *bufferCopy = malloc(bufferSize); // Check if allocation succeded - if (bufferCopy == NULL) { + if (bufferCopy == NULL) throw std::bad_alloc(); - } // Copy user data memcpy(bufferCopy, buffer, bufferSize); @@ -162,9 +160,8 @@ bool BinaryQueue::Empty() const void BinaryQueue::Consume(size_t size) { // Check parameters - if (size > m_size) { + if (size > m_size) Throw(Exception::OutOfData); - } size_t bytesLeft = size; @@ -189,13 +186,11 @@ void BinaryQueue::Consume(size_t size) void BinaryQueue::Flatten(void *buffer, size_t bufferSize) const { // Check parameters - if (bufferSize == 0) { + if (bufferSize == 0) return; - } - if (bufferSize > m_size) { + if (bufferSize > m_size) Throw(Exception::OutOfData); - } size_t bytesLeft = bufferSize; void *ptr = buffer; @@ -264,14 +259,17 @@ BinaryQueue::Bucket::~Bucket() } BinaryQueue::BucketVisitor::~BucketVisitor() -{} +{ +} BinaryQueue::BucketVisitorCall::BucketVisitorCall(BucketVisitor *visitor) : m_visitor(visitor) -{} +{ +} BinaryQueue::BucketVisitorCall::~BucketVisitorCall() -{} +{ +} void BinaryQueue::BucketVisitorCall::operator()(Bucket *bucket) const { @@ -294,9 +292,8 @@ BinaryQueueAutoPtr BinaryQueue::Read(size_t size) std::unique_ptr<void, std::function<void(void*)>> bufferCopy(malloc(available), free); - if (!bufferCopy.get()) { + if (!bufferCopy.get()) throw std::bad_alloc(); - } BinaryQueueAutoPtr result(new BinaryQueue()); diff --git a/src/manager/dpl/core/src/errno_string.cpp b/src/manager/dpl/core/src/errno_string.cpp index fb1e2ac7..b9185299 100644 --- a/src/manager/dpl/core/src/errno_string.cpp +++ b/src/manager/dpl/core/src/errno_string.cpp @@ -34,8 +34,7 @@ #include <memory> namespace CKM { -namespace // anonymous -{ +namespace { // anonymous const size_t DEFAULT_ERRNO_STRING_SIZE = 32; } // namespace anonymous diff --git a/src/manager/dpl/db/include/dpl/db/sql_connection.h b/src/manager/dpl/db/include/dpl/db/sql_connection.h index 7c6e7565..6a05fdf4 100644 --- a/src/manager/dpl/db/include/dpl/db/sql_connection.h +++ b/src/manager/dpl/db/include/dpl/db/sql_connection.h @@ -38,14 +38,12 @@ namespace DB { /** * SQL connection class */ -class SqlConnection -{ +class SqlConnection { public: /** * SQL Exception classes */ - class Exception - { + class Exception { public: DECLARE_EXCEPTION_TYPE(CKM::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, SyntaxError) @@ -63,7 +61,7 @@ class SqlConnection typedef std::vector<std::string> Row; typedef std::vector<Row> Rows; - static int Callback(void*,int,char**,char**); + static int Callback(void*, int, char**, char**); const Row& GetNames() const { return m_names; } const Rows& GetValues() const { return m_values; } private: @@ -79,8 +77,7 @@ class SqlConnection /* * SQL processed data command */ - class DataCommand - { + class DataCommand { private: SqlConnection *m_masterConnection; sqlcipher3_stmt *m_stmt; @@ -392,13 +389,11 @@ class SqlConnection typedef std::unique_ptr<DataCommand> DataCommandUniquePtr; // Open flags - class Flag - { + class Flag { public: - enum Option - { + enum Option { RO = SQLCIPHER_OPEN_NOMUTEX | SQLCIPHER_OPEN_READONLY, - RW = SQLCIPHER_OPEN_NOMUTEX | SQLCIPHER_OPEN_READWRITE, + RW = SQLCIPHER_OPEN_NOMUTEX | SQLCIPHER_OPEN_READWRITE, CRW = RW | SQLCIPHER_OPEN_CREATE }; }; @@ -410,8 +405,7 @@ class SqlConnection * Synchronization object used to synchronize SQL connection * to the same database across different threads and processes */ - class SynchronizationObject - { + class SynchronizationObject { public: virtual ~SynchronizationObject() {} diff --git a/src/manager/dpl/db/src/naive_synchronization_object.cpp b/src/manager/dpl/db/src/naive_synchronization_object.cpp index c31e7420..ece4f26d 100644 --- a/src/manager/dpl/db/src/naive_synchronization_object.cpp +++ b/src/manager/dpl/db/src/naive_synchronization_object.cpp @@ -52,9 +52,8 @@ void NanoSleep(uint64_t nanoseconds) timespec remainingTime; for (;;) { - if (nanosleep(&requestedTime, &remainingTime) == 0) { + if (nanosleep(&requestedTime, &remainingTime) == 0) break; - } int error = errno; Assert(error == EINTR); diff --git a/src/manager/dpl/db/src/sql_connection.cpp b/src/manager/dpl/db/src/sql_connection.cpp index 20a01f27..9b053a05 100644..100755 --- a/src/manager/dpl/db/src/sql_connection.cpp +++ b/src/manager/dpl/db/src/sql_connection.cpp @@ -47,8 +47,7 @@ struct ScopedVaList { namespace CKM { namespace DB { -namespace // anonymous -{ +namespace { // anonymous class ScopedNotifyAll { private: @@ -60,13 +59,13 @@ class ScopedNotifyAll explicit ScopedNotifyAll( SqlConnection::SynchronizationObject *synchronizationObject) : m_synchronizationObject(synchronizationObject) - {} + { + } ~ScopedNotifyAll() { - if (!m_synchronizationObject) { + if (!m_synchronizationObject) return; - } LogPedantic("Notifying after successful synchronize"); m_synchronizationObject->NotifyAll(); @@ -126,9 +125,8 @@ SqlConnection::DataCommand::~DataCommand() { LogPedantic("SQL data command finalizing"); - if (sqlcipher3_finalize(m_stmt) != SQLCIPHER_OK) { + if (sqlcipher3_finalize(m_stmt) != SQLCIPHER_OK) LogError("Failed to finalize data command"); - } // Decrement stored data command count --m_masterConnection->m_dataCommandsCount; @@ -262,88 +260,80 @@ void SqlConnection::DataCommand::BindInteger( SqlConnection::ArgumentIndex position, const boost::optional<int> &value) { - if (!value) { + if (!value) BindNull(position); - } else { + else BindInteger(position, *value); - } } void SqlConnection::DataCommand::BindInt8( SqlConnection::ArgumentIndex position, const boost::optional<int8_t> &value) { - if (!value) { + if (!value) BindNull(position); - } else { + else BindInt8(position, *value); - } } void SqlConnection::DataCommand::BindInt16( SqlConnection::ArgumentIndex position, const boost::optional<int16_t> &value) { - if (!value) { + if (!value) BindNull(position); - } else { + else BindInt16(position, *value); - } } void SqlConnection::DataCommand::BindInt32( SqlConnection::ArgumentIndex position, const boost::optional<int32_t> &value) { - if (!value) { + if (!value) BindNull(position); - } else { + else BindInt32(position, *value); - } } void SqlConnection::DataCommand::BindInt64( SqlConnection::ArgumentIndex position, const boost::optional<int64_t> &value) { - if (!value) { + if (!value) BindNull(position); - } else { + else BindInt64(position, *value); - } } void SqlConnection::DataCommand::BindFloat( SqlConnection::ArgumentIndex position, const boost::optional<float> &value) { - if (!value) { + if (!value) BindNull(position); - } else { + else BindFloat(position, *value); - } } void SqlConnection::DataCommand::BindDouble( SqlConnection::ArgumentIndex position, const boost::optional<double> &value) { - if (!value) { + if (!value) BindNull(position); - } else { + else BindDouble(position, *value); - } } void SqlConnection::DataCommand::BindBlob( SqlConnection::ArgumentIndex position, const boost::optional<RawBuffer> &value) { - if (!!value) { + if (!!value) BindBlob(position, *value); - } else { + else BindNull(position); - } } bool SqlConnection::DataCommand::Step() @@ -407,9 +397,8 @@ void SqlConnection::DataCommand::Reset() void SqlConnection::DataCommand::CheckColumnIndex( SqlConnection::ColumnIndex column) { - if (column < 0 || column >= sqlcipher3_column_count(m_stmt)) { + if (column < 0 || column >= sqlcipher3_column_count(m_stmt)) ThrowMsg(Exception::InvalidColumn, "Column index is out of bounds"); - } } bool SqlConnection::DataCommand::IsColumnNull( @@ -501,9 +490,8 @@ std::string SqlConnection::DataCommand::GetColumnString( LogPedantic("Value: " << (value ? value : "NULL")); - if (value == NULL) { + if (value == NULL) return std::string(); - } return std::string(value); } @@ -517,9 +505,8 @@ RawBuffer SqlConnection::DataCommand::GetColumnBlob( const unsigned char *value = reinterpret_cast<const unsigned char*>( sqlcipher3_column_blob(m_stmt, column)); - if (value == NULL) { + if (value == NULL) return RawBuffer(); - } int length = sqlcipher3_column_bytes(m_stmt, column); LogPedantic("Got blob of length: " << length); @@ -533,9 +520,9 @@ boost::optional<int> SqlConnection::DataCommand::GetColumnOptionalInteger( LogPedantic("SQL data command get column optional integer: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<int>(); - } + int value = sqlcipher3_column_int(m_stmt, column); LogPedantic(" Value: " << value); return boost::optional<int>(value); @@ -547,9 +534,9 @@ boost::optional<int8_t> SqlConnection::DataCommand::GetColumnOptionalInt8( LogPedantic("SQL data command get column optional int8: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<int8_t>(); - } + int8_t value = static_cast<int8_t>(sqlcipher3_column_int(m_stmt, column)); LogPedantic(" Value: " << value); return boost::optional<int8_t>(value); @@ -561,9 +548,9 @@ boost::optional<int16_t> SqlConnection::DataCommand::GetColumnOptionalInt16( LogPedantic("SQL data command get column optional int16: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<int16_t>(); - } + int16_t value = static_cast<int16_t>(sqlcipher3_column_int(m_stmt, column)); LogPedantic(" Value: " << value); return boost::optional<int16_t>(value); @@ -575,9 +562,9 @@ boost::optional<int32_t> SqlConnection::DataCommand::GetColumnOptionalInt32( LogPedantic("SQL data command get column optional int32: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<int32_t>(); - } + int32_t value = static_cast<int32_t>(sqlcipher3_column_int(m_stmt, column)); LogPedantic(" Value: " << value); return boost::optional<int32_t>(value); @@ -589,9 +576,9 @@ boost::optional<int64_t> SqlConnection::DataCommand::GetColumnOptionalInt64( LogPedantic("SQL data command get column optional int64: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<int64_t>(); - } + int64_t value = static_cast<int64_t>(sqlcipher3_column_int64(m_stmt, column)); LogPedantic(" Value: " << value); return boost::optional<int64_t>(value); @@ -603,9 +590,9 @@ boost::optional<float> SqlConnection::DataCommand::GetColumnOptionalFloat( LogPedantic("SQL data command get column optional float: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<float>(); - } + float value = static_cast<float>(sqlcipher3_column_double(m_stmt, column)); LogPedantic(" Value: " << value); return boost::optional<float>(value); @@ -617,9 +604,9 @@ boost::optional<double> SqlConnection::DataCommand::GetColumnOptionalDouble( LogPedantic("SQL data command get column optional double: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<double>(); - } + double value = sqlcipher3_column_double(m_stmt, column); LogPedantic(" Value: " << value); return boost::optional<double>(value); @@ -631,9 +618,9 @@ boost::optional<RawBuffer> SqlConnection::DataCommand::GetColumnOptionalBlob( LogPedantic("SQL data command get column blog: [" << column << "]"); CheckColumnIndex(column); - if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) { + if (sqlcipher3_column_type(m_stmt, column) == SQLCIPHER_NULL) return boost::optional<RawBuffer>(); - } + const unsigned char *value = reinterpret_cast<const unsigned char*>( sqlcipher3_column_blob(m_stmt, column)); @@ -672,14 +659,14 @@ void SqlConnection::Connect(const std::string &address, TurnOnForeignKeys(); } -const std::string SQLCIPHER_RAW_PREFIX="x'"; -const std::string SQLCIPHER_RAW_SUFIX="'"; +const std::string SQLCIPHER_RAW_PREFIX = "x'"; +const std::string SQLCIPHER_RAW_SUFIX = "'"; const std::size_t SQLCIPHER_RAW_DATA_SIZE = 32; RawBuffer rawToHexString(const RawBuffer &raw) { RawBuffer output; - for(auto &e: raw) { + for (auto &e: raw) { char result[3]; snprintf(result, sizeof(result), "%02X", static_cast<unsigned int>(e)); output.push_back(static_cast<unsigned char>(result[0])); @@ -688,7 +675,8 @@ RawBuffer rawToHexString(const RawBuffer &raw) return output; } -RawBuffer createHexPass(const RawBuffer &rawPass){ +RawBuffer createHexPass(const RawBuffer &rawPass) +{ // We are required to pass 64byte long hex password made out of 32byte raw // binary data RawBuffer output; @@ -736,8 +724,7 @@ void SqlConnection::ResetKey(const RawBuffer &rawPassOld, } AssertMsg(rawPassOld.size() == SQLCIPHER_RAW_DATA_SIZE && rawPassNew.size() == SQLCIPHER_RAW_DATA_SIZE, - "Binary data for raw password should be 32 bytes long." - ); + "Binary data for raw password should be 32 bytes long."); // sqlcipher3_rekey requires for key to be already set if (!m_isKeySet) SetKey(rawPassOld); @@ -817,9 +804,8 @@ SqlConnection::SqlConnection(const std::string &address, // Connect to DB SqlConnection::Connect(address, option); - if (!m_synchronizationObject) { + if (!m_synchronizationObject) LogPedantic("No synchronization object defined"); - } } SqlConnection::~SqlConnection() @@ -839,7 +825,7 @@ SqlConnection::~SqlConnection() int SqlConnection::Output::Callback(void* param, int columns, char** values, char** names) { - if(param) + if (param) static_cast<Output*>(param)->SetResults(columns, values, names); return 0; } @@ -847,11 +833,11 @@ int SqlConnection::Output::Callback(void* param, int columns, char** values, cha void SqlConnection::Output::SetResults(int columns, char** values, char** names) { if (m_names.empty()) { - for (int i=0;i<columns;i++) + for (int i=0; i < columns; i++) m_names.push_back(names[i] ? names[i] : "NULL"); } Row row; - for (int i=0;i<columns;i++) + for (int i=0; i < columns; i++) row.push_back(values[i] ? values[i] : "NULL"); m_values.push_back(std::move(row)); } @@ -898,9 +884,8 @@ void SqlConnection::ExecCommandHelper(Output* out, const char* format, va_list a sqlcipher3_free(errorBuffer); } - if (ret == SQLCIPHER_OK) { + if (ret == SQLCIPHER_OK) return; - } if (ret == SQLCIPHER_BUSY) { LogPedantic("Collision occurred while executing SQL command"); @@ -952,9 +937,8 @@ SqlConnection::DataCommandUniquePtr SqlConnection::PrepareDataCommand( va_list args; va_start(args, format); - if (vasprintf(&rawBuffer, format, args) == -1) { + if (vasprintf(&rawBuffer, format, args) == -1) rawBuffer = NULL; - } va_end(args); diff --git a/src/manager/dpl/log/include/dpl/log/abstract_log_provider.h b/src/manager/dpl/log/include/dpl/log/abstract_log_provider.h index 4960e377..dd40fb33 100644 --- a/src/manager/dpl/log/include/dpl/log/abstract_log_provider.h +++ b/src/manager/dpl/log/include/dpl/log/abstract_log_provider.h @@ -24,8 +24,7 @@ namespace CKM { namespace Log { -class AbstractLogProvider -{ +class AbstractLogProvider { public: enum class LogLevel { None, diff --git a/src/manager/dpl/log/include/dpl/log/dlog_log_provider.h b/src/manager/dpl/log/include/dpl/log/dlog_log_provider.h index b594aa7b..77ad4ae9 100644 --- a/src/manager/dpl/log/include/dpl/log/dlog_log_provider.h +++ b/src/manager/dpl/log/include/dpl/log/dlog_log_provider.h @@ -27,8 +27,7 @@ namespace CKM { namespace Log { -class DLOGLogProvider : public AbstractLogProvider -{ +class DLOGLogProvider : public AbstractLogProvider { public: DLOGLogProvider(); virtual ~DLOGLogProvider(); diff --git a/src/manager/dpl/log/include/dpl/log/journal_log_provider.h b/src/manager/dpl/log/include/dpl/log/journal_log_provider.h index 08f56bca..3d9455c4 100644 --- a/src/manager/dpl/log/include/dpl/log/journal_log_provider.h +++ b/src/manager/dpl/log/include/dpl/log/journal_log_provider.h @@ -26,8 +26,7 @@ namespace CKM { namespace Log { -class JournalLogProvider: public AbstractLogProvider -{ +class JournalLogProvider: public AbstractLogProvider { public: JournalLogProvider(); virtual ~JournalLogProvider(); diff --git a/src/manager/dpl/log/include/dpl/log/log.h b/src/manager/dpl/log/include/dpl/log/log.h index 1865a236..aac1e7fe 100644 --- a/src/manager/dpl/log/include/dpl/log/log.h +++ b/src/manager/dpl/log/include/dpl/log/log.h @@ -38,8 +38,7 @@ namespace Log { /** * CKM log system */ -class COMMON_API LogSystem -{ +class COMMON_API LogSystem { public: NONCOPYABLE(LogSystem) @@ -101,8 +100,7 @@ class COMMON_API LogSystem /* * Replacement low overhead null logging class */ -class NullStream -{ +class NullStream { public: NullStream() {} @@ -133,11 +131,9 @@ typedef Singleton<LogSystem> LogSystemSingleton; } while (0) #define DPL_MACRO_FOR_LOGGING(message, level) \ -do \ -{ \ +do { \ if (level > CKM::Log::AbstractLogProvider::LogLevel::None && \ - CKM::Log::LogSystemSingleton::Instance().GetLogLevel() >= level) \ - { \ + CKM::Log::LogSystemSingleton::Instance().GetLogLevel() >= level) { \ std::ostringstream platformLog; \ platformLog << message; \ CKM::Log::LogSystemSingleton::Instance().Log(level, \ @@ -149,11 +145,9 @@ do } while (0) #define DPL_MACRO_FOR_LOGGING_POSITION(message, level, file, line, function) \ -do \ -{ \ +do { \ if (level > CKM::Log::AbstractLogProvider::LogLevel::None && \ - CKM::Log::LogSystemSingleton::Instance().GetLogLevel() >= level) \ - { \ + CKM::Log::LogSystemSingleton::Instance().GetLogLevel() >= level) { \ std::ostringstream platformLog; \ platformLog << message; \ CKM::Log::LogSystemSingleton::Instance().Log(level, \ @@ -194,7 +188,7 @@ do do { \ (void) file; (void) line; (void) function; \ DPL_MACRO_DUMMY_LOGGING(message, CKM::Log::AbstractLogProvider::LogLevel::Debug); \ - } while(0) + } while (0) #endif // BUILD_TYPE_DEBUG #endif // CENT_KEY_LOG_H diff --git a/src/manager/dpl/log/include/dpl/log/old_style_log_provider.h b/src/manager/dpl/log/include/dpl/log/old_style_log_provider.h index 57f7ebef..bb5b197f 100644 --- a/src/manager/dpl/log/include/dpl/log/old_style_log_provider.h +++ b/src/manager/dpl/log/include/dpl/log/old_style_log_provider.h @@ -26,8 +26,7 @@ namespace CKM { namespace Log { -class OldStyleLogProvider : public AbstractLogProvider -{ +class OldStyleLogProvider : public AbstractLogProvider { public: OldStyleLogProvider(); virtual ~OldStyleLogProvider() {} diff --git a/src/manager/dpl/log/src/dlog_log_provider.cpp b/src/manager/dpl/log/src/dlog_log_provider.cpp index 1b4449ed..1536965d 100644 --- a/src/manager/dpl/log/src/dlog_log_provider.cpp +++ b/src/manager/dpl/log/src/dlog_log_provider.cpp @@ -34,19 +34,24 @@ namespace { typedef void (*dlogMacro)(const char*, const char*); // I can't map LOG_ values because SLOG uses token concatenation -void error(const char* tag, const char* msg) { +void error(const char* tag, const char* msg) +{ SLOG(LOG_ERROR, tag, "%s", msg); } -void warning(const char* tag, const char* msg) { +void warning(const char* tag, const char* msg) +{ SLOG(LOG_WARN, tag, "%s", msg); } -void info(const char* tag, const char* msg) { +void info(const char* tag, const char* msg) +{ SLOG(LOG_INFO, tag, "%s", msg); } -void debug(const char* tag, const char* msg) { +void debug(const char* tag, const char* msg) +{ SLOG(LOG_DEBUG, tag, "%s", msg); } -void pedantic(const char* tag, const char* msg) { +void pedantic(const char* tag, const char* msg) +{ SLOG(LOG_VERBOSE, tag, "%s", msg); } std::map<AbstractLogProvider::LogLevel, dlogMacro> dlogMacros = { @@ -62,10 +67,12 @@ std::map<AbstractLogProvider::LogLevel, dlogMacro> dlogMacros = { DLOGLogProvider::DLOGLogProvider() -{} +{ +} DLOGLogProvider::~DLOGLogProvider() -{} +{ +} void DLOGLogProvider::SetTag(const char *tag) { diff --git a/src/manager/dpl/log/src/journal_log_provider.cpp b/src/manager/dpl/log/src/journal_log_provider.cpp index 8f7af576..2453cdc2 100644 --- a/src/manager/dpl/log/src/journal_log_provider.cpp +++ b/src/manager/dpl/log/src/journal_log_provider.cpp @@ -39,10 +39,12 @@ std::map<AbstractLogProvider::LogLevel, int> journalLevel = { } // namespace anonymous JournalLogProvider::JournalLogProvider() -{} +{ +} JournalLogProvider::~JournalLogProvider() -{} +{ +} void JournalLogProvider::Log(AbstractLogProvider::LogLevel level, const char *message, diff --git a/src/manager/dpl/log/src/log.cpp b/src/manager/dpl/log/src/log.cpp index 7e617691..9d246754 100644 --- a/src/manager/dpl/log/src/log.cpp +++ b/src/manager/dpl/log/src/log.cpp @@ -36,8 +36,7 @@ IMPLEMENT_SAFE_SINGLETON(CKM::Log::LogSystem); namespace CKM { namespace Log { -namespace // anonymous -{ +namespace { // anonymous /* * Set these variables to desired values in /etc/sysconfig/central-key-manager and restart * central-key-manager service to use them. @@ -54,7 +53,8 @@ const char * const DLOG = "DLOG"; const char * const JOURNALD = "JOURNALD"; } // namespace anonymous -LogSystem::LogSystem() : m_providerCtor({ +LogSystem::LogSystem() : + m_providerCtor({ #ifdef BUILD_TYPE_DEBUG { CONSOLE, []{ return static_cast<AbstractLogProvider*>(new OldStyleLogProvider()); } }, #endif // BUILD_TYPE_DEBUG diff --git a/src/manager/dpl/log/src/old_style_log_provider.cpp b/src/manager/dpl/log/src/old_style_log_provider.cpp index 66b18f1b..c62dac4a 100644..100755 --- a/src/manager/dpl/log/src/old_style_log_provider.cpp +++ b/src/manager/dpl/log/src/old_style_log_provider.cpp @@ -33,8 +33,8 @@ namespace CKM { namespace Log { -namespace // anonymous -{ +namespace { // anonymous + using namespace CKM::Colors::Text; const char *DEBUG_BEGIN = GREEN_BEGIN; const char *DEBUG_END = GREEN_END; @@ -82,7 +82,8 @@ std::map<AbstractLogProvider::LogLevel, ColorMark> consoleLevel = { } // namespace anonymous OldStyleLogProvider::OldStyleLogProvider() -{} +{ +} void OldStyleLogProvider::Log(AbstractLogProvider::LogLevel level, const char *message, @@ -102,7 +103,6 @@ void OldStyleLogProvider::Log(AbstractLogProvider::LogLevel level, } catch (const std::out_of_range&) { fprintf(stdout, "Unsupported log level: %d\n", level); } - } } diff --git a/src/manager/initial-values/BufferHandler.cpp b/src/manager/initial-values/BufferHandler.cpp index 0ceff740..38a7be35 100644..100755 --- a/src/manager/initial-values/BufferHandler.cpp +++ b/src/manager/initial-values/BufferHandler.cpp @@ -27,8 +27,7 @@ #include <xml-utils.h> #include <base64.h> -namespace -{ +namespace { const char * const XML_ATTR_IV = "IV"; } @@ -41,7 +40,7 @@ BufferHandler::~BufferHandler() {} void BufferHandler::Start(const XML::Parser::Attributes &attr) { // get key type - if(attr.find(XML_ATTR_IV) != attr.end()) { + if (attr.find(XML_ATTR_IV) != attr.end()) { std::string IVstring = attr.at(XML_ATTR_IV); Base64Decoder base64; base64.reset(); @@ -61,32 +60,31 @@ void BufferHandler::Characters(const std::string & data) void BufferHandler::End() { // decoding section - switch(m_encoding) + switch (m_encoding) { + // PEM requires that "----- END" section comes right after "\n" character + case PEM: { - // PEM requires that "----- END" section comes right after "\n" character - case PEM: - { - std::string trimmed = XML::trimEachLine(std::string(m_data.begin(), m_data.end())); - m_data = RawBuffer(trimmed.begin(), trimmed.end()); - break; - } + std::string trimmed = XML::trimEachLine(std::string(m_data.begin(), m_data.end())); + m_data = RawBuffer(trimmed.begin(), trimmed.end()); + break; + } - // Base64 decoder also does not accept any whitespaces - case DER: - case BASE64: - case ENCRYPTED: - { - std::string trimmed = XML::trimEachLine(std::string(m_data.begin(), m_data.end())); - Base64Decoder base64; - base64.reset(); - base64.append(RawBuffer(trimmed.begin(), trimmed.end())); - base64.finalize(); - m_data = base64.get(); - break; - } + // Base64 decoder also does not accept any whitespaces + case DER: + case BASE64: + case ENCRYPTED: + { + std::string trimmed = XML::trimEachLine(std::string(m_data.begin(), m_data.end())); + Base64Decoder base64; + base64.reset(); + base64.append(RawBuffer(trimmed.begin(), trimmed.end())); + base64.finalize(); + m_data = base64.get(); + break; + } - default: - break; + default: + break; } } diff --git a/src/manager/initial-values/BufferHandler.h b/src/manager/initial-values/BufferHandler.h index ef4d2cf9..2a44f450 100644 --- a/src/manager/initial-values/BufferHandler.h +++ b/src/manager/initial-values/BufferHandler.h @@ -31,8 +31,7 @@ namespace CKM { namespace InitialValues { -class BufferHandler : public XML::Parser::ElementHandler -{ +class BufferHandler : public XML::Parser::ElementHandler { public: typedef std::shared_ptr<BufferHandler> BufferHandlerPtr; @@ -43,17 +42,21 @@ public: virtual void Characters(const std::string & data); virtual void End(); - const RawBuffer & getData() const { + const RawBuffer & getData() const + { return m_data; } - bool isEncrypted() const { - if(m_encoding == EncodingType::ENCRYPTED) + bool isEncrypted() const + { + if (m_encoding == EncodingType::ENCRYPTED) return true; return false; } - const RawBuffer & getIV() const { + const RawBuffer & getIV() const + { return m_IV; } + private: EncodingType m_encoding; RawBuffer m_IV; diff --git a/src/manager/initial-values/CertHandler.h b/src/manager/initial-values/CertHandler.h index e31cbfa6..8e246d20 100644 --- a/src/manager/initial-values/CertHandler.h +++ b/src/manager/initial-values/CertHandler.h @@ -29,8 +29,7 @@ namespace CKM { namespace InitialValues { -class CertHandler : public InitialValueHandler -{ +class CertHandler : public InitialValueHandler { public: explicit CertHandler(CKMLogic & db_logic, const CKM::RawBuffer &encryptedKey) : InitialValueHandler(db_logic, encryptedKey) {} diff --git a/src/manager/initial-values/DataHandler.h b/src/manager/initial-values/DataHandler.h index cb5987b8..bab8316f 100644 --- a/src/manager/initial-values/DataHandler.h +++ b/src/manager/initial-values/DataHandler.h @@ -29,11 +29,10 @@ namespace CKM { namespace InitialValues { -class DataHandler : public InitialValueHandler -{ +class DataHandler : public InitialValueHandler { public: - explicit DataHandler(CKMLogic & db_logic, const CKM::RawBuffer &encryptedKey) - : InitialValueHandler(db_logic, encryptedKey) {} + explicit DataHandler(CKMLogic & db_logic, const CKM::RawBuffer &encryptedKey) : + InitialValueHandler(db_logic, encryptedKey) {} virtual ~DataHandler(); virtual DataType getDataType() const; diff --git a/src/manager/initial-values/InitialValueHandler.cpp b/src/manager/initial-values/InitialValueHandler.cpp index 71186248..d4d01bdb 100644..100755 --- a/src/manager/initial-values/InitialValueHandler.cpp +++ b/src/manager/initial-values/InitialValueHandler.cpp @@ -28,8 +28,7 @@ #include <EncodingType.h> #include <ckm/ckm-type.h> -namespace -{ +namespace { const char * const XML_ATTR_NAME = "name"; const char * const XML_ATTR_PASSWORD = "password"; const char * const XML_ATTR_EXPORTABLE = "exportable"; @@ -41,16 +40,15 @@ namespace InitialValues { void InitialValueHandler::Start(const XML::Parser::Attributes &attr) { // get name - if(attr.find(XML_ATTR_NAME) != attr.end()) + if (attr.find(XML_ATTR_NAME) != attr.end()) m_name = Alias(attr.at(XML_ATTR_NAME)); // get password - if(attr.find(XML_ATTR_PASSWORD) != attr.end()) + if (attr.find(XML_ATTR_PASSWORD) != attr.end()) m_password = Password(attr.at(XML_ATTR_PASSWORD).c_str()); // get exportable - if(attr.find(XML_ATTR_EXPORTABLE) != attr.end()) - { + if (attr.find(XML_ATTR_EXPORTABLE) != attr.end()) { std::string flagVal = attr.at(XML_ATTR_EXPORTABLE); std::transform(flagVal.begin(), flagVal.end(), flagVal.begin(), ::tolower); std::istringstream is(flagVal); @@ -64,12 +62,11 @@ void InitialValueHandler::End() LogError("Invalid data with name: " << m_name << ", reason: no key data!"); return; } - // save data Policy policy(m_password, m_exportable); Crypto::DataEncryption de; - if(m_bufferHandler->isEncrypted()) { + if (m_bufferHandler->isEncrypted()) { de.encryptedKey = m_encryptedKey; de.iv = m_bufferHandler->getIV(); } @@ -79,15 +76,14 @@ void InitialValueHandler::End() de, policy); - if(CKM_API_SUCCESS != ec) { + if (CKM_API_SUCCESS != ec) { LogError("Saving type: " << getDataType() << " with params: name(" << m_name << "), exportable(" << m_exportable<< ") failed, code: " << ec); return; } // save permissions - for(const auto & permission : m_permissions) - { + for (const auto & permission : m_permissions) { ec = m_db_logic.setPermissionHelper( Credentials(CKMLogic::SYSTEM_DB_UID, OWNER_ID_SYSTEM), m_name, @@ -100,8 +96,7 @@ void InitialValueHandler::End() ") failed, code: " << ec); } } -} - +} BufferHandler::BufferHandlerPtr InitialValueHandler::CreateBufferHandler(EncodingType type) { diff --git a/src/manager/initial-values/InitialValueHandler.h b/src/manager/initial-values/InitialValueHandler.h index 0e9dcc50..29043d46 100644 --- a/src/manager/initial-values/InitialValueHandler.h +++ b/src/manager/initial-values/InitialValueHandler.h @@ -35,14 +35,13 @@ namespace CKM { namespace InitialValues { -class InitialValueHandler : public NoCharactersHandler -{ +class InitialValueHandler : public NoCharactersHandler { public: typedef std::shared_ptr<InitialValueHandler> InitialValueHandlerPtr; explicit InitialValueHandler(CKMLogic & db_logic, const CKM::RawBuffer &encryptedKey) : m_exportable(false), m_db_logic(db_logic), m_encryptedKey(encryptedKey) {} - virtual ~InitialValueHandler() {}; + virtual ~InitialValueHandler() {} BufferHandler::BufferHandlerPtr CreateBufferHandler(EncodingType type); PermissionHandler::PermissionHandlerPtr CreatePermissionHandler(); diff --git a/src/manager/initial-values/InitialValuesFile.cpp b/src/manager/initial-values/InitialValuesFile.cpp index 31cebb0b..d13e8218 100644..100755 --- a/src/manager/initial-values/InitialValuesFile.cpp +++ b/src/manager/initial-values/InitialValuesFile.cpp @@ -184,17 +184,16 @@ void InitialValuesFile::registerElementListeners() void InitialValuesFile::Error(const XML::Parser::ErrorType errorType, const std::string & log_msg) { - switch(errorType) - { - case XML::Parser::VALIDATION_ERROR: - LogWarning("validating error: " << log_msg); - break; - case XML::Parser::PARSE_WARNING: - LogWarning("parsing warning: " << log_msg); - break; - case XML::Parser::PARSE_ERROR: - LogWarning("parsing error: " << log_msg); - break; + switch (errorType) { + case XML::Parser::VALIDATION_ERROR: + LogWarning("validating error: " << log_msg); + break; + case XML::Parser::PARSE_WARNING: + LogWarning("parsing warning: " << log_msg); + break; + case XML::Parser::PARSE_ERROR: + LogWarning("parsing error: " << log_msg); + break; } } @@ -206,7 +205,7 @@ int InitialValuesFile::Validate(const std::string &XSD_file) int InitialValuesFile::Parse() { int ec = m_parser.Parse(); - if(!m_header || !m_header->isCorrectVersion()) { + if (!m_header || !m_header->isCorrectVersion()) { LogError("bypassing XML file: " << m_filename << " - wrong file version!"); ec = XML::Parser::ERROR_INVALID_VERSION; } @@ -216,23 +215,22 @@ int InitialValuesFile::Parse() XML::Parser::ElementHandlerPtr InitialValuesFile::GetObjectHandler(ObjectType type, const CKM::RawBuffer &encryptedKey) { - switch(type) - { - case KEY: - m_currentHandler = std::make_shared<KeyHandler>(m_db_logic, encryptedKey); - break; + switch (type) { + case KEY: + m_currentHandler = std::make_shared<KeyHandler>(m_db_logic, encryptedKey); + break; - case CERT: - m_currentHandler = std::make_shared<CertHandler>(m_db_logic, encryptedKey); - break; + case CERT: + m_currentHandler = std::make_shared<CertHandler>(m_db_logic, encryptedKey); + break; - case DATA: - m_currentHandler = std::make_shared<DataHandler>(m_db_logic, encryptedKey); - break; + case DATA: + m_currentHandler = std::make_shared<DataHandler>(m_db_logic, encryptedKey); + break; - default: - m_currentHandler.reset(); - break; + default: + m_currentHandler.reset(); + break; } return m_currentHandler; @@ -248,7 +246,7 @@ void InitialValuesFile::ReleaseObjectHandler(ObjectType /*type*/) XML::Parser::ElementHandlerPtr InitialValuesFile::GetBufferHandler(EncodingType type) { - if( !m_currentHandler ) + if ( !m_currentHandler ) return XML::Parser::ElementHandlerPtr(); return m_currentHandler->CreateBufferHandler(type); @@ -260,7 +258,7 @@ void InitialValuesFile::ReleaseBufferHandler(EncodingType /*type*/) XML::Parser::ElementHandlerPtr InitialValuesFile::GetPermissionHandler() { - if( !m_currentHandler ) + if ( !m_currentHandler ) return XML::Parser::ElementHandlerPtr(); return m_currentHandler->CreatePermissionHandler(); @@ -271,11 +269,14 @@ void InitialValuesFile::ReleasePermissionHandler() InitialValuesFile::EncryptionKeyHandler::EncryptionKeyHandler(InitialValuesFile & parent) : m_parent(parent) {} -void InitialValuesFile::EncryptionKeyHandler::Characters(const std::string &data) { +void InitialValuesFile::EncryptionKeyHandler::Characters(const std::string &data) +{ m_encryptedKey.reserve(m_encryptedKey.size() + data.size()); m_encryptedKey.insert(m_encryptedKey.end(), data.begin(), data.end()); }; -void InitialValuesFile::EncryptionKeyHandler::End() { + +void InitialValuesFile::EncryptionKeyHandler::End() +{ std::string trimmed = XML::trimEachLine(std::string(m_encryptedKey.begin(), m_encryptedKey.end())); Base64Decoder base64; base64.reset(); @@ -284,24 +285,28 @@ void InitialValuesFile::EncryptionKeyHandler::End() { m_encryptedKey = base64.get(); }; -CKM::RawBuffer InitialValuesFile::EncryptionKeyHandler::getEncryptedKey() const { +CKM::RawBuffer InitialValuesFile::EncryptionKeyHandler::getEncryptedKey() const +{ return m_encryptedKey; } -InitialValuesFile::HeaderHandler::HeaderHandler(InitialValuesFile & parent) - : m_version(-1), m_parent(parent) {} +InitialValuesFile::HeaderHandler::HeaderHandler(InitialValuesFile & parent) : + m_version(-1), m_parent(parent) +{ +} + void InitialValuesFile::HeaderHandler::Start(const XML::Parser::Attributes & attr) { // get key type - if(attr.find(XML_ATTR_VERSION) != attr.end()) - { + if (attr.find(XML_ATTR_VERSION) != attr.end()) { m_version = atoi(attr.at(XML_ATTR_VERSION).c_str()); - if(isCorrectVersion()) + if (isCorrectVersion()) m_parent.registerElementListeners(); } } -bool InitialValuesFile::HeaderHandler::isCorrectVersion() const { +bool InitialValuesFile::HeaderHandler::isCorrectVersion() const +{ return m_version == XML_CURRENT_VERSION; } diff --git a/src/manager/initial-values/InitialValuesFile.h b/src/manager/initial-values/InitialValuesFile.h index c3cccbb8..bd450910 100644 --- a/src/manager/initial-values/InitialValuesFile.h +++ b/src/manager/initial-values/InitialValuesFile.h @@ -36,8 +36,7 @@ namespace CKM { namespace InitialValues { -class InitialValuesFile -{ +class InitialValuesFile { public: InitialValuesFile(const std::string &XML_filename, CKMLogic & db_logic); @@ -62,13 +61,12 @@ protected: void ReleasePermissionHandler(); private: - class HeaderHandler : public XML::Parser::ElementHandler - { + class HeaderHandler : public XML::Parser::ElementHandler { public: explicit HeaderHandler(InitialValuesFile & parent); virtual void Start(const XML::Parser::Attributes & attr); - virtual void Characters(const std::string &) {}; - virtual void End() {}; + virtual void Characters(const std::string &) {} + virtual void End() {} bool isCorrectVersion() const; @@ -77,15 +75,15 @@ private: InitialValuesFile & m_parent; }; - class EncryptionKeyHandler : public XML::Parser::ElementHandler - { + class EncryptionKeyHandler : public XML::Parser::ElementHandler { public: explicit EncryptionKeyHandler(InitialValuesFile & parent); - virtual void Start(const XML::Parser::Attributes &) {}; + virtual void Start(const XML::Parser::Attributes &) {} virtual void Characters(const std::string &data); virtual void End(); CKM::RawBuffer getEncryptedKey() const; + private: CKM::RawBuffer m_encryptedKey; InitialValuesFile & m_parent; @@ -104,7 +102,6 @@ private: void registerElementListeners(); static void Error(const XML::Parser::ErrorType errorType, const std::string & logMsg); - }; } diff --git a/src/manager/initial-values/KeyHandler.cpp b/src/manager/initial-values/KeyHandler.cpp index 5b2bb46c..ef358e82 100644..100755 --- a/src/manager/initial-values/KeyHandler.cpp +++ b/src/manager/initial-values/KeyHandler.cpp @@ -27,8 +27,7 @@ #include <InitialValueHandler.h> #include <ckm/ckm-type.h> -namespace -{ +namespace { const char * const XML_ATTR_TYPE = "type"; const char * const XML_ATTR_TYPE_VAL_RSA_PRV = "RSA_PRV"; const char * const XML_ATTR_TYPE_VAL_RSA_PUB = "RSA_PUB"; @@ -49,19 +48,19 @@ void KeyHandler::Start(const XML::Parser::Attributes &attr) InitialValueHandler::Start(attr); // get key type - if(attr.find(XML_ATTR_TYPE) != attr.end()) + if (attr.find(XML_ATTR_TYPE) != attr.end()) m_keyType = KeyHandler::parseType(attr.at(XML_ATTR_TYPE)); } KeyType KeyHandler::parseType(const std::string & typeStr) { - if (typeStr == XML_ATTR_TYPE_VAL_RSA_PRV) return KeyType::KEY_RSA_PRIVATE; - else if(typeStr == XML_ATTR_TYPE_VAL_RSA_PUB) return KeyType::KEY_RSA_PUBLIC; - else if(typeStr == XML_ATTR_TYPE_VAL_DSA_PRV) return KeyType::KEY_DSA_PRIVATE; - else if(typeStr == XML_ATTR_TYPE_VAL_DSA_PUB) return KeyType::KEY_DSA_PUBLIC; - else if(typeStr == XML_ATTR_TYPE_VAL_ECDSA_PRV) return KeyType::KEY_ECDSA_PRIVATE; - else if(typeStr == XML_ATTR_TYPE_VAL_ECDSA_PUB) return KeyType::KEY_ECDSA_PUBLIC; - else if(typeStr == XML_ATTR_TYPE_VAL_AES) return KeyType::KEY_AES; + if (typeStr == XML_ATTR_TYPE_VAL_RSA_PRV) return KeyType::KEY_RSA_PRIVATE; + else if (typeStr == XML_ATTR_TYPE_VAL_RSA_PUB) return KeyType::KEY_RSA_PUBLIC; + else if (typeStr == XML_ATTR_TYPE_VAL_DSA_PRV) return KeyType::KEY_DSA_PRIVATE; + else if (typeStr == XML_ATTR_TYPE_VAL_DSA_PUB) return KeyType::KEY_DSA_PUBLIC; + else if (typeStr == XML_ATTR_TYPE_VAL_ECDSA_PRV) return KeyType::KEY_ECDSA_PRIVATE; + else if (typeStr == XML_ATTR_TYPE_VAL_ECDSA_PUB) return KeyType::KEY_ECDSA_PUBLIC; + else if (typeStr == XML_ATTR_TYPE_VAL_AES) return KeyType::KEY_AES; else // should not happen throw std::runtime_error("error: invalid value discovered as key type"); } diff --git a/src/manager/initial-values/KeyHandler.h b/src/manager/initial-values/KeyHandler.h index b921b47c..9f374135 100644 --- a/src/manager/initial-values/KeyHandler.h +++ b/src/manager/initial-values/KeyHandler.h @@ -30,16 +30,16 @@ namespace CKM { namespace InitialValues { -class KeyHandler : public InitialValueHandler -{ +class KeyHandler : public InitialValueHandler { public: - explicit KeyHandler(CKMLogic & db_logic, const CKM::RawBuffer &encryptedKey) - : InitialValueHandler(db_logic, encryptedKey), m_keyType(KeyType::KEY_NONE) {} + explicit KeyHandler(CKMLogic & db_logic, const CKM::RawBuffer &encryptedKey) : + InitialValueHandler(db_logic, encryptedKey), m_keyType(KeyType::KEY_NONE) {} virtual ~KeyHandler(); virtual void Start(const XML::Parser::Attributes &); virtual DataType getDataType() const; + protected: static KeyType parseType(const std::string & typeStr); diff --git a/src/manager/initial-values/NoCharactersHandler.cpp b/src/manager/initial-values/NoCharactersHandler.cpp index 8c3f9691..0ee9ff93 100644..100755 --- a/src/manager/initial-values/NoCharactersHandler.cpp +++ b/src/manager/initial-values/NoCharactersHandler.cpp @@ -31,7 +31,7 @@ namespace InitialValues { void NoCharactersHandler::Characters(const std::string & data) { auto f = find_if(data.begin(), data.end(), [](char c){ return std::isspace(c) == 0;}); - if(f != data.end()) + if (f != data.end()) throw std::runtime_error( "error: value handler detected raw data outside data-specific tag"); } diff --git a/src/manager/initial-values/NoCharactersHandler.h b/src/manager/initial-values/NoCharactersHandler.h index 2a9a4182..63f16c8d 100644 --- a/src/manager/initial-values/NoCharactersHandler.h +++ b/src/manager/initial-values/NoCharactersHandler.h @@ -27,8 +27,7 @@ namespace CKM { namespace InitialValues { -class NoCharactersHandler : public XML::Parser::ElementHandler -{ +class NoCharactersHandler : public XML::Parser::ElementHandler { public: void Characters(const std::string & data); diff --git a/src/manager/initial-values/PermissionHandler.cpp b/src/manager/initial-values/PermissionHandler.cpp index 63e9ee02..80ff0317 100644..100755 --- a/src/manager/initial-values/PermissionHandler.cpp +++ b/src/manager/initial-values/PermissionHandler.cpp @@ -23,8 +23,7 @@ #include <ckm/ckm-type.h> #include <PermissionHandler.h> -namespace -{ +namespace { const char * const XML_ATTR_ACCESSOR = "accessor"; } @@ -36,7 +35,7 @@ PermissionHandler::~PermissionHandler() {} void PermissionHandler::Start(const XML::Parser::Attributes & attr) { // get accessor label - if(attr.find(XML_ATTR_ACCESSOR) != attr.end()) + if (attr.find(XML_ATTR_ACCESSOR) != attr.end()) m_accessor = Label(attr.at(XML_ATTR_ACCESSOR)); } diff --git a/src/manager/initial-values/PermissionHandler.h b/src/manager/initial-values/PermissionHandler.h index 9eb3ca47..5d1f44b0 100644 --- a/src/manager/initial-values/PermissionHandler.h +++ b/src/manager/initial-values/PermissionHandler.h @@ -30,8 +30,7 @@ namespace CKM { namespace InitialValues { -class PermissionHandler : public NoCharactersHandler -{ +class PermissionHandler : public NoCharactersHandler { public: typedef std::shared_ptr<PermissionHandler> PermissionHandlerPtr; @@ -40,9 +39,11 @@ public: virtual void Start(const XML::Parser::Attributes &); virtual void End(); - const Label & getAccessor() const { + const Label & getAccessor() const + { return m_accessor; } + private: Label m_accessor; }; diff --git a/src/manager/initial-values/SWKeyFile.cpp b/src/manager/initial-values/SWKeyFile.cpp index f6141852..e8605506 100644..100755 --- a/src/manager/initial-values/SWKeyFile.cpp +++ b/src/manager/initial-values/SWKeyFile.cpp @@ -40,10 +40,10 @@ const char * const XML_ATTR_VERSION = "version"; namespace CKM { namespace InitialValues { -SWKeyFile::SWKeyFile(const std::string &XML_filename) - : m_parser(XML_filename), - m_header(std::make_shared<HeaderHandler>(*this)), - m_RSAKeyHandler(std::make_shared<RSAKeyHandler>(*this)) +SWKeyFile::SWKeyFile(const std::string &XML_filename) : + m_parser(XML_filename), + m_header(std::make_shared<HeaderHandler>(*this)), + m_RSAKeyHandler(std::make_shared<RSAKeyHandler>(*this)) { m_parser.RegisterErrorCb(SWKeyFile::Error); m_parser.RegisterElementCb(XML_TAG_DEVICE_KEY, @@ -70,17 +70,16 @@ void SWKeyFile::registerElementListeners() void SWKeyFile::Error(const XML::Parser::ErrorType errorType, const std::string & log_msg) { - switch(errorType) - { - case XML::Parser::VALIDATION_ERROR: - LogWarning("validating error: " << log_msg); - break; - case XML::Parser::PARSE_WARNING: - LogWarning("parsing warning: " << log_msg); - break; - case XML::Parser::PARSE_ERROR: - LogWarning("parsing error: " << log_msg); - break; + switch (errorType) { + case XML::Parser::VALIDATION_ERROR: + LogWarning("validating error: " << log_msg); + break; + case XML::Parser::PARSE_WARNING: + LogWarning("parsing warning: " << log_msg); + break; + case XML::Parser::PARSE_ERROR: + LogWarning("parsing error: " << log_msg); + break; } } @@ -92,7 +91,7 @@ int SWKeyFile::Validate(const std::string &XSD_file) int SWKeyFile::Parse() { int ec = m_parser.Parse(); - if(!m_header || !m_header->isCorrectVersion()) { + if (!m_header || !m_header->isCorrectVersion()) { LogError("bypassing XML file: " << m_filename << " - wrong file version!"); ec = XML::Parser::ERROR_INVALID_VERSION; } @@ -103,15 +102,18 @@ int SWKeyFile::Parse() SWKeyFile::RSAKeyHandler::RSAKeyHandler(SWKeyFile & parent) : m_parent(parent) -{} +{ +} -void SWKeyFile::RSAKeyHandler::Characters(const std::string &data) { +void SWKeyFile::RSAKeyHandler::Characters(const std::string &data) +{ //m_encryptedKey.reserve(m_encryptedKey.size() + data.size()); //m_encryptedKey.insert(m_encryptedKey.end(), data.begin(), data.end()); std::copy(data.begin(), data.end(), std::back_inserter(m_encryptedKey)); } -void SWKeyFile::RSAKeyHandler::End() { +void SWKeyFile::RSAKeyHandler::End() +{ // std::string trimmed = XML::trimEachLine(std::string(m_encryptedKey.begin(), m_encryptedKey.end())); Base64Decoder base64; @@ -121,24 +123,29 @@ void SWKeyFile::RSAKeyHandler::End() { m_encryptedKey = base64.get(); }; -Crypto::GObjShPtr SWKeyFile::RSAKeyHandler::getPrivKey() { +Crypto::GObjShPtr SWKeyFile::RSAKeyHandler::getPrivKey() +{ return std::make_shared<Crypto::SW::AKey>(m_encryptedKey, DataType::KEY_RSA_PRIVATE); } -SWKeyFile::HeaderHandler::HeaderHandler(SWKeyFile & parent) - : m_version(-1), m_parent(parent) {} +SWKeyFile::HeaderHandler::HeaderHandler(SWKeyFile & parent) : + m_version(-1), m_parent(parent) +{ +} + void SWKeyFile::HeaderHandler::Start(const XML::Parser::Attributes & attr) { // get key type - if(attr.find(XML_ATTR_VERSION) != attr.end()) - { + if (attr.find(XML_ATTR_VERSION) != attr.end()) { m_version = atoi(attr.at(XML_ATTR_VERSION).c_str()); - if(isCorrectVersion()) + if (isCorrectVersion()) m_parent.registerElementListeners(); } } -bool SWKeyFile::HeaderHandler::isCorrectVersion() const { + +bool SWKeyFile::HeaderHandler::isCorrectVersion() const +{ return m_version == XML_SW_KEY_CURRENT_VERSION; } diff --git a/src/manager/initial-values/SWKeyFile.h b/src/manager/initial-values/SWKeyFile.h index 887c0a98..8768ade1 100644 --- a/src/manager/initial-values/SWKeyFile.h +++ b/src/manager/initial-values/SWKeyFile.h @@ -37,26 +37,25 @@ namespace CKM { namespace InitialValues { -class SWKeyFile -{ +class SWKeyFile { public: explicit SWKeyFile(const std::string &XML_filename); int Validate(const std::string &XSD_file); int Parse(); - Crypto::GObjShPtr getPrivKey() { + Crypto::GObjShPtr getPrivKey() + { return m_deviceKey; } private: - class HeaderHandler : public XML::Parser::ElementHandler - { + class HeaderHandler : public XML::Parser::ElementHandler { public: explicit HeaderHandler(SWKeyFile & parent); virtual void Start(const XML::Parser::Attributes & attr); - virtual void Characters(const std::string &) {}; - virtual void End() {}; + virtual void Characters(const std::string &) {} + virtual void End() {} bool isCorrectVersion() const; @@ -65,15 +64,15 @@ private: SWKeyFile & m_parent; }; - class RSAKeyHandler : public XML::Parser::ElementHandler - { + class RSAKeyHandler : public XML::Parser::ElementHandler { public: explicit RSAKeyHandler(SWKeyFile & parent); - virtual void Start(const XML::Parser::Attributes &) {}; + virtual void Start(const XML::Parser::Attributes &) {} virtual void Characters(const std::string &data); virtual void End(); Crypto::GObjShPtr getPrivKey(); + private: CKM::RawBuffer m_encryptedKey; SWKeyFile & m_parent; @@ -90,7 +89,6 @@ private: void registerElementListeners(); static void Error(const XML::Parser::ErrorType errorType, const std::string & logMsg); - }; } diff --git a/src/manager/initial-values/initial-value-loader.cpp b/src/manager/initial-values/initial-value-loader.cpp index 01bb79c3..c0d4b932 100644..100755 --- a/src/manager/initial-values/initial-value-loader.cpp +++ b/src/manager/initial-values/initial-value-loader.cpp @@ -35,21 +35,21 @@ const char * const INIT_VALUES_FILE_SUFFIX = ".xml"; namespace CKM { namespace InitialValues { -void LoadFiles(CKMLogic &logic) { +void LoadFiles(CKMLogic &logic) +{ try { std::vector<std::string> filesToParse; DIR *dp = opendir(INIT_VALUES_DIR); - if(dp) - { + if (dp) { struct dirent *entry; - while ((entry = readdir(dp))) - { + while ((entry = readdir(dp))) { std::string filename = std::string(entry->d_name); // check if XML file std::string lowercaseFilename = filename; std::transform(lowercaseFilename.begin(), lowercaseFilename.end(), lowercaseFilename.begin(), ::tolower); - if(lowercaseFilename.find(INIT_VALUES_FILE_SUFFIX) == std::string::npos) + + if (lowercaseFilename.find(INIT_VALUES_FILE_SUFFIX) == std::string::npos) continue; filesToParse.push_back(std::string(INIT_VALUES_DIR) + filename); @@ -58,18 +58,16 @@ void LoadFiles(CKMLogic &logic) { } // parse - for(const auto & file : filesToParse) - { + for (const auto & file : filesToParse) { InitialValues::InitialValuesFile xmlFile(file.c_str(), logic); int rc = xmlFile.Validate(INIT_VALUES_XSD); - if(rc == XML::Parser::PARSE_SUCCESS) - { + if (rc == XML::Parser::PARSE_SUCCESS) { rc = xmlFile.Parse(); - if(rc != XML::Parser::PARSE_SUCCESS) + if (rc != XML::Parser::PARSE_SUCCESS) LogError("invalid initial values file: " << file << ", parsing code: " << rc); - } - else + } else { LogError("invalid initial values file: " << file << ", validation code: " << rc); + } unlink(file.c_str()); } } catch (...) { diff --git a/src/manager/initial-values/parser.cpp b/src/manager/initial-values/parser.cpp index 6d6cd1ea..170e9b52 100644..100755 --- a/src/manager/initial-values/parser.cpp +++ b/src/manager/initial-values/parser.cpp @@ -42,8 +42,8 @@ struct LibXmlCleanup { } // namespace anonymous -Parser::Parser(const std::string &XML_filename) - : m_errorCb(0) +Parser::Parser(const std::string &XML_filename) : + m_errorCb(0) { m_XMLfile = XML_filename; memset(&m_saxHandler, 0, sizeof(m_saxHandler)); @@ -59,7 +59,7 @@ Parser::~Parser() int Parser::Validate(const std::string &XSD_schema) { - if(XSD_schema.empty()) { + if (XSD_schema.empty()) { LogError("no XSD file path given"); return ERROR_INVALID_ARGUMENT; } @@ -68,7 +68,7 @@ int Parser::Validate(const std::string &XSD_schema) std::unique_ptr<xmlSchemaParserCtxt, void(*)(xmlSchemaParserCtxtPtr)> parserCtxt(xmlSchemaNewParserCtxt(XSD_schema.c_str()), [](xmlSchemaParserCtxtPtr ctx){ xmlSchemaFreeParserCtxt(ctx); }); - if(!parserCtxt) { + if (!parserCtxt) { LogError("XSD file path is invalid"); return ERROR_INVALID_ARGUMENT; } @@ -76,7 +76,7 @@ int Parser::Validate(const std::string &XSD_schema) std::unique_ptr<xmlSchema, void(*)(xmlSchemaPtr)> schema(xmlSchemaParse(parserCtxt.get()), [](xmlSchemaPtr schemaPtr){ xmlSchemaFree(schemaPtr); }); - if(!schema) { + if (!schema) { LogError("Parsing XSD file failed"); return ERROR_XSD_PARSE_FAILED; } @@ -85,7 +85,7 @@ int Parser::Validate(const std::string &XSD_schema) std::unique_ptr<xmlSchemaValidCtxt, void(*)(xmlSchemaValidCtxtPtr)> validCtxt(xmlSchemaNewValidCtxt(schema.get()), [](xmlSchemaValidCtxtPtr validCtxPtr){ xmlSchemaFreeValidCtxt(validCtxPtr); }); - if(!validCtxt) { + if (!validCtxt) { LogError("Internal parser error"); return ERROR_INTERNAL; } @@ -96,29 +96,29 @@ int Parser::Validate(const std::string &XSD_schema) xmlThrDefSetGenericErrorFunc(this, &Parser::ErrorValidate); retCode = xmlSchemaValidateFile(validCtxt.get(), m_XMLfile.c_str(), 0); - if(0 != retCode) { + if (0 != retCode) { LogWarning("Validating XML file failed, ec: " << retCode); retCode = ERROR_XML_VALIDATION_FAILED; - } - else + } else { retCode = PARSE_SUCCESS; + } return retCode; } int Parser::Parse() { - if(m_elementListenerMap.empty()) { + if (m_elementListenerMap.empty()) { LogError("Can not parse XML file: no registered element callbacks."); return ERROR_INVALID_ARGUMENT; } int retCode = xmlSAXUserParseFile(&m_saxHandler, this, m_XMLfile.c_str()); - if(0 != retCode) { + if (0 != retCode) { LogWarning("Parsing XML file failed, ec: " << retCode); return ERROR_XML_PARSE_FAILED; } // if error detected while parsing - if(m_elementListenerMap.empty()) { + if (m_elementListenerMap.empty()) { LogError("Critical error detected while parsing."); return ERROR_INTERNAL; } @@ -127,7 +127,7 @@ int Parser::Parse() int Parser::RegisterErrorCb(const ErrorCb newCb) { - if(m_errorCb) { + if (m_errorCb) { LogError("Callback already registered!"); return ERROR_CALLBACK_PRESENT; } @@ -139,12 +139,12 @@ int Parser::RegisterElementCb(const char * elementName, const StartCb startCb, const EndCb endCb) { - if(!elementName) + if (!elementName) return ERROR_INVALID_ARGUMENT; std::string key(elementName); - if(m_elementListenerMap.find(elementName) != m_elementListenerMap.end()) { + if (m_elementListenerMap.find(elementName) != m_elementListenerMap.end()) { LogError("Callback for element " << elementName << " already registered!"); return ERROR_CALLBACK_PRESENT; } @@ -157,30 +157,28 @@ void Parser::StartElement(const xmlChar *name, const xmlChar **attrs) { std::string key(reinterpret_cast<const char*>(name)); - if(m_elementListenerMap.find(key) == m_elementListenerMap.end()) + if (m_elementListenerMap.find(key) == m_elementListenerMap.end()) return; ElementHandlerPtr newHandler; const ElementListener & current = m_elementListenerMap[key]; - if(current.startCb) - { + if (current.startCb) { Attributes attribs; { size_t numAttrs = 0; std::string key; - while(attrs && attrs[numAttrs]) - { + while (attrs && attrs[numAttrs]) { const char *attrChr = reinterpret_cast<const char*>(attrs[numAttrs]); - if((numAttrs%2)==0) + if ((numAttrs%2) == 0) key = std::string(attrChr); else attribs[key] = std::string(attrChr); - numAttrs ++; + numAttrs++; } } newHandler = current.startCb(); - if(newHandler) + if (newHandler) newHandler->Start(attribs); } // always put a handler, even if it's empty. This will not break @@ -191,19 +189,19 @@ void Parser::StartElement(const xmlChar *name, void Parser::EndElement(const xmlChar *name) { std::string key(reinterpret_cast<const char*>(name)); - if(m_elementListenerMap.find(key) == m_elementListenerMap.end()) + if (m_elementListenerMap.find(key) == m_elementListenerMap.end()) return; // this should never ever happen - if( m_elementHandlerStack.empty() ) + if (m_elementHandlerStack.empty()) throw std::runtime_error("internal error: element queue desynchronized!"); ElementHandlerPtr ¤tHandler = m_elementHandlerStack.top(); - if(currentHandler) + if (currentHandler) currentHandler->End(); const ElementListener & current = m_elementListenerMap[key]; - if(current.endCb) + if (current.endCb) current.endCb(currentHandler); m_elementHandlerStack.pop(); @@ -212,31 +210,28 @@ void Parser::EndElement(const xmlChar *name) void Parser::Characters(const xmlChar *ch, size_t chLen) { std::string chars(reinterpret_cast<const char*>(ch), chLen); - if(chars.empty()) + if (chars.empty()) return; - if( !m_elementHandlerStack.empty() ) - { + if (!m_elementHandlerStack.empty()) { ElementHandlerPtr ¤tHandler = m_elementHandlerStack.top(); - if(currentHandler) + if (currentHandler) currentHandler->Characters(chars); } } void Parser::Error(const ErrorType errorType, const char *msg, va_list &args) { - if(!m_errorCb) + if (!m_errorCb) return; va_list args2; - try - { + try { va_copy(args2, args); std::vector<char> buf(1 + std::vsnprintf(NULL, 0, msg, args)); std::vsnprintf(buf.data(), buf.size(), msg, args2); m_errorCb(errorType, trim(std::string(buf.begin(), buf.end()))); - } - catch(...) { + } catch (...) { LogError("Error callback throwed an exception."); // if an error handler throwed exception, // do not call further callbacks @@ -248,21 +243,18 @@ void Parser::Error(const ErrorType errorType, const char *msg, va_list &args) // // -------------------------- start of static wrappers -------------------------- // -void Parser::CallbackHelper(std::function<void (void)> func) +void Parser::CallbackHelper(std::function<void(void)> func) { - try - { + try { func(); return; - } - catch(const std::exception &e) { + } catch (const std::exception &e) { LogError("parser error: " << e.what()); - if(m_errorCb) + if (m_errorCb) m_errorCb(PARSE_ERROR, e.what()); - } - catch(...) { + } catch (...) { LogError("unknown parser error"); - if(m_errorCb) + if (m_errorCb) m_errorCb(PARSE_ERROR, "unknown parser error"); } // raise error flag - unregister listeners diff --git a/src/manager/initial-values/parser.h b/src/manager/initial-values/parser.h index 605ba494..ab80f0eb 100644 --- a/src/manager/initial-values/parser.h +++ b/src/manager/initial-values/parser.h @@ -35,8 +35,7 @@ namespace CKM { namespace XML { -class Parser -{ +class Parser { public: enum ErrorCode { PARSE_SUCCESS = 0, @@ -66,17 +65,16 @@ public: int RegisterErrorCb(const ErrorCb newCb); typedef std::map<std::string, std::string> Attributes; - class ElementHandler - { - public: - virtual ~ElementHandler() {} - - // methods below may throw std::exception to invalidate the parsing process - // and remove all element listeners. - // In this case, parsing error code returned to the user after std::exception. - virtual void Start(const Attributes &) = 0; - virtual void Characters(const std::string & data) = 0; - virtual void End() = 0; + class ElementHandler { + public: + virtual ~ElementHandler() {} + + // methods below may throw std::exception to invalidate the parsing process + // and remove all element listeners. + // In this case, parsing error code returned to the user after std::exception. + virtual void Start(const Attributes &) = 0; + virtual void Characters(const std::string & data) = 0; + virtual void End() = 0; }; typedef std::shared_ptr<ElementHandler> ElementHandlerPtr; @@ -117,15 +115,14 @@ private: std::string m_XMLfile; ErrorCb m_errorCb; - struct ElementListener - { + struct ElementListener { StartCb startCb; EndCb endCb; }; std::map<std::string, ElementListener> m_elementListenerMap; std::stack<ElementHandlerPtr> m_elementHandlerStack; - void CallbackHelper(std::function<void (void)> func); + void CallbackHelper(std::function<void(void)> func); }; } diff --git a/src/manager/initial-values/xml-utils.cpp b/src/manager/initial-values/xml-utils.cpp index 0553c01f..e7a3a909 100644..100755 --- a/src/manager/initial-values/xml-utils.cpp +++ b/src/manager/initial-values/xml-utils.cpp @@ -25,8 +25,7 @@ #include <algorithm> #include <xml-utils.h> -namespace -{ +namespace { const char * const WHITESPACE = " \n\r\t\v"; const char * const LINE_WHITESPACE = " \r\t\v"; @@ -69,16 +68,18 @@ T removeChars(const T& input, const char *what) return out; } -RawBuffer removeWhiteChars(const RawBuffer &buffer) { +RawBuffer removeWhiteChars(const RawBuffer &buffer) +{ return removeChars(buffer, WHITESPACE); } -std::string trimEachLine(const std::string& input) { +std::string trimEachLine(const std::string& input) +{ std::stringstream ss(input); std::stringstream output; std::string line; - while(std::getline(ss, line, '\n')) { + while (std::getline(ss, line, '\n')) { auto afterTrim = ::trim(line, LINE_WHITESPACE); if (!afterTrim.empty()) output << afterTrim << std::endl; @@ -87,7 +88,8 @@ std::string trimEachLine(const std::string& input) { return output.str(); } -std::string trim(const std::string &s) { +std::string trim(const std::string &s) +{ return removeChars(s, WHITESPACE); } diff --git a/src/manager/initial-values/xml-utils.h b/src/manager/initial-values/xml-utils.h index 8ef94fd8..94385954 100644 --- a/src/manager/initial-values/xml-utils.h +++ b/src/manager/initial-values/xml-utils.h @@ -26,8 +26,7 @@ #include <string> #include <ckm/ckm-raw-buffer.h> namespace CKM { -namespace XML -{ +namespace XML { RawBuffer removeWhiteChars(const RawBuffer &buffer); std::string trim(const std::string& s); diff --git a/src/manager/main/communication-manager.h b/src/manager/main/communication-manager.h index 13a8a979..92a0a1be 100644 --- a/src/manager/main/communication-manager.h +++ b/src/manager/main/communication-manager.h @@ -31,8 +31,7 @@ namespace CKM { * class responsible for keeping a list of listeners for given M type of message and notifying them */ template <typename M> -class MessageManager -{ +class MessageManager { public: NONCOPYABLE(MessageManager); @@ -47,10 +46,11 @@ public: // Returns the number of listeners called size_t SendMessage(const M& msg) const { - for(auto& it : m_listeners) + for (auto& it : m_listeners) it(msg); return m_listeners.size(); } + protected: MessageManager() {} // No one is going to destroy this class directly (only via inherited class). Hence no 'virtual' @@ -70,8 +70,7 @@ struct CommunicationManager; */ template <typename First, typename... Args> struct CommunicationManager<First, Args...> : - public MessageManager<First>, public CommunicationManager<Args...> -{ + public MessageManager<First>, public CommunicationManager<Args...> { public: CommunicationManager() {} NONCOPYABLE(CommunicationManager); diff --git a/src/manager/main/cynara-mockup.cpp b/src/manager/main/cynara-mockup.cpp index 7ea143a1..ecd84ab3 100644..100755 --- a/src/manager/main/cynara-mockup.cpp +++ b/src/manager/main/cynara-mockup.cpp @@ -25,10 +25,11 @@ namespace CKM { -Cynara::Cynara(GenericSocketManager *socketManager) - : m_socketManager(socketManager) - , m_cynara(nullptr) -{} +Cynara::Cynara(GenericSocketManager *socketManager) : + m_socketManager(socketManager), + m_cynara(nullptr) +{ +} void Cynara::Request( const std::string &, @@ -42,19 +43,21 @@ void Cynara::Request( void Cynara::ProcessSocket() {} -Cynara::~Cynara(){} +Cynara::~Cynara() {} void Cynara::ChangeStatus( int, int, cynara_async_status) -{} +{ +} void Cynara::ProcessResponse( cynara_check_id, cynara_async_call_cause, int) -{} +{ +} void Cynara::SendRequest( const std::string &, @@ -62,21 +65,24 @@ void Cynara::SendRequest( const std::string &, const std::string &, StatusCallback) -{} +{ +} void Cynara::ChangeStatusCallback( int, int, cynara_async_status, void *) -{} +{ +} void Cynara::ProcessResponseCallback( cynara_check_id, cynara_async_call_cause, int, void *) -{} +{ +} bool Cynara::GetUserFromSocket( int, diff --git a/src/manager/main/cynara.cpp b/src/manager/main/cynara.cpp index ffdbe0e4..a4c30be6 100644..100755 --- a/src/manager/main/cynara.cpp +++ b/src/manager/main/cynara.cpp @@ -34,8 +34,7 @@ Cynara::Cynara(GenericSocketManager *socketManager) : m_socketManager(socketManager) , m_cynara(nullptr) { - if (CYNARA_API_SUCCESS != cynara_async_initialize(&m_cynara, NULL, ChangeStatusCallback, this)) - { + if (CYNARA_API_SUCCESS != cynara_async_initialize(&m_cynara, NULL, ChangeStatusCallback, this)) { LogError("Cynara initialization failed."); throw std::runtime_error("Cynara initialization failed."); } @@ -55,7 +54,7 @@ void Cynara::Request( user.c_str(), privilege.c_str()); - switch(ret) { + switch (ret) { default: case CYNARA_API_ACCESS_DENIED: callback(false); @@ -73,17 +72,19 @@ void Cynara::Request( } } -void Cynara::ProcessSocket() { - if (CYNARA_API_SUCCESS != cynara_async_process(m_cynara)) { +void Cynara::ProcessSocket() +{ + if (CYNARA_API_SUCCESS != cynara_async_process(m_cynara)) LogError("Function: cynara_async_process failed."); - } } -Cynara::~Cynara(){ +Cynara::~Cynara() +{ cynara_async_finish(m_cynara); } -void Cynara::ChangeStatus(int oldFd, int newFd, cynara_async_status status) { +void Cynara::ChangeStatus(int oldFd, int newFd, cynara_async_status status) +{ m_socketManager->CynaraSocket(oldFd, newFd, status == CYNARA_STATUS_FOR_RW); } @@ -147,7 +148,8 @@ void Cynara::ProcessResponseCallback( static_cast<Cynara*>(ptr)->ProcessResponse(checkId, cause, response); } -bool Cynara::GetUserFromSocket(int socket, std::string &user) { +bool Cynara::GetUserFromSocket(int socket, std::string &user) +{ char *ptr; if (CYNARA_API_SUCCESS != cynara_creds_socket_get_user(socket, USER_METHOD_DEFAULT, &ptr)) return false; @@ -156,9 +158,10 @@ bool Cynara::GetUserFromSocket(int socket, std::string &user) { return true; } -bool Cynara::GetClientFromSocket(int socket, std::string &client) { +bool Cynara::GetClientFromSocket(int socket, std::string &client) +{ char *ptr; - if (CYNARA_API_SUCCESS!=cynara_creds_socket_get_client(socket, CLIENT_METHOD_DEFAULT, &ptr)) + if (CYNARA_API_SUCCESS != cynara_creds_socket_get_client(socket, CLIENT_METHOD_DEFAULT, &ptr)) return false; client = ptr; free(ptr); diff --git a/src/manager/main/generic-socket-manager.h b/src/manager/main/generic-socket-manager.h index f8da4956..fab3d8a0 100644 --- a/src/manager/main/generic-socket-manager.h +++ b/src/manager/main/generic-socket-manager.h @@ -103,10 +103,13 @@ struct GenericSocketService { bool allowed; }; - virtual void SetSocketManager(GenericSocketManager *manager) { + virtual void SetSocketManager(GenericSocketManager *manager) + { m_serviceManager = manager; } - virtual void SetCommManager(CommMgr *manager) { + + virtual void SetCommManager(CommMgr *manager) + { m_commMgr = manager; } @@ -121,7 +124,8 @@ struct GenericSocketService { virtual void Stop() = 0; GenericSocketService() : m_serviceManager(NULL), m_commMgr(NULL) {} - virtual ~GenericSocketService(){} + virtual ~GenericSocketService() {} + protected: GenericSocketManager *m_serviceManager; CommMgr *m_commMgr; diff --git a/src/manager/main/key-manager-main.cpp b/src/manager/main/key-manager-main.cpp index 67a6631c..c3c256fc 100644 --- a/src/manager/main/key-manager-main.cpp +++ b/src/manager/main/key-manager-main.cpp @@ -61,7 +61,8 @@ void registerSocketService(CKM::SocketManager &manager, const std::string& servi delete service; } -int main(void) { +int main(void) +{ UNHANDLED_EXCEPTION_HANDLER_BEGIN { CKM::Singleton<CKM::Log::LogSystem>::Instance().SetTag("CKM"); @@ -103,9 +104,7 @@ int main(void) { CKM::KeyProvider::closeLibrary(); CKM::deinitOpenSsl(); - } - catch (const std::runtime_error& e) - { + } catch (const std::runtime_error& e) { LogError(e.what()); } UNHANDLED_EXCEPTION_HANDLER_END diff --git a/src/manager/main/message-service.h b/src/manager/main/message-service.h index 65512c0b..ab046acd 100644 --- a/src/manager/main/message-service.h +++ b/src/manager/main/message-service.h @@ -44,17 +44,19 @@ class MessageService; // aggregating template template <typename Msg, typename ...Msgs> -class MessageService<Msg, Msgs...> : public MessageService<Msg>, public MessageService<Msgs...> -{ +class MessageService<Msg, Msgs...> : public MessageService<Msg>, public MessageService<Msgs...> { protected: // RECEIVER THREAD template <typename Mgr> - void Register(Mgr& mgr) { + void Register(Mgr& mgr) + { MessageService<Msg>::Register(mgr); MessageService<Msgs...>::Register(mgr); } + // RECEIVER THREAD - void CheckMessages() { + void CheckMessages() + { MessageService<Msg>::CheckMessages(); MessageService<Msgs...>::CheckMessages(); } @@ -63,8 +65,7 @@ protected: // single Message type (Msg) handler template <typename Msg> -class MessageService<Msg> -{ +class MessageService<Msg> { public: MessageService() {} virtual ~MessageService() {} @@ -111,7 +112,7 @@ void MessageService<Msg>::AddMessage(const Msg& msg) template <typename Msg> void MessageService<Msg>::CheckMessages() { - while(true) { + while (true) { m_messagesMutex.lock(); if (m_messages.empty()) { m_messagesMutex.unlock(); @@ -133,8 +134,7 @@ void MessageService<Msg>::CheckMessages() // thread based service with messages support template <typename ...Msgs> -class ThreadMessageService : public ThreadService, public MessageService<Msgs...> -{ +class ThreadMessageService : public ThreadService, public MessageService<Msgs...> { public: ThreadMessageService() {} virtual ~ThreadMessageService() {} @@ -142,18 +142,21 @@ public: // RECEIVER THREAD: register as a listener of all supported messages template <typename Mgr> - void Register(Mgr& mgr) { + void Register(Mgr& mgr) + { MessageService<Msgs...>::Register(mgr); } private: // SENDER THREAD: adds callback to RECEIVER THREAD event queue and wakes it - virtual void Notify() { + virtual void Notify() + { CreateEvent([this]() { this->CheckMessages(); }); } // RECEIVER THREAD - void CheckMessages() { + void CheckMessages() + { MessageService<Msgs...>::CheckMessages(); } }; diff --git a/src/manager/main/service-messages.h b/src/manager/main/service-messages.h index 26989ee6..61ebbb45 100644 --- a/src/manager/main/service-messages.h +++ b/src/manager/main/service-messages.h @@ -33,8 +33,7 @@ namespace CKM { // inter-service communication message base class -struct MsgBase -{ +struct MsgBase { explicit MsgBase(int id) : id(id) {} virtual ~MsgBase() {} @@ -42,8 +41,7 @@ struct MsgBase }; // key request -struct MsgKeyRequest : public MsgBase -{ +struct MsgKeyRequest : public MsgBase { MsgKeyRequest(int id, const Credentials& cred, const Name& name, @@ -54,7 +52,9 @@ struct MsgKeyRequest : public MsgBase name(name), label(label), password(password) - {} + { + } + Credentials cred; Name name; Label label; @@ -62,13 +62,14 @@ struct MsgKeyRequest : public MsgBase }; // key response -struct MsgKeyResponse : public MsgBase -{ +struct MsgKeyResponse : public MsgBase { MsgKeyResponse(int id, const Crypto::GObjShPtr& key, int errorCode = CKM_API_SUCCESS) : MsgBase(id), key(key), error(errorCode) - {} + { + } + Crypto::GObjShPtr key; int error; }; diff --git a/src/manager/main/service-thread.h b/src/manager/main/service-thread.h index 32087b76..b459b96e 100644 --- a/src/manager/main/service-thread.h +++ b/src/manager/main/service-thread.h @@ -55,15 +55,18 @@ public: ServiceThread() : m_state(State::NoThread) , m_quit(false) - {} + { + } - void Create() { + void Create() + { assert(m_state == State::NoThread); m_thread = std::thread(ThreadLoopStatic, this); m_state = State::Work; } - void Join() { + void Join() + { assert(m_state != State::NoThread); { std::lock_guard<std::mutex> lock(m_eventQueueMutex); @@ -95,14 +98,16 @@ protected: m_waitCondition.notify_one(); } - static void ThreadLoopStatic(ServiceThread *ptr) { + static void ThreadLoopStatic(ServiceThread *ptr) + { ptr->ThreadLoop(); // cleanup openssl in every thread deinitOpenSslThread(); } - void ThreadLoop(){ + void ThreadLoop() + { for (;;) { EventDescription description; { diff --git a/src/manager/main/socket-2-id-mockup.cpp b/src/manager/main/socket-2-id-mockup.cpp index 889e8ead..1d103cb9 100644 --- a/src/manager/main/socket-2-id-mockup.cpp +++ b/src/manager/main/socket-2-id-mockup.cpp @@ -26,7 +26,8 @@ namespace CKM { -int Socket2Id::getPkgIdFromSmack(const std::string &smack, std::string &pkgId) { +int Socket2Id::getPkgIdFromSmack(const std::string &smack, std::string &pkgId) +{ static const std::string SMACK_PREFIX_APPID = "User::App::"; if (smack.empty()) { @@ -52,17 +53,16 @@ int Socket2Id::getPkgIdFromSmack(const std::string &smack, std::string &pkgId) { return 0; } -int Socket2Id::translate(int sock, std::string &result) { +int Socket2Id::translate(int sock, std::string &result) +{ std::string smack; std::string pkgId; - if (0 > getCredentialsFromSocket(sock, smack)) { + if (0 > getCredentialsFromSocket(sock, smack)) return -1; - } - if (0 > getPkgIdFromSmack(smack, pkgId)) { + if (0 > getPkgIdFromSmack(smack, pkgId)) return -1; - } result = std::move(pkgId); return 0; diff --git a/src/manager/main/socket-2-id-wrapper.cpp b/src/manager/main/socket-2-id-wrapper.cpp index c5979539..2c037f88 100644 --- a/src/manager/main/socket-2-id-wrapper.cpp +++ b/src/manager/main/socket-2-id-wrapper.cpp @@ -28,7 +28,8 @@ namespace CKM { -int Socket2Id::getPkgIdFromSmack(const std::string &smack, std::string &pkgId) { +int Socket2Id::getPkgIdFromSmack(const std::string &smack, std::string &pkgId) +{ // TODO // Conversion from smack label to pkgId should be done // by security-manager. Current version of security-manager @@ -67,12 +68,12 @@ int Socket2Id::getPkgIdFromSmack(const std::string &smack, std::string &pkgId) { return 0; } -int Socket2Id::translate(int sock, std::string &result) { +int Socket2Id::translate(int sock, std::string &result) +{ std::string smack; - if (0 > getCredentialsFromSocket(sock, smack)) { + if (0 > getCredentialsFromSocket(sock, smack)) return -1; - } StringMap::iterator it = m_stringMap.find(smack); @@ -82,9 +83,8 @@ int Socket2Id::translate(int sock, std::string &result) { } std::string pkgId; - if (0 > getPkgIdFromSmack(smack, pkgId)) { + if (0 > getPkgIdFromSmack(smack, pkgId)) return -1; - } result = pkgId; m_stringMap.emplace(std::move(smack), std::move(pkgId)); diff --git a/src/manager/main/socket-2-id.cpp b/src/manager/main/socket-2-id.cpp index 40cd714a..b71f88be 100644 --- a/src/manager/main/socket-2-id.cpp +++ b/src/manager/main/socket-2-id.cpp @@ -30,14 +30,15 @@ namespace CKM { namespace { -int assignToString(std::vector<char> &vec, socklen_t len, std::string &res) { +int assignToString(std::vector<char> &vec, socklen_t len, std::string &res) +{ if (vec.size() <= len) return -1; vec[len] = 0; // old implementation getsockopt returns cstring without 0 - if (vec[len-1] == 0) { + + if (vec[len-1] == 0) --len; // new implementation of getsockopt returns cstring size+1 - } res.assign(vec.data(), len); return 0; @@ -45,13 +46,13 @@ int assignToString(std::vector<char> &vec, socklen_t len, std::string &res) { } // namespace anonymous -int Socket2Id::getCredentialsFromSocket(int sock, std::string &res) { +int Socket2Id::getCredentialsFromSocket(int sock, std::string &res) +{ std::vector<char> result(SMACK_LABEL_LEN+1); socklen_t length = SMACK_LABEL_LEN; - if (0 == getsockopt(sock, SOL_SOCKET, SO_PEERSEC, result.data(), &length)) { + if (0 == getsockopt(sock, SOL_SOCKET, SO_PEERSEC, result.data(), &length)) return assignToString(result, length, res); - } if (errno != ERANGE) { LogError("getsockopt failed"); @@ -68,7 +69,8 @@ int Socket2Id::getCredentialsFromSocket(int sock, std::string &res) { return assignToString(result, length, res); } -void Socket2Id::resetCache() { +void Socket2Id::resetCache() +{ m_stringMap.clear(); } diff --git a/src/manager/main/socket-2-id.h b/src/manager/main/socket-2-id.h index 046f998b..85b0ef1c 100644 --- a/src/manager/main/socket-2-id.h +++ b/src/manager/main/socket-2-id.h @@ -33,6 +33,7 @@ public: void resetCache(); virtual ~Socket2Id() {} + private: int getCredentialsFromSocket(int sock, std::string &res); int getPkgIdFromSmack(const std::string &smack, std::string &pkgId); diff --git a/src/manager/main/socket-manager.cpp b/src/manager/main/socket-manager.cpp index 6caeaf82..e892f7ff 100644..100755 --- a/src/manager/main/socket-manager.cpp +++ b/src/manager/main/socket-manager.cpp @@ -52,13 +52,13 @@ namespace { const time_t SOCKET_TIMEOUT = 1000; -int getCredentialsFromSocket(int sock, CKM::Credentials &cred) { +int getCredentialsFromSocket(int sock, CKM::Credentials &cred) +{ static CKM::Socket2Id sock2id; std::string ownerId; - if (0 > sock2id.translate(sock, ownerId)) { + if (0 > sock2id.translate(sock, ownerId)) return -1; - } ucred peerCred; socklen_t length = sizeof(ucred); @@ -77,7 +77,8 @@ int getCredentialsFromSocket(int sock, CKM::Credentials &cred) { namespace CKM { struct DummyService : public GenericSocketService { - ServiceDescriptionVector GetServiceDescription() { + ServiceDescriptionVector GetServiceDescription() + { return ServiceDescriptionVector(); } @@ -92,7 +93,8 @@ struct DummyService : public GenericSocketService { }; struct SignalService : public GenericSocketService { - int GetDescriptor() { + int GetDescriptor() + { LogInfo("set up"); sigset_t mask; sigemptyset(&mask); @@ -102,7 +104,8 @@ struct SignalService : public GenericSocketService { return signalfd(-1, &mask, 0); } - ServiceDescriptionVector GetServiceDescription() { + ServiceDescriptionVector GetServiceDescription() + { return ServiceDescriptionVector(); } @@ -114,10 +117,11 @@ struct SignalService : public GenericSocketService { void Event(const CloseEvent &) {} // not supported void Event(const SecurityEvent &) {} // not supported - void Event(const ReadEvent &event) { + void Event(const ReadEvent &event) + { LogDebug("Get signal information"); - if(sizeof(struct signalfd_siginfo) != event.rawBuffer.size()) { + if (sizeof(struct signalfd_siginfo) != event.rawBuffer.size()) { LogError("Wrong size of signalfd_siginfo struct. Expected: " << sizeof(signalfd_siginfo) << " Get: " << event.rawBuffer.size()); @@ -165,16 +169,18 @@ SocketManager::CreateDefaultReadSocketDescription(int sock, bool timeout) return desc; } -SocketManager::SocketManager() - : m_maxDesc(0) - , m_counter(0) +SocketManager::SocketManager() : + m_maxDesc(0), + m_counter(0) { FD_ZERO(&m_readSet); FD_ZERO(&m_writeSet); + if (-1 == pipe(m_notifyMe)) { int err = errno; ThrowMsg(Exception::InitFailed, "Error in pipe: " << GetErrnoString(err)); } + LogInfo("Pipe: Read desc: " << m_notifyMe[0] << " Write desc: " << m_notifyMe[1]); auto &desc = CreateDefaultReadSocketDescription(m_notifyMe[0], false); @@ -190,6 +196,7 @@ SocketManager::SocketManager() auto *signalService = new SignalService; signalService->SetSocketManager(this); int filefd = signalService->GetDescriptor(); + if (-1 == filefd) { LogError("Error in SignalService.GetDescriptor()"); delete signalService; @@ -203,7 +210,8 @@ SocketManager::SocketManager() m_cynara.reset(new Cynara(this)); } -SocketManager::~SocketManager() { +SocketManager::~SocketManager() +{ m_cynara.reset(nullptr); std::set<GenericSocketService*> serviceMap; @@ -229,10 +237,12 @@ SocketManager::~SocketManager() { close(m_notifyMe[1]); } -void SocketManager::ReadyForAccept(int sock) { +void SocketManager::ReadyForAccept(int sock) +{ struct sockaddr_un clientAddr; unsigned int clientLen = sizeof(clientAddr); int client = accept4(sock, (struct sockaddr*) &clientAddr, &clientLen, SOCK_NONBLOCK); + if (-1 == client) { int err = errno; LogDebug("Error in accept: " << GetErrnoString(err)); @@ -245,8 +255,7 @@ void SocketManager::ReadyForAccept(int sock) { if (0 > getCredentialsFromSocket(client, peerCred) || !Cynara::GetUserFromSocket(client, user) - || !Cynara::GetClientFromSocket(client, smack)) - { + || !Cynara::GetClientFromSocket(client, smack)) { LogDebug("Error in getting credentials from socket."); TEMP_FAILURE_RETRY(close(client)); return; @@ -267,7 +276,8 @@ void SocketManager::ReadyForAccept(int sock) { desc.service->Event(event); } -void SocketManager::SecurityStatus(int sock, int counter, bool allowed) { +void SocketManager::SecurityStatus(int sock, int counter, bool allowed) +{ auto &desc = m_socketDescriptionVector[sock]; if (!desc.isOpen()) { LogDebug("Client from socket " << sock << @@ -288,7 +298,8 @@ void SocketManager::SecurityStatus(int sock, int counter, bool allowed) { desc.service->Event(event); } -void SocketManager::ReadyForRead(int sock) { +void SocketManager::ReadyForRead(int sock) +{ if (m_socketDescriptionVector[sock].isListen()) { ReadyForAccept(sock); return; @@ -316,18 +327,19 @@ void SocketManager::ReadyForRead(int sock) { desc.service->Event(event); } else if (size == -1) { int err = errno; - switch(err) { - case EAGAIN: - case EINTR: - break; - default: - LogDebug("Reading sock error: " << GetErrnoString(err)); - CloseSocket(sock); + switch (err) { + case EAGAIN: + case EINTR: + break; + default: + LogDebug("Reading sock error: " << GetErrnoString(err)); + CloseSocket(sock); } } } -void SocketManager::ReadyForWrite(int sock) { +void SocketManager::ReadyForWrite(int sock) +{ if (m_socketDescriptionVector[sock].isCynara()) { m_cynara->ProcessSocket(); return; @@ -336,9 +348,10 @@ void SocketManager::ReadyForWrite(int sock) { auto &desc = m_socketDescriptionVector[sock]; size_t size = desc.rawBuffer.size(); ssize_t result = write(sock, &desc.rawBuffer[0], size); + if (result == -1) { int err = errno; - switch(err) { + switch (err) { case EAGAIN: case EINTR: // select will trigger write once again, nothing to do @@ -368,7 +381,8 @@ void SocketManager::ReadyForWrite(int sock) { desc.service->Event(event); } -void SocketManager::MainLoop() { +void SocketManager::MainLoop() +{ // remove evironment values passed by systemd sd_listen_fds(1); @@ -376,7 +390,7 @@ void SocketManager::MainLoop() { sd_notify(0, "READY=1"); m_working = true; - while(m_working) { + while (m_working) { fd_set readSet = m_readSet; fd_set writeSet = m_writeSet; @@ -386,7 +400,7 @@ void SocketManager::MainLoop() { // I need to extract timeout from priority_queue. // Timeout in priority_queue may be deprecated. // I need to find some actual one. - while(!m_timeoutQueue.empty()) { + while (!m_timeoutQueue.empty()) { auto &top = m_timeoutQueue.top(); auto &desc = m_socketDescriptionVector[top.sock]; @@ -451,7 +465,7 @@ void SocketManager::MainLoop() { } if (-1 == ret) { - switch(errno) { + switch (errno) { case EINTR: LogDebug("EINTR in select"); break; @@ -462,7 +476,7 @@ void SocketManager::MainLoop() { } continue; } - for(int i = 0; i<m_maxDesc+1 && ret; ++i) { + for (int i = 0; i < m_maxDesc+1 && ret; ++i) { if (FD_ISSET(i, &readSet)) { ReadyForRead(i); --ret; @@ -498,10 +512,9 @@ int SocketManager::GetSocketFromSystemD( ThrowMsg(Exception::InitFailed, "Error in sd_listend_fds"); } - for(fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) { + for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) { if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1, - desc.serviceHandlerPath.c_str(), 0)) - { + desc.serviceHandlerPath.c_str(), 0)) { LogInfo("Useable socket " << desc.serviceHandlerPath << " was passed by SystemD under descriptor " << fd); return fd; @@ -516,9 +529,8 @@ int SocketManager::CreateDomainSocketHelp( { int sockfd; - if(desc.serviceHandlerPath.size()*sizeof(decltype(desc.serviceHandlerPath)::value_type) >= - sizeof(static_cast<sockaddr_un*>(0)->sun_path)) - { + if (desc.serviceHandlerPath.size()*sizeof(decltype(desc.serviceHandlerPath)::value_type) >= + sizeof(static_cast<sockaddr_un*>(0)->sun_path)) { LogError("Service handler path too long: " << desc.serviceHandlerPath.size()); ThrowMsg(Exception::InitFailed, "Service handler path too long: " << desc.serviceHandlerPath.size()); @@ -599,16 +611,16 @@ void SocketManager::CreateDomainSocket( " Handler: " << desc.serviceHandlerPath.c_str()); } -void SocketManager::RegisterSocketService(GenericSocketService *service) { +void SocketManager::RegisterSocketService(GenericSocketService *service) +{ service->SetSocketManager(this); service->SetCommManager(&m_commMgr); auto serviceVector = service->GetServiceDescription(); Try { for (auto iter = serviceVector.begin(); iter != serviceVector.end(); ++iter) CreateDomainSocket(service, *iter); - } Catch (Exception::Base) { - for (int i =0; i < (int)m_socketDescriptionVector.size(); ++i) - { + } Catch(Exception::Base) { + for (int i =0; i < (int)m_socketDescriptionVector.size(); ++i) { auto &desc = m_socketDescriptionVector[i]; if (desc.service == service && desc.isOpen()) { close(i); @@ -619,26 +631,30 @@ void SocketManager::RegisterSocketService(GenericSocketService *service) { } } -void SocketManager::Close(ConnectionID connectionID) { +void SocketManager::Close(ConnectionID connectionID) +{ CloseEvent event; event.sock = connectionID.sock; event.counter = connectionID.counter; AddEvent(event); } -void SocketManager::Write(ConnectionID connectionID, const RawBuffer &rawBuffer) { +void SocketManager::Write(ConnectionID connectionID, const RawBuffer &rawBuffer) +{ WriteEvent event{connectionID, rawBuffer}; AddEvent(event); } -void SocketManager::SecurityCheck(ConnectionID connectionID) { +void SocketManager::SecurityCheck(ConnectionID connectionID) +{ SecurityEvent event; event.sock = connectionID.sock; event.counter = connectionID.counter; AddEvent(event); } -void SocketManager::CreateEvent(EventFunction fun) { +void SocketManager::CreateEvent(EventFunction fun) +{ { std::lock_guard<std::mutex> ulock(m_eventQueueMutex); m_eventQueue.push(std::move(fun)); @@ -646,12 +662,14 @@ void SocketManager::CreateEvent(EventFunction fun) { NotifyMe(); } -void SocketManager::NotifyMe() { +void SocketManager::NotifyMe() +{ TEMP_FAILURE_RETRY(write(m_notifyMe[1], "You have message ;-)", 1)); } -void SocketManager::ProcessQueue() { - while(1) { +void SocketManager::ProcessQueue() +{ + while (1) { EventFunction fun; { std::lock_guard<std::mutex> ulock(m_eventQueueMutex); @@ -664,7 +682,8 @@ void SocketManager::ProcessQueue() { } } -void SocketManager::Handle(const WriteEvent &event) { +void SocketManager::Handle(const WriteEvent &event) +{ auto &desc = m_socketDescriptionVector[event.connectionID.sock]; if (!desc.isOpen()) { @@ -672,8 +691,7 @@ void SocketManager::Handle(const WriteEvent &event) { return; } - if (desc.counter != event.connectionID.counter) - { + if (desc.counter != event.connectionID.counter) { LogDebug("Received packet for write but counter is broken. Packet ignored!"); return; } @@ -686,7 +704,8 @@ void SocketManager::Handle(const WriteEvent &event) { FD_SET(event.connectionID.sock, &m_writeSet); } -void SocketManager::Handle(const CloseEvent &event) { +void SocketManager::Handle(const CloseEvent &event) +{ if (!m_socketDescriptionVector[event.sock].isOpen()) return; @@ -696,7 +715,8 @@ void SocketManager::Handle(const CloseEvent &event) { CloseSocket(event.sock); } -void SocketManager::Handle(const SecurityEvent &event) { +void SocketManager::Handle(const SecurityEvent &event) +{ auto& desc = m_socketDescriptionVector[event.sock]; if (!desc.isOpen()) return; @@ -715,7 +735,8 @@ void SocketManager::Handle(const SecurityEvent &event) { }); } -void SocketManager::CloseSocket(int sock) { +void SocketManager::CloseSocket(int sock) +{ auto &desc = m_socketDescriptionVector[sock]; if (!(desc.isOpen())) { @@ -745,7 +766,8 @@ void SocketManager::CloseSocket(int sock) { FD_CLR(sock, &m_writeSet); } -void SocketManager::CynaraSocket(int oldFd, int newFd, bool isRW) { +void SocketManager::CynaraSocket(int oldFd, int newFd, bool isRW) +{ if (newFd != oldFd) { if (newFd >= 0) { auto &desc = CreateDefaultReadSocketDescription(newFd, false); diff --git a/src/manager/main/socket-manager.h b/src/manager/main/socket-manager.h index 522e79c7..933d9b1d 100644 --- a/src/manager/main/socket-manager.h +++ b/src/manager/main/socket-manager.h @@ -50,7 +50,6 @@ public: DECLARE_EXCEPTION_TYPE(Base, InitFailed) }; - SocketManager(); virtual ~SocketManager(); virtual void MainLoop(); @@ -103,7 +102,9 @@ protected: : interfaceID(-1) , service(NULL) , m_flags(0) - {} + { + } + private: static const char LISTEN = 1 << 0; static const char OPEN = 1 << 1; @@ -119,7 +120,8 @@ protected: // support for generic event Queue typedef std::function<void(void)> EventFunction; template <typename E> - void AddEvent(E event) { + void AddEvent(E event) + { CreateEvent([this, event]() {this->Handle(event);}); } void CreateEvent(EventFunction fun); @@ -140,7 +142,8 @@ protected: struct Timeout { time_t time; int sock; - bool operator<(const Timeout &second) const { + bool operator<(const Timeout &second) const + { return time > second.time; // mininum first! } }; diff --git a/src/manager/main/thread-service.cpp b/src/manager/main/thread-service.cpp index 9f744b52..b9c1b409 100644 --- a/src/manager/main/thread-service.cpp +++ b/src/manager/main/thread-service.cpp @@ -32,18 +32,21 @@ ThreadService::~ThreadService() { } -void ThreadService::Handle(const AcceptEvent &event) { +void ThreadService::Handle(const AcceptEvent &event) +{ LogDebug("Accept event"); auto &info = m_connectionInfoMap[event.connectionID.counter]; info.interfaceID = event.interfaceID; info.credentials = event.credentials; } -void ThreadService::Handle(const WriteEvent &event) { +void ThreadService::Handle(const WriteEvent &event) +{ LogDebug("Write event (" << event.size << " bytes )"); } -void ThreadService::Handle(const ReadEvent &event) { +void ThreadService::Handle(const ReadEvent &event) +{ LogDebug("Read event"); auto &info = m_connectionInfoMap[event.connectionID.counter]; info.buffer.Push(event.rawBuffer); @@ -58,12 +61,14 @@ void ThreadService::Handle(const ReadEvent &event) { m_serviceManager->SecurityCheck(event.connectionID); } -void ThreadService::Handle(const CloseEvent &event) { +void ThreadService::Handle(const CloseEvent &event) +{ LogDebug("Close event"); m_connectionInfoMap.erase(event.connectionID.counter); } -void ThreadService::Handle(const SecurityEvent &event) { +void ThreadService::Handle(const SecurityEvent &event) +{ LogDebug("Security event"); auto it = m_connectionInfoMap.find(event.connectionID.counter); diff --git a/src/manager/main/thread-service.h b/src/manager/main/thread-service.h index 219bfc02..209375fd 100644 --- a/src/manager/main/thread-service.h +++ b/src/manager/main/thread-service.h @@ -28,8 +28,7 @@ namespace CKM { -class ThreadService: public GenericSocketService, public ServiceThread -{ +class ThreadService: public GenericSocketService, public ServiceThread { public: ThreadService(); virtual ~ThreadService(); @@ -47,7 +46,8 @@ protected: bool allowed) = 0; template <typename E> - void ThreadEvent(const E& event) { + void ThreadEvent(const E& event) + { CreateEvent([this, event]() { this->Handle(event); }); } diff --git a/src/manager/service/access-control.cpp b/src/manager/service/access-control.cpp index e5eba2b9..a3cecb47 100644..100755 --- a/src/manager/service/access-control.cpp +++ b/src/manager/service/access-control.cpp @@ -69,9 +69,9 @@ int AccessControl::canSave( const CKM::Credentials &accessorCred, const Label & ownerLabel) const { - if(isSystemService(accessorCred)) + if (isSystemService(accessorCred)) return CKM_API_SUCCESS; - if(ownerLabel != accessorCred.smackLabel) + if (ownerLabel != accessorCred.smackLabel) return CKM_API_ERROR_ACCESS_DENIED; return CKM_API_SUCCESS; @@ -88,9 +88,9 @@ int AccessControl::canRead( const CKM::Credentials &accessorCred, const PermissionForLabel & permissionLabel) const { - if(isSystemService(accessorCred)) + if (isSystemService(accessorCred)) return CKM_API_SUCCESS; - if(permissionLabel & Permission::READ) + if (permissionLabel & Permission::READ) return CKM_API_SUCCESS; return CKM_API_ERROR_DB_ALIAS_UNKNOWN; @@ -102,11 +102,11 @@ int AccessControl::canExport( const PermissionForLabel & permissionLabel) const { int ec; - if(CKM_API_SUCCESS != (ec = canRead(accessorCred, permissionLabel))) + if (CKM_API_SUCCESS != (ec = canRead(accessorCred, permissionLabel))) return ec; // check if can export - if(row.exportable == 0) + if (row.exportable == 0) return CKM_API_ERROR_NOT_EXPORTABLE; // prevent extracting private keys during cc-mode on @@ -120,11 +120,11 @@ int AccessControl::canDelete( const CKM::Credentials &accessorCred, const PermissionForLabel & permissionLabel) const { - if(isSystemService(accessorCred)) + if (isSystemService(accessorCred)) return CKM_API_SUCCESS; - if(permissionLabel & Permission::REMOVE) + if (permissionLabel & Permission::REMOVE) return CKM_API_SUCCESS; - if(permissionLabel & Permission::READ) + if (permissionLabel & Permission::READ) return CKM_API_ERROR_ACCESS_DENIED; return CKM_API_ERROR_DB_ALIAS_UNKNOWN; diff --git a/src/manager/service/access-control.h b/src/manager/service/access-control.h index 75297c42..0141af4b 100644 --- a/src/manager/service/access-control.h +++ b/src/manager/service/access-control.h @@ -30,8 +30,7 @@ namespace CKM { -class AccessControl -{ +class AccessControl { public: /** * return true if client uid is from the system services uid space @@ -77,6 +76,7 @@ public: void updateCCMode(); bool isCCMode() const; + private: bool m_ccMode; }; diff --git a/src/manager/service/certificate-config.h b/src/manager/service/certificate-config.h index b9d053d8..22c0caf4 100644 --- a/src/manager/service/certificate-config.h +++ b/src/manager/service/certificate-config.h @@ -26,16 +26,27 @@ namespace CKM { -class CertificateConfig -{ +class CertificateConfig { public: - static void addSystemCertificateDir(const std::string& dir) { m_sysCertDirs.insert(dir); } - static void addSystemCertificateFile(const std::string& file) { m_sysCertFiles.insert(file); } + static void addSystemCertificateDir(const std::string& dir) + { + m_sysCertDirs.insert(dir); + } + static void addSystemCertificateFile(const std::string& file) + { + m_sysCertFiles.insert(file); + } typedef std::set<std::string> PathSet; - static const PathSet& getSystemCertificateDirs() { return m_sysCertDirs; } - static const PathSet& getSystemCertificateFiles() { return m_sysCertFiles; } + static const PathSet& getSystemCertificateDirs() + { + return m_sysCertDirs; + } + static const PathSet& getSystemCertificateFiles() + { + return m_sysCertFiles; + } private: CertificateConfig(); diff --git a/src/manager/service/certificate-store.cpp b/src/manager/service/certificate-store.cpp index 565f4fdf..66295e7a 100644..100755 --- a/src/manager/service/certificate-store.cpp +++ b/src/manager/service/certificate-store.cpp @@ -32,7 +32,8 @@ namespace CKM { -CertificateStore::CertificateStore() : m_store(X509_STORE_new()) +CertificateStore::CertificateStore() : + m_store(X509_STORE_new()) { if (!m_store) { LogError("Failed to create store"); @@ -59,7 +60,7 @@ int CertificateStore::verifyCertificate( trustedVector.size() << "trusted certificates" << " and system certificates set to: " << useTrustedSystemCertificates); - X509_STORE_CTX_PTR csc= create_x509_store_ctx(); + X509_STORE_CTX_PTR csc = create_x509_store_ctx(); if (!csc) { LogError("failed to create csc"); return CKM_API_ERROR_UNKNOWN; @@ -93,9 +94,8 @@ int CertificateStore::verifyCertificate( return CKM_API_ERROR_UNKNOWN; } - if(stateCCMode) { + if (stateCCMode) X509_VERIFY_PARAM_set_flags(csc->param, X509_V_FLAG_X509_STRICT); - } int result = X509_verify_cert(csc.get()); // 1 == ok; 0 == fail; -1 == error @@ -131,12 +131,14 @@ int CertificateStore::addSystemCertificateDirs() LogError("Error in X509_STORE_add_lookup"); return CKM_API_ERROR_UNKNOWN; } - for(const auto& i: dirs) { + + for (const auto& i : dirs) { if (!X509_LOOKUP_add_dir(dir_lookup, i.c_str(), X509_FILETYPE_PEM)) { LogError("Error in X509_LOOKUP_add_dir"); return CKM_API_ERROR_UNKNOWN; } } + return CKM_API_SUCCESS; } @@ -153,7 +155,7 @@ int CertificateStore::addSystemCertificateFiles() return CKM_API_ERROR_UNKNOWN; } - for(const auto& i:files) { + for (const auto& i : files) { if (!X509_LOOKUP_load_file(file_lookup, i.c_str(), X509_FILETYPE_PEM)) { LogError("Error in X509_LOOKUP_load_file"); return CKM_API_ERROR_UNKNOWN; @@ -166,7 +168,7 @@ int CertificateStore::addCustomTrustedCertificates(const CertificateImplVector & { // add trusted certificates to store for (const auto& i:trustedVector) { - if(1 != X509_STORE_add_cert(m_store, i.getX509())) { + if (1 != X509_STORE_add_cert(m_store, i.getX509())) { LogError("failed to add certificate to the store"); return CKM_API_ERROR_UNKNOWN; } diff --git a/src/manager/service/ckm-logic.cpp b/src/manager/service/ckm-logic.cpp index 8c967f32..e55bba8c 100644..100755 --- a/src/manager/service/ckm-logic.cpp +++ b/src/manager/service/ckm-logic.cpp @@ -38,18 +38,21 @@ namespace { const char * const CERT_SYSTEM_DIR = "/etc/ssl/certs"; const char * const SYSTEM_DB_PASSWD = "cAtRugU7"; -bool isLabelValid(const CKM::Label &label) { +bool isLabelValid(const CKM::Label &label) +{ // TODO: copy code from libprivilege control (for check smack label) if (label.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Label::npos) return false; return true; } -bool isNameValid(const CKM::Name &name) { +bool isNameValid(const CKM::Name &name) +{ if (name.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Name::npos) return false; return true; } + } // anonymous namespace namespace CKM { @@ -63,9 +66,10 @@ CKMLogic::CKMLogic() m_accessControl.updateCCMode(); } -CKMLogic::~CKMLogic(){} +CKMLogic::~CKMLogic() {} -void CKMLogic::loadDKEKFile(uid_t user, const Password &password) { +void CKMLogic::loadDKEKFile(uid_t user, const Password &password) +{ auto &handle = m_userDataMap[user]; FileSystem fs(user); @@ -80,7 +84,8 @@ void CKMLogic::loadDKEKFile(uid_t user, const Password &password) { handle.keyProvider = KeyProvider(wrappedDKEK, password); } -void CKMLogic::saveDKEKFile(uid_t user, const Password &password) { +void CKMLogic::saveDKEKFile(uid_t user, const Password &password) +{ auto &handle = m_userDataMap[user]; FileSystem fs(user); @@ -89,12 +94,11 @@ void CKMLogic::saveDKEKFile(uid_t user, const Password &password) { int CKMLogic::unlockDatabase(uid_t user, const Password & password) { - if (0<m_userDataMap.count(user) && m_userDataMap[user].keyProvider.isInitialized()) + if (0 < m_userDataMap.count(user) && m_userDataMap[user].keyProvider.isInitialized()) return CKM_API_SUCCESS; int retCode = CKM_API_SUCCESS; - try - { + try { auto &handle = m_userDataMap[user]; FileSystem fs(user); @@ -111,11 +115,10 @@ int CKMLogic::unlockDatabase(uid_t user, const Password & password) handle.database = DB::Crypto(fs.getDBPath(), key); handle.crypto = CryptoLogic(); - if ( !m_accessControl.isSystemService(user) ) - { + if (!m_accessControl.isSystemService(user)) { // remove data of removed apps during locked state AppLabelVector removedApps = fs.clearRemovedsApps(); - for(auto& appSmackLabel : removedApps) { + for (auto& appSmackLabel : removedApps) { handle.crypto.removeKey(appSmackLabel); handle.database.deleteKey(appSmackLabel); } @@ -144,8 +147,7 @@ UserData & CKMLogic::selectDatabase(const Credentials &cred, const Label &incomi // * if user database is unlocked [mandatory] // * if not - proceed with regular user database // * if explicit system database label given -> switch to system DB - if ( !m_accessControl.isSystemService(cred) ) - { + if (!m_accessControl.isSystemService(cred)) { if (0 == m_userDataMap.count(cred.clientUid)) ThrowErr(Exc::DatabaseLocked, "database with UID: ", cred.clientUid, " locked"); @@ -156,6 +158,7 @@ UserData & CKMLogic::selectDatabase(const Credentials &cred, const Label &incomi // system database selected, modify the label if (CKM_API_SUCCESS != unlockSystemDB() ) ThrowErr(Exc::DatabaseLocked, "can not unlock system database"); + return m_userDataMap[SYSTEM_DB_UID]; } @@ -163,20 +166,16 @@ RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password) { int retCode = CKM_API_SUCCESS; - if( !m_accessControl.isSystemService(user) ) - { + if (!m_accessControl.isSystemService(user)) retCode = unlockDatabase(user, password); - } - else - { - // do not allow lock/unlock operations for system users + else // do not allow lock/unlock operations for system users retCode = CKM_API_ERROR_INPUT_PARAM; - } return MessageBuffer::Serialize(retCode).Pop(); } -RawBuffer CKMLogic::updateCCMode() { +RawBuffer CKMLogic::updateCCMode() +{ m_accessControl.updateCCMode(); return MessageBuffer::Serialize(CKM_API_SUCCESS).Pop(); } @@ -184,21 +183,16 @@ RawBuffer CKMLogic::updateCCMode() { RawBuffer CKMLogic::lockUserKey(uid_t user) { int retCode = CKM_API_SUCCESS; - if( !m_accessControl.isSystemService(user) ) - { + if (!m_accessControl.isSystemService(user)) m_userDataMap.erase(user); - } - else - { - // do not allow lock/unlock operations for system users + else // do not allow lock/unlock operations for system users retCode = CKM_API_ERROR_INPUT_PARAM; - } return MessageBuffer::Serialize(retCode).Pop(); - } -RawBuffer CKMLogic::removeUserData(uid_t user) { +RawBuffer CKMLogic::removeUserData(uid_t user) +{ int retCode = CKM_API_SUCCESS; if (m_accessControl.isSystemService(user)) @@ -217,7 +211,7 @@ int CKMLogic::changeUserPasswordHelper(uid_t user, const Password &newPassword) { // do not allow to change system database password - if( m_accessControl.isSystemService(user) ) + if (m_accessControl.isSystemService(user)) return CKM_API_ERROR_INPUT_PARAM; loadDKEKFile(user, oldPassword); @@ -232,8 +226,7 @@ RawBuffer CKMLogic::changeUserPassword( const Password &newPassword) { int retCode = CKM_API_SUCCESS; - try - { + try { retCode = changeUserPasswordHelper(user, oldPassword, newPassword); } catch (const Exc::Exception &e) { retCode = e.error(); @@ -250,12 +243,11 @@ int CKMLogic::resetUserPasswordHelper( const Password &newPassword) { // do not allow to reset system database password - if( m_accessControl.isSystemService(user) ) + if (m_accessControl.isSystemService(user)) return CKM_API_ERROR_INPUT_PARAM; int retCode = CKM_API_SUCCESS; - if (0 == m_userDataMap.count(user)) - { + if (0 == m_userDataMap.count(user)) { // Check if key exists. If exists we must return error FileSystem fs(user); auto wrappedDKEKMain = fs.getDKEK(); @@ -285,11 +277,11 @@ RawBuffer CKMLogic::resetUserPassword( return MessageBuffer::Serialize(retCode).Pop(); } -RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) { +RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) +{ int retCode = CKM_API_SUCCESS; try { - if (smackLabel.empty()) { retCode = CKM_API_ERROR_INPUT_PARAM; } else { @@ -305,7 +297,6 @@ RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) { } } } - } catch (const Exc::Exception &e) { retCode = e.error(); } catch (const CKM::Exception &e) { @@ -330,22 +321,20 @@ int CKMLogic::checkSaveConditions( // check if allowed to save using ownerLabel int access_ec = m_accessControl.canSave(cred, ownerLabel); - if( access_ec != CKM_API_SUCCESS) - { + if (access_ec != CKM_API_SUCCESS) { LogDebug("label " << cred.smackLabel << " can not save rows using label " << ownerLabel); return access_ec; } // check if not a duplicate - if( handler.database.isNameLabelPresent(name, ownerLabel)) + if (handler.database.isNameLabelPresent(name, ownerLabel)) return CKM_API_ERROR_DB_ALIAS_EXISTS; // encryption section - if (!handler.crypto.haveKey(ownerLabel)) - { + if (!handler.crypto.haveKey(ownerLabel)) { RawBuffer got_key; auto key_optional = handler.database.getKey(ownerLabel); - if(!key_optional) { + if (!key_optional) { LogDebug("No Key in database found. Generating new one for label: " << ownerLabel); got_key = handler.keyProvider.generateDEK(ownerLabel); handler.database.saveKey(ownerLabel, got_key); @@ -386,32 +375,28 @@ int CKMLogic::verifyBinaryData(Crypto::Data &input) const int CKMLogic::toBinaryData(const Crypto::Data &input, Crypto::Data &output) const { // verify the data integrity - if (input.type.isKey()) - { + if (input.type.isKey()) { KeyShPtr output_key; - if(input.type.isSKey()) + if (input.type.isSKey()) output_key = CKM::Key::createAES(input.data); else output_key = CKM::Key::create(input.data); - if(output_key.get() == NULL) - { + + if (output_key.get() == NULL) { LogDebug("provided binary data is not valid key data"); return CKM_API_ERROR_INPUT_PARAM; } output = std::move(Crypto::Data(input.type, output_key->getDER())); - } - else if (input.type.isCertificate() || input.type.isChainCert()) - { + } else if (input.type.isCertificate() || input.type.isChainCert()) { CertificateShPtr cert = CKM::Certificate::create(input.data, DataFormat::FORM_DER); - if(cert.get() == NULL) - { + if (cert.get() == NULL) { LogDebug("provided binary data is not valid certificate data"); return CKM_API_ERROR_INPUT_PARAM; } output = std::move(Crypto::Data(input.type, cert->getDER())); - } - else + } else { output = input; + } // TODO: add here BINARY_DATA verification, i.e: max size etc. return CKM_API_SUCCESS; } @@ -429,10 +414,8 @@ int CKMLogic::verifyAndSaveDataHelper( // check if data is correct Crypto::Data binaryData; retCode = toBinaryData(data, binaryData); - if(retCode == CKM_API_SUCCESS) - { + if (retCode == CKM_API_SUCCESS) retCode = saveDataHelper(cred, name, label, binaryData, policy); - } } catch (const Exc::Exception &e) { retCode = e.error(); } catch (const CKM::Exception &e) { @@ -491,31 +474,30 @@ int CKMLogic::extractPKCS12Data( DB::RowVector &output) const { // private key is mandatory - if( !pkcs.getKey() ) + if (!pkcs.getKey()) return CKM_API_ERROR_INVALID_FORMAT; Key* keyPtr = pkcs.getKey().get(); Crypto::Data keyData(DataType(keyPtr->getType()), keyPtr->getDER()); int retCode = verifyBinaryData(keyData); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; output.push_back(createEncryptedRow(crypto, name, ownerLabel, keyData, keyPolicy)); // certificate is mandatory - if( !pkcs.getCertificate() ) + if (!pkcs.getCertificate()) return CKM_API_ERROR_INVALID_FORMAT; Crypto::Data certData(DataType::CERTIFICATE, pkcs.getCertificate().get()->getDER()); retCode = verifyBinaryData(certData); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; output.push_back(createEncryptedRow(crypto, name, ownerLabel, certData, certPolicy)); // CA cert chain unsigned int cert_index = 0; - for(const auto & ca : pkcs.getCaCertificateShPtrVector()) - { + for (const auto & ca : pkcs.getCaCertificateShPtrVector()) { Crypto::Data caCertData(DataType::getChainDatatype(cert_index ++), ca->getDER()); int retCode = verifyBinaryData(caCertData); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; output.push_back(createEncryptedRow(crypto, name, ownerLabel, caCertData, certPolicy)); @@ -571,8 +553,7 @@ int CKMLogic::removeDataHelper( handler.database.getPermissionRow(name, ownerLabel, cred.smackLabel); int retCode = m_accessControl.canDelete(cred, PermissionForLabel(cred.smackLabel, permissionRowOpt)); - if(retCode != CKM_API_SUCCESS) - { + if (retCode != CKM_API_SUCCESS) { LogWarning("access control check result: " << retCode); return retCode; } @@ -587,11 +568,11 @@ int CKMLogic::removeDataHelper( // load app key if needed retCode = loadAppKey(handler, rows.front().ownerLabel); - if(CKM_API_SUCCESS != retCode) + if (CKM_API_SUCCESS != retCode) return retCode; // destroy it in store - for(auto& r : rows) { + for (auto& r : rows) { try { handler.crypto.decryptRow(Password(), r); m_decider.getStore(r).destroy(r); @@ -615,16 +596,11 @@ RawBuffer CKMLogic::removeData( { int retCode = CKM_API_ERROR_UNKNOWN; - try - { + try { retCode = removeDataHelper(cred, name, label); - } - catch (const Exc::Exception &e) - { + } catch (const Exc::Exception &e) { retCode = e.error(); - } - catch (const CKM::Exception &e) - { + } catch (const CKM::Exception &e) { LogError("Error: " << e.GetMessage()); retCode = CKM_API_ERROR_DB_ERROR; } @@ -642,8 +618,7 @@ int CKMLogic::readSingleRow(const Name &name, DB::Row &row) { DB::Crypto::RowOptional row_optional; - if (dataType.isKey()) - { + if (dataType.isKey()) { // read all key types row_optional = database.getRow(name, ownerLabel, @@ -656,7 +631,7 @@ int CKMLogic::readSingleRow(const Name &name, dataType); } - if(!row_optional) { + if (!row_optional) { LogDebug("No row for given name, label and type"); return CKM_API_ERROR_DB_ALIAS_UNKNOWN; } else { @@ -674,33 +649,27 @@ int CKMLogic::readMultiRow(const Name &name, DB::RowVector &output) { if (dataType.isKey()) - { // read all key types database.getRows(name, ownerLabel, DataType::DB_KEY_FIRST, DataType::DB_KEY_LAST, output); - } else if (dataType.isChainCert()) - { // read all key types database.getRows(name, ownerLabel, DataType::DB_CHAIN_FIRST, DataType::DB_CHAIN_LAST, output); - } else - { // read anything else database.getRows(name, ownerLabel, dataType, output); - } - if(!output.size()) { + if (!output.size()) { LogDebug("No row for given name, label and type"); return CKM_API_ERROR_DB_ALIAS_UNKNOWN; } @@ -719,7 +688,7 @@ int CKMLogic::checkDataPermissionsHelper(const Credentials &cred, PermissionMaskOptional permissionRowOpt = database.getPermissionRow(name, ownerLabel, accessorLabel); - if(exportFlag) + if (exportFlag) return m_accessControl.canExport(cred, row, PermissionForLabel(accessorLabel, permissionRowOpt)); return m_accessControl.canRead(cred, PermissionForLabel(accessorLabel, permissionRowOpt)); } @@ -735,7 +704,7 @@ Crypto::GObjUPtr CKMLogic::rowToObject( // decrypt row Crypto::GObjUPtr obj; - if(CryptoLogic::getSchemeVersion(row.encryptionScheme) == CryptoLogic::ENCRYPTION_V2) { + if (CryptoLogic::getSchemeVersion(row.encryptionScheme) == CryptoLogic::ENCRYPTION_V2) { handler.crypto.decryptRow(Password(), row); obj = store.getObject(row, pass); @@ -784,7 +753,7 @@ int CKMLogic::readDataHelper( DB::Crypto::Transaction transaction(&handler.database); DB::RowVector rows; int retCode = readMultiRow(name, ownerLabel, dataType, handler.database, rows); - if(CKM_API_SUCCESS != retCode) + if (CKM_API_SUCCESS != retCode) return retCode; // all read rows belong to the same owner @@ -792,16 +761,16 @@ int CKMLogic::readDataHelper( // check access rights retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel, firstRow, exportFlag, handler.database); - if(CKM_API_SUCCESS != retCode) + if (CKM_API_SUCCESS != retCode) return retCode; // load app key if needed retCode = loadAppKey(handler, firstRow.ownerLabel); - if(CKM_API_SUCCESS != retCode) + if (CKM_API_SUCCESS != retCode) return retCode; // decrypt row - for(auto &row : rows) + for (auto &row : rows) objs.push_back(rowToObject(handler, std::move(row), password)); // rowToObject may modify db transaction.commit(); @@ -844,19 +813,19 @@ int CKMLogic::readDataHelper( DB::Crypto::Transaction transaction(&handler.database); DB::Row row; int retCode = readSingleRow(name, ownerLabel, dataType, handler.database, row); - if(CKM_API_SUCCESS != retCode) + if (CKM_API_SUCCESS != retCode) return retCode; objDataType = row.dataType; // check access rights retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel, row, exportFlag, handler.database); - if(CKM_API_SUCCESS != retCode) + if (CKM_API_SUCCESS != retCode) return retCode; // load app key if needed retCode = loadAppKey(handler, row.ownerLabel); - if(CKM_API_SUCCESS != retCode) + if (CKM_API_SUCCESS != retCode) return retCode; obj = rowToObject(handler, std::move(row), password); @@ -881,7 +850,7 @@ RawBuffer CKMLogic::getData( try { Crypto::GObjUPtr obj; retCode = readDataHelper(true, cred, dataType, name, label, password, obj, objDataType); - if(retCode == CKM_API_SUCCESS) + if (retCode == CKM_API_SUCCESS) row.data = std::move(obj->getBinary()); } catch (const Exc::Exception &e) { retCode = e.error(); @@ -918,28 +887,28 @@ int CKMLogic::getPKCS12Helper( // read private key (mandatory) Crypto::GObjUPtr keyObj; retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, label, keyPassword, keyObj); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; privKey = CKM::Key::create(keyObj->getBinary()); // read certificate (mandatory) Crypto::GObjUPtr certObj; retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, label, certPassword, certObj); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; cert = CKM::Certificate::create(certObj->getBinary(), DataFormat::FORM_DER); // read CA cert chain (optional) Crypto::GObjUPtrVector caChainObjs; retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, label, certPassword, caChainObjs); - if(retCode != CKM_API_SUCCESS && + if (retCode != CKM_API_SUCCESS && retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN) return retCode; - for(auto &caCertObj : caChainObjs) + for (auto &caCertObj : caChainObjs) caChain.push_back(CKM::Certificate::create(caCertObj->getBinary(), DataFormat::FORM_DER)); // if anything found, return it - if(privKey || cert || caChain.size()>0) + if (privKey || cert || caChain.size() > 0) retCode = CKM_API_SUCCESS; return retCode; @@ -963,7 +932,7 @@ RawBuffer CKMLogic::getPKCS12( retCode = getPKCS12Helper(cred, name, label, keyPassword, certPassword, privKey, cert, caChain); // prepare response - if(retCode == CKM_API_SUCCESS) + if (retCode == CKM_API_SUCCESS) output = PKCS12Serializable(privKey, cert, caChain); } catch (const Exc::Exception &e) { retCode = e.error(); @@ -984,8 +953,7 @@ int CKMLogic::getDataListHelper(const Credentials &cred, LabelNameVector &labelNameVector) { int retCode = CKM_API_ERROR_DB_LOCKED; - if (0 < m_userDataMap.count(cred.clientUid)) - { + if (0 < m_userDataMap.count(cred.clientUid)) { auto &database = m_userDataMap[cred.clientUid].database; try { @@ -1024,19 +992,15 @@ RawBuffer CKMLogic::getDataList( LabelNameVector labelNameVector; int retCode = unlockSystemDB(); - if (CKM_API_SUCCESS == retCode) - { + if (CKM_API_SUCCESS == retCode) { // system database - if (m_accessControl.isSystemService(cred)) - { + if (m_accessControl.isSystemService(cred)) { // lookup system DB retCode = getDataListHelper(Credentials(SYSTEM_DB_UID, OWNER_ID_SYSTEM), dataType, systemVector); - } - else - { + } else { // user - lookup system, then client DB retCode = getDataListHelper(Credentials(SYSTEM_DB_UID, cred.smackLabel), @@ -1044,8 +1008,7 @@ RawBuffer CKMLogic::getDataList( systemVector); // private database - if(retCode == CKM_API_SUCCESS) - { + if (retCode == CKM_API_SUCCESS) { retCode = getDataListHelper(cred, dataType, userVector); @@ -1053,11 +1016,11 @@ RawBuffer CKMLogic::getDataList( } } - if(retCode == CKM_API_SUCCESS) - { + if (retCode == CKM_API_SUCCESS) { labelNameVector.insert(labelNameVector.end(), systemVector.begin(), systemVector.end()); labelNameVector.insert(labelNameVector.end(), userVector.begin(), userVector.end()); } + auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET_LIST), commandId, retCode, @@ -1074,18 +1037,18 @@ int CKMLogic::importInitialData( { try { // Inital values are always imported with root credentials. Label is not important. - Credentials rootCred(0,""); + Credentials rootCred(0, ""); auto &handler = selectDatabase(rootCred, OWNER_ID_SYSTEM); // check if save is possible DB::Crypto::Transaction transaction(&handler.database); int retCode = checkSaveConditions(rootCred, handler, name, OWNER_ID_SYSTEM); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; Crypto::GStore& store = - m_decider.getStore(data.type, policy.extractable, !enc.encryptedKey.empty()); + m_decider.getStore(data.type, policy.extractable, !enc.encryptedKey.empty()); Token token; @@ -1127,13 +1090,13 @@ int CKMLogic::saveDataHelper( // use client label if not explicitly provided const Label &ownerLabel = label.empty() ? cred.smackLabel : label; - if( m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM)!=0) + if (m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; // check if save is possible DB::Crypto::Transaction transaction(&handler.database); int retCode = checkSaveConditions(cred, handler, name, ownerLabel); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; // save the data @@ -1156,19 +1119,19 @@ int CKMLogic::saveDataHelper( // use client label if not explicitly provided const Label &ownerLabel = label.empty() ? cred.smackLabel : label; - if( m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM)!=0) + if (m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; // check if save is possible DB::Crypto::Transaction transaction(&handler.database); int retCode = checkSaveConditions(cred, handler, name, ownerLabel); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; // extract and encrypt the data DB::RowVector encryptedRows; retCode = extractPKCS12Data(handler.crypto, name, ownerLabel, pkcs, keyPolicy, certPolicy, encryptedRows); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; // save the data @@ -1190,13 +1153,13 @@ int CKMLogic::createKeyAESHelper( // use client label if not explicitly provided const Label &ownerLabel = label.empty() ? cred.smackLabel : label; - if( m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM)!=0) + if (m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; // check if save is possible DB::Crypto::Transaction transaction(&handler.database); int retCode = checkSaveConditions(cred, handler, name, ownerLabel); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; // create key in store @@ -1229,18 +1192,20 @@ int CKMLogic::createKeyPairHelper( auto &handlerPub = selectDatabase(cred, labelPublic); AlgoType keyType = AlgoType::RSA_GEN; - if(!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType)) + if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType)) ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found."); + DataType dt(keyType); - if(!dt.isKey()) + if (!dt.isKey()) ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value."); // use client label if not explicitly provided const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel : labelPrivate; - if( m_accessControl.isSystemService(cred) && ownerLabelPrv.compare(OWNER_ID_SYSTEM)!=0) + if (m_accessControl.isSystemService(cred) && ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; + const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel : labelPublic; - if( m_accessControl.isSystemService(cred) && ownerLabelPub.compare(OWNER_ID_SYSTEM)!=0) + if (m_accessControl.isSystemService(cred) && ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0) return CKM_API_ERROR_INPUT_PARAM; bool exportable = policyPrivate.extractable || policyPublic.extractable; @@ -1367,9 +1332,9 @@ int CKMLogic::readCertificateHelper( i.first, CKM::Password(), caChainObjs); - if(ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN) + if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN) return ec; - for(auto &caCertObj : caChainObjs) + for (auto &caCertObj : caChainObjs) certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER); } return CKM_API_SUCCESS; @@ -1391,13 +1356,13 @@ int CKMLogic::getCertificateChainHelper( for (auto &e: untrustedCertificates) { CertificateImpl c(e, DataFormat::FORM_DER); - if(c.empty()) + if (c.empty()) return CKM_API_ERROR_INPUT_PARAM; untrustedCertVector.push_back(std::move(c)); } for (auto &e: trustedCertificates) { CertificateImpl c(e, DataFormat::FORM_DER); - if(c.empty()) + if (c.empty()) return CKM_API_ERROR_INPUT_PARAM; trustedCertVector.push_back(std::move(c)); } @@ -1540,9 +1505,8 @@ RawBuffer CKMLogic::createSignature( try { Crypto::GObjUPtr obj; retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName, ownerLabel, password, obj); - if(retCode == CKM_API_SUCCESS) { + if (retCode == CKM_API_SUCCESS) signature = obj->sign(cryptoAlg, message); - } } catch (const Exc::Exception &e) { retCode = e.error(); } catch (const CKM::Exception &e) { @@ -1580,13 +1544,11 @@ RawBuffer CKMLogic::verifySignature( // rather than private key from the same PKCS. Crypto::GObjUPtr obj; retCode = readDataHelper(false, cred, DataType::CERTIFICATE, publicKeyOrCertName, ownerLabel, password, obj); - if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN) { + if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN) retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, publicKeyOrCertName, ownerLabel, password, obj); - } - if (retCode == CKM_API_SUCCESS) { + if (retCode == CKM_API_SUCCESS) retCode = obj->verify(params, message, signature); - } } catch (const Exc::Exception &e) { retCode = e.error(); } catch (const CKM::Exception &e) { @@ -1621,7 +1583,7 @@ int CKMLogic::setPermissionHelper( return CKM_API_ERROR_INPUT_PARAM; // currently we don't support modification of owner's permissions to his own rows - if (ownerLabel==accessorLabel) + if (ownerLabel == accessorLabel) return CKM_API_ERROR_INPUT_PARAM; // system database does not support write/remove permissions @@ -1631,18 +1593,17 @@ int CKMLogic::setPermissionHelper( // can the client modify permissions to owner's row? int retCode = m_accessControl.canModify(cred, ownerLabel); - if(retCode != CKM_API_SUCCESS) + if (retCode != CKM_API_SUCCESS) return retCode; DB::Crypto::Transaction transaction(&handler.database); - if( !handler.database.isNameLabelPresent(name, ownerLabel) ) + if (!handler.database.isNameLabelPresent(name, ownerLabel)) return CKM_API_ERROR_DB_ALIAS_UNKNOWN; // removing non-existing permissions: fail - if(permissionMask == Permission::NONE) - { - if(!handler.database.getPermissionRow(name, ownerLabel, accessorLabel)) + if (permissionMask == Permission::NONE) { + if (!handler.database.getPermissionRow(name, ownerLabel, accessorLabel)) return CKM_API_ERROR_INPUT_PARAM; } @@ -1680,7 +1641,7 @@ int CKMLogic::loadAppKey(UserData& handle, const Label& appLabel) if (!handle.crypto.haveKey(appLabel)) { RawBuffer key; auto key_optional = handle.database.getKey(appLabel); - if(!key_optional) { + if (!key_optional) { LogError("No key for given label in database"); return CKM_API_ERROR_DB_ERROR; } diff --git a/src/manager/service/ckm-logic.h b/src/manager/service/ckm-logic.h index 3c1cb3a3..dafe530d 100644 --- a/src/manager/service/ckm-logic.h +++ b/src/manager/service/ckm-logic.h @@ -215,7 +215,6 @@ protected: int unlockSystemDB(); private: - // select private/system database depending on asking uid and owner label. // output: database handler and effective label UserData & selectDatabase(const Credentials &incoming_cred, diff --git a/src/manager/service/ckm-service.cpp b/src/manager/service/ckm-service.cpp index c87a4434..6773c478 100644..100755 --- a/src/manager/service/ckm-service.cpp +++ b/src/manager/service/ckm-service.cpp @@ -36,21 +36,24 @@ const CKM::InterfaceID SOCKET_ID_STORAGE = 1; namespace CKM { -CKMService::CKMService() - : m_logic(new CKMLogic) +CKMService::CKMService() : + m_logic(new CKMLogic) { InitialValues::LoadFiles(*m_logic); } -CKMService::~CKMService() { +CKMService::~CKMService() +{ delete m_logic; } -void CKMService::Start() { +void CKMService::Start() +{ Create(); } -void CKMService::Stop() { +void CKMService::Stop() +{ Join(); } @@ -75,7 +78,7 @@ bool CKMService::ProcessOne( ConnectionInfo &info, bool /*allowed*/) { - LogDebug ("process One"); + LogDebug("process One"); RawBuffer response; Try { @@ -90,9 +93,9 @@ bool CKMService::ProcessOne( m_serviceManager->Write(conn, response); return true; - } Catch (MessageBuffer::Exception::Base) { + } Catch(MessageBuffer::Exception::Base) { LogError("Broken protocol. Closing socket."); - } Catch (Exception::BrokenProtocol) { + } Catch(Exception::BrokenProtocol) { LogError("Broken protocol. Closing socket."); } catch (const DataType::Exception::Base &e) { LogError("Closing socket. DBDataType::Exception: " << e.DumpToString()); @@ -108,7 +111,8 @@ bool CKMService::ProcessOne( return false; } -RawBuffer CKMService::ProcessControl(MessageBuffer &buffer) { +RawBuffer CKMService::ProcessControl(MessageBuffer &buffer) +{ int command = 0; uid_t user = 0; ControlCommand cc; @@ -121,7 +125,7 @@ RawBuffer CKMService::ProcessControl(MessageBuffer &buffer) { cc = static_cast<ControlCommand>(command); - switch(cc) { + switch (cc) { case ControlCommand::UNLOCK_USER_KEY: buffer.Deserialize(user, newPass); return m_logic->unlockUserKey(user, newPass); @@ -187,211 +191,213 @@ RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer) LogDebug("Process storage. Command: " << command); - switch(static_cast<LogicCommand>(command)) { - case LogicCommand::SAVE: - { - RawBuffer rawData; - PolicySerializable policy; - buffer.Deserialize(tmpDataType, name, label, rawData, policy); - return m_logic->saveData( - cred, - msgID, - name, - label, - Crypto::Data(DataType(tmpDataType), std::move(rawData)), - policy); - } - case LogicCommand::SAVE_PKCS12: - { - RawBuffer rawData; - PKCS12Serializable pkcs; - PolicySerializable keyPolicy, certPolicy; - buffer.Deserialize(name, label, pkcs, keyPolicy, certPolicy); - return m_logic->savePKCS12( - cred, - msgID, - name, - label, - pkcs, - keyPolicy, - certPolicy); - } - case LogicCommand::REMOVE: - { - buffer.Deserialize(name, label); - return m_logic->removeData( - cred, - msgID, - name, - label); - } - case LogicCommand::GET: - { - Password password; - buffer.Deserialize(tmpDataType, name, label, password); - return m_logic->getData( - cred, - msgID, - DataType(tmpDataType), - name, - label, - password); - } - case LogicCommand::GET_PKCS12: - { - Password passKey; - Password passCert; - buffer.Deserialize(name, - label, - passKey, - passCert); - return m_logic->getPKCS12( - cred, - msgID, - name, - label, - passKey, - passCert); - } - case LogicCommand::GET_LIST: - { - buffer.Deserialize(tmpDataType); - return m_logic->getDataList( - cred, - msgID, - DataType(tmpDataType)); - } - case LogicCommand::CREATE_KEY_AES: - { - int size = 0; - Name keyName; - Label keyLabel; - PolicySerializable policyKey; - buffer.Deserialize(size, - policyKey, - keyName, - keyLabel); - return m_logic->createKeyAES( - cred, - msgID, - size, - keyName, - keyLabel, - policyKey); - } - case LogicCommand::CREATE_KEY_PAIR: - { - CryptoAlgorithmSerializable keyGenAlgorithm; - Name privateKeyName; - Label privateKeyLabel; - Name publicKeyName; - Label publicKeyLabel; - PolicySerializable policyPrivateKey; - PolicySerializable policyPublicKey; - buffer.Deserialize(keyGenAlgorithm, - policyPrivateKey, - policyPublicKey, - privateKeyName, - privateKeyLabel, - publicKeyName, - publicKeyLabel); - return m_logic->createKeyPair( - cred, - msgID, - keyGenAlgorithm, - privateKeyName, - privateKeyLabel, - publicKeyName, - publicKeyLabel, - policyPrivateKey, - policyPublicKey); - } - case LogicCommand::GET_CHAIN_CERT: - { - RawBuffer certificate; - RawBufferVector untrustedVector; - RawBufferVector trustedVector; - bool systemCerts = false; - buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts); - return m_logic->getCertificateChain( - cred, - msgID, - certificate, - untrustedVector, - trustedVector, - systemCerts); - } - case LogicCommand::GET_CHAIN_ALIAS: - { - RawBuffer certificate; - LabelNameVector untrustedVector; - LabelNameVector trustedVector; - bool systemCerts = false; - buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts); - return m_logic->getCertificateChain( - cred, - msgID, - certificate, - untrustedVector, - trustedVector, - systemCerts); - } - case LogicCommand::CREATE_SIGNATURE: - { - Password password; // password for private_key - RawBuffer message; - - CryptoAlgorithmSerializable cAlgorithm; - buffer.Deserialize(name, label, password, message, cAlgorithm); - - return m_logic->createSignature( - cred, - msgID, - name, - label, - password, // password for private_key - message, - cAlgorithm); - } - case LogicCommand::VERIFY_SIGNATURE: - { - Password password; // password for public_key (optional) - RawBuffer message; - RawBuffer signature; - CryptoAlgorithmSerializable cAlg; - - buffer.Deserialize(name, - label, - password, - message, - signature, - cAlg); - - return m_logic->verifySignature( - cred, - msgID, - name, - label, - password, // password for public_key (optional) - message, - signature, - cAlg); - } - case LogicCommand::SET_PERMISSION: - { - PermissionMask permissionMask = 0; - buffer.Deserialize(name, label, accessorLabel, permissionMask); - return m_logic->setPermission( - cred, - command, - msgID, - name, - label, - accessorLabel, - permissionMask); - } - default: - Throw(Exception::BrokenProtocol); + switch (static_cast<LogicCommand>(command)) { + case LogicCommand::SAVE: + { + RawBuffer rawData; + PolicySerializable policy; + buffer.Deserialize(tmpDataType, name, label, rawData, policy); + return m_logic->saveData( + cred, + msgID, + name, + label, + Crypto::Data(DataType(tmpDataType), std::move(rawData)), + policy); + } + case LogicCommand::SAVE_PKCS12: + { + RawBuffer rawData; + PKCS12Serializable pkcs; + PolicySerializable keyPolicy, certPolicy; + buffer.Deserialize(name, label, pkcs, keyPolicy, certPolicy); + return m_logic->savePKCS12( + cred, + msgID, + name, + label, + pkcs, + keyPolicy, + certPolicy); + } + case LogicCommand::REMOVE: + { + buffer.Deserialize(name, label); + return m_logic->removeData( + cred, + msgID, + name, + label); + } + case LogicCommand::GET: + { + Password password; + buffer.Deserialize(tmpDataType, name, label, password); + return m_logic->getData( + cred, + msgID, + DataType(tmpDataType), + name, + label, + password); + } + case LogicCommand::GET_PKCS12: + { + Password passKey; + Password passCert; + buffer.Deserialize( + name, + label, + passKey, + passCert); + return m_logic->getPKCS12( + cred, + msgID, + name, + label, + passKey, + passCert); + } + case LogicCommand::GET_LIST: + { + buffer.Deserialize(tmpDataType); + return m_logic->getDataList( + cred, + msgID, + DataType(tmpDataType)); + } + case LogicCommand::CREATE_KEY_AES: + { + int size = 0; + Name keyName; + Label keyLabel; + PolicySerializable policyKey; + buffer.Deserialize( + size, + policyKey, + keyName, + keyLabel); + return m_logic->createKeyAES( + cred, + msgID, + size, + keyName, + keyLabel, + policyKey); + } + case LogicCommand::CREATE_KEY_PAIR: + { + CryptoAlgorithmSerializable keyGenAlgorithm; + Name privateKeyName; + Label privateKeyLabel; + Name publicKeyName; + Label publicKeyLabel; + PolicySerializable policyPrivateKey; + PolicySerializable policyPublicKey; + buffer.Deserialize(keyGenAlgorithm, + policyPrivateKey, + policyPublicKey, + privateKeyName, + privateKeyLabel, + publicKeyName, + publicKeyLabel); + return m_logic->createKeyPair( + cred, + msgID, + keyGenAlgorithm, + privateKeyName, + privateKeyLabel, + publicKeyName, + publicKeyLabel, + policyPrivateKey, + policyPublicKey); + } + case LogicCommand::GET_CHAIN_CERT: + { + RawBuffer certificate; + RawBufferVector untrustedVector; + RawBufferVector trustedVector; + bool systemCerts = false; + buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts); + return m_logic->getCertificateChain( + cred, + msgID, + certificate, + untrustedVector, + trustedVector, + systemCerts); + } + case LogicCommand::GET_CHAIN_ALIAS: + { + RawBuffer certificate; + LabelNameVector untrustedVector; + LabelNameVector trustedVector; + bool systemCerts = false; + buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts); + return m_logic->getCertificateChain( + cred, + msgID, + certificate, + untrustedVector, + trustedVector, + systemCerts); + } + case LogicCommand::CREATE_SIGNATURE: + { + Password password; // password for private_key + RawBuffer message; + + CryptoAlgorithmSerializable cAlgorithm; + buffer.Deserialize(name, label, password, message, cAlgorithm); + + return m_logic->createSignature( + cred, + msgID, + name, + label, + password, // password for private_key + message, + cAlgorithm); + } + case LogicCommand::VERIFY_SIGNATURE: + { + Password password; // password for public_key (optional) + RawBuffer message; + RawBuffer signature; + CryptoAlgorithmSerializable cAlg; + + buffer.Deserialize(name, + label, + password, + message, + signature, + cAlg); + + return m_logic->verifySignature( + cred, + msgID, + name, + label, + password, // password for public_key (optional) + message, + signature, + cAlg); + } + case LogicCommand::SET_PERMISSION: + { + PermissionMask permissionMask = 0; + buffer.Deserialize(name, label, accessorLabel, permissionMask); + return m_logic->setPermission( + cred, + command, + msgID, + name, + label, + accessorLabel, + permissionMask); + } + default: + Throw(Exception::BrokenProtocol); } } @@ -412,14 +418,16 @@ void CKMService::ProcessMessage(MsgKeyRequest msg) } } -void CKMService::CustomHandle(const ReadEvent &event) { +void CKMService::CustomHandle(const ReadEvent &event) +{ LogDebug("Read event"); auto &info = m_connectionInfoMap[event.connectionID.counter]; info.buffer.Push(event.rawBuffer); - while(ProcessOne(event.connectionID, info, true)); + while (ProcessOne(event.connectionID, info, true)); } -void CKMService::CustomHandle(const SecurityEvent & /*event*/) { +void CKMService::CustomHandle(const SecurityEvent & /*event*/) +{ LogError("This should not happend! SecurityEvent was called on CKMService!"); } diff --git a/src/manager/service/ckm-service.h b/src/manager/service/ckm-service.h index 5b6221e4..b927f40c 100644 --- a/src/manager/service/ckm-service.h +++ b/src/manager/service/ckm-service.h @@ -30,8 +30,7 @@ namespace CKM { class CKMLogic; -class CKMService : public ThreadMessageService<MsgKeyRequest> -{ +class CKMService : public ThreadMessageService<MsgKeyRequest> { public: CKMService(); CKMService(const CKMService &) = delete; @@ -41,11 +40,13 @@ public: // Custom add custom support for ReadEvent and SecurityEvent // because we want to bypass security check in CKMService - virtual void Event(const ReadEvent &event) { + virtual void Event(const ReadEvent &event) + { CreateEvent([this, event]() { this->CustomHandle(event); }); } - virtual void Event(const SecurityEvent &event) { + virtual void Event(const SecurityEvent &event) + { CreateEvent([this, event]() { this->CustomHandle(event); }); } diff --git a/src/manager/service/crypto-logic.cpp b/src/manager/service/crypto-logic.cpp index b5b59598..2fd9d7df 100644..100755 --- a/src/manager/service/crypto-logic.cpp +++ b/src/manager/service/crypto-logic.cpp @@ -72,11 +72,13 @@ const int ENCR_ORDER_V2 = CryptoLogic::ENCRYPTION_V2 << ENCR_ORDER_OFFSET; CryptoLogic::CryptoLogic() {} -CryptoLogic::CryptoLogic(CryptoLogic &&second) { +CryptoLogic::CryptoLogic(CryptoLogic &&second) +{ m_keyMap = std::move(second.m_keyMap); } -CryptoLogic& CryptoLogic::operator=(CryptoLogic &&second) { +CryptoLogic& CryptoLogic::operator=(CryptoLogic &&second) +{ if (this == &second) return *this; m_keyMap = std::move(second.m_keyMap); @@ -91,16 +93,15 @@ bool CryptoLogic::haveKey(const Label &smackLabel) void CryptoLogic::pushKey(const Label &smackLabel, const RawBuffer &applicationKey) { - if (smackLabel.length() == 0) { + if (smackLabel.length() == 0) ThrowErr(Exc::InternalError, "Empty smack label."); - } - if (applicationKey.size() == 0) { + + if (applicationKey.size() == 0) ThrowErr(Exc::InternalError, "Empty application key."); - } - if (haveKey(smackLabel)) { + + if (haveKey(smackLabel)) ThrowErr(Exc::InternalError, "Application key for ", smackLabel, "label already exists."); - } m_keyMap[smackLabel] = applicationKey; } @@ -125,19 +126,17 @@ RawBuffer CryptoLogic::passwordToKey( 1024, result.size(), result.data())) - { ThrowErr(Exc::InternalError, "PCKS5_PKKDF_HMAC_SHA1 failed."); - } return result; } -RawBuffer CryptoLogic::generateRandIV() const { +RawBuffer CryptoLogic::generateRandIV() const +{ RawBuffer civ(EVP_MAX_IV_LENGTH); - if (1 != RAND_bytes(civ.data(), civ.size())) { + if (1 != RAND_bytes(civ.data(), civ.size())) ThrowErr(Exc::InternalError, "RAND_bytes failed to generate IV."); - } return civ; } @@ -153,18 +152,15 @@ void CryptoLogic::encryptRow(DB::Row &row) crow.algorithmType = DBCMAlgType::AES_GCM_256; crow.dataSize = crow.data.size(); - if (crow.dataSize <= 0) { + if (crow.dataSize <= 0) ThrowErr(Exc::InternalError, "Invalid dataSize."); - } - if (!haveKey(row.ownerLabel)) { + if (!haveKey(row.ownerLabel)) ThrowErr(Exc::InternalError, "Missing application key for ", row.ownerLabel, " label."); - } - if (crow.iv.empty()) { + if (crow.iv.empty()) crow.iv = generateRandIV(); - } key = m_keyMap[row.ownerLabel]; crow.encryptionScheme = ENCR_APPKEY; @@ -201,33 +197,28 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row) RawBuffer key; RawBuffer digest, dataDigest; - if (row.algorithmType != DBCMAlgType::AES_GCM_256) { + if (row.algorithmType != DBCMAlgType::AES_GCM_256) ThrowErr(Exc::AuthenticationFailed, "Invalid algorithm type."); - } - if ((row.encryptionScheme & ENCR_PASSWORD) && password.empty()) { + if ((row.encryptionScheme & ENCR_PASSWORD) && password.empty()) ThrowErr(Exc::AuthenticationFailed, "DB row is password protected, but given password is empty."); - } - if(!(row.encryptionScheme & ENCR_PASSWORD) && !password.empty()) { + if (!(row.encryptionScheme & ENCR_PASSWORD) && !password.empty()) ThrowErr(Exc::AuthenticationFailed, "DB row is not password protected, but given password is not empty."); - } - if ((row.encryptionScheme & ENCR_APPKEY) && !haveKey(row.ownerLabel)) { + if ((row.encryptionScheme & ENCR_APPKEY) && !haveKey(row.ownerLabel)) ThrowErr(Exc::AuthenticationFailed, "Missing application key for ", row.ownerLabel, " label."); - } decBase64(crow.iv); - if (crow.encryptionScheme & ENCR_BASE64) { + if (crow.encryptionScheme & ENCR_BASE64) decBase64(crow.data); - } - if((crow.encryptionScheme >> ENCR_ORDER_OFFSET) == ENCR_ORDER_V2) { + if ((crow.encryptionScheme >> ENCR_ORDER_OFFSET) == ENCR_ORDER_V2) { if (crow.encryptionScheme & ENCR_APPKEY) { key = m_keyMap[crow.ownerLabel]; crow.data = Crypto::SW::Internals::decryptDataAesGcm(key, crow.data, crow.iv, crow.tag); @@ -243,13 +234,12 @@ void CryptoLogic::decryptRow(const Password &password, DB::Row &row) crow.data = Crypto::SW::Internals::decryptDataAesGcm(key, crow.data, crow.iv, crow.tag); } } - if (static_cast<int>(crow.data.size()) < crow.dataSize) { + + if (static_cast<int>(crow.data.size()) < crow.dataSize) ThrowErr(Exc::AuthenticationFailed, "Decrypted row size mismatch"); - } - if (static_cast<int>(crow.data.size()) > crow.dataSize) { + if (static_cast<int>(crow.data.size()) > crow.dataSize) crow.data.resize(crow.dataSize); - } row = std::move(crow); } catch(const CKM::Base64Encoder::Exception::Base &e) { @@ -270,9 +260,8 @@ void CryptoLogic::encBase64(RawBuffer &data) benc.finalize(); encdata = benc.get(); - if (encdata.size() == 0) { + if (encdata.size() == 0) ThrowErr(Exc::InternalError, "Base64Encoder returned empty data."); - } data = std::move(encdata); } @@ -284,15 +273,13 @@ void CryptoLogic::decBase64(RawBuffer &data) bdec.reset(); bdec.append(data); - if (!bdec.finalize()) { + if (!bdec.finalize()) ThrowErr(Exc::InternalError, "Failed in Base64Decoder.finalize."); - } decdata = bdec.get(); - if (decdata.size() == 0) { + if (decdata.size() == 0) ThrowErr(Exc::InternalError, "Base64Decoder returned empty data."); - } data = std::move(decdata); } diff --git a/src/manager/service/crypto-logic.h b/src/manager/service/crypto-logic.h index aa4a0e89..8bc25548 100644 --- a/src/manager/service/crypto-logic.h +++ b/src/manager/service/crypto-logic.h @@ -35,7 +35,7 @@ public: CryptoLogic& operator=(CryptoLogic &&second); CryptoLogic& operator=(const CryptoLogic &second) = delete; - virtual ~CryptoLogic(){} + virtual ~CryptoLogic() {} void decryptRow(const Password &password, DB::Row &row); void encryptRow(DB::Row &row); diff --git a/src/manager/service/crypto-request.h b/src/manager/service/crypto-request.h index d8acf2b9..c8c16bf4 100644 --- a/src/manager/service/crypto-request.h +++ b/src/manager/service/crypto-request.h @@ -27,8 +27,7 @@ namespace CKM { -struct CryptoRequest -{ +struct CryptoRequest { ConnectionID conn; Credentials cred; EncryptionCommand command; diff --git a/src/manager/service/db-crypto.cpp b/src/manager/service/db-crypto.cpp index 572b2a08..b70c85e1 100644..100755 --- a/src/manager/service/db-crypto.cpp +++ b/src/manager/service/db-crypto.cpp @@ -176,11 +176,13 @@ namespace DB { other.m_inUserTransaction = false; } - Crypto::~Crypto() { + Crypto::~Crypto() + { delete m_connection; } - Crypto& Crypto::operator=(Crypto&& other) { + Crypto& Crypto::operator=(Crypto&& other) + { if (this == &other) return *this; delete m_connection; @@ -226,22 +228,20 @@ namespace DB { bool Crypto::getDBVersion(int & schemaVersion) { SchemaInfo SchemaInfo(this); - if(SchemaInfo.getVersionInfo(schemaVersion)) { + if (SchemaInfo.getVersionInfo(schemaVersion)) { LogDebug("Current DB version: " << schemaVersion); return true; - } - else - { + } else { LogDebug("No DB version known or DB not present"); // special case: old CKM_TABLE exists - if(m_connection->CheckTableExist("CKM_TABLE")) { + if (m_connection->CheckTableExist("CKM_TABLE")) { schemaVersion = DB_VERSION_1; return true; } // special case: new scheme exists, but no SCHEMA_INFO table present - else if(m_connection->CheckTableExist("NAME_TABLE")) { + else if (m_connection->CheckTableExist("NAME_TABLE")) { schemaVersion = DB_VERSION_2; return true; } @@ -254,22 +254,17 @@ namespace DB { { // run migration if old database is present int schemaVersion; - if( getDBVersion(schemaVersion)==false || // DB empty or corrupted - schemaVersion > DB_VERSION_CURRENT) // or too new scheme - { + if ( getDBVersion(schemaVersion) == false || // DB empty or corrupted + schemaVersion > DB_VERSION_CURRENT) { // or too new scheme LogDebug("no database or database corrupted, initializing the DB"); resetDB(); - } - else - { + } else { // migration needed LogDebug("DB migration from version " << schemaVersion << " to version " << DB_VERSION_CURRENT << " started."); Transaction transaction(this); - for(int vi=schemaVersion; vi<DB_VERSION_CURRENT; vi++) - { + for (int vi = schemaVersion; vi < DB_VERSION_CURRENT; vi++) { ScriptOptional script = getMigrationScript(vi); - if(!script) - { + if (!script) { LogError("Error, script to migrate database from version: " << vi << " to version: " << vi+1 << " not available, resetting the DB"); resetDB(); @@ -290,12 +285,11 @@ namespace DB { { std::string scriptPath = SCRIPTS_PATH + scriptName + std::string(".sql"); std::ifstream is(scriptPath); - if(is.fail()) { + if (is.fail()) { LogError("Script " << scriptPath << " not found!"); return ScriptOptional(); } - - std::istreambuf_iterator<char> begin(is),end; + std::istreambuf_iterator<char> begin(is), end; return ScriptOptional(std::string(begin, end)); } @@ -305,14 +299,14 @@ namespace DB { return getScript(scriptPath); } - void Crypto::createDBSchema() { + void Crypto::createDBSchema() + { Transaction transaction(this); ScriptOptional script = getScript(SCRIPT_CREATE_SCHEMA); - if(!script) - { + + if (!script) ThrowErr(Exc::DatabaseFailed, "Can not create the database schema: no initialization script"); - } m_connection->ExecCommand((*script).c_str()); SchemaInfo SchemaInfo(this); @@ -320,20 +314,20 @@ namespace DB { transaction.commit(); } - void Crypto::resetDB() { + void Crypto::resetDB() + { Transaction transaction(this); ScriptOptional script = getScript(SCRIPT_DROP_ALL_ITEMS); - if(!script) - { + if (!script) ThrowErr(Exc::DatabaseFailed, "Can not clear the database: no clearing script"); - } m_connection->ExecCommand((*script).c_str()); createDBSchema(); transaction.commit(); } - bool Crypto::isNameLabelPresent(const Name &name, const Label &owner) const { + bool Crypto::isNameLabelPresent(const Name &name, const Label &owner) const + { Try { NameTable nameTable(this->m_connection); return nameTable.isPresent(name, owner); @@ -368,7 +362,8 @@ namespace DB { ThrowErr(Exc::DatabaseFailed, "Couldn't save Row"); } - void Crypto::saveRow(const Row &row) { + void Crypto::saveRow(const Row &row) + { Try { // transaction is present in the layer above NameTable nameTable(this->m_connection); @@ -389,7 +384,8 @@ namespace DB { ThrowErr(Exc::DatabaseFailed, "Couldn't save Row"); } - void Crypto::updateRow(const Row &row) { + void Crypto::updateRow(const Row &row) + { Try { // transaction is present in the layer above ObjectTable objectTable(this->m_connection); @@ -410,15 +406,14 @@ namespace DB { Try { // transaction is present in the layer above NameTable nameTable(this->m_connection); - if(nameTable.isPresent(name, ownerLabel)) - { + if (nameTable.isPresent(name, ownerLabel)) { nameTable.deleteRow(name, ownerLabel); return true; } return false; - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare delete statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute delete statement"); } ThrowErr(Exc::DatabaseFailed, @@ -426,7 +421,8 @@ namespace DB { } Row Crypto::getRow( - const SqlConnection::DataCommandUniquePtr &selectCommand) const { + const SqlConnection::DataCommandUniquePtr &selectCommand) const + { Row row; row.name = selectCommand->GetColumnString(0); row.ownerLabel = selectCommand->GetColumnString(1); @@ -450,11 +446,11 @@ namespace DB { Try { PermissionTable permissionTable(this->m_connection); return permissionTable.getPermissionRow(name, ownerLabel, accessorLabel); - } Catch (SqlConnection::Exception::InvalidColumn) { + } Catch(SqlConnection::Exception::InvalidColumn) { LogError("Select statement invalid column error"); - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare select statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute select statement"); } return PermissionMaskOptional(); @@ -481,11 +477,10 @@ namespace DB { selectCommand->BindInteger(2, typeRangeStop); // name table reference - selectCommand->BindString (101, name.c_str()); - selectCommand->BindString (102, ownerLabel.c_str()); + selectCommand->BindString(101, name.c_str()); + selectCommand->BindString(102, ownerLabel.c_str()); - if(selectCommand->Step()) - { + if (selectCommand->Step()) { // extract data Row current_row = getRow(selectCommand); @@ -494,11 +489,11 @@ namespace DB { } else { return RowOptional(); } - } Catch (SqlConnection::Exception::InvalidColumn) { + } Catch(SqlConnection::Exception::InvalidColumn) { LogError("Select statement invalid column error"); - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare select statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute select statement"); } ThrowErr(Exc::DatabaseFailed, @@ -531,20 +526,19 @@ namespace DB { selectCommand->BindInteger(2, typeRangeStop); // name table reference - selectCommand->BindString (101, name.c_str()); - selectCommand->BindString (102, ownerLabel.c_str()); + selectCommand->BindString(101, name.c_str()); + selectCommand->BindString(102, ownerLabel.c_str()); - while(selectCommand->Step()) - { + while (selectCommand->Step()) { // extract data output.push_back(getRow(selectCommand)); } return; - } Catch (SqlConnection::Exception::InvalidColumn) { + } Catch(SqlConnection::Exception::InvalidColumn) { LogError("Select statement invalid column error"); - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare select statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute select statement"); } ThrowErr(Exc::DatabaseFailed, @@ -568,7 +562,7 @@ namespace DB { DataType typeRangeStart, DataType typeRangeStop) { - Try{ + Try { Transaction transaction(this); SqlConnection::DataCommandUniquePtr selectCommand = m_connection->PrepareDataCommand(DB_CMD_NAME_SELECT_BY_TYPE_AND_PERMISSION); @@ -577,17 +571,17 @@ namespace DB { selectCommand->BindString(104, smackLabel.c_str()); selectCommand->BindInteger(4, static_cast<int>(Permission::READ | Permission::REMOVE)); - while(selectCommand->Step()) { + while (selectCommand->Step()) { Label ownerLabel = selectCommand->GetColumnString(0); Name name = selectCommand->GetColumnString(1); labelNameVector.push_back(std::make_pair(ownerLabel, name)); } return; - } Catch (SqlConnection::Exception::InvalidColumn) { + } Catch(SqlConnection::Exception::InvalidColumn) { LogError("Select statement invalid column error"); - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare select statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute select statement"); } ThrowErr(Exc::DatabaseFailed, @@ -597,8 +591,6 @@ namespace DB { " accessible to client label ", smackLabel); } - - void Crypto::saveKey( const Label& label, const RawBuffer &key) @@ -610,9 +602,9 @@ namespace DB { insertCommand->BindBlob(2, key); insertCommand->Step(); return; - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare insert key statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute insert statement"); } ThrowErr(Exc::DatabaseFailed, "Couldn't save key for label ", label); @@ -625,24 +617,23 @@ namespace DB { m_connection->PrepareDataCommand(DB_CMD_KEY_SELECT); selectCommand->BindString(1, label.c_str()); - if (selectCommand->Step()) { + if (selectCommand->Step()) return RawBufferOptional( selectCommand->GetColumnBlob(0)); - } else { + else return RawBufferOptional(); - } - - } Catch (SqlConnection::Exception::InvalidColumn) { + } Catch(SqlConnection::Exception::InvalidColumn) { LogError("Select statement invalid column error"); - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare insert key statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute insert statement"); } ThrowErr(Exc::DatabaseFailed, "Couldn't get key for label ", label); } - void Crypto::deleteKey(const Label& label) { + void Crypto::deleteKey(const Label& label) + { Try { Transaction transaction(this); @@ -656,9 +647,9 @@ namespace DB { transaction.commit(); return; - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare insert key statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute insert statement"); } ThrowErr(Exc::DatabaseFailed, "Couldn't delete key for label ", label); @@ -674,16 +665,16 @@ namespace DB { PermissionTable permissionTable(this->m_connection); permissionTable.setPermission(name, ownerLabel, accessorLabel, permissionMask); return; - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare set statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute set statement"); } ThrowErr(Exc::DatabaseFailed, "Couldn't set permissions for name ", name); } - - void Crypto::SchemaInfo::setVersionInfo() { + void Crypto::SchemaInfo::setVersionInfo() + { SqlConnection::DataCommandUniquePtr insertContextCommand = m_db->m_connection->PrepareDataCommand(DB_CMD_SCHEMA_SET); insertContextCommand->BindString(101, DB_SCHEMA_VERSION_FIELD); @@ -700,15 +691,15 @@ namespace DB { m_db->m_connection->PrepareDataCommand(DB_CMD_SCHEMA_GET); selectCommand->BindString(101, DB_SCHEMA_VERSION_FIELD); - if(selectCommand->Step()) { + if (selectCommand->Step()) { version = static_cast<int>(atoi(selectCommand->GetColumnString(1).c_str())); return true; } - } Catch (SqlConnection::Exception::InvalidColumn) { + } Catch(SqlConnection::Exception::InvalidColumn) { LogError("Select statement invalid column error"); - } Catch (SqlConnection::Exception::SyntaxError) { + } Catch(SqlConnection::Exception::SyntaxError) { LogError("Couldn't prepare select statement"); - } Catch (SqlConnection::Exception::InternalError) { + } Catch(SqlConnection::Exception::InternalError) { LogError("Couldn't execute select statement"); } return false; @@ -720,8 +711,7 @@ namespace DB { const Label& accessorLabel, const PermissionMask permissionMask) { - if(permissionMask == Permission::NONE) - { + if (permissionMask == Permission::NONE) { // clear permissions SqlConnection::DataCommandUniquePtr deletePermissionCommand = m_connection->PrepareDataCommand(DB_CMD_PERMISSION_DELETE); @@ -729,9 +719,7 @@ namespace DB { deletePermissionCommand->BindString(101, name.c_str()); deletePermissionCommand->BindString(102, ownerLabel.c_str()); deletePermissionCommand->Step(); - } - else - { + } else { // add new permissions SqlConnection::DataCommandUniquePtr setPermissionCommand = m_connection->PrepareDataCommand(DB_CMD_PERMISSION_SET); @@ -756,8 +744,7 @@ namespace DB { selectCommand->BindString(101, name.c_str()); selectCommand->BindString(102, ownerLabel.c_str()); - if(selectCommand->Step()) - { + if (selectCommand->Step()) { // there is entry for the <name, ownerLabel> pair return PermissionMaskOptional(PermissionMask(selectCommand->GetColumnInteger(0))); } @@ -771,8 +758,8 @@ namespace DB { // insert NAMES item SqlConnection::DataCommandUniquePtr insertNameCommand = m_connection->PrepareDataCommand(DB_CMD_NAME_INSERT); - insertNameCommand->BindString (101, name.c_str()); - insertNameCommand->BindString (102, ownerLabel.c_str()); + insertNameCommand->BindString(101, name.c_str()); + insertNameCommand->BindString(102, ownerLabel.c_str()); insertNameCommand->Step(); } @@ -807,11 +794,11 @@ namespace DB { m_connection->PrepareDataCommand(DB_CMD_NAME_COUNT_ROWS); checkCmd->BindString(101, name.c_str()); checkCmd->BindString(102, ownerLabel.c_str()); - if(checkCmd->Step()) { + if (checkCmd->Step()) { int element_count = checkCmd->GetColumnInteger(0); LogDebug("Item name: " << name << " ownerLabel: " << ownerLabel << " hit count: " << element_count); - if(element_count > 0) + if (element_count > 0) return true; } return false; @@ -825,15 +812,15 @@ namespace DB { insertObjectCommand->BindInteger(2, static_cast<int>(row.dataType)); insertObjectCommand->BindInteger(3, static_cast<int>(row.algorithmType)); insertObjectCommand->BindInteger(4, row.encryptionScheme); - insertObjectCommand->BindBlob (5, row.iv); + insertObjectCommand->BindBlob(5, row.iv); insertObjectCommand->BindInteger(6, row.dataSize); - insertObjectCommand->BindBlob (7, row.data); - insertObjectCommand->BindBlob (8, row.tag); + insertObjectCommand->BindBlob(7, row.data); + insertObjectCommand->BindBlob(8, row.tag); insertObjectCommand->BindInteger(9, static_cast<int>(row.backendId)); // name table reference - insertObjectCommand->BindString (101, row.name.c_str()); - insertObjectCommand->BindString (102, row.ownerLabel.c_str()); + insertObjectCommand->BindString(101, row.name.c_str()); + insertObjectCommand->BindString(102, row.ownerLabel.c_str()); insertObjectCommand->Step(); } @@ -845,14 +832,14 @@ namespace DB { updateObjectCommand->BindInteger(2, static_cast<int>(row.dataType)); updateObjectCommand->BindInteger(3, static_cast<int>(row.algorithmType)); updateObjectCommand->BindInteger(4, row.encryptionScheme); - updateObjectCommand->BindBlob (5, row.iv); + updateObjectCommand->BindBlob(5, row.iv); updateObjectCommand->BindInteger(6, row.dataSize); - updateObjectCommand->BindBlob (7, row.data); - updateObjectCommand->BindBlob (8, row.tag); + updateObjectCommand->BindBlob(7, row.data); + updateObjectCommand->BindBlob(8, row.tag); // name table reference - updateObjectCommand->BindString (101, row.name.c_str()); - updateObjectCommand->BindString (102, row.ownerLabel.c_str()); + updateObjectCommand->BindString(101, row.name.c_str()); + updateObjectCommand->BindString(102, row.ownerLabel.c_str()); updateObjectCommand->Step(); } diff --git a/src/manager/service/db-crypto.h b/src/manager/service/db-crypto.h index fff626e9..8b8925b7 100644 --- a/src/manager/service/db-crypto.h +++ b/src/manager/service/db-crypto.h @@ -39,259 +39,266 @@ namespace CKM { namespace DB { - class Crypto { - public: - typedef boost::optional<Row> RowOptional; - typedef boost::optional<RawBuffer> RawBufferOptional; - Crypto() : - m_connection(NULL), - m_inUserTransaction(false) - {}; - // user name instead of path? - Crypto(const std::string &path, const RawBuffer &rawPass); - Crypto(const Crypto &other) = delete; - Crypto(Crypto &&other); - - Crypto& operator=(const Crypto& ) = delete; - Crypto& operator=(Crypto&& other); - - virtual ~Crypto(); - - void saveRow( - const Row &row); - - void saveRows( - const Name &name, - const Label &owner, - const RowVector &rows); - - void updateRow( - const Row &row); - - bool isNameLabelPresent( - const Name &name, - const Label &owner) const; - - RowOptional getRow( - const Name &name, - const Label &ownerLabel, - DataType type); - - RowOptional getRow( - const Name &name, - const Label &ownerLabel, - DataType typeRangeStart, - DataType typeRangeStop); - - void getRows( - const Name &name, - const Label &ownerLabel, - DataType type, - RowVector &output); - - void getRows( - const Name &name, - const Label &ownerLabel, - DataType typeRangeStart, - DataType typeRangeStop, - RowVector &output); - - void listNames( - const Label &smackLabel, - LabelNameVector& labelNameVector, - DataType type); - - void listNames( - const Label &smackLabel, - LabelNameVector& labelNameVector, - DataType typeRangeStart, - DataType typeRangeStop); - - bool deleteRow( - const Name &name, - const Label &ownerLabel); - - // keys - void saveKey(const Label& label, const RawBuffer &key); - RawBufferOptional getKey(const Label& label); - void deleteKey(const Label& label); - - - // permissions - void setPermission( - const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, - const PermissionMask permissionMask); - - PermissionMaskOptional getPermissionRow( - const Name &name, - const Label &ownerLabel, - const Label &accessorLabel) const; - - - // transactions - int beginTransaction(); - int commitTransaction(); - int rollbackTransaction(); - - class Transaction { - public: - Transaction(Crypto *db) - : m_db(db), - m_inTransaction(false) { - if(!m_db->m_inUserTransaction) { - Try { - m_db->m_connection->ExecCommand("BEGIN EXCLUSIVE"); - m_db->m_inUserTransaction = true; - m_inTransaction = true; - } Catch (SqlConnection::Exception::InternalError) { - ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); - } Catch (SqlConnection::Exception::Base) { - ThrowErr(Exc::TransactionFailed, "Couldn't begin transaction"); - } - } +class Crypto { +public: + typedef boost::optional<Row> RowOptional; + typedef boost::optional<RawBuffer> RawBufferOptional; + Crypto() : + m_connection(NULL), + m_inUserTransaction(false) + { + } + // user name instead of path? + Crypto(const std::string &path, const RawBuffer &rawPass); + Crypto(const Crypto &other) = delete; + Crypto(Crypto &&other); + + Crypto& operator=(const Crypto& ) = delete; + Crypto& operator=(Crypto&& other); + + virtual ~Crypto(); + + void saveRow( + const Row &row); + + void saveRows( + const Name &name, + const Label &owner, + const RowVector &rows); + + void updateRow( + const Row &row); + + bool isNameLabelPresent( + const Name &name, + const Label &owner) const; + + RowOptional getRow( + const Name &name, + const Label &ownerLabel, + DataType type); + + RowOptional getRow( + const Name &name, + const Label &ownerLabel, + DataType typeRangeStart, + DataType typeRangeStop); + + void getRows( + const Name &name, + const Label &ownerLabel, + DataType type, + RowVector &output); + + void getRows( + const Name &name, + const Label &ownerLabel, + DataType typeRangeStart, + DataType typeRangeStop, + RowVector &output); + + void listNames( + const Label &smackLabel, + LabelNameVector& labelNameVector, + DataType type); + + void listNames( + const Label &smackLabel, + LabelNameVector& labelNameVector, + DataType typeRangeStart, + DataType typeRangeStop); + + bool deleteRow( + const Name &name, + const Label &ownerLabel); + + // keys + void saveKey(const Label& label, const RawBuffer &key); + RawBufferOptional getKey(const Label& label); + void deleteKey(const Label& label); + + + // permissions + void setPermission( + const Name &name, + const Label &ownerLabel, + const Label &accessorLabel, + const PermissionMask permissionMask); + + PermissionMaskOptional getPermissionRow( + const Name &name, + const Label &ownerLabel, + const Label &accessorLabel) const; + + + // transactions + int beginTransaction(); + int commitTransaction(); + int rollbackTransaction(); + + class Transaction { + public: + Transaction(Crypto *db) : + m_db(db), + m_inTransaction(false) + { + if (!m_db->m_inUserTransaction) { + Try { + m_db->m_connection->ExecCommand("BEGIN EXCLUSIVE"); + m_db->m_inUserTransaction = true; + m_inTransaction = true; + } Catch(SqlConnection::Exception::InternalError) { + ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); + } Catch(SqlConnection::Exception::Base) { + ThrowErr(Exc::TransactionFailed, "Couldn't begin transaction"); } - void commit() { - if(m_inTransaction) { - Try { - m_db->m_connection->CommitTransaction(); - m_db->m_inUserTransaction = false; - m_inTransaction = false; - } Catch (SqlConnection::Exception::InternalError) { - ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); - } Catch (SqlConnection::Exception::Base) { - ThrowErr(Exc::TransactionFailed, "Couldn't commit transaction"); - } - } + } + } + void commit() + { + if (m_inTransaction) { + Try { + m_db->m_connection->CommitTransaction(); + m_db->m_inUserTransaction = false; + m_inTransaction = false; + } Catch(SqlConnection::Exception::InternalError) { + ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); + } Catch(SqlConnection::Exception::Base) { + ThrowErr(Exc::TransactionFailed, "Couldn't commit transaction"); } - void rollback() { - if(m_inTransaction) { - Try { - m_db->m_connection->RollbackTransaction(); - m_db->m_inUserTransaction = false; - m_inTransaction = false; - } Catch (SqlConnection::Exception::InternalError) { - ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); - } Catch (SqlConnection::Exception::Base) { - ThrowErr(Exc::TransactionFailed, "Couldn't rollback transaction"); - } - } + } + } + void rollback() + { + if (m_inTransaction) { + Try { + m_db->m_connection->RollbackTransaction(); + m_db->m_inUserTransaction = false; + m_inTransaction = false; + } Catch(SqlConnection::Exception::InternalError) { + ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); + } Catch(SqlConnection::Exception::Base) { + ThrowErr(Exc::TransactionFailed, "Couldn't rollback transaction"); } - ~Transaction() { - Try { - if(m_inTransaction) { - m_db->m_inUserTransaction = false; - m_db->m_connection->RollbackTransaction(); - } - } Catch (SqlConnection::Exception::InternalError) { - ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); - } Catch (SqlConnection::Exception::Base) { - LogError("Transaction rollback failed!"); - } + } + } + ~Transaction() + { + Try { + if (m_inTransaction) { + m_db->m_inUserTransaction = false; + m_db->m_connection->RollbackTransaction(); } - private: - Crypto *m_db; - bool m_inTransaction; - }; - - protected: - SqlConnection* m_connection; - private: - bool m_inUserTransaction; - - void resetDB(); - void initDatabase(); - void createDBSchema(); - /** - * return current database version - * - * @param[out] schemaVersion if success, will contain DB schema version code - * - * @return false on DB empty or corrupted, true if information read - */ - bool getDBVersion(int & schemaVersion); - typedef boost::optional<std::string> ScriptOptional; - ScriptOptional getScript(const std::string &scriptName) const; - ScriptOptional getMigrationScript(int db_version) const; - - Row getRow( - const SqlConnection::DataCommandUniquePtr &selectCommand) const; - - void createTable( - const char *create_cmd, - const char *table_name); - - void createView( - const char* create_cmd); - - class SchemaInfo { - public: - explicit SchemaInfo(const Crypto *db) : m_db(db) {} - - void setVersionInfo(); - bool getVersionInfo(int & version) const; - - private: - const Crypto *m_db; - }; - - public: - class NameTable { - public: - explicit NameTable(SqlConnection* connection) : m_connection(connection) {} - - void addRow( - const Name &name, - const Label &ownerLabel); - - void deleteRow( - const Name &name, - const Label &ownerLabel); - - void deleteAllRows( - const Label &ownerLabel); - - bool isPresent( - const Name &name, - const Label &ownerLabel) const; - - private: - SqlConnection* m_connection; - }; - - class ObjectTable { - public: - explicit ObjectTable(SqlConnection* connection) : m_connection(connection) {} - - void addRow( - const Row &row); - void updateRow( - const Row &row); - - private: - SqlConnection* m_connection; - }; - - class PermissionTable { - public: - explicit PermissionTable(SqlConnection* connection) : m_connection(connection) {} - - void setPermission( - const Name &name, - const Label &ownerLabel, - const Label &accessorLabel, - const PermissionMask permissionMask); - - PermissionMaskOptional getPermissionRow( - const Name &name, - const Label &ownerLabel, - const Label &accessorLabel) const; - - private: - SqlConnection* m_connection; - }; + } Catch(SqlConnection::Exception::InternalError) { + ThrowErr(Exc::TransactionFailed, "sqlite got into infinite busy state"); + } Catch(SqlConnection::Exception::Base) { + LogError("Transaction rollback failed!"); + } + } + + private: + Crypto *m_db; + bool m_inTransaction; }; + +protected: + SqlConnection* m_connection; + +private: + bool m_inUserTransaction; + + void resetDB(); + void initDatabase(); + void createDBSchema(); + /** + * return current database version + * + * @param[out] schemaVersion if success, will contain DB schema version code + * + * @return false on DB empty or corrupted, true if information read + */ + bool getDBVersion(int & schemaVersion); + typedef boost::optional<std::string> ScriptOptional; + ScriptOptional getScript(const std::string &scriptName) const; + ScriptOptional getMigrationScript(int db_version) const; + + Row getRow( + const SqlConnection::DataCommandUniquePtr &selectCommand) const; + + void createTable( + const char *create_cmd, + const char *table_name); + + void createView( + const char* create_cmd); + + class SchemaInfo { + public: + explicit SchemaInfo(const Crypto *db) : m_db(db) {} + + void setVersionInfo(); + bool getVersionInfo(int & version) const; + + private: + const Crypto *m_db; + }; + +public: + class NameTable { + public: + explicit NameTable(SqlConnection* connection) : m_connection(connection) {} + + void addRow( + const Name &name, + const Label &ownerLabel); + + void deleteRow( + const Name &name, + const Label &ownerLabel); + + void deleteAllRows( + const Label &ownerLabel); + + bool isPresent( + const Name &name, + const Label &ownerLabel) const; + + private: + SqlConnection* m_connection; + }; + + class ObjectTable { + public: + explicit ObjectTable(SqlConnection* connection) : m_connection(connection) {} + + void addRow( + const Row &row); + void updateRow( + const Row &row); + + private: + SqlConnection* m_connection; + }; + + class PermissionTable { + public: + explicit PermissionTable(SqlConnection* connection) : m_connection(connection) {} + + void setPermission( + const Name &name, + const Label &ownerLabel, + const Label &accessorLabel, + const PermissionMask permissionMask); + + PermissionMaskOptional getPermissionRow( + const Name &name, + const Label &ownerLabel, + const Label &accessorLabel) const; + + private: + SqlConnection* m_connection; + }; +}; } // namespace DB } // namespace CKM diff --git a/src/manager/service/db-row.h b/src/manager/service/db-row.h index 04907af4..82f12739 100644 --- a/src/manager/service/db-row.h +++ b/src/manager/service/db-row.h @@ -43,7 +43,8 @@ struct Row : public Token { , algorithmType(DBCMAlgType::NONE) , encryptionScheme(0) , dataSize(data.size()) - {} + { + } Name name; Label ownerLabel; diff --git a/src/manager/service/encryption-logic.cpp b/src/manager/service/encryption-logic.cpp index 36c4e10d..cefb0867 100644..100755 --- a/src/manager/service/encryption-logic.cpp +++ b/src/manager/service/encryption-logic.cpp @@ -28,7 +28,7 @@ namespace CKM { void EncryptionLogic::Crypt(const CryptoRequest& request) { // check arguments - if(request.input.empty()) { + if (request.input.empty()) { LogError("No input data"); m_service.RespondToClient(request, CKM_API_ERROR_INPUT_PARAM); return; diff --git a/src/manager/service/encryption-logic.h b/src/manager/service/encryption-logic.h index 9dbd7b03..91247bae 100644 --- a/src/manager/service/encryption-logic.h +++ b/src/manager/service/encryption-logic.h @@ -30,14 +30,14 @@ namespace CKM { -class EncryptionLogic -{ +class EncryptionLogic { public: EncryptionLogic(IEncryptionService& service) : m_service(service) {} virtual ~EncryptionLogic() {} void Crypt(const CryptoRequest& request); void KeyRetrieved(MsgKeyResponse response); + private: IEncryptionService& m_service; diff --git a/src/manager/service/encryption-service.cpp b/src/manager/service/encryption-service.cpp index f5de2718..e2ea7c69 100644..100755 --- a/src/manager/service/encryption-service.cpp +++ b/src/manager/service/encryption-service.cpp @@ -33,7 +33,8 @@ const CKM::InterfaceID SOCKET_ID_ENCRYPTION = 0; namespace CKM { -EncryptionService::EncryptionService() : m_logic(*this) +EncryptionService::EncryptionService() : + m_logic(*this) { } @@ -58,7 +59,7 @@ void EncryptionService::RequestKey(const CryptoRequest& request) { MsgKeyRequest kReq(request.msgId, request.cred, request.name, request.label, request.password); if (!m_commMgr->SendMessage(kReq)) - throw std::runtime_error("No listener found"); // TODO + throw std::runtime_error("No listener found");// TODO } GenericSocketService::ServiceDescriptionVector EncryptionService::GetServiceDescription() @@ -68,11 +69,13 @@ GenericSocketService::ServiceDescriptionVector EncryptionService::GetServiceDesc }; } -void EncryptionService::Start() { +void EncryptionService::Start() +{ Create(); } -void EncryptionService::Stop() { +void EncryptionService::Stop() +{ Join(); } @@ -89,7 +92,7 @@ bool EncryptionService::ProcessOne( ConnectionInfo &info, bool /*allowed*/) { - LogDebug ("process One"); + LogDebug("process One"); try { if (!info.buffer.Ready()) return false; @@ -130,14 +133,16 @@ void EncryptionService::ProcessEncryption(const ConnectionID &conn, m_logic.Crypt(req); } -void EncryptionService::CustomHandle(const ReadEvent &event) { +void EncryptionService::CustomHandle(const ReadEvent &event) +{ LogDebug("Read event"); auto &info = m_connectionInfoMap[event.connectionID.counter]; info.buffer.Push(event.rawBuffer); - while(ProcessOne(event.connectionID, info, true)); + while (ProcessOne(event.connectionID, info, true)); } -void EncryptionService::CustomHandle(const SecurityEvent &/*event*/) { +void EncryptionService::CustomHandle(const SecurityEvent &/*event*/) +{ LogError("This should not happend! SecurityEvent was called on EncryptionService!"); } diff --git a/src/manager/service/encryption-service.h b/src/manager/service/encryption-service.h index e93c87f4..4ea81e60 100644 --- a/src/manager/service/encryption-service.h +++ b/src/manager/service/encryption-service.h @@ -29,8 +29,7 @@ namespace CKM { -class EncryptionService : public ThreadMessageService<MsgKeyResponse>, public IEncryptionService -{ +class EncryptionService : public ThreadMessageService<MsgKeyResponse>, public IEncryptionService { public: EncryptionService(); virtual ~EncryptionService(); @@ -41,11 +40,13 @@ public: // Custom add custom support for ReadEvent and SecurityEvent // because we want to bypass security check in EncryptionService - virtual void Event(const ReadEvent &event) { + virtual void Event(const ReadEvent &event) + { CreateEvent([this, event]() { this->CustomHandle(event); }); } - virtual void Event(const SecurityEvent &event) { + virtual void Event(const SecurityEvent &event) + { CreateEvent([this, event]() { this->CustomHandle(event); }); } diff --git a/src/manager/service/file-lock.cpp b/src/manager/service/file-lock.cpp index 3bc6e38c..95def7f3 100644..100755 --- a/src/manager/service/file-lock.cpp +++ b/src/manager/service/file-lock.cpp @@ -50,9 +50,8 @@ FileLock::FileLock(const char* const file) { // Open lock file m_lockFd = TEMP_FAILURE_RETRY(creat(file, 0644)); - if (m_lockFd == -1) { + if (m_lockFd == -1) throw io_exception("Cannot open lock file. Errno: ", strerror(errno)); - } if (-1 == lockf(m_lockFd, F_TLOCK, 0)) { if (errno == EACCES || errno == EAGAIN) @@ -69,7 +68,7 @@ FileLock::FileLock(const char* const file) int ret = fsync(m_lockFd); if (-1 == ret) - throw io_exception("Fsync failed. Errno: ",strerror(errno)); + throw io_exception("Fsync failed. Errno: ", strerror(errno)); } FileLock::~FileLock() diff --git a/src/manager/service/file-lock.h b/src/manager/service/file-lock.h index b56e29a8..ded400a4 100644 --- a/src/manager/service/file-lock.h +++ b/src/manager/service/file-lock.h @@ -25,8 +25,7 @@ namespace CKM { -class FileLock -{ +class FileLock { public: explicit FileLock(const char* const file); ~FileLock(); diff --git a/src/manager/service/file-system.cpp b/src/manager/service/file-system.cpp index 376d78d4..e569d1dd 100644..100755 --- a/src/manager/service/file-system.cpp +++ b/src/manager/service/file-system.cpp @@ -55,7 +55,8 @@ namespace CKM { FileSystem::FileSystem(uid_t uid) : m_uid(uid) -{} +{ +} std::string FileSystem::getDBPath() const { @@ -64,25 +65,29 @@ std::string FileSystem::getDBPath() const return ss.str(); } -std::string FileSystem::getDKEKPath() const { +std::string FileSystem::getDKEKPath() const +{ std::stringstream ss; ss << CKM_DATA_PATH << CKM_KEY_PREFIX << m_uid; return ss.str(); } -std::string FileSystem::getDBDEKPath() const { +std::string FileSystem::getDBDEKPath() const +{ std::stringstream ss; ss << CKM_DATA_PATH << CKM_DB_KEY_PREFIX << m_uid; return ss.str(); } -std::string FileSystem::getRemovedAppsPath() const { +std::string FileSystem::getRemovedAppsPath() const +{ std::stringstream ss; ss << CKM_DATA_PATH << CKM_REMOVED_APP_PREFIX << m_uid; return ss.str(); } -RawBuffer FileSystem::loadFile(const std::string &path) const { +RawBuffer FileSystem::loadFile(const std::string &path) const +{ std::ifstream is(path); if (is.fail() && ENOENT == errno) @@ -94,8 +99,8 @@ RawBuffer FileSystem::loadFile(const std::string &path) const { "Error opening file: ", path, " Reason: ", description); } - std::istreambuf_iterator<char> begin(is),end; - std::vector<char> buff(begin,end); // This trick does not work with boost vector + std::istreambuf_iterator<char> begin(is), end; + std::vector<char> buff(begin, end); // This trick does not work with boost vector RawBuffer buffer(buff.size()); memcpy(buffer.data(), buff.data(), buff.size()); @@ -112,7 +117,8 @@ RawBuffer FileSystem::getDBDEK() const return loadFile(getDBDEKPath()); } -void FileSystem::saveFile(const std::string &path, const RawBuffer &buffer) const { +void FileSystem::saveFile(const std::string &path, const RawBuffer &buffer) const +{ std::ofstream os(path, std::ios::out | std::ofstream::binary | std::ofstream::trunc); std::copy(buffer.begin(), buffer.end(), std::ostreambuf_iterator<char>(os)); @@ -125,11 +131,13 @@ void FileSystem::saveFile(const std::string &path, const RawBuffer &buffer) cons ThrowErr(Exc::FileSystemFailed, "Failed to save file: ", path); } -void FileSystem::saveDKEK(const RawBuffer &buffer) const { +void FileSystem::saveDKEK(const RawBuffer &buffer) const +{ saveFile(getDKEKPath(), buffer); } -void FileSystem::saveDBDEK(const RawBuffer &buffer) const { +void FileSystem::saveDBDEK(const RawBuffer &buffer) const +{ saveFile(getDBDEKPath(), buffer); } @@ -153,9 +161,9 @@ AppLabelVector FileSystem::clearRemovedsApps() const std::string line; std::ifstream removedAppsFile(getRemovedAppsPath()); if (removedAppsFile.is_open()) { - while (! removedAppsFile.eof() ) { - getline (removedAppsFile,line); - if(line.size() > 0) + while (!removedAppsFile.eof()) { + getline(removedAppsFile, line); + if (line.size() > 0) removedApps.push_back(line); } removedAppsFile.close(); @@ -167,7 +175,8 @@ AppLabelVector FileSystem::clearRemovedsApps() const return removedApps; } -int FileSystem::init() { +int FileSystem::init() +{ errno = 0; if ((mkdir(CKM_DATA_PATH.c_str(), 0700)) && (errno != EEXIST)) { int err = errno; @@ -177,7 +186,8 @@ int FileSystem::init() { return 0; } -UidVector FileSystem::getUIDsFromDBFile() { +UidVector FileSystem::getUIDsFromDBFile() +{ UidVector uids; std::unique_ptr<DIR, std::function<int(DIR*)>> dirp(::opendir(CKM_DATA_PATH.c_str()), ::closedir); @@ -201,9 +211,8 @@ UidVector FileSystem::getUIDsFromDBFile() { while ( (!readdir_r(dirp.get(), pEntry.get(), &pDirEntry)) && pDirEntry ) { // Ignore files with diffrent prefix - if (strncmp(pDirEntry->d_name, CKM_KEY_PREFIX.c_str(), CKM_KEY_PREFIX.size())) { + if (strncmp(pDirEntry->d_name, CKM_KEY_PREFIX.c_str(), CKM_KEY_PREFIX.size())) continue; - } // We find database. Let's extract user id. try { @@ -220,7 +229,8 @@ UidVector FileSystem::getUIDsFromDBFile() { return uids; } -int FileSystem::removeUserData() const { +int FileSystem::removeUserData() const +{ int err, retCode = 0; if (unlink(getDBPath().c_str())) { diff --git a/src/manager/service/file-system.h b/src/manager/service/file-system.h index 6b396c3c..145d77ef 100644 --- a/src/manager/service/file-system.h +++ b/src/manager/service/file-system.h @@ -54,7 +54,8 @@ public: static UidVector getUIDsFromDBFile(); static FileLock lock(); - virtual ~FileSystem(){} + virtual ~FileSystem() {} + protected: std::string getDKEKPath() const; std::string getDBDEKPath() const; diff --git a/src/manager/service/key-provider.cpp b/src/manager/service/key-provider.cpp index 23ca201e..eddc4728 100644..100755 --- a/src/manager/service/key-provider.cpp +++ b/src/manager/service/key-provider.cpp @@ -43,7 +43,8 @@ WrappedKeyAndInfo& WrappedKeyAndInfoContainer::getWrappedKeyAndInfo() return *wrappedKeyAndInfo; } -void WrappedKeyAndInfoContainer::setKeyInfoKeyLength(const unsigned int length){ +void WrappedKeyAndInfoContainer::setKeyInfoKeyLength(const unsigned int length) +{ wrappedKeyAndInfo->keyInfo.keyLength = length; } @@ -104,29 +105,28 @@ KeyAndInfoContainer::~KeyAndInfoContainer() memset(ptr, 0, sizeof(KeyAndInfo)); // verification for (size_t size = 0; size < sizeof(KeyAndInfo); ++size) { - if (ptr[size]) { + if (ptr[size]) LogError("Write momory error! Memory used by key was not owerwritten."); - } } delete keyAndInfo; } -KeyProvider::KeyProvider() - : m_kmcDKEK(NULL) - , m_isInitialized(false) +KeyProvider::KeyProvider() : + m_kmcDKEK(NULL), + m_isInitialized(false) { LogDebug("Created empty KeyProvider"); } KeyProvider::KeyProvider( const RawBuffer &domainKEKInWrapForm, - const Password &password) - : m_kmcDKEK(new KeyAndInfoContainer()) - , m_isInitialized(true) + const Password &password) : + m_kmcDKEK(new KeyAndInfoContainer()), + m_isInitialized(true) { - if (!m_isInitialized) { + if (!m_isInitialized) ThrowErr(Exc::InternalError, "Object not initialized!. Should not happened"); - } + if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) { LogError("input size:" << domainKEKInWrapForm.size() << " Expected: " << sizeof(WrappedKeyAndInfo)); @@ -150,7 +150,6 @@ KeyProvider::KeyProvider( PBKDF2_ITERATIONS, MAX_KEY_SIZE, PKEK1)) { - delete[] concat_user_pass; ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); } @@ -166,7 +165,6 @@ KeyProvider::KeyProvider( PKEK1, wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv, m_kmcDKEK->getKeyAndInfo().key))) { - ThrowErr(Exc::AuthenticationFailed, "VerifyDomainKEK failed in KeyProvider Constructor"); } @@ -202,9 +200,8 @@ bool KeyProvider::isInitialized() RawBuffer KeyProvider::getPureDomainKEK() { - if (!m_isInitialized) { + if (!m_isInitialized) ThrowErr(Exc::InternalError, "Object not initialized!"); - } // TODO secure return RawBuffer(m_kmcDKEK->getKeyAndInfo().key, (m_kmcDKEK->getKeyAndInfo().key) + m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength); @@ -212,9 +209,8 @@ RawBuffer KeyProvider::getPureDomainKEK() RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password) { - if (!m_isInitialized) { + if (!m_isInitialized) ThrowErr(Exc::InternalError, "Object not initialized!"); - } WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer(); @@ -233,7 +229,6 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password) PBKDF2_ITERATIONS, MAX_KEY_SIZE, PKEK1)) { - delete[] concat_user_pass; ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); } @@ -245,15 +240,13 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password) int wrappedKeyLength; if (0 > (wrappedKeyLength = encryptAes256Gcm( - m_kmcDKEK->getKeyAndInfo().key, - m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength, - PKEK1, - m_kmcDKEK->getKeyAndInfo().keyInfo.iv, - wkmcDKEK.getWrappedKeyAndInfo().wrappedKey, - wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag))) { - + m_kmcDKEK->getKeyAndInfo().key, + m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength, + PKEK1, + m_kmcDKEK->getKeyAndInfo().keyInfo.iv, + wkmcDKEK.getWrappedKeyAndInfo().wrappedKey, + wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag))) ThrowErr(Exc::InternalError, "WrapDKEK Failed in KeyProvider::getDomainKEK"); - } wkmcDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength); @@ -264,11 +257,10 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password) RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm) { - if (!m_isInitialized) { + if (!m_isInitialized) ThrowErr(Exc::InternalError, "Object not initialized!"); - } - if (DEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)){ + if (DEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) { LogError("input size:" << DEKInWrapForm.size() << " Expected: " << sizeof(WrappedKeyAndInfo)); ThrowErr(Exc::InternalError, @@ -283,28 +275,24 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm) int keyLength; if (!PKCS5_PBKDF2_HMAC_SHA1( - wkmcDEK.getWrappedKeyAndInfo().keyInfo.label, - strlen(wkmcDEK.getWrappedKeyAndInfo().keyInfo.label), - m_kmcDKEK->getKeyAndInfo().key, - MAX_SALT_SIZE, - PBKDF2_ITERATIONS, - MAX_KEY_SIZE, - PKEK2)) { - + wkmcDEK.getWrappedKeyAndInfo().keyInfo.label, + strlen(wkmcDEK.getWrappedKeyAndInfo().keyInfo.label), + m_kmcDKEK->getKeyAndInfo().key, + MAX_SALT_SIZE, + PBKDF2_ITERATIONS, + MAX_KEY_SIZE, + PKEK2)) ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); - } if (0 > (keyLength = decryptAes256Gcm( - wkmcDEK.getWrappedKeyAndInfo().wrappedKey, - wkmcDEK.getWrappedKeyAndInfo().keyInfo.keyLength, - wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag, - PKEK2, - wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, - kmcDEK.getKeyAndInfo().key))) { - + wkmcDEK.getWrappedKeyAndInfo().wrappedKey, + wkmcDEK.getWrappedKeyAndInfo().keyInfo.keyLength, + wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag, + PKEK2, + wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, + kmcDEK.getKeyAndInfo().key))) ThrowErr(Exc::InternalError, "UnwrapDEK Failed in KeyProvider::getPureDEK"); - } kmcDEK.setKeyInfoKeyLength((unsigned int)keyLength); @@ -316,9 +304,8 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm) RawBuffer KeyProvider::generateDEK(const std::string &smackLabel) { - if (!m_isInitialized) { + if (!m_isInitialized) ThrowErr(Exc::InternalError, "Object not initialized!"); - } WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer(); std::string resized_smackLabel; @@ -331,35 +318,29 @@ RawBuffer KeyProvider::generateDEK(const std::string &smackLabel) uint8_t key[MAX_KEY_SIZE], PKEK2[MAX_KEY_SIZE]; if (!RAND_bytes(key, m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength) || - !RAND_bytes(wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE)) { - + !RAND_bytes(wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE)) ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); - } if (!PKCS5_PBKDF2_HMAC_SHA1( - resized_smackLabel.c_str(), - strlen(resized_smackLabel.c_str()), - m_kmcDKEK->getKeyAndInfo().key, - MAX_SALT_SIZE, - PBKDF2_ITERATIONS, - MAX_KEY_SIZE, - PKEK2)) { - + resized_smackLabel.c_str(), + strlen(resized_smackLabel.c_str()), + m_kmcDKEK->getKeyAndInfo().key, + MAX_SALT_SIZE, + PBKDF2_ITERATIONS, + MAX_KEY_SIZE, + PKEK2)) ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); - } int wrappedKeyLength; if (0 > (wrappedKeyLength = encryptAes256Gcm( - key, - m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength, - PKEK2, - wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, - wkmcDEK.getWrappedKeyAndInfo().wrappedKey, - wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag))) { - + key, + m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength, + PKEK2, + wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv, + wkmcDEK.getWrappedKeyAndInfo().wrappedKey, + wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag))) ThrowErr(Exc::InternalError, "GenerateDEK Failed in KeyProvider::generateDEK"); - } wkmcDEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength); wkmcDEK.setKeyInfoSalt(m_kmcDKEK->getKeyAndInfo().key, MAX_SALT_SIZE); @@ -403,22 +384,19 @@ RawBuffer KeyProvider::reencrypt( PBKDF2_ITERATIONS, MAX_KEY_SIZE, PKEK1)) { - delete[] concat_user_pass; ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); } delete[] concat_user_pass; if (0 > (keyLength = decryptAes256Gcm( - wkmcOldDKEK.getWrappedKeyAndInfo().wrappedKey, - wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.keyLength, - wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.tag, - PKEK1, - wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.iv, - kmcDKEK.getKeyAndInfo().key))) { - + wkmcOldDKEK.getWrappedKeyAndInfo().wrappedKey, + wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.keyLength, + wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.tag, + PKEK1, + wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.iv, + kmcDKEK.getKeyAndInfo().key))) ThrowErr(Exc::AuthenticationFailed, "Incorrect Old Password "); - } kmcDKEK.setKeyInfo(&(wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo)); kmcDKEK.setKeyInfoKeyLength((unsigned int)keyLength); @@ -428,14 +406,13 @@ RawBuffer KeyProvider::reencrypt( newPass.c_str()); if (!PKCS5_PBKDF2_HMAC_SHA1( - concat_user_pass, - strlen(concat_user_pass), - kmcDKEK.getKeyAndInfo().keyInfo.salt, - MAX_SALT_SIZE, - PBKDF2_ITERATIONS, - MAX_KEY_SIZE, - PKEK1)) { - + concat_user_pass, + strlen(concat_user_pass), + kmcDKEK.getKeyAndInfo().keyInfo.salt, + MAX_SALT_SIZE, + PBKDF2_ITERATIONS, + MAX_KEY_SIZE, + PKEK1)) { delete[] concat_user_pass; ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); } @@ -446,15 +423,13 @@ RawBuffer KeyProvider::reencrypt( wkmcNewDKEK.setKeyInfo(&(kmcDKEK.getKeyAndInfo().keyInfo)); if (0 > (wrappedKeyLength = encryptAes256Gcm( - kmcDKEK.getKeyAndInfo().key, - kmcDKEK.getKeyAndInfo().keyInfo.keyLength, - PKEK1, - kmcDKEK.getKeyAndInfo().keyInfo.iv, - wkmcNewDKEK.getWrappedKeyAndInfo().wrappedKey, - wkmcNewDKEK.getWrappedKeyAndInfo().keyInfo.tag))) { - + kmcDKEK.getKeyAndInfo().key, + kmcDKEK.getKeyAndInfo().keyInfo.keyLength, + PKEK1, + kmcDKEK.getKeyAndInfo().keyInfo.iv, + wkmcNewDKEK.getWrappedKeyAndInfo().wrappedKey, + wkmcNewDKEK.getWrappedKeyAndInfo().keyInfo.tag))) ThrowErr(Exc::InternalError, "UpdateDomainKEK in KeyProvider::reencrypt Failed"); - } wkmcNewDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength); @@ -471,22 +446,21 @@ RawBuffer KeyProvider::generateDomainKEK( uint8_t key[MAX_KEY_SIZE], PKEK1[MAX_KEY_SIZE]; if (!RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt, MAX_SALT_SIZE) || - !RAND_bytes(key, MAX_KEY_SIZE) || - !RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE)) + !RAND_bytes(key, MAX_KEY_SIZE) || + !RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv, MAX_IV_SIZE)) ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR"); int wrappedKeyLength; char *concat_user_pass = NULL; concat_user_pass = concat_password_user(user.c_str(), userPassword.c_str()); if (!PKCS5_PBKDF2_HMAC_SHA1( - concat_user_pass, - strlen(concat_user_pass), - wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt, - MAX_SALT_SIZE, - PBKDF2_ITERATIONS, - MAX_KEY_SIZE, - PKEK1)) { - + concat_user_pass, + strlen(concat_user_pass), + wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt, + MAX_SALT_SIZE, + PBKDF2_ITERATIONS, + MAX_KEY_SIZE, + PKEK1)) { delete[] concat_user_pass; ThrowErr(Exc::InternalError, "OPENSSL_ENGINED_ERROR"); } @@ -494,16 +468,14 @@ RawBuffer KeyProvider::generateDomainKEK( delete[] concat_user_pass; if (0 > (wrappedKeyLength = encryptAes256Gcm( - key, - MAX_KEY_SIZE, - PKEK1, - wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv, - wkmcDKEK.getWrappedKeyAndInfo().wrappedKey, - wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag))) { - + key, + MAX_KEY_SIZE, + PKEK1, + wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv, + wkmcDKEK.getWrappedKeyAndInfo().wrappedKey, + wkmcDKEK.getWrappedKeyAndInfo().keyInfo.tag))) ThrowErr(Exc::InternalError, "GenerateDomainKEK Failed in KeyProvider::generateDomainKEK"); - } wkmcDKEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength); wkmcDKEK.setKeyInfoLabel(user); @@ -531,40 +503,34 @@ KeyProvider::~KeyProvider() int KeyProvider::encryptAes256Gcm(const unsigned char *plaintext, int plaintext_len, const unsigned char *key, const unsigned char *iv, unsigned char *ciphertext, unsigned char *tag) { - EVP_CIPHER_CTX *ctx; int len; int ciphertext_len = 0; - if (!(ctx = EVP_CIPHER_CTX_new())) { + if (!(ctx = EVP_CIPHER_CTX_new())) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL)) { + if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL)) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) { + if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL)) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) { + if (!EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) return OPENSSL_ENGINE_ERROR; - } + ciphertext_len = len; - if (!EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) { + if (!EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) return OPENSSL_ENGINE_ERROR; - } + ciphertext_len += len; - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, MAX_IV_SIZE, tag)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, MAX_IV_SIZE, tag)) return OPENSSL_ENGINE_ERROR; - } EVP_CIPHER_CTX_free(ctx); @@ -573,47 +539,40 @@ int KeyProvider::encryptAes256Gcm(const unsigned char *plaintext, int plaintext_ int KeyProvider::decryptAes256Gcm(const unsigned char *ciphertext, int ciphertext_len, unsigned char *tag, const unsigned char *key, const unsigned char *iv, unsigned char *plaintext) { - EVP_CIPHER_CTX *ctx; int len; int plaintext_len; int ret; - if (!(ctx = EVP_CIPHER_CTX_new())) { + if (!(ctx = EVP_CIPHER_CTX_new())) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL)) { + if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL)) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) { + + if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL)) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, MAX_IV_SIZE, tag)) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, MAX_IV_SIZE, tag)) return OPENSSL_ENGINE_ERROR; - } - if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) { + if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) return OPENSSL_ENGINE_ERROR; - } + plaintext_len = len; - if (!(ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len))) { + if (!(ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len))) return OPENSSL_ENGINE_ERROR; - } EVP_CIPHER_CTX_free(ctx); if (ret > 0) { plaintext_len += len; return plaintext_len; - } - else { + } else { return -1; } } @@ -628,12 +587,12 @@ char * KeyProvider::concat_password_user(const char *user, const char *password) resized_user = new char[MAX_LABEL_SIZE]; memcpy(resized_user, user, MAX_LABEL_SIZE-1); resized_user[MAX_LABEL_SIZE-1] = '\0'; - } - else { + } else { resized_user = new char[strlen(user)+1]; memcpy(resized_user, user, strlen(user)); resized_user[strlen(user)] = '\0'; } + concat_user_pass_len = strlen(resized_user) + strlen(password) + 1; concat_user_pass = new char[concat_user_pass_len]; diff --git a/src/manager/service/key-provider.h b/src/manager/service/key-provider.h index 918a6224..feaf8c4c 100644 --- a/src/manager/service/key-provider.h +++ b/src/manager/service/key-provider.h @@ -65,7 +65,7 @@ typedef struct WrappedKeyAndInfo_ { uint8_t wrappedKey[MAX_WRAPPED_KEY_SIZE]; } WrappedKeyAndInfo; -class WrappedKeyAndInfoContainer{ +class WrappedKeyAndInfoContainer { public: WrappedKeyAndInfoContainer(); WrappedKeyAndInfoContainer(const unsigned char*); @@ -75,11 +75,12 @@ public: void setKeyInfoSalt(const unsigned char*, const int); void setKeyInfo(const KeyComponentsInfo*); ~WrappedKeyAndInfoContainer(); + private: WrappedKeyAndInfo *wrappedKeyAndInfo; }; -class KeyAndInfoContainer{ +class KeyAndInfoContainer { public: KeyAndInfoContainer(); KeyAndInfoContainer(const unsigned char*); @@ -87,6 +88,7 @@ public: void setKeyInfoKeyLength(const unsigned int); void setKeyInfo(const KeyComponentsInfo*); ~KeyAndInfoContainer(); + private: KeyAndInfo *keyAndInfo; }; @@ -144,6 +146,7 @@ public: static int closeLibrary(); virtual ~KeyProvider(); + private: // KeyAndInfoContainer class std::shared_ptr<KeyAndInfoContainer> m_kmcDKEK; @@ -168,7 +171,6 @@ private: static char * concat_password_user( const char *user, const char *password); - }; } // namespace CKM diff --git a/src/manager/service/ocsp-logic.cpp b/src/manager/service/ocsp-logic.cpp index 5e28d19a..5cc512a7 100644..100755 --- a/src/manager/service/ocsp-logic.cpp +++ b/src/manager/service/ocsp-logic.cpp @@ -76,7 +76,8 @@ void OCSPLogic::setNetAvailable() m_isNetAvailable = false; } -RawBuffer OCSPLogic::ocspCheck(int commandId, const RawBufferVector &rawChain, bool allowed) { +RawBuffer OCSPLogic::ocspCheck(int commandId, const RawBufferVector &rawChain, bool allowed) +{ CertificateImplVector certChain; OCSPModule ocsp; int retCode = CKM_API_SUCCESS; @@ -91,7 +92,7 @@ RawBuffer OCSPLogic::ocspCheck(int commandId, const RawBufferVector &rawChain, b retCode = CKM_API_ERROR_NOT_SUPPORTED; } else if (!allowed) { retCode = CKM_API_ERROR_ACCESS_DENIED; - } else if(rawChain.size() < 2) { + } else if (rawChain.size() < 2) { LogError("Certificate chain should contain at least 2 certificates"); retCode = CKM_API_ERROR_INPUT_PARAM; } else { diff --git a/src/manager/service/ocsp-logic.h b/src/manager/service/ocsp-logic.h index 6a065c1e..b700d86f 100644 --- a/src/manager/service/ocsp-logic.h +++ b/src/manager/service/ocsp-logic.h @@ -34,13 +34,11 @@ public: OCSPLogic& operator=(OCSPLogic &&) = delete; RawBuffer ocspCheck(int commandId, const RawBufferVector &rawChain, bool allowed); - virtual ~OCSPLogic(){} + virtual ~OCSPLogic() {} + private: void setNetAvailable(); bool m_isNetAvailable; }; - - - } // namespace CKM diff --git a/src/manager/service/ocsp-service.cpp b/src/manager/service/ocsp-service.cpp index e65114d1..b6449d01 100644..100755 --- a/src/manager/service/ocsp-service.cpp +++ b/src/manager/service/ocsp-service.cpp @@ -36,17 +36,21 @@ namespace CKM { OCSPService::OCSPService() : m_logic(new OCSPLogic()) -{} +{ +} -OCSPService::~OCSPService() { +OCSPService::~OCSPService() +{ delete m_logic; } -void OCSPService::Start() { +void OCSPService::Start() +{ Create(); } -void OCSPService::Stop() { +void OCSPService::Stop() +{ Join(); } @@ -62,7 +66,7 @@ bool OCSPService::ProcessOne( ConnectionInfo &info, bool allowed) { - LogDebug ("process One"); + LogDebug("process One"); Try { if (!info.buffer.Ready()) @@ -78,7 +82,7 @@ bool OCSPService::ProcessOne( m_serviceManager->Write(conn, response); return true; - } Catch (MessageBuffer::Exception::Base) { + } Catch(MessageBuffer::Exception::Base) { LogError("Broken protocol. Closing socket."); } catch (const std::string &e) { LogError("String exception(" << e << "). Closing socket"); diff --git a/src/manager/service/ocsp-service.h b/src/manager/service/ocsp-service.h index a8453bab..725d0e49 100644 --- a/src/manager/service/ocsp-service.h +++ b/src/manager/service/ocsp-service.h @@ -28,8 +28,7 @@ namespace CKM { class OCSPLogic; -class OCSPService : public CKM::ThreadService -{ +class OCSPService : public CKM::ThreadService { public: OCSPService(); OCSPService(const OCSPService &) = delete; diff --git a/src/manager/service/ocsp.cpp b/src/manager/service/ocsp.cpp index 4172d0fa..aa5fa968 100644..100755 --- a/src/manager/service/ocsp.cpp +++ b/src/manager/service/ocsp.cpp @@ -41,7 +41,8 @@ namespace CKM { namespace { typedef std::unique_ptr<BIO, std::function<void(BIO*)>> BioUniquePtr; -void BIO_write_and_free(BIO* bio) { +void BIO_write_and_free(BIO* bio) +{ if (!bio) return; @@ -57,23 +58,25 @@ void BIO_write_and_free(BIO* bio) { } // namespace anonymous -OCSPModule::OCSPModule() { +OCSPModule::OCSPModule() +{ // Do nothing. } -OCSPModule::~OCSPModule(){ +OCSPModule::~OCSPModule() +{ // Do nothing. } -int OCSPModule::verify(const CertificateImplVector &certificateChain) { +int OCSPModule::verify(const CertificateImplVector &certificateChain) +{ bool unsupported = false; // ocsp is unsupported in certificate in chain (except root CA) // create trusted store X509_STACK_PTR trustedCerts = create_x509_stack(); // skip first 2 certificates - for (auto it=certificateChain.cbegin()+2; it < certificateChain.cend(); it++) - { + for (auto it = certificateChain.cbegin() + 2; it < certificateChain.cend(); it++) { if (it->empty()) { LogError("Error. Broken certificate chain."); return CKM_API_OCSP_STATUS_INTERNAL_ERROR; @@ -81,7 +84,7 @@ int OCSPModule::verify(const CertificateImplVector &certificateChain) { sk_X509_push(trustedCerts.get(), it->getX509()); } - for (int i=0; i < static_cast<int>(certificateChain.size())-1; i++) {// except root certificate + for (int i = 0; i < static_cast<int>(certificateChain.size()) - 1; i++) {// except root certificate if (certificateChain[i].empty() || certificateChain[i+1].empty()) { LogError("Error. Broken certificate chain."); return CKM_API_OCSP_STATUS_INTERNAL_ERROR; @@ -102,7 +105,7 @@ int OCSPModule::verify(const CertificateImplVector &certificateChain) { // remove first element from trustedCerts store sk_X509_delete(trustedCerts.get(), 0); - if(result != CKM_API_OCSP_STATUS_GOOD) { + if (result != CKM_API_OCSP_STATUS_GOOD) { LogError("Fail to OCSP certification check. Errorcode=[" << result << "], on certChain[" << i << "]"); return result; @@ -115,7 +118,8 @@ int OCSPModule::verify(const CertificateImplVector &certificateChain) { return CKM_API_OCSP_STATUS_GOOD; } -int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCerts, const std::string &constUrl) { +int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCerts, const std::string &constUrl) +{ OCSP_REQUEST *req = NULL; OCSP_RESPONSE *resp = NULL; OCSP_BASICRESP *bs = NULL; @@ -133,16 +137,15 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer char subj_buf[256]; int reason = 0; // const char *reason_str = NULL;0 - X509_STORE *trustedStore=NULL; + X509_STORE *trustedStore = NULL; BioUniquePtr bioLogger(BIO_new(BIO_s_mem()), BIO_write_and_free); std::vector<char> url(constUrl.begin(), constUrl.end()); url.push_back(0); - if (!OCSP_parse_url(url.data(), &host, &port, &path, &use_ssl)) { + if (!OCSP_parse_url(url.data(), &host, &port, &path, &use_ssl)) /* report error */ return CKM_API_OCSP_STATUS_INVALID_URL; - } LogDebug("Host: " << host); LogDebug("Port: " << port); @@ -156,9 +159,8 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer return CKM_API_OCSP_STATUS_INTERNAL_ERROR; } - if (port != NULL) { - BIO_set_conn_port(cbio, port); - } + if (port != NULL) + BIO_set_conn_port(cbio, port); if (use_ssl == 1) { BIO *sbio = NULL; @@ -188,73 +190,68 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer /* report error */ /* free stuff */ - if (host != NULL) { + if (host != NULL) OPENSSL_free(host); - } - if (port != NULL) { + if (port != NULL) OPENSSL_free(port); - } - if (path != NULL) { + if (path != NULL) OPENSSL_free(path); - } + host = port = path = NULL; - if (use_ssl && use_ssl_ctx) { + if (use_ssl && use_ssl_ctx) SSL_CTX_free(use_ssl_ctx); - } + use_ssl_ctx = NULL; - if (cbio != NULL) { + if (cbio != NULL) BIO_free_all(cbio); - } + cbio = NULL; return CKM_API_OCSP_STATUS_NET_ERROR; } req = OCSP_REQUEST_new(); - - if(req == NULL) { + if (req == NULL) { LogDebug("Error in OCPS_REQUEST_new"); return CKM_API_OCSP_STATUS_INTERNAL_ERROR; } + certid = OCSP_cert_to_id(NULL, cert, issuer); - if(certid == NULL) { + if (certid == NULL) { LogDebug("Error in OCSP_cert_to_id"); return CKM_API_OCSP_STATUS_INTERNAL_ERROR; } - if(OCSP_request_add0_id(req, certid) == NULL) { + if (OCSP_request_add0_id(req, certid) == NULL) { LogDebug("Error in OCSP_request_add0_id"); return CKM_API_OCSP_STATUS_INTERNAL_ERROR; } resp = OCSP_sendreq_bio(cbio, path, req); - /* free some stuff we no longer need */ - if (host != NULL) { + if (host != NULL) OPENSSL_free(host); - } - if (port != NULL) { + if (port != NULL) OPENSSL_free(port); - } - if (path != NULL) { + if (path != NULL) OPENSSL_free(path); - } + host = port = path = NULL; - if (use_ssl && use_ssl_ctx) { + if (use_ssl && use_ssl_ctx) SSL_CTX_free(use_ssl_ctx); - } + use_ssl_ctx = NULL; - if (cbio != NULL) { + if (cbio != NULL) BIO_free_all(cbio); - } + cbio = NULL; if (!resp) { @@ -288,11 +285,12 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer return CKM_API_OCSP_STATUS_INVALID_RESPONSE; } - if(trustedCerts != NULL) { + if (trustedCerts != NULL) { trustedStore = X509_STORE_new(); - for(int tmpIdx=0; tmpIdx<sk_X509_num(trustedCerts); tmpIdx++) { + + for (int tmpIdx = 0; tmpIdx < sk_X509_num(trustedCerts); tmpIdx++) X509_STORE_add_cert(trustedStore, sk_X509_value(trustedCerts, tmpIdx)); - } + X509_STORE_add_cert(trustedStore, issuer); } @@ -323,7 +321,7 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer } (void)X509_NAME_oneline(X509_get_subject_name(cert), subj_buf, 255); - if(!OCSP_resp_find_status(bs, certid, &ocspStatus, &reason, + if (!OCSP_resp_find_status(bs, certid, &ocspStatus, &reason, &rev, &thisupd, &nextupd)) { /* report error */ ERR_print_errors(bioLogger.get()); @@ -369,12 +367,12 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer bs = NULL; } - if(trustedStore != NULL) { + if (trustedStore != NULL) { X509_STORE_free(trustedStore); trustedStore = NULL; } - switch(ocspStatus) { + switch (ocspStatus) { case V_OCSP_CERTSTATUS_GOOD: return CKM_API_OCSP_STATUS_GOOD; case V_OCSP_CERTSTATUS_REVOKED: diff --git a/src/manager/service/ocsp.h b/src/manager/service/ocsp.h index c6db7660..a1d7afea 100644 --- a/src/manager/service/ocsp.h +++ b/src/manager/service/ocsp.h @@ -36,6 +36,7 @@ public: // all error code from project will be defined in public client api // OK, UNKNOWN, REVOKED, NO_NETWORK, TIMEOUT int verify(const CertificateImplVector &certificateChain); + private: int ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCerts, const std::string &url); }; diff --git a/src/manager/service/permission.h b/src/manager/service/permission.h index ef8d689e..c2846999 100644 --- a/src/manager/service/permission.h +++ b/src/manager/service/permission.h @@ -33,13 +33,14 @@ struct PermissionForLabel { PermissionForLabel(const Label & accessor, const PermissionMaskOptional mask) { accessorLabel = accessor; - if(mask) + if (mask) permissionMask = *mask; else permissionMask = Permission::NONE; } - int operator&(const Permission &bit) const { + int operator&(const Permission &bit) const + { return permissionMask & bit; } }; diff --git a/src/manager/service/token.h b/src/manager/service/token.h index f6940377..0173708a 100644 --- a/src/manager/service/token.h +++ b/src/manager/service/token.h @@ -29,19 +29,22 @@ namespace CKM { struct Token { - Token() - : backendId(CryptoBackend::None) - {} - Token(CryptoBackend pBackendId, DataType pDataType, const RawBuffer &pData) - : backendId(pBackendId) - , dataType(pDataType) - , data(pData) - {} + Token() : + backendId(CryptoBackend::None) + { + } + + Token(CryptoBackend pBackendId, DataType pDataType, const RawBuffer &pData) : + backendId(pBackendId), + dataType(pDataType), + data(pData) + { + } CryptoBackend backendId; DataType dataType; RawBuffer data; }; -typedef std::pair<Token,Token> TokenPair; +typedef std::pair<Token, Token> TokenPair; } // namespace CKM diff --git a/src/pam_plugin/pam-key-manager-plugin.cpp b/src/pam_plugin/pam-key-manager-plugin.cpp index 0cf09430..792e6aec 100644..100755 --- a/src/pam_plugin/pam-key-manager-plugin.cpp +++ b/src/pam_plugin/pam-key-manager-plugin.cpp @@ -36,8 +36,7 @@ #include <shadow.h> #include <ckm/ckm-control.h> -namespace -{ +namespace { #define PASSWORD_SHADOWED "x" std::string old_password; @@ -50,15 +49,14 @@ bool identify_user_pwd(pam_handle_t *pamh, uid_t & uid, std::string & passwd) struct passwd *pwd; if ((pwd = getpwnam(user)) == NULL) return true; - if(strcmp(pwd->pw_passwd, PASSWORD_SHADOWED)==0) - { + if (strcmp(pwd->pw_passwd, PASSWORD_SHADOWED) == 0) { struct spwd *pwd_sh; if ((pwd_sh = getspnam(user)) == NULL) return true; passwd = std::string(pwd_sh->sp_pwdp); - } - else + } else { passwd = std::string(pwd->pw_passwd); + } uid = pwd->pw_uid; return false; } @@ -70,25 +68,24 @@ pam_sm_open_session(pam_handle_t *pamh, int /*flags*/, int /*argc*/, const char // identify user uid_t uid = -1; std::string passwd; - if(identify_user_pwd(pamh, uid, passwd)) + if (identify_user_pwd(pamh, uid, passwd)) return PAM_SESSION_ERR; auto control = CKM::Control::create(); int ec = control->unlockUserKey(uid, passwd.c_str()); - if(ec == CKM_API_SUCCESS) + if (ec == CKM_API_SUCCESS) return PAM_SUCCESS; - if(ec == CKM_API_ERROR_AUTHENTICATION_FAILED) - { + if (ec == CKM_API_ERROR_AUTHENTICATION_FAILED) { pam_syslog(pamh, LOG_ERR, "key-manager and system password desynchronized," "removing key-manager database for user: %d\n", uid); // key-manager<->system password desync // remove the user content ec = control->removeUserData(uid); - if(ec == CKM_API_SUCCESS) { + if (ec == CKM_API_SUCCESS) { ec = CKM::Control::create()->unlockUserKey(uid, passwd.c_str()); - if(ec == CKM_API_SUCCESS) + if (ec == CKM_API_SUCCESS) return PAM_SUCCESS; pam_syslog(pamh, LOG_ERR, "key-manager and system password desynchronized," "attempt to create new database failed: %d\n", ec); @@ -107,10 +104,10 @@ pam_sm_close_session(pam_handle_t *pamh, int /*flags*/, int /*argc*/, const char // identify user uid_t uid = -1; std::string passwd; - if(identify_user_pwd(pamh, uid, passwd)) + if (identify_user_pwd(pamh, uid, passwd)) return PAM_SESSION_ERR; - if(CKM::Control::create()->lockUserKey(uid) == CKM_API_SUCCESS) + if (CKM::Control::create()->lockUserKey(uid) == CKM_API_SUCCESS) return PAM_SUCCESS; return PAM_SESSION_ERR; @@ -119,7 +116,7 @@ pam_sm_close_session(pam_handle_t *pamh, int /*flags*/, int /*argc*/, const char COMMON_API PAM_EXTERN int pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, const char **argv) { - if(argc==0) { + if (argc == 0) { pam_syslog(pamh, LOG_ERR, "key-manager plugin called with inappropriate arguments\n"); return PAM_SERVICE_ERR; } @@ -127,25 +124,21 @@ pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, const char **argv) // identify user uid_t uid = -1; std::string passwd; - if(identify_user_pwd(pamh, uid, passwd)) + if (identify_user_pwd(pamh, uid, passwd)) return PAM_USER_UNKNOWN; // attention: argv[0] is the argument, not the binary/so name // args are in arg_name=value format - if(strstr(argv[0], "change_step")) - { - if(strstr(argv[0], "before")) - { - if( ! (flags & PAM_PRELIM_CHECK)) + if (strstr(argv[0], "change_step")) { + if (strstr(argv[0], "before")) { + if (!(flags & PAM_PRELIM_CHECK)) old_password = passwd; return PAM_SUCCESS; - } - else if(strstr(argv[0], "after")) - { - if(flags & PAM_PRELIM_CHECK) + } else if (strstr(argv[0], "after")) { + if (flags & PAM_PRELIM_CHECK) return PAM_SUCCESS; - if(old_password.size() == 0) { + if (old_password.size() == 0) { pam_syslog(pamh, LOG_ERR, "attempt to change key-manager password w/o old password\n"); return PAM_SERVICE_ERR; } |