--- /dev/null
+# Copyright (c) 2017 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# @file CMakeLists.txt
+# @author Pawel Kowalski <p.kowalski2@partner.samsung.com>
+# @author Jaroslaw Pelczar <j.pelczar@samsung.com>
+#
+
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+
+IF(POLICY CMP0048)
+ CMAKE_POLICY(SET CMP0048 NEW)
+ENDIF()
+
+IF(POLICY CMP0069)
+ CMAKE_POLICY(SET CMP0069 NEW)
+ENDIF()
+
+INCLUDE(GNUInstallDirs)
+
+IF(NOT (CMAKE_VERSION VERSION_LESS 3.9))
+ INCLUDE(CheckIPOSupported)
+ check_ipo_supported(RESULT IPO_ALLOWED)
+ELSE()
+ SET(IPO_ALLOWED YES)
+ENDIF()
+
+INCLUDE(cmake/CheckFrameworks.cmake)
+INCLUDE(cmake/CStandard.cmake)
+
+SET(CMAKE_POSITION_INDEPENDENT_CODE "True")
+SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pie")
+
+INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
+
+ADD_SUBDIRECTORY(src)
--- /dev/null
+Copyright (c) 2000 - 2019 Samsung Electronics Co., Ltd. All rights reserved.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
--- /dev/null
+IF(CMAKE_VERSION VERSION_LESS 3.1)
+ include(CheckCXXCompilerFlag)
+ include(CheckCCompilerFlag)
+
+ message(STATUS "Using old cmake, will detect C++11 and C11 manually")
+
+ CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
+ CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
+ CHECK_CXX_COMPILER_FLAG("-std=gnu++11" COMPILER_SUPPORTS_GNUXX11)
+ CHECK_CXX_COMPILER_FLAG("-std=gnu++0x" COMPILER_SUPPORTS_GNUXX0X)
+ CHECK_CXX_COMPILER_FLAG("/std:c++14" COMPILER_SUPPORTS_STDCXX14)
+ CHECK_CXX_COMPILER_FLAG("/std:c++latest" COMPILER_SUPPORTS_STDCXXLATEST)
+
+ IF(COMPILER_SUPPORTS_CXX11)
+ SET(OLD_CMAKE_CXXFLAGS_CXX11 "-std=c++11")
+ ELSEIF(COMPILER_SUPPORTS_CXX0X)
+ SET(OLD_CMAKE_CXXFLAGS_CXX11 "-std=c++0x")
+ ELSEIF(COMPILER_SUPPORTS_GNUXX11)
+ SET(OLD_CMAKE_CXXFLAGS_CXX11 "-std=gnu++11")
+ ELSEIF(COMPILER_SUPPORTS_GNUXX0X)
+ SET(OLD_CMAKE_CXXFLAGS_CXX11 "-std=gnu++0x")
+ ELSEIF(COMPILER_SUPPORTS_STDCXXLATEST)
+ SET(OLD_CMAKE_CXXFLAGS_CXX11 "/std:c++latest")
+ ELSEIF(COMPILER_SUPPORTS_STDCXX14)
+ SET(OLD_CMAKE_CXXFLAGS_CXX11 "/std:c++14")
+ ELSE()
+ MESSAGE(FATAL_ERROR "No known way to enable C++11. Please upgrade cmake or compiler")
+ ENDIF()
+
+ CHECK_C_COMPILER_FLAG("-std=c11" COMPILER_SUPPORTS_C11)
+ CHECK_C_COMPILER_FLAG("-std=gnu11" COMPILER_SUPPORTS_GNU11)
+
+ IF(COMPILER_SUPPORTS_C11)
+ SET(OLD_CMAKE_CLAGS_C11 "-std=c11")
+ ELSEIF(COMPILER_SUPPORTS_GNU11)
+ SET(OLD_CMAKE_CLAGS_C11 "-std=gnu11")
+ ELSE()
+ IF((CMAKE_C_COMPILER_ID MATCHES "Clang") OR (CMAKE_C_COMPILER_ID MATCHES "GNU"))
+ MESSAGE(FATAL_ERROR "Can't find way to enable C11")
+ ENDIF()
+ ENDIF()
+ENDIF()
+
+MACRO(ApplyCxx11Standard TargetName)
+ IF(CMAKE_VERSION VERSION_LESS 3.1)
+ IF(NOT __OLD_CMAKE_CXX11_ALREADY_APPLIED)
+ SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OLD_CMAKE_CXXFLAGS_CXX11}")
+ SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OLD_CMAKE_CLAGS_C11}")
+ SET(__OLD_CMAKE_CXX11_ALREADY_APPLIED TRUE)
+ ENDIF()
+ ELSE()
+ set_property(TARGET ${TargetName}
+ PROPERTY
+ CXX_STANDARD 11)
+ set_property(TARGET ${TargetName}
+ PROPERTY
+ CXX_STANDARD_REQUIRED TRUE)
+ set_property(TARGET ${TargetName}
+ PROPERTY
+ C_STANDARD 11)
+ set_property(TARGET ${TargetName}
+ PROPERTY
+ C_STANDARD_REQUIRED TRUE)
+ ENDIF()
+ENDMACRO(ApplyCxx11Standard)
--- /dev/null
+INCLUDE(CheckIncludeFile)
+INCLUDE(CheckIncludeFileCXX)
+INCLUDE(CheckLibraryExists)
+INCLUDE(CheckFunctionExists)
+INCLUDE(CheckIncludeFiles)
+
+FIND_PACKAGE(Boost 1.54
+ REQUIRED
+ COMPONENTS
+ log)
+
+FIND_PACKAGE(PkgConfig REQUIRED)
+
+PKG_CHECK_MODULES(DLOG dlog)
+
+#### Find mbedtls ####
+
+find_library(MBEDTLS_LIB
+ mbedtls)
+
+find_library(MBEDCRYPTO_LIB
+ mbedcrypto)
+
+find_library(MBEDX509_LIB
+ mbedx509)
+
+IF(MBEDTLS_LIB-NOTFOUND)
+ message(FATAL_ERROR "mbedtls not found ...")
+ENDIF()
+
+IF(MBEDCRYPTO_LIB-NOTFOUND)
+ message(FATAL_ERROR "mbedcrypto not found ...")
+ENDIF()
+
+IF(MBEDX509_LIB-NOTFOUND)
+ message(FATAL_ERROR "mbedx509 not found ...")
+ENDIF()
+
+CHECK_INCLUDE_FILES("mbedtls/rsa.h;mbedtls/ecdsa.h" MBEDTLS_HEADERS_OK)
+
+IF(NOT MBEDTLS_HEADERS_OK)
+ message(FATAL_ERROR "No mbedtls headers")
+ENDIF()
+
+#### Find dcm-backend-api.h header ####
+
+FIND_FILE(DCM_BACKEND_API_H device-certificate-manager-backend/dcm-backend-api.h)
+IF(NOT DCM_BACKEND_API_H)
+ message(FATAL_ERROR "No dcm-backend-api.h")
+ENDIF()
--- /dev/null
+Name: device-certificate-manager-backend-dummy
+Summary: Device Certificate Manager dummy (based on the OpenSSL) backend library
+Version: 1.0
+Release: 1
+Group: Security/Development
+License: Apache-2.0
+Source0: %{name}-%{version}.tar.gz
+Source1001: device-certificate-manager-backend.manifest
+BuildRequires: cmake
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(iotivity)
+BuildRequires: pkgconfig(protobuf)
+BuildRequires: pkgconfig(device-certificate-manager-backend)
+BuildRequires: boost-devel
+BuildRequires: openssl
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+Requires: device-certificate-manager
+
+%description
+Device Certificate Manager dummy (based on the OpenSSL) backend library
+
+%prep
+%setup -q
+cp -a %{SOURCE1001} .
+
+%build
+
+%cmake . -DVERSION=%{version} \
+ -DCMAKE_BUILD_TYPE=%{?build_type:%build_type}%{!?build_type:Release} \
+ -DDCM_BACKEND_API=%{dcm_backend_api} \
+ -DDCM_BACKEND_TYPE=dummy
+
+make %{?jobs:-j%jobs}
+
+%install
+%make_install
+
+%files
+%manifest device-certificate-manager-backend.manifest
+%license LICENSE
+%{_libdir}/lib%{dcm_backend_api}.so*
--- /dev/null
+Name: device-certificate-manager-backend-kse
+Summary: Device Certificate Manager KONAISE backend library
+Version: 1.0
+Release: 1
+Group: Security/Development
+License: Apache-2.0
+Source0: %{name}-%{version}.tar.gz
+Source1001: device-certificate-manager-backend.manifest
+BuildRequires: cmake
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(iotivity)
+BuildRequires: pkgconfig(protobuf)
+BuildRequires: pkgconfig(device-certificate-manager-backend)
+BuildRequires: boost-devel
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+Requires: device-certificate-manager
+
+%description
+Device Certificate Manager KONAISE backend library
+
+%package -n device-certificate-manager-backend-kse-tests
+Summary: Internal tool for testing the DCM KONAISE backend
+Group: Security/Testing
+Requires: device-certificate-manager-backend-kse
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+
+%description tests
+Internal tool for testing the DCM KONAISE backend
+
+%prep
+%setup -q
+cp -a %{SOURCE1001} .
+
+%build
+
+%cmake . -DVERSION=%{version} \
+ -DCMAKE_BUILD_TYPE=%{?build_type:%build_type}%{!?build_type:Release} \
+ -DDCM_BACKEND_API=%{dcm_backend_api} \
+ -DDCM_BACKEND_TYPE=kse
+
+make %{?jobs:-j%jobs}
+
+%install
+%make_install
+
+%files
+%manifest device-certificate-manager-backend.manifest
+%license LICENSE
+%{_libdir}/lib%{dcm_backend_api}.so*
+
+%files tests
+%manifest device-certificate-manager-backend.manifest
+%license LICENSE
+%{_bindir}/dcm_konaise_tool
--- /dev/null
+<manifest>
+ <request>
+ <domain name="_" />
+ </request>
+</manifest>
--- /dev/null
+#
+# DCM backends build script
+# Jaroslaw Pelczar <j.pelczar@samsung.com>
+#
+
+###### Setup include paths and library directories #######
+
+ADD_DEFINITIONS(-DBOOST_LOG_DYN_LINK)
+
+IF(DLOG_FOUND)
+ include_directories(${DLOG_INCLUDE_DIRS})
+ link_directories(${DLOG_LIBRARY_DIRS})
+ add_definitions(${DLOG_CFLAGS_OTHER})
+ add_definitions(-DUSE_DLOG_LOGGING=1)
+ENDIF(DLOG_FOUND)
+
+include_directories(${Boost_INCLUDE_DIRS})
+include_directories(device-certificate-manager)
+link_directories(${Boost_LIBRARY_DIRS})
+
+include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR})
+
+###### Crypto Backends #######
+
+ADD_DEFINITIONS(-DDCM_BACKEND)
+
+IF(DCM_BACKEND_TYPE STREQUAL "dummy")
+ add_subdirectory(dummy-backend)
+ELSEIF(DCM_BACKEND_TYPE STREQUAL "kse")
+ add_subdirectory(kse-backend)
+ELSE()
+ add_subdirectory(dummy-backend)
+ENDIF()
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "abstractcryptobackend.h"
+
+abstract_crypto_backend::abstract_crypto_backend() {
+}
+
+abstract_crypto_backend::~abstract_crypto_backend() {
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef ABSTRACTCRYPTOBACKEND_H_
+#define ABSTRACTCRYPTOBACKEND_H_
+
+#include <boost/noncopyable.hpp>
+#include <memory>
+#include <string>
+
+#include <device-certificate-manager-backend/dcm-backend-api.h>
+
+class abstract_crypto_backend_context;
+
+class abstract_crypto_backend : public std::enable_shared_from_this<abstract_crypto_backend>,
+ public boost::noncopyable
+{
+protected:
+ abstract_crypto_backend();
+
+public:
+ virtual ~abstract_crypto_backend();
+};
+
+#endif /* ABSTRACTCRYPTOBACKEND_H_ */
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "abstractcryptobackendcontext.h"
+
+abstract_crypto_backend_context::abstract_crypto_backend_context() {
+}
+
+abstract_crypto_backend_context::~abstract_crypto_backend_context() {
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef ABSTRACTCRYPTOBACKENDCONTEXT_H_
+#define ABSTRACTCRYPTOBACKENDCONTEXT_H_
+
+#include "abstractcryptobackend.h"
+
+class abstract_crypto_backend_context : public std::enable_shared_from_this<abstract_crypto_backend_context> {
+protected:
+ abstract_crypto_backend_context();
+
+public:
+ virtual ~abstract_crypto_backend_context();
+
+ virtual int request_certificate_chain(std::string& mutable_chain) = 0;
+
+ virtual int sign_crypto_data(MessageDigestType digestType, const std::string& dataToSign,
+ std::string& digestResult) = 0;
+
+ virtual CryptoKeyType key_type() = 0;
+
+ virtual unsigned int key_length() = 0;
+};
+
+#endif /* ABSTRACTCRYPTOBACKENDCONTEXT_H_ */
--- /dev/null
+# Copyright (c) 2017 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# @file src/see-backend/CMakeLists.txt
+# @author Pawel Kowalski <p.kowalski2@partner.samsung.com>
+# @author Jaroslaw Pelczar <j.pelczar@samsung.com>
+#
+
+find_program(OPENSSL_TOOL openssl)
+
+IF(NOT OPENSSL_TOOL)
+ MESSAGE(FATAL_ERROR "openssl required to build dummy CA")
+ENDIF()
+
+add_executable(helper_bin2c bin2c.c)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootCA.key
+ COMMAND ${OPENSSL_TOOL} genrsa -out ${CMAKE_CURRENT_BINARY_DIR}/rootCA.key 1024)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootCA.pem
+ COMMAND ${OPENSSL_TOOL} req -x509 -new -nodes -key ${CMAKE_CURRENT_BINARY_DIR}/rootCA.key
+ -sha256 -days 1024 -out ${CMAKE_CURRENT_BINARY_DIR}/rootCA.pem
+ -subj "/C=PL/ST=Test1/L=Test2/O=Dis/CN=www.example.com"
+ DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/rootCA.key)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.key
+ COMMAND ${OPENSSL_TOOL} ecparam -name secp521r1 -genkey -noout -out ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.key)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.pem
+ COMMAND ${OPENSSL_TOOL} req -x509 -new -nodes -key ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.key
+ -sha256 -days 1024 -out ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.pem
+ -subj "/C=PL/ST=Test1/L=Test2/O=Dis/CN=www.example.com"
+ DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.key)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootCA_rsa_key.c
+ COMMAND $<TARGET_FILE:helper_bin2c> ${CMAKE_CURRENT_BINARY_DIR}/rootCA.key ${CMAKE_CURRENT_BINARY_DIR}/rootCA_rsa_key.c dummy_rootca_rsa_key
+ DEPENDS helper_bin2c ${CMAKE_CURRENT_BINARY_DIR}/rootCA.key)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootCA_rsa_cert.c
+ COMMAND $<TARGET_FILE:helper_bin2c> ${CMAKE_CURRENT_BINARY_DIR}/rootCA.pem ${CMAKE_CURRENT_BINARY_DIR}/rootCA_rsa_cert.c dummy_rootca_rsa_cert
+ DEPENDS helper_bin2c ${CMAKE_CURRENT_BINARY_DIR}/rootCA.pem)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootCA_ecdsa_key.c
+ COMMAND $<TARGET_FILE:helper_bin2c> ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.key ${CMAKE_CURRENT_BINARY_DIR}/rootCA_ecdsa_key.c dummy_rootca_ecdsa_key
+ DEPENDS helper_bin2c ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.key)
+
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rootCA_ecdsa_cert.c
+ COMMAND $<TARGET_FILE:helper_bin2c> ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.pem ${CMAKE_CURRENT_BINARY_DIR}/rootCA_ecdsa_cert.c dummy_rootca_ecdsa_cert
+ DEPENDS helper_bin2c ${CMAKE_CURRENT_BINARY_DIR}/rootECDSA.pem)
+
+###### Include and library directories ######
+
+IF(DLOG_FOUND)
+ include_directories(${DLOG_INCLUDE_DIRS})
+ link_directories(${DLOG_LIBRARY_DIRS})
+ add_definitions(-DUSE_DLOG_LOGGING=1)
+ENDIF()
+
+include_directories(${Boost_INCLUDE_DIRS})
+link_directories(${Boost_LIBRARY_DIRS})
+
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+
+###### Library sources ######
+
+add_library(${DCM_BACKEND_API}
+ SHARED
+ dcm-backend-api-dummy.cpp
+ ../abstractcryptobackend.cpp
+ ../abstractcryptobackendcontext.cpp
+ dummycryptobackend.cpp
+ dummycryptobackendcontext.cpp
+ ${CMAKE_CURRENT_BINARY_DIR}/rootCA_ecdsa_key.c
+ ${CMAKE_CURRENT_BINARY_DIR}/rootCA_ecdsa_cert.c
+ ${CMAKE_CURRENT_BINARY_DIR}/rootCA_rsa_key.c
+ ${CMAKE_CURRENT_BINARY_DIR}/rootCA_rsa_cert.c
+)
+
+###### Linking ######
+
+ApplyCxx11Standard(${DCM_BACKEND_API})
+
+target_link_libraries(${DCM_BACKEND_API}
+ ${Boost_SYSTEM_LIBRARY}
+ ${CMAKE_THREAD_LIBS_INIT}
+ ${MBEDTLS_LIB}
+ ${MBEDCRYPTO_LIB}
+)
+
+IF(DLOG_FOUND)
+ target_link_libraries(${DCM_BACKEND_API} ${DLOG_LIBRARIES})
+ENDIF()
+
+###### Properties of library ######
+
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY DEFINE_SYMBOL DCM_BACKEND_API_DUMMY_EXPORT)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY VISIBILITY_INLINES_HIDDEN TRUE)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY VERSION 1.0)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY C_VISIBILITY_PRESET hidden)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY CXX_VISIBILITY_PRESET hidden)
+
+###### Installation ######
+
+install(TARGETS
+ ${DCM_BACKEND_API}
+ LIBRARY DESTINATION
+ ${CMAKE_INSTALL_LIBDIR}
+)
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2018 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <stdio.h>
+#include <stdlib.h>
+
+int main(int argc, char** argv)
+{
+ int ret = 0;
+ size_t size;
+ char *buffer = NULL;
+
+ if(argc != 4)
+ return -1;
+
+ FILE *infile = fopen(argv[1], "rb");
+ FILE *outfile = fopen(argv[2], "wb");
+ if(!infile || !outfile) {
+ perror("fopen() failed");
+ ret = -1;
+ goto exit;
+ }
+
+ if(fseek(infile, 0L, SEEK_END) < 0) {
+ perror("fseek() failed");
+ ret = -1;
+ goto exit;
+ }
+ if((size = ftell(infile)) <= 0) {
+ perror("ftell() failed");
+ ret = -1;
+ goto exit;
+ }
+ if(fseek(infile, 0L, SEEK_SET) < 0) {
+ perror("fseek() failed");
+ ret = -1;
+ goto exit;
+ }
+
+ buffer = (char *)malloc(size);
+ if(!buffer) {
+ perror("malloc() failed");
+ ret = -1;
+ goto exit;
+ }
+
+ if(fread(buffer, 1, size, infile) <= 0) {
+ perror("fread() failed");
+ ret = -1;
+ goto exit;
+ }
+
+ fprintf(outfile, "#include <sys/types.h>\nsize_t %s_size = %zd;\nunsigned char %s[]= {\n",
+ argv[3], size, argv[3]);
+
+ for(size_t i = 0 ; i < size ; ++i) {
+ if(!(i % 64)) {
+ fprintf(outfile, "\n");
+ }
+ fprintf(outfile, "0x%02X,", (unsigned char)buffer[i]);
+ }
+ fprintf(outfile, "0\n};\n");
+
+exit:
+ if(infile) fclose(infile);
+ if(outfile) fclose(outfile);
+ free(buffer);
+ return ret;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Pawel Kowalski <p.kowalski2@partner.samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "dummycryptobackend.h"
+#include "dummycryptobackendcontext.h"
+
+void dcm_backend_create_key_context(dcm_backend_context& ctx,
+ const std::string& keyType) {
+ ctx.backend = new dummy_crypto_backend_context(keyType);
+}
+
+void dcm_backend_free_key_context(dcm_backend_context& ctx) {
+ delete static_cast<dummy_crypto_backend_context*>(ctx.backend);
+}
+
+int dcm_backend_request_certificate_chain(dcm_backend_context& ctx,
+ std::string& mutable_chain) {
+ return static_cast<dummy_crypto_backend_context*>(ctx.backend)
+ ->request_certificate_chain(mutable_chain);
+}
+
+int dcm_backend_sign_crypto_data(dcm_backend_context& ctx,
+ MessageDigestType digestType,
+ const std::string& dataToSign,
+ std::string& digestResult) {
+ return static_cast<dummy_crypto_backend_context*>(ctx.backend)
+ ->sign_crypto_data(digestType, dataToSign, digestResult);
+}
+
+CryptoKeyType dcm_backend_key_type(dcm_backend_context& ctx) {
+ return static_cast<dummy_crypto_backend_context*>(ctx.backend)->key_type();
+}
+
+unsigned int dcm_backend_key_length(dcm_backend_context& ctx) {
+ return static_cast<dummy_crypto_backend_context*>(ctx.backend)->key_length();
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "dummycryptobackend.h"
+#include "dummycryptobackendcontext.h"
+#include "logging.h"
+
+dummy_crypto_backend::dummy_crypto_backend() {
+ BOOST_LOG_FUNCTION();
+}
+
+dummy_crypto_backend::~dummy_crypto_backend() {
+ BOOST_LOG_FUNCTION();
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef DUMMY_BACKEND_DUMMYCRYPTOBACKEND_H_
+#define DUMMY_BACKEND_DUMMYCRYPTOBACKEND_H_
+
+#include "abstractcryptobackend.h"
+
+class dummy_crypto_backend final : public abstract_crypto_backend {
+public:
+ dummy_crypto_backend();
+ virtual ~dummy_crypto_backend();
+};
+
+#endif /* DUMMY_BACKEND_DUMMYCRYPTOBACKEND_H_ */
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "dummycryptobackendcontext.h"
+#include <mbedtls/pk.h>
+#include <mbedtls/ctr_drbg.h>
+#include <iostream>
+#include "logging.h"
+
+extern "C" {
+ extern size_t dummy_rootca_rsa_key_size;
+ extern char dummy_rootca_rsa_key[];
+ extern size_t dummy_rootca_rsa_cert_size;
+ extern char dummy_rootca_rsa_cert[];
+ extern size_t dummy_rootca_ecdsa_key_size;
+ extern char dummy_rootca_ecdsa_key[];
+ extern size_t dummy_rootca_ecdsa_cert_size;
+ extern char dummy_rootca_ecdsa_cert[];
+}
+
+dummy_crypto_backend_context::dummy_crypto_backend_context(const std::string& keyType) {
+ BOOST_LOG_FUNCTION();
+ if(keyType.empty() || keyType == "RSA") {
+ fKey = CRYPTO_KEY_TYPE_RSA;
+ } else if(keyType == "ECDSA") {
+ fKey = CRYPTO_KEY_TYPE_ECDSA;
+ } else {
+ throw std::invalid_argument("Unsupported key type");
+ }
+
+ mbedtls_entropy_init( &fEntropy );
+ mbedtls_ctr_drbg_init( &fCtrDrbg );
+
+ int ret = mbedtls_ctr_drbg_seed( &fCtrDrbg,
+ mbedtls_entropy_func,
+ &fEntropy,
+ (const unsigned char *)this,
+ sizeof(dummy_crypto_backend_context) );
+
+ if(!ret) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Can't seed entropy source";
+ mbedtls_ctr_drbg_free( &fCtrDrbg );
+ mbedtls_entropy_free( &fEntropy );
+ throw std::runtime_error("seed failure");
+ }
+}
+
+dummy_crypto_backend_context::~dummy_crypto_backend_context() {
+ BOOST_LOG_FUNCTION();
+ mbedtls_ctr_drbg_free( &fCtrDrbg );
+ mbedtls_entropy_free( &fEntropy );
+}
+
+int dummy_crypto_backend_context::request_certificate_chain(std::string& mutable_chain)
+{
+ BOOST_LOG_FUNCTION();
+ if(fKey == CRYPTO_KEY_TYPE_RSA) {
+ mutable_chain.assign(dummy_rootca_rsa_cert, dummy_rootca_rsa_cert_size);
+ } else {
+ mutable_chain.assign(dummy_rootca_ecdsa_cert, dummy_rootca_ecdsa_cert_size);
+ }
+
+ return 0;
+}
+
+int dummy_crypto_backend_context::sign_crypto_data(MessageDigestType digestType,
+ const std::string& dataToSign,
+ std::string& digestResult)
+{
+ BOOST_LOG_FUNCTION();
+ int error;
+
+ mbedtls_pk_context pk;
+ mbedtls_pk_init(&pk);
+
+ if(fKey == CRYPTO_KEY_TYPE_RSA) {
+ error = mbedtls_pk_parse_key(&pk,
+ (const unsigned char *)dummy_rootca_rsa_key,
+ dummy_rootca_rsa_key_size + 1, // Include 0 byte for PEM
+ nullptr, 0);
+
+ } else {
+ error = mbedtls_pk_parse_key(&pk,
+ (const unsigned char *)dummy_rootca_ecdsa_key,
+ dummy_rootca_ecdsa_key_size + 1, // Include 0 byte for PEM
+ nullptr, 0);
+ }
+
+ if(error != 0) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Can't parse private key";
+ mbedtls_pk_free(&pk);
+ return error;
+ }
+
+ size_t sig_len = 0;
+ digestResult.resize(MBEDTLS_MPI_MAX_SIZE);
+
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Maximum digest size is " << digestResult.size();
+
+ error = mbedtls_pk_sign(&pk,
+ static_cast<mbedtls_md_type_t>(digestType),
+ (const unsigned char *)dataToSign.c_str(),
+ dataToSign.size(),
+ (unsigned char *)digestResult.c_str(),
+ &sig_len,
+ &mbedtls_ctr_drbg_random,
+ &fCtrDrbg);
+
+ if(error != 0) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Signature generation failed";
+ } else {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Signature size is " << sig_len;
+ digestResult.resize(sig_len);
+ }
+
+ mbedtls_pk_free(&pk);
+
+ return error;
+}
+
+CryptoKeyType dummy_crypto_backend_context::dummy_crypto_backend_context::key_type()
+{
+ return fKey;
+}
+
+unsigned int dummy_crypto_backend_context::key_length()
+{
+ BOOST_LOG_FUNCTION();
+ unsigned int keyLength = 0;
+
+ mbedtls_pk_context pk;
+ mbedtls_pk_init(&pk);
+
+ if(fKey == CRYPTO_KEY_TYPE_RSA) {
+ int error = mbedtls_pk_parse_key(&pk,
+ (const unsigned char *)dummy_rootca_rsa_key,
+ dummy_rootca_rsa_key_size + 1, // Include 0 byte for PEM
+ nullptr, 0);
+
+ assert(error == 0);
+ assert(mbedtls_pk_get_type(&pk) == MBEDTLS_PK_RSA);
+ (void)error;
+ } else {
+ int error = mbedtls_pk_parse_key(&pk,
+ (const unsigned char *)dummy_rootca_ecdsa_key,
+ dummy_rootca_ecdsa_key_size + 1, // Include 0 byte for PEM
+ nullptr, 0);
+
+ assert(error == 0);
+ assert(mbedtls_pk_get_type(&pk) == MBEDTLS_PK_ECKEY);
+ (void)error;
+ }
+
+ keyLength = mbedtls_pk_get_bitlen(&pk);
+ mbedtls_pk_free(&pk);
+
+ return keyLength;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef DUMMY_BACKEND_DUMMYCRYPTOBACKENDCONTEXT_H_
+#define DUMMY_BACKEND_DUMMYCRYPTOBACKENDCONTEXT_H_
+
+#include "abstractcryptobackendcontext.h"
+#include <mbedtls/ctr_drbg.h>
+#include <mbedtls/entropy.h>
+
+class dummy_crypto_backend_context final : public abstract_crypto_backend_context {
+public:
+ dummy_crypto_backend_context(const std::string& keyType);
+ virtual ~dummy_crypto_backend_context();
+
+ virtual int request_certificate_chain(std::string& mutable_chain) override;
+
+ virtual int sign_crypto_data(MessageDigestType digestType, const std::string& dataToSign,
+ std::string& digestResult) override;
+
+ virtual CryptoKeyType key_type() override;
+
+ virtual unsigned int key_length() override;
+
+private:
+ CryptoKeyType fKey;
+ mbedtls_entropy_context fEntropy;
+ mbedtls_ctr_drbg_context fCtrDrbg;
+};
+
+#endif /* DUMMY_BACKEND_DUMMYCRYPTOBACKENDCONTEXT_H_ */
--- /dev/null
+# Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# @file src/kse-backend/CMakeLists.txt
+# @author Pawel Kowalski <p.kowalski2@partner.samsung.com>
+#
+
+###### Include and library directories ######
+
+IF(DLOG_FOUND)
+ include_directories(${DLOG_INCLUDE_DIRS})
+ link_directories(${DLOG_LIBRARY_DIRS})
+ add_definitions(-DUSE_DLOG_LOGGING=1)
+ENDIF()
+
+include_directories(${Boost_INCLUDE_DIRS})
+link_directories(${Boost_LIBRARY_DIRS})
+
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+
+###### Library sources ######
+
+add_library(${DCM_BACKEND_API}
+ SHARED
+ dcm-backend-api-kse.cpp
+ soresolver.cpp
+ ../abstractcryptobackend.cpp
+ ../abstractcryptobackendcontext.cpp
+ ksebackend.cpp
+ ksebackendcontext.cpp
+)
+
+###### Linking ######
+
+ApplyCxx11Standard(${DCM_BACKEND_API})
+
+target_link_libraries(${DCM_BACKEND_API}
+ ${Boost_SYSTEM_LIBRARY}
+ ${CMAKE_THREAD_LIBS_INIT}
+ ${MBEDTLS_LIB}
+ ${MBEDCRYPTO_LIB}
+)
+
+IF(DLOG_FOUND)
+ target_link_libraries(${DCM_BACKEND_API} ${DLOG_LIBRARIES})
+ENDIF()
+
+###### Properties of library ######
+
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY DEFINE_SYMBOL DCM_BACKEND_API_SEE_EXPORT)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY VISIBILITY_INLINES_HIDDEN TRUE)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY VERSION 1.0)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY C_VISIBILITY_PRESET hidden)
+set_property(TARGET ${DCM_BACKEND_API} PROPERTY CXX_VISIBILITY_PRESET hidden)
+
+###### Installation ######
+
+install(TARGETS
+ ${DCM_BACKEND_API}
+ LIBRARY DESTINATION
+ ${CMAKE_INSTALL_LIBDIR}
+)
+
+ADD_SUBDIRECTORY(tools)
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "cert_utils.h"
+#include <vector>
+#include <map>
+#include <algorithm>
+#include <cstring>
+#include <cstdlib>
+#include <mbedtls/pem.h>
+#include <stdexcept>
+#include <cassert>
+#include <set>
+#include <list>
+#include "logging.h"
+
+int x509_crt_rewriter::parse(const unsigned char * buffer, size_t length)
+{
+ BOOST_LOG_FUNCTION();
+ return mbedtls_x509_crt_parse(fChain, buffer, length);
+}
+
+/*
+ * Like memcmp, but case-insensitive and always returns -1 if different
+ */
+static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
+{
+ size_t i;
+ unsigned char diff;
+ const unsigned char *n1 = (const unsigned char *)s1, *n2 = (const unsigned char *)s2;
+
+ for( i = 0; i < len; i++ )
+ {
+ diff = n1[i] ^ n2[i];
+
+ if( diff == 0 )
+ continue;
+
+ if( diff == 32 &&
+ ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
+ ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
+ {
+ continue;
+ }
+
+ return( -1 );
+ }
+
+ return( 0 );
+}
+
+/*
+ * Compare two X.509 strings, case-insensitive, and allowing for some encoding
+ * variations (but not all).
+ *
+ * Return 0 if equal, -1 otherwise.
+ */
+static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
+{
+ if( a->tag == b->tag &&
+ a->len == b->len &&
+ memcmp( a->p, b->p, b->len ) == 0 )
+ {
+ return( 0 );
+ }
+
+ if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
+ ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
+ a->len == b->len &&
+ x509_memcasecmp( a->p, b->p, b->len ) == 0 )
+ {
+ return( 0 );
+ }
+
+ return( -1 );
+}
+
+/*
+ * Compare two X.509 Names (aka rdnSequence).
+ *
+ * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
+ * we sometimes return unequal when the full algorithm would return equal,
+ * but never the other way. (In particular, we don't do Unicode normalisation
+ * or space folding.)
+ *
+ * Return 0 if equal, -1 otherwise.
+ */
+static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
+{
+ /* Avoid recursion, it might not be optimised by the compiler */
+ while( a != NULL || b != NULL )
+ {
+ if( a == NULL || b == NULL )
+ return( -1 );
+
+ /* type */
+ if( a->oid.tag != b->oid.tag ||
+ a->oid.len != b->oid.len ||
+ memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
+ {
+ return( -1 );
+ }
+
+ /* value */
+ if( x509_string_cmp( &a->val, &b->val ) != 0 )
+ return( -1 );
+
+ /* structure of the list of sets */
+ if( a->next_merged != b->next_merged )
+ return( -1 );
+
+ a = a->next;
+ b = b->next;
+ }
+
+ /* a == NULL == b */
+ return( 0 );
+}
+
+void x509_crt_rewriter::sort_chain()
+{
+ BOOST_LOG_FUNCTION();
+
+ // Only 1 certificate - don't bother
+ if(!fChain->next) {
+ fChainSize = fChain->raw.len;
+ fNumCerts = 1;
+ return;
+ }
+
+ std::vector<mbedtls_x509_crt *> list;
+ std::multimap<mbedtls_x509_crt *, mbedtls_x509_crt *> subject_of;
+ std::set<mbedtls_x509_crt *> visited;
+
+ // Build list of all certificates
+ for(auto * cert = fChain ; cert ; cert = cert->next) {
+ list.push_back(cert);
+ }
+
+ // Create graph vertices to map issuer to subject
+ for(size_t i = 0 ; i < list.size() ; ++i) {
+ mbedtls_x509_crt * issuer = nullptr;
+ // Find issuer - ignore ourselves as we always want root CA issuer to be nullptr
+ for(size_t j = 0 ; j < list.size() ; ++j) {
+ if(i != j && x509_name_cmp(&list[i]->issuer, &list[j]->subject) == 0) {
+ issuer = list[j];
+ break;
+ }
+ }
+
+ // In case there are multiple subjects for one issuer, the chain
+ // must be horribly broken
+ subject_of.emplace(issuer, list[i]);
+ }
+
+ // BFS algorithm queue
+ std::list<mbedtls_x509_crt *> queue;
+ // Final output chain
+ std::list<mbedtls_x509_crt *> final_chain;
+
+ // Find root certificates - they will not have any issuer
+ auto root_range = subject_of.equal_range(nullptr);
+
+ // Perform BFS for each root
+ for(auto it = root_range.first ; it != root_range.second ; ++it) {
+ mbedtls_x509_crt * root_cert = it->second;
+
+ if(visited.find(root_cert) == visited.end()) {
+ visited.insert(root_cert);
+ queue.push_back(root_cert);
+
+ while(!queue.empty()) {
+ auto s = queue.front();
+ // Write out chain from root back to leaf
+ final_chain.push_back(s);
+ queue.pop_front();
+
+ auto range = subject_of.equal_range(s);
+ for(auto it = range.first ; it != range.second ; ++it) {
+ mbedtls_x509_crt * cert = it->second;
+ if(visited.find(cert) == visited.end()) {
+ visited.insert(cert);
+ queue.push_back(cert);
+ }
+ }
+ }
+ }
+ }
+
+ fChain = nullptr;
+ fChainSize = 0;
+ fNumCerts = list.size();
+
+ // Rebuild certificate linked list
+ for(auto it = final_chain.begin() ; it != final_chain.end() ; ++it) {
+ auto cert(*it);
+ cert->next = fChain;
+ fChain = cert;
+ fChainSize += cert->raw.len;
+ }
+}
+
+#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
+#define PEM_END_CRT "-----END CERTIFICATE-----\n"
+
+std::string x509_crt_rewriter::emit_pem()
+{
+ BOOST_LOG_FUNCTION();
+ std::string buffer;
+
+ if(fChainSize == 0)
+ throw std::runtime_error("State failure");
+
+ // Always rewrite the chain as PEM
+
+ buffer.resize(fChainSize * 4 + fNumCerts * (sizeof(PEM_BEGIN_CRT) + sizeof(PEM_END_CRT)));
+
+ unsigned char * out_buffer = (unsigned char *)buffer.c_str();
+ size_t out_capacity = buffer.size();
+ size_t total_size = 0;
+ size_t this_len;
+
+ for(auto cert = fChain ; cert ; cert = cert->next) {
+ int error = mbedtls_pem_write_buffer(PEM_BEGIN_CRT,
+ PEM_END_CRT,
+ cert->raw.p,
+ cert->raw.len,
+ out_buffer + total_size,
+ out_capacity - total_size,
+ &this_len);
+
+ if(error != 0) {
+ throw std::runtime_error("Certificate write failure");
+ }
+
+ // Account for final 0 byte
+ total_size += this_len - 1;
+ }
+
+ buffer.resize(total_size);
+ buffer.push_back(0);
+
+ return buffer;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef CERT_UTILS_H_
+#define CERT_UTILS_H_
+
+#include <mbedtls/x509_crt.h>
+#include <string>
+
+struct x509_crt_rewriter {
+private:
+ mbedtls_x509_crt * fChain;
+ size_t fChainSize = 0;
+ size_t fNumCerts = 0;
+
+public:
+ x509_crt_rewriter() :
+ fChain(new mbedtls_x509_crt())
+ {
+ mbedtls_x509_crt_init(fChain);
+ }
+
+ ~x509_crt_rewriter() {
+ mbedtls_x509_crt_free(fChain);
+ delete fChain;
+ }
+
+ int parse(const unsigned char * buffer, size_t length);
+ void sort_chain();
+ std::string emit_pem();
+};
+
+#endif /* CERT_UTILS_H_ */
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Pawel Kowalski <p.kowalski2@partner.samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "ksebackend.h"
+#include "ksebackendcontext.h"
+
+static std::shared_ptr<kse_backend> backend(new kse_backend());
+
+void dcm_backend_create_key_context(dcm_backend_context& ctx,
+ const std::string& keyType) {
+ ctx.backend = new kse_backend_context(backend, keyType);
+}
+
+void dcm_backend_free_key_context(dcm_backend_context& ctx) {
+ delete static_cast<kse_backend_context*>(ctx.backend);
+}
+
+int dcm_backend_request_certificate_chain(dcm_backend_context& ctx,
+ std::string& mutable_chain) {
+ return static_cast<kse_backend_context*>(ctx.backend)
+ ->request_certificate_chain(mutable_chain);
+}
+
+int dcm_backend_sign_crypto_data(dcm_backend_context& ctx,
+ MessageDigestType digestType,
+ const std::string& dataToSign,
+ std::string& digestResult) {
+ return static_cast<kse_backend_context*>(ctx.backend)
+ ->sign_crypto_data(digestType, dataToSign, digestResult);
+}
+
+CryptoKeyType dcm_backend_key_type(dcm_backend_context& ctx) {
+ return static_cast<kse_backend_context*>(ctx.backend)->key_type();
+}
+
+unsigned int dcm_backend_key_length(dcm_backend_context& ctx) {
+ return static_cast<kse_backend_context*>(ctx.backend)->key_length();
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifdef USE_KONAISE_HEADERS
+#include <konaise.h>
+#else
+
+#ifndef _KONAISE_SECURITY_H_
+#define _KONAISE_SECURITY_H_
+
+typedef struct _hal_init_param {
+ uint32_t i2c_port;
+ uint32_t gpio;
+} hal_init_param;
+
+
+typedef struct _hal_data {
+ void *data;
+ uint32_t data_len;
+ void *priv;
+} hal_data;
+
+typedef enum {
+ HAL_HASH_MD5,
+ HAL_HASH_SHA1,
+ HAL_HASH_SHA224,
+ HAL_HASH_SHA256,
+ HAL_HASH_SHA384,
+ HAL_HASH_SHA512,
+ HAL_HASH_UNKNOWN,
+} hal_hash_type;
+
+typedef enum {
+ HAL_ECDSA_BRAINPOOL_P256R1,
+ HAL_ECDSA_BRAINPOOL_P384R1,
+ HAL_ECDSA_BRAINPOOL_P512R1,
+ HAL_ECDSA_SEC_P256R1,
+ HAL_ECDSA_SEC_P384R1,
+ HAL_ECDSA_SEC_P512R1,
+} hal_ecdsa_curve;
+
+typedef struct _hal_ecdsa_mode {
+ hal_ecdsa_curve curve;
+ hal_hash_type hash_t;
+} hal_ecdsa_mode;
+
+
+#endif
+
+#endif
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Dongsun Lee <ds73.lee@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "ksebackend.h"
+#include "ksebackendcontext.h"
+#include "logging.h"
+#include <mutex>
+
+#include "konaise.h"
+
+#define KSE_LIB_NAME "libkonaise.so"
+
+kse_backend::kse_backend() :
+ fKseInitOK(false),
+ fSoResolver(std::string(KSE_LIB_NAME))
+{
+ BOOST_LOG_FUNCTION();
+ initialize_kse();
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Constructed KSE backend";
+}
+
+kse_backend::~kse_backend() {
+ BOOST_LOG_FUNCTION();
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Destructed KSE backend";
+}
+
+void kse_backend::initialize_kse() {
+ if(fKseInitOK)
+ return;
+
+ BOOST_LOG_FUNCTION();
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Initializing KSE backend";
+
+ std::unique_lock<std::mutex> locker(fKSEMutex);
+
+ if(!fSoResolver.ensure_loaded()) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "KSE framework init failure: Fail to load KSE library";
+ fKseInitOK = false;
+ return;
+ }
+
+ try {
+ hal_init_param init_parm = {};
+ int error = fSoResolver.invoke<int>(nullptr, "hal_init", &init_parm);
+
+ if(error != 0) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "KSE framework init failure: " << error;
+ fKseInitOK = false;
+ } else {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "KSE framework initialized";
+ fKseInitOK = true;
+ }
+ } catch(...) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Caught exception when initializing KSE backend";
+ fKseInitOK = false;
+ }
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Dongsun Lee <ds73.lee@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+
+#ifndef KSE_BACKEND_KSEBACKEND_H_
+#define KSE_BACKEND_KSEBACKEND_H_
+
+#include "abstractcryptobackend.h"
+#include "soresolver.h"
+#include <mutex>
+
+
+class kse_backend: public abstract_crypto_backend
+{
+public:
+ kse_backend();
+ virtual ~kse_backend();
+
+ inline so_resolver& get_so_resolver() {
+ return fSoResolver;
+ }
+
+private:
+ void initialize_kse();
+
+private:
+ bool fKseInitOK;
+ std::mutex fKSEMutex;
+ so_resolver fSoResolver;
+};
+
+#endif /* KSE_BACKEND_KSEBACKEND_H_ */
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Dongsun Lee <ds73.lee@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "ksebackendcontext.h"
+#include "logging.h"
+#include "konaise.h"
+#include "cert_utils.h"
+
+#include <mbedtls/asn1write.h>
+#include <mbedtls/error.h>
+#include <mbedtls/pk.h>
+
+#include <boost/algorithm/hex.hpp>
+
+#define PRIVATE_KEY_INDEX 1
+#define SUBCA_CERT_INDEX 2
+#define LEAF_CERT_INDEX 3
+
+static int kse_get_certificate_key = 0;
+static int kse_get_ecdsa_signature_key = 1;
+
+kse_backend_context::kse_backend_context(std::shared_ptr<kse_backend> backend, const std::string& keyType) :
+ fBackendPtr(backend)
+{
+ BOOST_LOG_FUNCTION();
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug)
+ << "Created new KSE with key " << keyType;
+
+ if(keyType.empty() || keyType == "ECDSA") {
+ fKeyType = CRYPTO_KEY_TYPE_ECDSA;
+ } else {
+ throw std::invalid_argument("Unsupported key type");
+ }
+
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug)
+ << "Created new KSE context at " << this;
+}
+
+kse_backend_context::~kse_backend_context()
+{
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug)
+ << "Deleting KSE context " << this;
+}
+
+int kse_backend_context::get_certificate(unsigned int index, std::string& outcert)
+{
+ hal_data cert = {0};
+ const char *method_name = "hal_get_certificate";
+
+ auto backend = fBackendPtr.lock();
+ if(!backend) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error)
+ << "Unable to acquire backend pointer";
+ return -EINVAL;
+ }
+
+ auto& resolver(backend->get_so_resolver());
+ int error = resolver.invoke<int, unsigned int, hal_data *>(&kse_get_certificate_key,
+ method_name, index, &cert);
+ if(error != 0) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error)
+ << "Failed to get certificate. error=" << error;
+ return -EINVAL;
+ }
+
+#ifdef ENABLE_DEBUG_LOGGING
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug)
+ << "KSE: Got certificate with " << cert.data_len
+ << " bytes and index " << index;
+#endif
+ try {
+ outcert.assign((const char *)cert.data, cert.data_len);
+ } catch(...) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error)
+ << "KSE: Got exception when assigning data";
+ free(cert.data);
+ throw;
+ }
+ free(cert.data);
+
+ return 0;
+}
+
+int kse_backend_context::request_certificate_chain(std::string& mutable_chain)
+{
+ BOOST_LOG_FUNCTION();
+#ifdef ENABLE_DEBUG_LOGGING
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug)
+ << "KSE : Request certificate chain";
+#endif
+
+ std::string leaf_cert;
+ std::string subca_cert;
+
+ int error = 0;
+
+ if(error = get_certificate(LEAF_CERT_INDEX, leaf_cert))
+ return error;
+ if(error = get_certificate(SUBCA_CERT_INDEX, subca_cert))
+ return error;
+
+ x509_crt_rewriter cert_writer;
+ if(error = cert_writer.parse(reinterpret_cast<const unsigned char *>(leaf_cert.c_str()),
+ leaf_cert.length()+1)) {
+ return error;
+ }
+ if(error = cert_writer.parse(reinterpret_cast<const unsigned char *>(subca_cert.c_str()),
+ subca_cert.length()+1)) {
+ return error;
+ }
+ cert_writer.sort_chain();
+
+ mutable_chain.append(cert_writer.emit_pem());
+
+#ifdef ENABLE_DEBUG_LOGGING
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug)
+ << "Requested certificate in " << this;
+#endif
+
+ return 0;
+}
+
+int kse_backend_context::sign_crypto_data(MessageDigestType digestType, const std::string& dataToSign,
+ std::string& digestResult)
+{
+ BOOST_LOG_FUNCTION();
+ hal_data hashed_data = { };
+ hal_data signed_data = { };
+
+ hashed_data.data = (void *)dataToSign.c_str();
+ hashed_data.data_len = dataToSign.size();
+
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "KSE: Sign " << hashed_data.data_len << " bytes";
+
+ auto backend = fBackendPtr.lock();
+
+ if(!backend) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Unable to acquire backend pointer";
+ return -EINVAL;
+ }
+
+ auto& resolver(backend->get_so_resolver());
+
+#ifdef ENABLE_DEBUG_LOGGING
+ try {
+ std::string hex;
+ boost::algorithm::hex((const unsigned char *)hashed_data.data,
+ (const unsigned char *)hashed_data.data + hashed_data.data_len,
+ std::back_inserter(hex));
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Hashed data is " << hex;
+ } catch(...) {
+ }
+#endif
+
+ const char *method_name = "hal_ecdsa_sign_md";
+ hal_ecdsa_mode mode = {HAL_ECDSA_SEC_P256R1, HAL_HASH_UNKNOWN};
+
+ int error = resolver.invoke<int, hal_data *, unsigned int, hal_ecdsa_mode *, hal_data *>(
+ &kse_get_ecdsa_signature_key, method_name,
+ &hashed_data, PRIVATE_KEY_INDEX, &mode, &signed_data);
+
+ if(error != 0) {
+ char buffer[256];
+ mbedtls_strerror(error, buffer, sizeof(buffer));
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) <<
+ "Unable to generate ECDSA signature in " <<
+ this <<
+ " (" << error << ") : " <<
+ std::string(buffer);
+
+ return MBEDTLS_ERR_PK_BAD_INPUT_DATA;
+ }
+
+#ifdef ENABLE_DEBUG_LOGGING
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Signature length is " << signed_data.data_len;
+
+ try {
+ std::string hex;
+ boost::algorithm::hex((const unsigned char *)signed_data.data,
+ (const unsigned char *)signed_data.data + signed_data.data_len,
+ std::back_inserter(hex));
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Hex signature is " << hex;
+ } catch(...) {
+ }
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "KSE: Generated ECDSA signature";
+#endif
+
+ digestResult.assign((const char *)signed_data.data, signed_data.data_len);
+
+ free(signed_data.data);
+ return 0;
+}
+
+CryptoKeyType kse_backend_context::key_type()
+{
+ return fKeyType;
+}
+
+unsigned int kse_backend_context::key_length()
+{
+ return 256;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Dongsun Lee <ds73.lee@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef KSE_BACKEND_KSEBACKENDCONTEXT_H_
+#define KSE_BACKEND_KSEBACKENDCONTEXT_H_
+
+#include "abstractcryptobackendcontext.h"
+#include "ksebackend.h"
+
+class kse_backend_context final : public abstract_crypto_backend_context {
+public:
+ kse_backend_context(std::shared_ptr<kse_backend> backend, const std::string& keyType);
+ virtual ~kse_backend_context();
+
+ virtual int request_certificate_chain(std::string& mutable_chain) override;
+
+ virtual int sign_crypto_data(MessageDigestType digestType, const std::string& dataToSign,
+ std::string& digestResult) override;
+
+ virtual CryptoKeyType key_type() override;
+
+ virtual unsigned int key_length() override;
+
+private:
+ int get_certificate(unsigned int index, std::string& cert);
+
+private:
+ CryptoKeyType fKeyType;
+ std::weak_ptr<kse_backend> fBackendPtr;
+};
+
+#endif /* KSE_BACKEND_KSEBACKENDCONTEXT_H_ */
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "soresolver.h"
+#include "logging.h"
+#include <dlfcn.h>
+
+so_resolver::so_resolver(const std::string& libraryName) :
+ fLibraryName(libraryName),
+ fLibraryHandle(nullptr)
+{
+}
+
+so_resolver::~so_resolver()
+{
+ if(fLibraryHandle.load(std::memory_order_relaxed)) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Unloading library " << fLibraryName;
+ dlclose(fLibraryHandle.exchange(nullptr, std::memory_order_relaxed));
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Unloaded library " << fLibraryName;
+ }
+}
+
+void * so_resolver::resolve_function(const int * key_ptr, const char * name) noexcept
+{
+ BOOST_LOG_FUNCTION();
+
+ std::unique_lock<std::mutex> locker(fCacheLock);
+
+ if(key_ptr) {
+ auto it = fCache.find(key_ptr);
+
+ if(it != fCache.end())
+ return it->second;
+ }
+
+ void * handle = fLibraryHandle.load(std::memory_order_relaxed);
+
+ if(handle) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Resolving symbol " << name << " from " << fLibraryName;
+ void * sym = dlsym(handle, name);
+ if(!sym) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Unable to resolve symbol " << name << " from " <<
+ fLibraryName << ": Error is " << dlerror();
+ } else {
+ try {
+ if(key_ptr) {
+ fCache.emplace(key_ptr, sym);
+ }
+ } catch(...) {
+ }
+ }
+ return sym;
+ }
+
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Trying to resolve symbol " << name << " from not loaded library " << fLibraryName;
+
+ return nullptr;
+}
+
+bool so_resolver::ensure_loaded() noexcept
+{
+ BOOST_LOG_FUNCTION();
+
+ std::unique_lock<std::mutex> locker(fCacheLock);
+
+ void * handle = fLibraryHandle.load(std::memory_order_acquire);
+
+ if(handle)
+ return true;
+
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Loading library " << fLibraryName;
+
+ handle = dlopen(fLibraryName.c_str(), RTLD_LAZY | RTLD_LOCAL);
+
+ if(!handle) {
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::error) << "Unable to load library " << fLibraryName << ": " << dlerror();
+ return false;
+ }
+
+ BOOST_LOG_SEV(dcm_logger::get(), log_severity::debug) << "Library loaded " << fLibraryName;
+
+ void * expectedValue = nullptr;
+
+ if(!fLibraryHandle.compare_exchange_strong(expectedValue, handle, std::memory_order_release)) {
+ // Someone else have opened the library
+ dlclose(handle);
+ }
+
+ return true;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef SORESOLVER_H_
+#define SORESOLVER_H_
+
+#include <boost/noncopyable.hpp>
+#include <string>
+#include <atomic>
+#include <stdexcept>
+#include <map>
+#include <mutex>
+
+class so_resolver : public boost::noncopyable {
+public:
+ so_resolver(const std::string& libraryName);
+ ~so_resolver();
+
+ bool ensure_loaded() noexcept;
+ void * resolve_function(const int * key_ptr, const char * name) noexcept;
+
+ template<typename ReturnValue, typename... Args> ReturnValue invoke(const int * __key_ptr, const char * name, Args... args) {
+ typedef ReturnValue (* function_t)(Args...);
+ function_t func = (function_t)resolve_function(__key_ptr, name);
+ if(!func) {
+ throw std::runtime_error("Trying to call unresolved function");
+ }
+ return func(args...);
+ }
+
+private:
+ std::string fLibraryName;
+ std::atomic<void *> fLibraryHandle;
+ std::mutex fCacheLock;
+ std::map<const int *, void *> fCache;
+};
+
+#endif /* SORESOLVER_H_ */
--- /dev/null
+#######################################################################################
+# For SE_KONAI
+
+ADD_DEFINITIONS(-DBOOST_LOG_DYN_LINK)
+include_directories(${Boost_INCLUDE_DIRS})
+link_directories(${Boost_LIBRARY_DIRS})
+
+include_directories(../src ../src/kse-backend)
+
+add_executable(dcm_konaise_tool
+ ../soresolver.cpp
+ konaise_tool.cpp)
+
+target_link_libraries(dcm_konaise_tool
+ ${Boost_LOG_LIBRARY}
+ ${Boost_SYSTEM_LIBRARY}
+ dl
+ ${CMAKE_THREAD_LIBS_INIT}
+)
+
+install(TARGETS dcm_konaise_tool RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
+#######################################################################################
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Dongsun Lee <ds73.lee@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include <iostream>
+#include <fstream>
+#include <vector>
+#include "soresolver.h"
+#include "konaise.h"
+
+#define KSE_LIB_NAME "libkonaise.so"
+
+static int kse_cert_get = 0x00;
+static int kse_cert_add = 0x01;
+static int kse_cert_del = 0x02;
+static int kse_key_get = 0x10;
+static int kse_key_add = 0x11;
+static int kse_key_del = 0x12;
+static int kse_ec_sign = 0x21;
+static int kse_ec_verify= 0x22;
+
+
+typedef enum {
+ /* AES */
+ HAL_KEY_AES_128,// 128 bits aes algorithm
+ HAL_KEY_AES_192, // 192 bits aes algorithm
+ HAL_KEY_AES_256, // 256 bits aes algorithm
+ /* RSA */
+ HAL_KEY_RSA_1024, // 1024 bits rsa algorithm
+ HAL_KEY_RSA_2048, // 2048 bits rsa algorithm
+ HAL_KEY_RSA_3072, // 3072 bits rsa algorithm
+ HAL_KEY_RSA_4096,
+ /* ECC: it doesn't support whole algorithm that mbedTLS support. it's have to be added*/
+ HAL_KEY_ECC_BRAINPOOL_P256R1, // ecc brainpool curve for p256r1
+ HAL_KEY_ECC_BRAINPOOL_P384R1, // ecc brainpool curve for p384r1
+ HAL_KEY_ECC_BRAINPOOL_P512R1, // ecc brainpool curve for p512r1
+ HAL_KEY_ECC_SEC_P256R1, // nist curve for p256r1
+ HAL_KEY_ECC_SEC_P384R1, // nist curve for p384r1
+ HAL_KEY_ECC_SEC_P512R1, // nist curve for p512r1
+ /* Hmac */
+ HAL_KEY_HMAC_MD5, // hmac with md5
+ HAL_KEY_HMAC_SHA1, // hmac with sha1
+ HAL_KEY_HMAC_SHA224, // hmac with sha224
+ HAL_KEY_HMAC_SHA256, // hmac with sha256
+ HAL_KEY_HMAC_SHA384, // hmac with sha384
+ HAL_KEY_HMAC_SHA512, // hmac with sha512
+ /* DH */
+ HAL_KEY_DH_1024,
+ HAL_KEY_DH_2048,
+ HAL_KEY_UNKNOWN,
+} hal_key_type;
+
+
+class SEKonai {
+public:
+ SEKonai(const std::string& libraryName) :
+ fSoResolver(libraryName)
+ {
+ loaded = fSoResolver.ensure_loaded();
+ }
+
+ ~SEKonai(){
+ }
+
+ bool is_loaded() {
+ return loaded;
+ }
+
+ void get_cert(int idx, const std::string& fileName){
+ hal_data cert = {0};
+
+ const char *method_name = "hal_get_certificate";
+ int error = fSoResolver.invoke<int, unsigned int, hal_data *>(&kse_cert_get,
+ method_name, idx, &cert);
+ if(error == 0) {
+ write_file(fileName, cert);
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ }
+
+ void get_key(hal_key_type key_type, int idx, const std::string& fileName) {
+ hal_data data = {0};
+ const char *method_name = "hal_get_key";
+ int error = fSoResolver.invoke<int, hal_key_type, unsigned int, hal_data *>(&kse_key_get,
+ method_name, key_type, idx, &data);
+ if(error == 0) {
+ write_file(fileName, data);
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ }
+
+ void add_cert(const std::string& fileName, int idx) {
+ hal_data *data = read_file(fileName);
+ const char *method_name = "hal_set_certificate";
+ int error = fSoResolver.invoke<int, unsigned int, hal_data *>(&kse_cert_add,
+ method_name, idx, data);
+ if(error == 0) {
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ free_hal_data(data);
+ }
+
+ void add_key(const std::string& fileName, hal_key_type key_type, int idx,
+ const std::string& privFileName) {
+ hal_data *key = read_file(fileName);
+ hal_data *priKey = {0};
+ if(privFileName.size() != 0)
+ priKey = read_file(privFileName);
+ const char *method_name = "hal_set_key";
+ int error = fSoResolver.invoke<int, hal_key_type, unsigned int, hal_data *, hal_data *>(
+ &kse_key_add, method_name, key_type, idx, key, priKey);
+ if(error == 0) {
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ free_hal_data(key);
+ free_hal_data(priKey);
+ }
+
+ void del_cert(int idx) {
+ const char *method_name = "hal_remove_certificate";
+ int error = fSoResolver.invoke<int, unsigned int>(&kse_key_del, method_name, idx);
+ if(error == 0) {
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ }
+
+ void del_key(hal_key_type key_type, int idx) {
+ const char *method_name = "hal_remove_key";
+ int error = fSoResolver.invoke<int, hal_key_type, unsigned int>(&kse_key_del, method_name,
+ key_type, idx);
+ if(error == 0) {
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ }
+
+ void ec_sec_p256r1_sign(std::string hash_file, int key_idx, std::string sig_file) {
+ hal_data *hashed_data = read_file(hash_file);
+ hal_data signed_data = {0};
+
+ const char *method_name = "hal_ecdsa_sign_md";
+ hal_ecdsa_mode mode = {HAL_ECDSA_SEC_P256R1, HAL_HASH_UNKNOWN};
+ int error = fSoResolver.invoke<int, hal_data *,
+ unsigned int, hal_ecdsa_mode *, hal_data *>(
+ &kse_ec_sign, method_name,
+ hashed_data, key_idx, &mode, &signed_data);
+ if(error == 0) {
+ write_file(sig_file, signed_data);
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ free_hal_data(hashed_data);
+ free(signed_data.data);
+ }
+
+ void ec_sec_p256r1_verify(std::string hash_file, int key_idx, std::string sig_file) {
+ // ec_sign hash_file key_index key_type sigfile(out)
+ hal_data *hashed_data = read_file(hash_file);
+ hal_data *signed_data = read_file(sig_file);
+
+ const char *method_name = "hal_ecdsa_verify_md";
+ hal_ecdsa_mode mode = {HAL_ECDSA_SEC_P256R1, HAL_HASH_UNKNOWN};
+ int error = fSoResolver.invoke<int, hal_ecdsa_mode, hal_data *, hal_data *,
+ unsigned int>(
+ &kse_ec_verify, method_name,
+ mode, hashed_data, signed_data, key_idx);
+ if(error == 0) {
+ std::cout << "SUCCEEDED in " << method_name << "." << std::endl;
+ } else {
+ std::cout << "FAILED in " << method_name << ". ERROR=" << error << std::endl;
+ }
+ free_hal_data(hashed_data);
+ free_hal_data(signed_data);
+ }
+
+ hal_key_type get_key_type(const std::string& keyType) {
+ if(keyType.compare("HAL_KEY_AES_128") == 0) return HAL_KEY_AES_128;
+ if(keyType.compare("HAL_KEY_AES_192") == 0) return HAL_KEY_AES_192;
+ if(keyType.compare("HAL_KEY_AES_256") == 0) return HAL_KEY_AES_256;
+ if(keyType.compare("HAL_KEY_RSA_1024") == 0) return HAL_KEY_RSA_1024;
+ if(keyType.compare("HAL_KEY_RSA_2048") == 0) return HAL_KEY_RSA_2048;
+ if(keyType.compare("HAL_KEY_RSA_3072") == 0) return HAL_KEY_RSA_3072;
+ if(keyType.compare("HAL_KEY_RSA_4096") == 0) return HAL_KEY_RSA_4096;
+ if(keyType.compare("HAL_KEY_ECC_BRAINPOOL_P256R1") == 0) return HAL_KEY_ECC_BRAINPOOL_P256R1;
+ if(keyType.compare("HAL_KEY_ECC_BRAINPOOL_P384R1") == 0) return HAL_KEY_ECC_BRAINPOOL_P384R1;
+ if(keyType.compare("HAL_KEY_ECC_BRAINPOOL_P512R1") == 0) return HAL_KEY_ECC_BRAINPOOL_P512R1;
+ if(keyType.compare("HAL_KEY_ECC_SEC_P256R1") == 0) return HAL_KEY_ECC_SEC_P256R1;
+ if(keyType.compare("HAL_KEY_ECC_SEC_P384R1") == 0) return HAL_KEY_ECC_SEC_P384R1;
+ if(keyType.compare("HAL_KEY_ECC_SEC_P512R1") == 0) return HAL_KEY_ECC_SEC_P512R1;
+ if(keyType.compare("HAL_KEY_HMAC_MD5") == 0) return HAL_KEY_HMAC_MD5;
+ if(keyType.compare("HAL_KEY_HMAC_SHA1") == 0) return HAL_KEY_HMAC_SHA1;
+ if(keyType.compare("HAL_KEY_HMAC_SHA224") == 0) return HAL_KEY_HMAC_SHA224;
+ if(keyType.compare("HAL_KEY_HMAC_SHA256") == 0) return HAL_KEY_HMAC_SHA256;
+ if(keyType.compare("HAL_KEY_HMAC_SHA384") == 0) return HAL_KEY_HMAC_SHA384;
+ if(keyType.compare("HAL_KEY_HMAC_SHA512") == 0) return HAL_KEY_HMAC_SHA512;
+ if(keyType.compare("HAL_KEY_DH_1024") == 0) return HAL_KEY_DH_1024;
+ if(keyType.compare("HAL_KEY_DH_2048") == 0) return HAL_KEY_DH_2048;
+ return HAL_KEY_UNKNOWN;
+ }
+
+ std::string get_key_type_str(hal_key_type keyType) {
+ switch(keyType) {
+ case HAL_KEY_AES_128: return std::string("HAL_KEY_AES_128");
+ case HAL_KEY_AES_192: return std::string("HAL_KEY_AES_192");
+ case HAL_KEY_AES_256: return std::string("HAL_KEY_AES_256");
+ case HAL_KEY_RSA_1024: return std::string("HAL_KEY_RSA_1024");
+ case HAL_KEY_RSA_2048: return std::string("HAL_KEY_RSA_2048");
+ case HAL_KEY_RSA_3072: return std::string("HAL_KEY_RSA_3072");
+ case HAL_KEY_RSA_4096: return std::string("HAL_KEY_RSA_4096");
+ case HAL_KEY_ECC_BRAINPOOL_P256R1: return std::string("HAL_KEY_ECC_BRAINPOOL_P256R1");
+ case HAL_KEY_ECC_BRAINPOOL_P384R1: return std::string("HAL_KEY_ECC_BRAINPOOL_P384R1");
+ case HAL_KEY_ECC_BRAINPOOL_P512R1: return std::string("HAL_KEY_ECC_BRAINPOOL_P512R1");
+ case HAL_KEY_ECC_SEC_P256R1: return std::string("HAL_KEY_ECC_SEC_P256R1");
+ case HAL_KEY_ECC_SEC_P384R1: return std::string("HAL_KEY_ECC_SEC_P384R1");
+ case HAL_KEY_ECC_SEC_P512R1: return std::string("HAL_KEY_ECC_SEC_P512R1");
+ case HAL_KEY_HMAC_MD5: return std::string("HAL_KEY_HMAC_MD5");
+ case HAL_KEY_HMAC_SHA1: return std::string("HAL_KEY_HMAC_SHA1");
+ case HAL_KEY_HMAC_SHA224: return std::string("HAL_KEY_HMAC_SHA224");
+ case HAL_KEY_HMAC_SHA256: return std::string("HAL_KEY_HMAC_SHA256");
+ case HAL_KEY_HMAC_SHA384: return std::string("HAL_KEY_HMAC_SHA384");
+ case HAL_KEY_HMAC_SHA512: return std::string("HAL_KEY_HMAC_SHA512");
+ case HAL_KEY_DH_1024: return std::string("HAL_KEY_DH_1024");
+ case HAL_KEY_DH_2048: return std::string("HAL_KEY_DH_2048");
+ default: return std::string("HAL_KEY_UNKNOWN");
+ }
+ }
+
+private:
+ so_resolver fSoResolver;
+ bool loaded;
+
+ void free_hal_data(hal_data *data) {
+ if(data == NULL)
+ return;
+ if(data->data != NULL)
+ free(data->data);
+ free(data);
+ }
+
+ void write_file(const std::string& fileName, hal_data in) {
+ std::fstream outfile;
+ outfile = std::fstream(fileName, std::ios::out | std::ios::binary);
+ outfile.write((char*)in.data, in.data_len);
+ outfile.close();
+ }
+
+ hal_data* read_file(const std::string& fileName) {
+ if(fileName.size() == 0)
+ return NULL;
+ std::ifstream input(fileName, std::ios::binary);
+ std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
+ unsigned char* data = (unsigned char*) malloc(buffer.size());
+ for(unsigned int i = 0; i < buffer.size(); i++)
+ data[i] = buffer[i];
+ hal_data *ret = (hal_data *) malloc(sizeof(hal_data));
+ ret->data = data;
+ ret->data_len = buffer.size();
+ ret->priv = NULL;
+ return ret;
+ }
+};
+
+void print_usage(char *prog_name) {
+ std::cout << prog_name << " command opt1 opt2 . . . " << std::endl;
+ std::cout << " example: " << prog_name << " get_cert index outfile" << std::endl;
+ std::cout << " example: " << prog_name << " add_cert infile index" << std::endl;
+ std::cout << " example: " << prog_name << " del_cert index" << std::endl;
+ std::cout << " example: " << prog_name << " get_key key_type index outfile" << std::endl;
+ std::cout << " example: " << prog_name << " add_key infile key_type index in_privfile"<<std::endl;
+ std::cout << " example: " << prog_name << " del_key key_type index" << std::endl;
+ std::cout << " example: " << prog_name << " ec_sec_p256r1_sign hash_file key_idx sigfile(out)" << std::endl;
+ std::cout << " example: " << prog_name << " ec_sec_p256r1_verify hash_file key_idx sigfile(in)" << std::endl;
+}
+
+int main(int argc, char ** argv)
+{
+ if(argc < 2) {
+ print_usage(argv[0]);
+ return -1;
+ }
+
+ SEKonai se(KSE_LIB_NAME);
+ if(!se.is_loaded()) {
+ std::cout << "LIBRARY WAS NOT LOADED!!" << std::endl;
+ return -1;
+ }
+ std::string cmd(argv[1]);
+
+ if((cmd.compare("get_cert") == 0) && argc > 3) {
+ se.get_cert(std::stoi(argv[2]), std::string(argv[3]));
+ }else if((cmd.compare("add_cert") == 0) && argc > 3) {
+ se.add_cert(std::string(argv[2]), std::stoi(argv[3]));
+ }else if((cmd.compare("del_cert") == 0) && argc > 2) {
+ se.del_cert(std::stoi(argv[2]));
+ }else if((cmd.compare("get_key") == 0) && argc > 4) {
+ se.get_key(se.get_key_type(std::string(argv[2])),
+ std::stoi(argv[3]), std::string(argv[4]));
+ }else if((cmd.compare("add_key") == 0) && argc >= 5) {
+ char * priv_file = nullptr;
+ if(argc > 5)
+ priv_file = argv[5];
+ se.add_key(std::string(argv[2]), se.get_key_type(std::string(argv[3])),
+ std::stoi(argv[4]), std::string(priv_file));
+ }else if((cmd.compare("del_key") == 0) && argc > 3) {
+ se.del_key(se.get_key_type(std::string(argv[2])), std::stoi(argv[3]));
+ }else if((cmd.compare("ec_sec_p256r1_sign") == 0) && argc > 4) {
+ se.ec_sec_p256r1_sign(std::string(argv[2]), std::stoi(argv[3]),
+ std::string(argv[4]));
+ }else if((cmd.compare("ec_sec_p256r1_verify") == 0) && argc > 4) {
+ se.ec_sec_p256r1_verify(std::string(argv[2]), std::stoi(argv[3]),
+ std::string(argv[4]));
+ }else {
+ print_usage(argv[0]);
+ return -1;
+ }
+
+ return 0;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2017 - 2019 Samsung Electronics All Rights Reserved.
+ *
+ * Author: Jaroslaw Pelczar <j.pelczar@samsung.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#ifndef LOGGING_H_
+#define LOGGING_H_
+
+#include <boost/log/common.hpp>
+#include <boost/log/expressions.hpp>
+#include <boost/log/attributes.hpp>
+#include <boost/log/sinks/sync_frontend.hpp>
+#include <boost/log/sinks/syslog_backend.hpp>
+#include <boost/log/sources/logger.hpp>
+#include <boost/log/utility/setup/console.hpp>
+#include <boost/log/utility/setup/common_attributes.hpp>
+#include <boost/log/attributes/timer.hpp>
+#include <boost/log/attributes/named_scope.hpp>
+
+#ifdef USE_DLOG_LOGGING
+#define LOG_TAG "DEVICE_CERTIFICATE_MANAGER_SERVER"
+#include <dlog.h>
+#endif
+
+enum class log_severity {
+ debug,
+ normal,
+ warning,
+ error
+};
+
+// Global logger declaration
+BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(dcm_logger, boost::log::sources::severity_logger_mt<log_severity>)
+
+#if defined(NDEBUG) && !defined(DEBUG)
+#else
+#define ENABLE_DEBUG_LOGGING 1
+#endif
+
+#endif /* LOGGING_H_ */