tizen 2.4 release accepted/tizen_2.4_mobile accepted/tizen/2.4/mobile/20151029.032142 submit/tizen_2.4/20151028.064535 tizen_2.4_mobile_release
authorjk7744.park <jk7744.park@samsung.com>
Sat, 24 Oct 2015 08:01:25 +0000 (17:01 +0900)
committerjk7744.park <jk7744.park@samsung.com>
Sat, 24 Oct 2015 08:01:25 +0000 (17:01 +0900)
89 files changed:
CMakeLists.txt
build/key-manager.pc.in
data/scripts/migrate_1.sql
data/scripts/migrate_2.sql
doc/images/capi_key_manager_overview_diagram.png [moved from doc/wearable/images/capi_key_manager_overview_diagram.png with 100% similarity]
doc/key-manager-client_doc.h [moved from doc/wearable/key-manager-client_doc.h with 100% similarity]
doc/key-manager-control_doc.h [moved from doc/wearable/key-manager-control_doc.h with 99% similarity]
doc/key-manager-types_doc.h [moved from doc/wearable/key-manager-types_doc.h with 100% similarity]
doc/key-manager_doc.h [moved from doc/mobile/key-manager_doc.h with 92% similarity]
doc/mobile/images/capi_key_manager_overview_diagram.png [deleted file]
doc/mobile/key-manager-client_doc.h [deleted file]
doc/mobile/key-manager-control_doc.h [deleted file]
doc/mobile/key-manager-types_doc.h [deleted file]
doc/wearable/key-manager_doc.h [deleted file]
packaging/key-manager-listener.manifest [deleted file]
packaging/key-manager.manifest
packaging/key-manager.spec
src/CMakeLists.txt
src/include/ckm/ckm-client-info.h [new file with mode: 0644]
src/include/ckm/ckm-control.h
src/include/ckm/ckm-error.h
src/include/ckm/ckm-type.h
src/include/ckmc/ckmc-control.h
src/include/ckmc/ckmc-error.h
src/include/ckmc/ckmc-manager.h
src/include/ckmc/ckmc-type.h
src/listener/CMakeLists.txt [deleted file]
src/listener/listener-daemon.cpp [deleted file]
src/manager/CMakeLists.txt
src/manager/client-capi/ckmc-control.cpp
src/manager/client-capi/ckmc-manager.cpp
src/manager/client-capi/ckmc-type-converter.cpp
src/manager/client-capi/ckmc-type-converter.h
src/manager/client-capi/ckmc-type.cpp
src/manager/client/client-control.cpp
src/manager/client/client-manager-impl.cpp
src/manager/client/client-manager-impl.h
src/manager/common/client-info-impl.cpp [new file with mode: 0644]
src/manager/common/key-impl.cpp
src/manager/common/key-impl.h
src/manager/common/protocols.cpp
src/manager/common/protocols.h
src/manager/dpl/core/include/dpl/serialization.h
src/manager/dpl/core/src/exception.cpp
src/manager/dpl/db/src/sql_connection.cpp
src/manager/dpl/log/src/log.cpp
src/manager/listener/listener-thread.cpp [new file with mode: 0644]
src/manager/listener/listener-thread.h [moved from src/manager/main/smack-check.h with 50% similarity]
src/manager/main/generic-socket-manager.h
src/manager/main/key-manager-main.cpp
src/manager/main/smack-check.cpp [deleted file]
src/manager/main/socket-manager.cpp
src/manager/main/socket-manager.h
src/manager/service/CryptoService.cpp
src/manager/service/CryptoService.h
src/manager/service/access-control.cpp
src/manager/service/certificate-store.cpp
src/manager/service/ckm-logic.cpp
src/manager/service/ckm-logic.h
src/manager/service/ckm-service.cpp
src/manager/service/crypto-logic.cpp
src/manager/service/crypto-logic.h
src/manager/service/db-crypto.cpp
src/manager/service/digest.cpp
src/manager/service/file-lock.cpp
src/manager/service/file-system.cpp
src/manager/service/file-system.h
src/manager/service/key-provider.cpp
src/manager/service/key-provider.h
src/manager/service/ocsp-logic.cpp
src/manager/service/ocsp-logic.h
src/manager/service/ocsp.cpp
src/manager/sqlcipher/sqlcipher.c
src/plugin/password-plugin.cpp
systemd/CMakeLists.txt
systemd/central-key-manager-api-control.socket
systemd/central-key-manager-api-ocsp.socket
systemd/central-key-manager-api-storage.socket
systemd/central-key-manager-listener.service [deleted file]
systemd/central-key-manager.service.in
systemd/central-key-manager.target [deleted file]
tests/CMakeLists.txt
tests/main_lcov.cpp [new file with mode: 0644]
tests/test_db_crypto.cpp
tests/test_lcov_certificate-impl.cpp [new file with mode: 0644]
tests/test_lcov_ckmc-type-converter.cpp [new file with mode: 0644]
tests/test_lcov_client-error.cpp [new file with mode: 0644]
tests/test_lcov_key-impl.cpp [new file with mode: 0644]
tools/ckm_so_loader.cpp

index b968db6..c2c1511 100644 (file)
@@ -58,15 +58,15 @@ IF (CMAKE_BUILD_TYPE MATCHES "DEBUG")
     ADD_DEFINITIONS("-DBUILD_TYPE_DEBUG")
 ENDIF (CMAKE_BUILD_TYPE MATCHES "DEBUG")
 
-IF (PROFILE_TARGET MATCHES "WEARABLE")
-    MESSAGE("PROFILE_TARGET_WEARABLE DEFINED")
-    ADD_DEFINITIONS("-DPROFILE_TARGET_WEARABLE")
-ENDIF (PROFILE_TARGET MATCHES "WEARABLE")
+IF (DEFINED PASSWORD_PROTECTION_DISABLE)
+    MESSAGE("PASSWORD_PROTECTION_DISABLE ENABLED !")
+    ADD_DEFINITIONS("-DPASSWORD_PROTECTION_DISABLE")
+ENDIF (DEFINED PASSWORD_PROTECTION_DISABLE)
 
-IF (FORM_FACTOR MATCHES "CIRCLE")
-    MESSAGE("FORM_FACTOR_CIRCLE DEFINED")
-    ADD_DEFINITIONS("-DFORM_FACTOR_CIRCLE")
-ENDIF (FORM_FACTOR MATCHES "CIRCLE")
+IF (DEFINED DB_PER_ZONE_ENABLE)
+    MESSAGE("DB_PER_ZONE ENABLED !")
+    ADD_DEFINITIONS("-DDB_PER_ZONE_ENABLE")
+ENDIF (DEFINED DB_PER_ZONE_ENABLE)
 
 IF (DEFINED SYSTEMD_ENV_FILE)
     ADD_DEFINITIONS(-DSYSTEMD_ENV_FILE="${SYSTEMD_ENV_FILE}")
@@ -80,6 +80,7 @@ SET(TARGET_LISTENER "key-manager-listener")
 SET(TARGET_PASSWORD_PLUGIN "security-server-plugin")
 
 SET(TARGET_TEST_MERGED "ckm-tests-internal")
+SET(TARGET_TEST_LCOV "ckm-tests-lcov-internal")
 
 INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/data/scripts/230.key-manager-migrate-dkek.patch.sh
     DESTINATION /etc/opt/upgrade
@@ -90,5 +91,8 @@ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/data/scripts/230.key-manager-migrate-d
 ADD_SUBDIRECTORY(src)
 ADD_SUBDIRECTORY(build)
 ADD_SUBDIRECTORY(systemd)
+
+IF (DEFINED CKM_BUILD_INTERNAL_TEST)
 ADD_SUBDIRECTORY(tests)
 ADD_SUBDIRECTORY(tools)
+ENDIF (DEFINED CKM_BUILD_INTERNAL_TEST)
index 4867073..e3c8834 100644 (file)
@@ -6,6 +6,6 @@ includedir=${prefix}/include
 Name: key-manager
 Description: Central Key Manager Package
 Version: @VERSION@
-Requires: openssl libsmack
+Requires: openssl
 Libs: -L${libdir} -lkey-manager-client -lkey-manager-common -lkey-manager-control-client
 Cflags: -I${includedir}/ckm
index 39e2d70..1ced1dd 100644 (file)
@@ -24,6 +24,7 @@
 -- isolate old data
 ALTER TABLE PERMISSION_TABLE RENAME TO OLD_PERMISSION_TABLE;
 DROP INDEX perm_index_idx;
+DROP INDEX ckm_index_label;
 
 
 -- create new structure
index 5c629fe..8bd2fd2 100644 (file)
 
 -- isolate old data
 DROP INDEX perm_index_idx;
+DROP INDEX name_index_idx;
 
 
 -- create new structure
 CREATE TABLE SCHEMA_INFO(name TEXT PRIMARY KEY NOT NULL,
                          value TEXT);
 ALTER TABLE NAME_TABLE RENAME TO NAMES;
+CREATE INDEX name_index_idx ON NAMES(idx);
 -- need to create OBJECT table from scratch,
 -- as SQLite does not support "ALTER COLUMN"
 -- (REFERENCES NAME_TABLE --> NAMES)
similarity index 99%
rename from doc/wearable/key-manager-control_doc.h
rename to doc/key-manager-control_doc.h
index 8c42b39..70675d8 100644 (file)
@@ -16,7 +16,6 @@
 #ifndef __TIZEN_CORE_KEY_MANAGER_CONTROL_DOC_H__
 #define __TIZEN_CORE_KEY_MANAGER_CONTROL_DOC_H__
 /**
- * @internal
  * @ingroup CAPI_KEY_MANAGER_MODULE
  * @defgroup CAPI_KEY_MANAGER_CONTROL_MODULE Key Manager Control
  * @brief    These APIs control the key manager state (Unlocked/Locked) and reflects the user's password change.
similarity index 92%
rename from doc/mobile/key-manager_doc.h
rename to doc/key-manager_doc.h
index 9c2723d..81e2979 100644 (file)
@@ -73,9 +73,7 @@
  * Alias Format
  *   - The format of alias is "package_id name".
  *   - If package_id is not provided by a client, the key-manager will add the package_id of the client to the name internally.
- *   - Alias should not include whitespace except the case of using as delimiter between package_id and name.
- *   - If the client use "package_id name" format of alias when saving something in key-manager, the client should use package_id of the client itself.
-       If the client doesn't, key-manager will return error code related to input parameter error.
+ *   - The client can specify only its own package id in the alias when storing a key, certificate, or data.
  *   - A client should specify the package id of the owner in the alias to retrieve a a key, certificate, or data shared by other applications.
  *   - Aliases are returned as the format of "package_id name" from the key-manager.
  *
diff --git a/doc/mobile/images/capi_key_manager_overview_diagram.png b/doc/mobile/images/capi_key_manager_overview_diagram.png
deleted file mode 100755 (executable)
index 9453909..0000000
Binary files a/doc/mobile/images/capi_key_manager_overview_diagram.png and /dev/null differ
diff --git a/doc/mobile/key-manager-client_doc.h b/doc/mobile/key-manager-client_doc.h
deleted file mode 100644 (file)
index 25d2084..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2014 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.
- */
-#ifndef __TIZEN_CORE_KEY_MANAGER_CLIENT_DOC_H__
-#define __TIZEN_CORE_KEY_MANAGER_CLIENT_DOC_H__
-/**
- * @ingroup CAPI_KEY_MANAGER_MODULE 
- * @defgroup CAPI_KEY_MANAGER_CLIENT_MODULE Key Manager Client
- * @brief    It provides APIs accessing on the secure repository and additional secure cryptographic operations.
- *
- * @section CAPI_KEY_MANAGER_CLIENT_MODULE_HEADER Required Header
- * \#include <ckmc/ckmc-manager.h>
- *
- * @section CAPI_KEY_MANAGER_CLIENT_MODULE_OVERVIEW Overview
- * It provides APIs for storing, getting, and removing APIs for keys, certificates, and sensitive data on/from the Key Manager secure repository which is protected by a user’s passwords.
- * Additionally, it provides secure cryptographic operations for non-exportable keys without revealing key values to clients.
- */
-
-#endif /* __TIZEN_CORE_KEY_MANAGER_CLIENT_DOC_H__ */
diff --git a/doc/mobile/key-manager-control_doc.h b/doc/mobile/key-manager-control_doc.h
deleted file mode 100644 (file)
index 8c42b39..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2014 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.
- */
-#ifndef __TIZEN_CORE_KEY_MANAGER_CONTROL_DOC_H__
-#define __TIZEN_CORE_KEY_MANAGER_CONTROL_DOC_H__
-/**
- * @internal
- * @ingroup CAPI_KEY_MANAGER_MODULE
- * @defgroup CAPI_KEY_MANAGER_CONTROL_MODULE Key Manager Control
- * @brief    These APIs control the key manager state (Unlocked/Locked) and reflects the user's password change.
- *
- * @section CAPI_KEY_MANAGER_CONTROL_MODULE_HEADER Required Header
- * \#include <ckmc/ckmc-control.h>
- *
- * @section CAPI_KEY_MANAGER_CONTROL_MODULE_OVERVIEW Overview
- * It provides APIs encrypting, decrypting, and re-encrypting a DKEK (with which a user's data file is encrypted).
- * When a user logs in for the first time, the DKEK will be generated randomly.
- */
-
-#endif /* __TIZEN_CORE_KEY_MANAGER_CONTROL_DOC_H__ */
diff --git a/doc/mobile/key-manager-types_doc.h b/doc/mobile/key-manager-types_doc.h
deleted file mode 100644 (file)
index c13d822..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2014 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.
- */
-#ifndef __TIZEN_CORE_KEY_MANAGER_TYPES_DOC_H__
-#define __TIZEN_CORE_KEY_MANAGER_TYPES_DOC_H__
-/**
- * @ingroup CAPI_KEY_MANAGER_MODULE
- * @defgroup CAPI_KEY_MANAGER_TYPES_MODULE Key Manager Data Types
- * @brief    It defines data types used in these APIs and provides utility methods handling them.
- *
- * @section CAPI_KEY_MANAGER_TYPES_MODULE_HEADER Required Header
- * \#include <ckmc/ckmc-type.h>
- *
- * @section CAPI_KEY_MANAGER_TYPES_MODULE_OVERVIEW Overview
- * It defines data types for key, certificate,raw buffer, and linked list used in these APIs.
- * It also provides new and free methods for them.
- *
- */
-
-#endif /* __TIZEN_CORE_KEY_MANAGER_TYPES_DOC_H__ */
diff --git a/doc/wearable/key-manager_doc.h b/doc/wearable/key-manager_doc.h
deleted file mode 100644 (file)
index 9c2723d..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (c) 2014 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.
- */
-#ifndef __TIZEN_CORE_KEY_MANAGER_DOC_H__
-#define __TIZEN_CORE_KEY_MANAGER_DOC_H__
-/**
- * @ingroup CAPI_SECURITY_FRAMEWORK
- * @defgroup CAPI_KEY_MANAGER_MODULE Key Manager
- * @brief    The key manager provides a secure repository protected by a user’s passwords for keys, certificates, and sensitive data of users and/or their APPs. 
- *           Additionally, the key manager provides secure cryptographic operations for non-exportable keys without revealing key values to clients.
- *
- * @section CAPI_KEY_MANAGER_MODULE_OVERVIEW Overview
- * <table>
- *   <tr><th>API</th><th>Description</th></tr>
- *   <tr>
- *     <td> @ref CAPI_KEY_MANAGER_CLIENT_MODULE</td>
- *     <td> Provides APIs for accessing the secure repository and additional secure cryptographic operations.</td>
- *   </tr>
- *   <tr>
- *     <td> @ref CAPI_KEY_MANAGER_TYPES_MODULE</td>
- *     <td> Defines data types used in these APIs and provides utility methods handling them.</td>
- *   </tr>
- * </table>
- *
- * It provides a secure repository for keys, certificates, and sensitive data of users and/or their APPs which are protected by a user’s passwords.
- * Additionally, it provides secure cryptographic operations for non-exportable keys without revealing key values to clients.
- *
- * @image html capi_key_manager_overview_diagram.png
- *
- * The key manager provides 2 types of API.
- * - secure repository APIs : These APIs provides storing, retrieving, and removing functions for keys, certificates, and data.
- * - secure crypto APIs : These APIs provides additional cryptographic operations (create asymmetric key pair, sign/verify signature, verify certificate).
- *
- * Data Store Policy:
- *   A client can specify simple access rules when storing a data in Key Manager.
- *   - Exportable/Non-Exportable:
- *     Only for data tagged as exportable, Key Manager returns the raw value of the data.
- *     If data is tagged as non-exportable, Key Manager does not return its raw value. 
- *     In that case, Key Manager provides secure cryptographic operations for non-exportable keys without revealing key values to clients.
- *   - Per Key Password:
- *     All data in Key Manager is protected by a user’s password.
- *     Besides, a client can encrypt its data using its own password additionally.
- *     If a client provides a password when storing a data, the data will be encrypted with the password. 
- *     This password should be provided when get the data from Key Manager.
- *
- * User Login/Logout and Data Protection
- *   - When a user logs in, logs out or changes his/her password, Key Manager should know about it.
- *     Privileged APPs such as LockScreen APP or Setting APP can notify the key manager using these control APIs.
- *   - When a user logs in, the key manager decrypts the user's DKEK (with which a user's data file is encrypted) with a user password.
- *     So during the login period, any client can access its data which is protected by a user's password.
- *     "user key" in API means DKEK.
- *   - When a user logs out, the key manager removes the user's DKEK from memory.
- *     Therefore, clients cannot access any data.
- *   - When a user changes his/her password, the key manager re-encrypts the user's DKEK with the new password.
- *
- * Data Access Control
- *   - By default, only the owner of a data can access to the data.
- *   - If the owner grants the access to other applications, those applications can read or delete the data from key-manager DB.
- *   - When an application is deleted, the data and access control information granted by the application are also removed.
- *
- * Alias Format
- *   - The format of alias is "package_id name".
- *   - If package_id is not provided by a client, the key-manager will add the package_id of the client to the name internally.
- *   - Alias should not include whitespace except the case of using as delimiter between package_id and name.
- *   - If the client use "package_id name" format of alias when saving something in key-manager, the client should use package_id of the client itself.
-       If the client doesn't, key-manager will return error code related to input parameter error.
- *   - A client should specify the package id of the owner in the alias to retrieve a a key, certificate, or data shared by other applications.
- *   - Aliases are returned as the format of "package_id name" from the key-manager.
- *
- */
-
-#endif /* __TIZEN_CORE_KEY_MANAGER_DOC_H__ */
diff --git a/packaging/key-manager-listener.manifest b/packaging/key-manager-listener.manifest
deleted file mode 100644 (file)
index c3b5d51..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-<manifest>
-       <define>
-               <domain name="key-manager-listener" />
-               <request>
-                       <smack request="pkgmgr::info" type="r" />
-                       <smack request="pkgmgr::db" type="rlx" />
-                       <smack request="ail::db" type="rlx" />
-               </request>
-       </define>
-       <request>
-               <domain name="key-manager-listener" />
-       </request>
-</manifest>
index 195c0a5..9e277de 100644 (file)
@@ -3,15 +3,27 @@
                <domain name="key-manager"/>
                <request>
                        <smack request="system::use_internet" type="w"/>
+                       <smack request="device::app_logging" type="rw"/>
+                       <smack request="device::sys_logging" type="rw"/>
+                       <smack request="security-server" type="rx"/>
+                       <smack request="sys-assert::core" type="rwxat"/>
+                       <smack request="pkgmgr::info" type="r" />
+                       <smack request="pkgmgr::db" type="rlx" />
+                       <smack request="key-manager::api-control" type="w"/>
+                       <smack request="ca-certificates::ssl-certs" type="rx"/>
+                       <smack request="systemd" type="rx"/>
+                       <smack request="connman" type="w"/>
                </request>
                <permit>
                        <smack permit="system::use_internet" type="w"/>
+                       <smack permit="connman" type="w"/>
                </permit>
        </define>
        <request>
                <domain name="key-manager" />
        </request>
        <assign>
-               <filesystem path="/etc/opt/upgrade/230.key-manager-migrate-dkek.patch.sh" label="_" exec_label="_"/>
+               <filesystem path="/etc/opt/upgrade/230.key-manager-migrate-dkek.patch.sh" label="_" exec_label="none"/>
+               <filesystem path="/opt/data/ckm" label="key-manager" type="transmutable"/>
        </assign>
 </manifest>
index 1d7728a..7a99765 100644 (file)
@@ -1,3 +1,5 @@
+%define ckm_build_internal_test 0
+
 Name:       key-manager
 Summary:    Central Key Manager and utilities
 Version:    0.1.13
@@ -6,20 +8,16 @@ Group:      System/Security
 License:    Apache-2.0 and BSL-1.0 and PD
 Source0:    %{name}-%{version}.tar.gz
 Source1001: key-manager.manifest
-Source1002: key-manager-listener.manifest
-Source1003: libkey-manager-client.manifest
-Source1004: libkey-manager-common.manifest
+Source1002: libkey-manager-client.manifest
+Source1003: libkey-manager-common.manifest
 BuildRequires: cmake
-BuildRequires: zip
-BuildRequires: pkgconfig(dlog)
 BuildRequires: pkgconfig(openssl)
-BuildRequires: libattr-devel
-BuildRequires: pkgconfig(libsmack)
 BuildRequires: pkgconfig(libsystemd-daemon)
-BuildRequires: pkgconfig(libsystemd-journal)
+BuildRequires: pkgconfig(vasum)
+BuildRequires: pkgconfig(capi-system-info)
 BuildRequires: boost-devel
-BuildRequires: pkgconfig(security-server)
-BuildRequires: model-build-features
+BuildRequires: pkgconfig(glib-2.0)
+BuildRequires: pkgconfig(pkgmgr)
 Requires: libkey-manager-common = %{version}-%{release}
 Requires(post): /sbin/ldconfig
 Requires(postun): /sbin/ldconfig
@@ -30,23 +28,13 @@ Central Key Manager daemon could be used as secure storage
 for certificate and private/public keys. It gives API for
 application to sign and verify (DSA/RSA/ECDSA) signatures.
 
-%package -n key-manager-listener
-License:    Apache-2.0
-Summary:    Package with listener daemon
-Group:      System/Security
-BuildRequires: pkgconfig(glib-2.0)
-BuildRequires: pkgconfig(capi-appfw-package-manager)
-Requires:   libkey-manager-client = %{version}-%{release}
-
-%description -n key-manager-listener
-Listener for central key manager. This daemon is responsible for
-receive notification from dbus about uninstall application
-and pass them to key-manager daemon.
-
 %package -n libkey-manager-common
 License:    Apache-2.0
 Summary:    Central Key Manager (common libraries)
 Group:      Development/Libraries
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(libcrypto)
+BuildRequires: pkgconfig(libsystemd-journal)
 Requires(post): /sbin/ldconfig
 Requires(postun): /sbin/ldconfig
 
@@ -57,6 +45,8 @@ Central Key Manager package (common library)
 License:    Apache-2.0
 Summary:    Central Key Manager (client)
 Group:      Development/Libraries
+BuildRequires: pkgconfig(capi-base-common)
+BuildRequires: pkgconfig(security-server)
 Requires:   key-manager = %{version}-%{release}
 Requires:   libkey-manager-common = %{version}-%{release}
 Requires(post): /sbin/ldconfig
@@ -70,44 +60,52 @@ License:    Apache-2.0
 Summary:    Central Key Manager (client-devel)
 Group:      Development/Libraries
 BuildRequires: pkgconfig(capi-base-common)
-Requires:   pkgconfig(capi-base-common)
 Requires:   libkey-manager-client = %{version}-%{release}
 
 %description -n libkey-manager-client-devel
 Central Key Manager package (client-devel)
 
+%if 0%{?ckm_build_internal_test}
 %package -n key-manager-tests
 License:    Apache-2.0 and BSL-1.0
 Summary:    Internal test for key-manager
 Group:      Development
-Requires:   boost-test
+BuildRequires: boost-test
 Requires:   key-manager = %{version}-%{release}
 
 %description -n key-manager-tests
 Internal test for key-manager implementation.
+%endif
 
 %prep
 %setup -q
 cp -a %{SOURCE1001} .
 cp -a %{SOURCE1002} .
 cp -a %{SOURCE1003} .
-cp -a %{SOURCE1004} .
 
 %build
 export CFLAGS="$CFLAGS -DTIZEN_DEBUG_ENABLE"
 export CXXFLAGS="$CXXFLAGS -DTIZEN_DEBUG_ENABLE"
 export FFLAGS="$FFLAGS -DTIZEN_DEBUG_ENABLE"
+
 export LDFLAGS+="-Wl,--rpath=%{_libdir},-Bsymbolic-functions "
 
+# password protection enabled
+%define ckm_password_protection_disable 0
+# zone disabled on 2.4
+%define ckm_db_per_zone_enable 0
 
 %cmake . -DVERSION=%{version} \
         -DCMAKE_BUILD_TYPE=%{?build_type:%build_type}%{!?build_type:RELEASE} \
         -DCMAKE_VERBOSE_MAKEFILE=ON \
-%if "%{?tizen_profile_name}" == "wearable"
-        -DPROFILE_TARGET=WEARABLE \
+%if 0%{?ckm_password_protection_disable}
+        -DPASSWORD_PROTECTION_DISABLE=1 \
 %endif
-%if "%{?model_build_feature_formfactor}" == "circle"
-        -DFORM_FACTOR=CIRCLE \
+%if 0%{?ckm_db_per_zone_enable}
+        -DDB_PER_ZONE_ENABLE=1 \
+%endif
+%if 0%{?ckm_build_internal_test}
+        -DCKM_BUILD_INTERNAL_TEST=1 \
 %endif
         -DSYSTEMD_UNIT_DIR=%{_unitdir} \
         -DSYSTEMD_ENV_FILE="/etc/sysconfig/central-key-manager"
@@ -121,21 +119,23 @@ cp LICENSE %{buildroot}/usr/share/license/%{name}
 cp LICENSE.BSL-1.0 %{buildroot}/usr/share/license/%{name}.BSL-1.0
 cp LICENSE %{buildroot}/usr/share/license/libkey-manager-client
 cp LICENSE %{buildroot}/usr/share/license/libkey-manager-control-client
-mkdir -p %{buildroot}/etc/security/
 mkdir -p %{buildroot}/usr/share/ckm/scripts
 cp data/scripts/*.sql %{buildroot}/usr/share/ckm/scripts
+
+%if 0%{?ckm_build_internal_test}
 mkdir -p %{buildroot}/usr/share/ckm-db-test
 cp tests/testme_ver1.db %{buildroot}/usr/share/ckm-db-test/
 cp tests/testme_ver2.db %{buildroot}/usr/share/ckm-db-test/
+%endif
 
 %make_install
 mkdir -p %{buildroot}%{_unitdir}/multi-user.target.wants
 mkdir -p %{buildroot}%{_unitdir}/sockets.target.wants
 ln -s ../central-key-manager.service %{buildroot}%{_unitdir}/multi-user.target.wants/central-key-manager.service
-ln -s ../central-key-manager-listener.service %{buildroot}%{_unitdir}/multi-user.target.wants/central-key-manager-listener.service
 ln -s ../central-key-manager-api-control.socket %{buildroot}%{_unitdir}/sockets.target.wants/central-key-manager-api-control.socket
 ln -s ../central-key-manager-api-storage.socket %{buildroot}%{_unitdir}/sockets.target.wants/central-key-manager-api-storage.socket
 ln -s ../central-key-manager-api-ocsp.socket %{buildroot}%{_unitdir}/sockets.target.wants/central-key-manager-api-ocsp.socket
+mkdir -p %{buildroot}/opt/data/ckm
 
 %clean
 rm -rf %{buildroot}
@@ -175,35 +175,13 @@ fi
 
 %postun -n libkey-manager-common -p /sbin/ldconfig
 
-%post -n key-manager-listener
-systemctl daemon-reload
-if [ $1 = 1 ]; then
-    # installation
-    systemctl start central-key-manager-listener.service
-fi
-if [ $1 = 2 ]; then
-    # update
-    systemctl restart central-key-manager-listener.service
-fi
-
-%preun -n key-manager-listener
-if [ $1 = 0 ]; then
-    # unistall
-    systemctl stop central-key-manager-listener.service
-fi
-
-%postun -n key-manager-listener
-if [ $1 = 0 ]; then
-    # unistall
-    systemctl daemon-reload
-fi
 
 %files -n key-manager
 %manifest key-manager.manifest
+%defattr(-,system,system,-)
 %{_bindir}/key-manager
 %{_unitdir}/multi-user.target.wants/central-key-manager.service
 %{_unitdir}/central-key-manager.service
-%{_unitdir}/central-key-manager.target
 %{_unitdir}/sockets.target.wants/central-key-manager-api-control.socket
 %{_unitdir}/central-key-manager-api-control.socket
 %{_unitdir}/sockets.target.wants/central-key-manager-api-storage.socket
@@ -212,22 +190,18 @@ fi
 %{_unitdir}/central-key-manager-api-ocsp.socket
 %{_datadir}/license/%{name}
 %{_datadir}/license/%{name}.BSL-1.0
-%{_datadir}/ckm/scripts/*.sql
-%attr(444, root, root) %{_datadir}/ckm/scripts/*.sql
+%attr(444, system, system) %{_datadir}/ckm/scripts/*.sql
 /etc/opt/upgrade/230.key-manager-migrate-dkek.patch.sh
-
-%files -n key-manager-listener
-%manifest key-manager-listener.manifest
-%{_bindir}/key-manager-listener
-%{_unitdir}/multi-user.target.wants/central-key-manager-listener.service
-%{_unitdir}/central-key-manager-listener.service
+%attr(700, system, system) /opt/data/ckm
 
 %files -n libkey-manager-common
 %manifest libkey-manager-common.manifest
+%defattr(-,system,system,-)
 %{_libdir}/libkey-manager-common.so.*
 
 %files -n libkey-manager-client
 %manifest libkey-manager-client.manifest
+%defattr(-,system,system,-)
 %{_libdir}/libkey-manager-client.so.*
 %{_libdir}/libkey-manager-control-client.so.*
 %{_libdir}/libsecurity-server-plugin.so*
@@ -235,7 +209,7 @@ fi
 %{_datadir}/license/libkey-manager-control-client
 
 %files -n libkey-manager-client-devel
-%defattr(-,root,root,-)
+%defattr(-,system,system,-)
 %{_libdir}/libkey-manager-client.so
 %{_libdir}/libkey-manager-control-client.so
 %{_libdir}/libkey-manager-common.so
@@ -248,6 +222,7 @@ fi
 %{_includedir}/ckm/ckm/ckm-password.h
 %{_includedir}/ckm/ckm/ckm-pkcs12.h
 %{_includedir}/ckm/ckm/ckm-raw-buffer.h
+%{_includedir}/ckm/ckm/ckm-client-info.h
 %{_includedir}/ckm/ckm/ckm-type.h
 %{_includedir}/ckm/ckmc/ckmc-manager.h
 %{_includedir}/ckm/ckmc/ckmc-control.h
@@ -255,9 +230,12 @@ fi
 %{_includedir}/ckm/ckmc/ckmc-type.h
 %{_libdir}/pkgconfig/*.pc
 
+%if 0%{?ckm_build_internal_test}
 %files -n key-manager-tests
-%defattr(-,root,root,-)
+%defattr(-,system,system,-)
 %{_bindir}/ckm-tests-internal
+%{_bindir}/ckm-tests-lcov-internal
 %{_datadir}/ckm-db-test/testme_ver1.db
 %{_datadir}/ckm-db-test/testme_ver2.db
 %{_bindir}/ckm_so_loader
+%endif
index 147638b..cb8c377 100644 (file)
@@ -1,12 +1,19 @@
 PKG_CHECK_MODULES(KEY_MANAGER_DEP
-    dlog
+    REQUIRED
     openssl
-    libsmack
-    libcrypto
     libsystemd-daemon
-    capi-base-common
+    vasum
+    capi-system-info
+    glib-2.0
+    dlog
+    pkgmgr
+    )
+
+PKG_CHECK_MODULES(KEY_MANAGER_CLIENT_DEP
     REQUIRED
+    capi-base-common
     )
+
 FIND_PACKAGE(Threads REQUIRED)
 
 SET(KEY_MANAGER_SRC_PATH ${PROJECT_SOURCE_DIR}/src)
@@ -16,7 +23,6 @@ SET(KEY_MANAGER_SOURCES
     ${KEY_MANAGER_PATH}/main/generic-socket-manager.cpp
     ${KEY_MANAGER_PATH}/main/socket-manager.cpp
     ${KEY_MANAGER_PATH}/main/key-manager-main.cpp
-    ${KEY_MANAGER_PATH}/main/smack-check.cpp
     ${KEY_MANAGER_PATH}/service/certificate-store.cpp
     ${KEY_MANAGER_PATH}/service/certificate-config.cpp
     ${KEY_MANAGER_PATH}/service/digest.cpp
@@ -32,6 +38,7 @@ SET(KEY_MANAGER_SOURCES
     ${KEY_MANAGER_PATH}/service/db-crypto.cpp
     ${KEY_MANAGER_PATH}/service/ocsp-service.cpp
     ${KEY_MANAGER_PATH}/service/ocsp-logic.cpp
+    ${KEY_MANAGER_PATH}/listener/listener-thread.cpp
     ${KEY_MANAGER_PATH}/dpl/core/src/assert.cpp
     ${KEY_MANAGER_PATH}/dpl/db/src/sql_connection.cpp
     ${KEY_MANAGER_PATH}/dpl/db/src/naive_synchronization_object.cpp
@@ -53,6 +60,7 @@ INCLUDE_DIRECTORIES(
     ${KEY_MANAGER_PATH}/main
     ${KEY_MANAGER_PATH}/common
     ${KEY_MANAGER_PATH}/service
+    ${KEY_MANAGER_PATH}/listener
     ${KEY_MANAGER_PATH}/sqlcipher
     ${KEY_MANAGER_PATH}/dpl/core/include
     ${KEY_MANAGER_PATH}/dpl/log/include
@@ -66,6 +74,7 @@ TARGET_LINK_LIBRARIES(${TARGET_KEY_MANAGER}
     ${CMAKE_THREAD_LIBS_INIT}
     ${KEY_MANAGER_DEP_LIBRARIES}
     ${TARGET_KEY_MANAGER_COMMON}
+    ${TARGET_KEY_MANAGER_CONTROL_CLIENT}
     -ldl -pie
     )
 
@@ -78,6 +87,10 @@ SET(KEY_MANAGER_CLIENT_SRC_PATH ${KEY_MANAGER_PATH}/client)
 SET(KEY_MANAGER_CLIENT_ASYNC_SRC_PATH ${KEY_MANAGER_PATH}/client-async)
 SET(KEY_MANAGER_CLIENT_CAPI_SRC_PATH ${KEY_MANAGER_PATH}/client-capi)
 
+INCLUDE_DIRECTORIES(SYSTEM
+    ${KEY_MANAGER_CLIENT_DEP_INCLUDE_DIRS}
+    )
+
 INCLUDE_DIRECTORIES(
     ${KEY_MANAGER_PATH}/client
     ${KEY_MANAGER_PATH}/client-async
@@ -116,7 +129,7 @@ SET_TARGET_PROPERTIES(
     )
 
 TARGET_LINK_LIBRARIES(${TARGET_KEY_MANAGER_CLIENT}
-    ${KEY_MANAGER_DEP_LIBRARIES}
+    ${KEY_MANAGER_CLIENT_DEP_LIBRARIES}
     ${TARGET_KEY_MANAGER_COMMON}
     )
 
@@ -154,7 +167,7 @@ SET_TARGET_PROPERTIES(
     )
 
 TARGET_LINK_LIBRARIES(${TARGET_KEY_MANAGER_CONTROL_CLIENT}
-    ${KEY_MANAGER_DEP_LIBRARIES}
+    ${KEY_MANAGER_CLIENT_DEP_LIBRARIES}
     ${TARGET_KEY_MANAGER_COMMON}
     )
 
@@ -175,9 +188,11 @@ INSTALL(FILES
     ${KEY_MANAGER_SRC_PATH}/include/ckm/ckm-password.h
     ${KEY_MANAGER_SRC_PATH}/include/ckm/ckm-pkcs12.h
     ${KEY_MANAGER_SRC_PATH}/include/ckm/ckm-raw-buffer.h
+    ${KEY_MANAGER_SRC_PATH}/include/ckm/ckm-client-info.h
     ${KEY_MANAGER_SRC_PATH}/include/ckm/ckm-type.h
     DESTINATION /usr/include/ckm/ckm
     )
+
 INSTALL(FILES
     ${KEY_MANAGER_SRC_PATH}/include/ckmc/ckmc-manager.h
     ${KEY_MANAGER_SRC_PATH}/include/ckmc/ckmc-control.h
@@ -188,5 +203,4 @@ INSTALL(FILES
 ################################################################################
 
 ADD_SUBDIRECTORY(manager)
-ADD_SUBDIRECTORY(listener)
 ADD_SUBDIRECTORY(plugin)
diff --git a/src/include/ckm/ckm-client-info.h b/src/include/ckm/ckm-client-info.h
new file mode 100644 (file)
index 0000000..c6c7e2b
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ *
+ * @file        ckm-client-info.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       ClientInfo implementation.
+ */
+#pragma once
+
+#include <string>
+
+#include <sys/types.h>
+
+#include <ckm/ckm-type.h>
+
+namespace CKM {
+
+// ClientInfo consists of (zone name & uid)
+class KEY_MANAGER_API ClientInfo {
+public:
+    ClientInfo() = delete;
+
+    ClientInfo(const uid_t uid);
+
+    ClientInfo(const std::string &zone, const uid_t uid);
+
+    virtual ~ClientInfo();
+
+    uid_t getUID() const;
+
+    ClientID getClientID() const;
+
+    std::string getZone() const;
+
+private:
+    const static std::string ZONE_DEFAULT;
+    const static std::string DELIMITER;
+    std::string m_zone;
+    uid_t m_uid;
+
+};
+
+
+} // namespace CKM
index 67250fe..15dfda9 100644 (file)
@@ -25,6 +25,7 @@
 #include <memory>
 
 #include <ckm/ckm-error.h>
+#include <ckm/ckm-client-info.h>
 #include <ckm/ckm-type.h>
 
 // Central Key Manager namespace
@@ -38,32 +39,32 @@ class KEY_MANAGER_API Control
 {
 public:
     // decrypt user key with password
-    virtual int unlockUserKey(uid_t user, const Password &password) = 0;
+    virtual int unlockUserKey(const ClientInfo &clientInfo, const Password &password) = 0;
 
     // remove user key from memory
-    virtual int lockUserKey(uid_t user) = 0;
+    virtual int lockUserKey(const ClientInfo &clientInfo) = 0;
 
     // remove user data from Store and erase key used for encryption
-    virtual int removeUserData(uid_t user) = 0;
+    virtual int removeUserData(const ClientInfo &clientInfo) = 0;
 
     // change password for user
-    virtual int changeUserPassword(uid_t user, const Password &oldPassword, const Password &newPassword) = 0;
+    virtual int changeUserPassword(const ClientInfo &clientInfo, const Password &oldPassword, const Password &newPassword) = 0;
 
     // This is work around for security-server api - resetPassword that may be called without passing oldPassword.
     // This api should not be supported on tizen 3.0
     // User must be already logged in and his DKEK is already loaded into memory in plain text form.
     // The service will use DKEK in plain text and encrypt it in encrypted form (using new password).
-    virtual int resetUserPassword(uid_t user, const Password &newPassword) = 0;
+    virtual int resetUserPassword(const ClientInfo &clientInfo, const Password &newPassword) = 0;
 
     // Required for tizen 2.3.
     // It will remove all application data owned by application identified
     // by smackLabel. This function will remove application data from unlocked
     // database only. This function may be used during application uninstallation.
-    virtual int removeApplicationData(const std::string &smackLabel) = 0;
+    virtual int removeApplicationData(const std::string &zone, const Label &smackLabel) = 0;
 
     virtual int updateCCMode() = 0;
 
-    virtual int setPermission(uid_t user,
+    virtual int setPermission(const ClientInfo &clientInfo,
                               const Alias &alias,
                               const Label &accessor,
                               PermissionMask permissionMask) = 0;
index 671ec25..372bd98 100644 (file)
@@ -93,6 +93,9 @@ extern "C" {
 /*! \brief   indicating that files are corrupted or access to files was denied */
 #define CKM_API_ERROR_FILE_SYSTEM -20
 
+/*! \brief   indicating that device needed to run API is not supported */
+#define CKM_API_ERROR_NOT_SUPPORTED -21
+
 #define CKM_API_OCSP_STATUS_GOOD                (1<<0)
 #define CKM_API_OCSP_STATUS_UNSUPPORTED         (1<<1)
 #define CKM_API_OCSP_STATUS_UNKNOWN             (1<<2)
index 53b87a7..1dbba03 100644 (file)
@@ -35,6 +35,7 @@ namespace CKM {
 typedef std::vector<RawBuffer> RawBufferVector;
 typedef std::string Alias;
 typedef std::string Label;
+typedef std::string ClientID;
 typedef std::vector<Alias> AliasVector;
 
 enum class KeyType : int {
index 0424e2c..6666950 100644 (file)
@@ -33,7 +33,6 @@ extern "C" {
 #endif
 
 /**
- * @internal
  * @addtogroup CAPI_KEY_MANAGER_CONTROL_MODULE
  * @{
  */
@@ -43,7 +42,7 @@ extern "C" {
  *        A decrypted user key exists only on memory. If this API is called for the first time, a
  *        user key will be generated internally.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel platform
  * @privilege %http://tizen.org/privilege/keymanager.admin
  *
@@ -72,7 +71,7 @@ int ckmc_unlock_user_key(uid_t user, const char *password);
 /**
  * @brief Removes a decrypted user key(DKEK) from memory
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel platform
  * @privilege %http://tizen.org/privilege/keymanager.admin
  *
@@ -95,7 +94,7 @@ int ckmc_lock_user_key(uid_t user);
 /**
  * @brief Removes user data from Store and erases a user key(DKEK) used for encryption.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel platform
  * @privilege %http://tizen.org/privilege/keymanager.admin
  *
@@ -120,7 +119,7 @@ int ckmc_remove_user_data(uid_t user);
  *        The key manager decrypts a user key (DKEK) with old password and re-encrypts a user key
  *        with new password.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel platform
  * @privilege %http://tizen.org/privilege/keymanager.admin
  *
@@ -147,7 +146,7 @@ int ckmc_change_user_password(uid_t user, const char *old_password, const char *
 /**
  * @brief Changes a password for a user without old password.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel platform
  * @privilege %http://tizen.org/privilege/keymanager.admin
  *
@@ -173,9 +172,10 @@ int ckmc_change_user_password(uid_t user, const char *old_password, const char *
 int ckmc_reset_user_password(uid_t user, const char *new_password);
 
 /**
+ * @deprecated, see ckmc_set_permission_by_adm()
  * @brief Allows another application to access client's application data
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel platform
  * @privilege %http://tizen.org/privilege/keymanager.admin
  *
@@ -198,9 +198,8 @@ int ckmc_reset_user_password(uid_t user, const char *new_password);
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
- * @see ckmc_allow_access()
- * @see ckmc_deny_access()
- * @see ckmc_deny_access_by_adm()
+ * @see ckmc_set_permission_by_adm()
+ * @see ckmc_set_permission()
  */
 int ckmc_allow_access_by_adm(uid_t user,
                              const char *owner,
@@ -209,9 +208,43 @@ int ckmc_allow_access_by_adm(uid_t user,
                              ckmc_access_right_e granted);
 
 /**
+ * @brief Allows another application to access client's application data
+ *
+ * @since_tizen 3.0
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/keymanager.admin
+ *
+ * @remarks Data identified by @a alias should exist
+ * @remarks @a alias must contain owner label (<owner label><ckmc_label_name_separator><name>)
+ *
+ * @param[in] user        User ID of a user whose data will be affected
+ * @param[in] alias       Data alias for which access will be granted
+ * @param[in] accessor    Package id of the application that will gain access rights
+ * @param[in] permissions Mask of permissions granted for @a accessor application
+ *                        (@a ckmc_permission_e)
+ *                        (previous permission mask will be replaced with the new mask value)
+ *
+ * @return @c 0 on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE                 Successful
+ * @retval #CKMC_ERROR_INVALID_PARAMETER    Input parameter is invalid
+ * @retval #CKMC_ERROR_DB_LOCKED            A user key is not loaded in memory (a user is not logged
+ *                                          in)
+ * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN     Alias does not exist
+ * @retval #CKMC_ERROR_PERMISSION_DENIED    Failed to access key manager
+ *
+ * @pre User is already logged in and the user key is already loaded into memory in plain text form.
+ *
+ * @see ckmc_set_permission()
+ */
+int ckmc_set_permission_by_adm(uid_t user, const char *alias, const char *accessor, int mask);
+
+
+/**
+ * @deprecated, see ckmc_set_permission_by_adm()
  * @brief Revokes another application's access to client's application data
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel platform
  * @privilege %http://tizen.org/privilege/keymanager.admin
  *
@@ -235,9 +268,8 @@ int ckmc_allow_access_by_adm(uid_t user,
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
- * @see ckmc_allow_access()
- * @see ckmc_deny_access()
- * @see ckmc_allow_access_by_adm()
+ * @see ckmc_set_permission()
+ * @see ckmc_set_permission_by_adm()
  */
 int ckmc_deny_access_by_adm(uid_t user, const char *owner, const char *alias, const char *accessor);
 
index 8c95db7..8a5729b 100644 (file)
@@ -33,7 +33,7 @@ extern "C" {
 
 /**
  * @brief Enumeration for Key Manager Errors.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 
 typedef enum{
@@ -41,6 +41,7 @@ typedef enum{
        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 */
index d0cd41f..c4a4580 100644 (file)
@@ -15,7 +15,7 @@
  *
  *
  * @file        ckmc-manager.h
- * @version     1.0
+ * @version     1.2
  * @brief       Provides management functions(storing, retrieving, and removing) for keys,
  *              certificates and data of a user and additional crypto functions.
  */
 #define __TIZEN_CORE_CKMC_MANAGER_H
 
 #include <stddef.h>
+#include <stdbool.h>
 #include <sys/types.h>
 #include <tizen.h>
-#include <ckmc/ckmc-type.h>
 #include <ckmc/ckmc-error.h>
-
+#include <ckmc/ckmc-type.h>
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -43,7 +43,7 @@ extern "C" {
 /**
  * @brief Stores a key inside key manager based on the provided policy.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -61,8 +61,7 @@ extern "C" {
  * @param[in] key     The key's binary value to be stored
  * @param[in] policy  The policy about how to store a key securely
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE              Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid
@@ -75,18 +74,20 @@ extern "C" {
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
- * @see ckmc_remove_key()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_key()
  * @see ckmc_get_key_alias_list()
+ * @see ckmc_key_free()
  * @see #ckmc_key_s
  * @see #ckmc_policy_s
  */
 int ckmc_save_key(const char *alias, const ckmc_key_s key, const ckmc_policy_s policy);
 
 /**
+ * @deprecated Deprecated since 2.4. [Use ckmc_remove_alias() instead]
  * @brief Removes a key from key manager.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -95,8 +96,7 @@ int ckmc_save_key(const char *alias, const ckmc_key_s key, const ckmc_policy_s p
  *
  * @param[in] alias The name of a key to be removed
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE              Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid
@@ -111,13 +111,14 @@ int ckmc_save_key(const char *alias, const ckmc_key_s key, const ckmc_policy_s p
  * @see ckmc_save_key()
  * @see ckmc_get_key()
  * @see ckmc_get_key_alias_list()
+ * @see ckmc_remove_alias()
  */
 int ckmc_remove_key(const char *alias);
 
 /**
  * @brief Gets a key from key manager.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -128,11 +129,10 @@ int ckmc_remove_key(const char *alias);
  * @param[in] alias     The name of a key to retrieve
  * @param[in] password  The password used in decrypting a key value \n
  *                      If password of policy is provided in ckmc_save_key(), the same password
- *                      should be provided.
- * @param[out] ppkey    The pointer to a newly created ckmc_key_s handle
+ *                      should be provided
+ * @param[out] ppkey    The pointer to a newly created #ckmc_key_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE              Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid
@@ -142,20 +142,22 @@ int ckmc_remove_key(const char *alias);
  * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN  Alias does not exist
  * @retval #CKMC_ERROR_PERMISSION_DENIED Failed to access key manager
  * @retval #CKMC_ERROR_AUTHENTICATION_FAILED
- *                                       Decryption failed because password is incorrect.
+ *                                       Decryption failed because password is incorrect
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_save_key()
- * @see ckmc_remove_key()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_key_alias_list()
+ * @see ckmc_key_free()
+ * @see #ckmc_key_s
  */
 int ckmc_get_key(const char *alias, const char *password, ckmc_key_s **ppkey);
 
 /**
  * @brief Gets all the alias of keys that the client can access.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -163,12 +165,11 @@ int ckmc_get_key(const char *alias, const char *password, ckmc_key_s **ppkey);
  * @remarks You must destroy the newly created @a ppalias_list by calling ckmc_alias_list_all_free()
  *          if it is no longer needed.
  *
- * @param[out] ppalias_list  The pointer to a newly created ckmc_alias_list_s handle containing all
+ * @param[out] ppalias_list  The pointer to a newly created #ckmc_alias_list_s handle containing all
  *                           available alias of keys \n
- *                           If there is no available key alias, *ppalias_list will be null.
+ *                           If there is no available key alias, @a *ppalias_list will be null
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE              Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid
@@ -181,8 +182,10 @@ int ckmc_get_key(const char *alias, const char *password, ckmc_key_s **ppkey);
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_save_key()
- * @see ckmc_remove_key()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_key()
+ * @see ckmc_alias_list_all_free()
+ * @see #ckmc_alias_list_s
  */
 int ckmc_get_key_alias_list(ckmc_alias_list_s** ppalias_list);
 
@@ -192,7 +195,7 @@ int ckmc_get_key_alias_list(ckmc_alias_list_s** ppalias_list);
 /**
  * @brief Stores a certificate inside key manager based on the provided policy.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -203,8 +206,7 @@ int ckmc_get_key_alias_list(ckmc_alias_list_s** ppalias_list);
  * @param[in] cert   The certificate's binary value to be stored
  * @param[in] policy The policy about how to store a certificate securely
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -217,7 +219,7 @@ int ckmc_get_key_alias_list(ckmc_alias_list_s** ppalias_list);
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
- * @see ckmc_remove_cert()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_cert()
  * @see ckmc_get_cert_alias_list()
  * @see #ckmc_cert_s
@@ -226,9 +228,10 @@ int ckmc_get_key_alias_list(ckmc_alias_list_s** ppalias_list);
 int ckmc_save_cert(const char *alias, const ckmc_cert_s cert, const ckmc_policy_s policy);
 
 /**
+ * @deprecated Deprecated since 2.4. [Use ckmc_remove_alias() instead]
  * @brief Removes a certificate from key manager.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -237,8 +240,7 @@ int ckmc_save_cert(const char *alias, const ckmc_cert_s cert, const ckmc_policy_
  *
  * @param[in] alias The name of a certificate to be removed
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -253,13 +255,14 @@ int ckmc_save_cert(const char *alias, const ckmc_cert_s cert, const ckmc_policy_
  * @see ckmc_save_cert()
  * @see ckmc_get_cert()
  * @see ckmc_get_cert_alias_list()
+ * @see ckmc_remove_alias()
  */
 int ckmc_remove_cert(const char *alias);
 
 /**
  * @brief Gets a certificate from key manager.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -271,11 +274,10 @@ int ckmc_remove_cert(const char *alias);
  * @param[in] alias    The name of a certificate to retrieve
  * @param[in] password The password used in decrypting a certificate value \n
  *                     If password of policy is provided in ckmc_save_cert(), the same password
- *                     should be provided.
- * @param[out] ppcert  The pointer to a newly created ckmc_cert_s handle
+ *                     should be provided
+ * @param[out] ppcert  The pointer to a newly created #ckmc_cert_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -285,20 +287,21 @@ int ckmc_remove_cert(const char *alias);
  * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN   Alias does not exists
  * @retval #CKMC_ERROR_PERMISSION_DENIED  Failed to access key manager
  * @retval #CKMC_ERROR_AUTHENTICATION_FAILED
- *                                        Decryption failed because password is incorrect.
+ *                                        Decryption failed because password is incorrect
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_save_cert()
- * @see ckmc_remove_cert()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_cert_alias_list()
+ * @see #ckmc_cert_s
  */
 int ckmc_get_cert(const char *alias, const char *password, ckmc_cert_s **ppcert);
 
 /**
  * @brief Gets all alias of certificates which the client can access.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -306,12 +309,11 @@ int ckmc_get_cert(const char *alias, const char *password, ckmc_cert_s **ppcert)
  * @remarks You must destroy the newly created @a ppalias_list by calling ckmc_alias_list_all_free()
  *          if it is no longer needed.
  *
- * @param[out] ppalias_list The pointer to a newly created ckmc_alias_list_s handle containing all
+ * @param[out] ppalias_list The pointer to a newly created #ckmc_alias_list_s handle containing all
  *                          available alias of keys \n
- *                          If there is no available key alias, *ppalias_list will be null.
+ *                          If there is no available key alias, @a *ppalias_list will be null
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -324,17 +326,95 @@ int ckmc_get_cert(const char *alias, const char *password, ckmc_cert_s **ppcert)
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_save_cert()
- * @see ckmc_remove_cert()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_cert()
+ * @see ckmc_alias_list_all_free()
+ * @see #ckmc_alias_list_s
  */
 int ckmc_get_cert_alias_list(ckmc_alias_list_s** ppalias_list);
 
 
 
+
+/**
+ * @brief Stores PKCS12's contents inside key manager based on the provided policies.
+ * All items from the PKCS12 will use the same alias.
+ *
+ * @since_tizen 2.4
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/keymanager
+ *
+ * @param[in] alias         The name of a data to be stored
+ * @param[in] pkcs          Pointer to the pkcs12 structure to be saved
+ * @param[in] key_policy    The policy about how to store pkcs's private key
+ * @param[in] cert_policy   The policy about how to store pkcs's certificate
+ *
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE               Successful
+ * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
+ * @retval #CKMC_ERROR_DB_LOCKED          A user key is not loaded in memory (a user is not logged
+ *                                        in)
+ * @retval #CKMC_ERROR_DB_ALIAS_EXISTS    Alias already exists
+ * @retval #CKMC_ERROR_DB_ERROR           Failed due to a database error
+ * @retval #CKMC_ERROR_PERMISSION_DENIED  Failed to access key manager
+ *
+ * @pre User is already logged in and the user key is already loaded into memory in plain text form.
+ *
+ * @see ckmc_remove_alias()
+ * @see ckmc_get_pkcs12()
+ * @see ckmc_get_data_alias_list()
+ * @see ckmc_pkcs12_load()
+ * @see #ckmc_pkcs12_s
+ * @see #ckmc_policy_s
+ */
+int ckmc_save_pkcs12(const char *alias,
+                     const ckmc_pkcs12_s *pkcs,
+                     const ckmc_policy_s key_policy,
+                     const ckmc_policy_s cert_policy);
+
+/**
+ * @brief Gets a pkcs12 from key manager.
+ *
+ * @since_tizen 2.4
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/keymanager
+ *
+ * @remarks A client can access only data stored by the client.
+ * @remarks You must destroy the newly created @a pkcs12 by calling ckmc_pkcs12_free() if it is no
+ *          longer needed.
+ *
+ * @param[in]  alias         The name of a data to retrieve
+ * @param[in]  key_password  Password that was used to encrypt privateKey (may be NULL)
+ * @param[in]  cert_password Password used to encrypt certificates (may be NULL)
+ * @param[out] pkcs12        The pointer to a newly created #ckmc_pkcs12_s handle
+ *
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE               Successful
+ * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
+ * @retval #CKMC_ERROR_DB_LOCKED          A user key is not loaded in memory (a user is not logged
+ *                                        in)
+ * @retval #CKMC_ERROR_DB_ERROR           Failed due to a database error
+ * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN   Alias does not exist
+ * @retval #CKMC_ERROR_PERMISSION_DENIED  Failed to access key manager
+ * @retval #CKMC_ERROR_AUTHENTICATION_FAILED
+ *                                        keyPassword or certPassword does not match with password
+ *                                        used to encrypt data
+ *
+ * @pre User is already logged in and the user key is already loaded into memory in plain text form.
+ *
+ * @see ckmc_save_pkcs12()
+ * @see ckmc_remove_alias()
+ * @see ckmc_pkcs12_free()
+ * @see #ckmc_pkcs12_s
+ */
+int ckmc_get_pkcs12(const char *alias, const char *key_password, const char *cert_password, ckmc_pkcs12_s **pkcs12);
+
 /**
  * @brief Stores a data inside key manager based on the provided policy.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -342,8 +422,7 @@ int ckmc_get_cert_alias_list(ckmc_alias_list_s** ppalias_list);
  * @param[in] data   The binary value to be stored
  * @param[in] policy The policy about how to store a data securely
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -355,7 +434,7 @@ int ckmc_get_cert_alias_list(ckmc_alias_list_s** ppalias_list);
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
- * @see ckmc_remove_data()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_data()
  * @see ckmc_get_data_alias_list()
  * @see #ckmc_raw_buffer_s
@@ -364,9 +443,10 @@ int ckmc_get_cert_alias_list(ckmc_alias_list_s** ppalias_list);
 int ckmc_save_data(const char *alias, ckmc_raw_buffer_s data, const ckmc_policy_s policy);
 
 /**
+ * @deprecated Deprecated since 2.4. [Use ckmc_remove_alias() instead]
  * @brief Removes a data from key manager.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -375,8 +455,7 @@ int ckmc_save_data(const char *alias, ckmc_raw_buffer_s data, const ckmc_policy_
  *
  * @param[in] alias The name of a data to be removed
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -391,13 +470,14 @@ int ckmc_save_data(const char *alias, ckmc_raw_buffer_s data, const ckmc_policy_
  * @see ckmc_save_data()
  * @see ckmc_get_data()
  * @see ckmc_get_data_alias_list()
+ * @see ckmc_remove_alias()
  */
 int ckmc_remove_data(const char *alias);
 
 /**
  * @brief Gets a data from key manager.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -408,11 +488,10 @@ int ckmc_remove_data(const char *alias);
  * @param[in]  alias     The name of a data to retrieve
  * @param[in]  password  The password used in decrypting a data value \n
  *                       If password of policy is provided in ckmc_save_data(), the same password
- *                       should be provided.
- * @param[out] ppdata    The pointer to a newly created ckmc_raw_buffer_s handle
+ *                       should be provided
+ * @param[out] ppdata    The pointer to a newly created #ckmc_raw_buffer_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -426,15 +505,17 @@ int ckmc_remove_data(const char *alias);
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_save_data()
- * @see ckmc_remove_data()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_data_alias_list()
+ * @see ckmc_buffer_free()
+ * @see #ckmc_raw_buffer_s
  */
 int ckmc_get_data(const char *alias, const char *password, ckmc_raw_buffer_s **ppdata);
 
 /**
  * @brief Gets all alias of data which the client can access.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -442,12 +523,11 @@ int ckmc_get_data(const char *alias, const char *password, ckmc_raw_buffer_s **p
  * @remarks You must destroy the newly created @a ppalias_list by calling ckmc_alias_list_all_free()
  *          if it is no longer needed.
  *
- * @param[out] ppalias_list The pointer to a newly created ckmc_alias_list_s handle containing all
+ * @param[out] ppalias_list The pointer to a newly created #ckmc_alias_list_s handle containing all
  *                          available alias of keys \n
- *                          If there is no available key alias, *ppalias_list will be null.
+ *                          If there is no available key alias, @a *ppalias_list will be null
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -460,8 +540,10 @@ int ckmc_get_data(const char *alias, const char *password, ckmc_raw_buffer_s **p
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_save_data()
- * @see ckmc_remove_data()
+ * @see ckmc_remove_alias()
  * @see ckmc_get_data()
+ * @see ckmc_alias_list_all_free()
+ * @see #ckmc_alias_list_s
  */
 int ckmc_get_data_alias_list(ckmc_alias_list_s** ppalias_list);
 
@@ -472,7 +554,7 @@ int ckmc_get_data_alias_list(ckmc_alias_list_s** ppalias_list);
  * @brief Creates RSA private/public key pair and stores them inside key manager based on each
  *        policy.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -480,14 +562,13 @@ int ckmc_get_data_alias_list(ckmc_alias_list_s** ppalias_list);
  *          in policy.
  *
  * @param[in] size                The size of key strength to be created \n
- *                                @c 1024, @c 2048, and @c 4096 are supported.
+ *                                @c 1024, @c 2048, and @c 4096 are supported
  * @param[in] private_key_alias   The name of private key to be stored
  * @param[in] public_key_alias    The name of public key to be stored
  * @param[in] policy_private_key  The policy about how to store a private key securely
  * @param[in] policy_public_key   The policy about how to store a public key securely
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -503,6 +584,7 @@ int ckmc_get_data_alias_list(ckmc_alias_list_s** ppalias_list);
  * @see ckmc_create_key_pair_ecdsa()
  * @see ckmc_create_signature()
  * @see ckmc_verify_signature()
+ * @see #ckmc_policy_s
  */
 int ckmc_create_key_pair_rsa(const size_t size,
                              const char *private_key_alias,
@@ -514,7 +596,7 @@ int ckmc_create_key_pair_rsa(const size_t size,
  * @brief Creates DSA private/public key pair and stores them inside key manager based on each
  *        policy.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -522,14 +604,13 @@ int ckmc_create_key_pair_rsa(const size_t size,
  *          in policy.
  *
  * @param[in] size                The size of key strength to be created \n
- *                                @c 1024, @c 2048, @c 3072 and @c 4096 are supported.
+ *                                @c 1024, @c 2048, @c 3072 and @c 4096 are supported
  * @param[in] private_key_alias   The name of private key to be stored
  * @param[in] public_key_alias    The name of public key to be stored
  * @param[in] policy_private_key  The policy about how to store a private key securely
  * @param[in] policy_public_key   The policy about how to store a public key securely
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -545,6 +626,7 @@ int ckmc_create_key_pair_rsa(const size_t size,
  * @see ckmc_create_key_pair_ecdsa()
  * @see ckmc_create_signature()
  * @see ckmc_verify_signature()
+ * @see #ckmc_policy_s
  */
 int ckmc_create_key_pair_dsa(const size_t size,
                              const char *private_key_alias,
@@ -556,7 +638,7 @@ int ckmc_create_key_pair_dsa(const size_t size,
  * @brief Creates ECDSA private/public key pair and stores them inside key manager based on each
  *        policy.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -569,8 +651,7 @@ int ckmc_create_key_pair_dsa(const size_t size,
  * @param[in] policy_private_key  The policy about how to store a private key securely
  * @param[in] policy_public_key   The policy about how to store a public key securely
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -587,6 +668,7 @@ int ckmc_create_key_pair_dsa(const size_t size,
  * @see ckmc_create_signature()
  * @see ckmc_verify_signature()
  * @see #ckmc_ec_type_e
+ * @see #ckmc_policy_s
  */
 int ckmc_create_key_pair_ecdsa(const ckmc_ec_type_e type,
                                const char *private_key_alias,
@@ -597,7 +679,7 @@ int ckmc_create_key_pair_ecdsa(const ckmc_ec_type_e type,
 /**
  * @brief Creates a signature on a given message using a private key and returns the signature.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -611,12 +693,11 @@ int ckmc_create_key_pair_ecdsa(const ckmc_ec_type_e type,
  * @param[in]  message            The message that is signed with a private key
  * @param[in]  hash               The hash algorithm used in creating signature
  * @param[in]  padding            The RSA padding algorithm used in creating signature \n
- *                                It is used only when the signature algorithm is RSA.
+ *                                It is used only when the signature algorithm is RSA
  * @param[out] ppsignature        The pointer to a newly created signature \n
- *                                If an error occurs, @a *ppsignature will be null.
+ *                                If an error occurs, @a *ppsignature will be null
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
@@ -626,7 +707,7 @@ int ckmc_create_key_pair_ecdsa(const ckmc_ec_type_e type,
  * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN   Alias does not exist
  * @retval #CKMC_ERROR_PERMISSION_DENIED  Failed to access key manager
  * @retval #CKMC_ERROR_AUTHENTICATION_FAILED
- *                                        Decryption failed because password is incorrect.
+ *                                        Decryption failed because password is incorrect
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
@@ -634,6 +715,7 @@ int ckmc_create_key_pair_ecdsa(const ckmc_ec_type_e type,
  * @see ckmc_create_key_pair_ecdsa()
  * @see ckmc_verify_signature()
  * @see ckmc_buffer_free()
+ * @see #ckmc_raw_buffer_s
  * @see #ckmc_hash_algo_e
  * @see #ckmc_rsa_padding_algo_e
  */
@@ -648,7 +730,7 @@ int ckmc_create_signature(const char *private_key_alias,
  * @brief Verifies a given signature on a given message using a public key and returns the signature
  *        status.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -661,10 +743,9 @@ int ckmc_create_signature(const char *private_key_alias,
  * @param[in] signature         The signature that is verified with public key
  * @param[in] hash              The hash algorithm used in verifying signature
  * @param[in] padding           The RSA padding algorithm used in verifying signature \n
- *                              It is used only when the signature algorithm is RSA.
+ *                              It is used only when the signature algorithm is RSA
  *
- * @return @c 0 on success and the signature is valid,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success and the signature is valid, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE                 Successful
  * @retval #CKMC_ERROR_VERIFICATION_FAILED  The signature is invalid
@@ -675,13 +756,14 @@ int ckmc_create_signature(const char *private_key_alias,
  * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN     Alias does not exist
  * @retval #CKMC_ERROR_PERMISSION_DENIED    Failed to access key manager
  * @retval #CKMC_ERROR_AUTHENTICATION_FAILED
- *                                          Decryption failed because password is incorrect.
+ *                                          Decryption failed because password is incorrect
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_create_key_pair_rsa()
+ * @see ckmc_create_key_pair_dsa()
  * @see ckmc_create_key_pair_ecdsa()
- * @see ckmc_verify_signature()
+ * @see #ckmc_raw_buffer_s
  * @see #ckmc_hash_algo_e
  * @see #ckmc_rsa_padding_algo_e
  */
@@ -695,7 +777,7 @@ int ckmc_verify_signature(const char *public_key_alias,
 /**
  * @brief Verifies a certificate chain and returns that chain.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -704,14 +786,13 @@ int ckmc_verify_signature(const char *public_key_alias,
  * @remarks You must destroy the newly created @a ppcert_chain_list by calling
  *          ckmc_cert_list_all_free() if it is no longer needed.
  *
- * @param[in] cert               The certificate to be verified
- * @param[in] untrustedcerts     The untrusted CA certificates to be used in verifying a certificate
+ * @param[in]  cert              The certificate to be verified
+ * @param[in]  untrustedcerts    The untrusted CA certificates to be used in verifying a certificate
  *                               chain
  * @param[out] ppcert_chain_list The pointer to a newly created certificate chain's handle \n
- *                               If an error occurs, @a *ppcert_chain_list will be null.
+ *                               If an error occurs, @a *ppcert_chain_list will be null
  *
- * @return @c 0 on success and the signature is valid,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success and the signature is valid, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE                 Successful
  * @retval #CKMC_ERROR_VERIFICATION_FAILED  The certificate chain is not valid
@@ -722,22 +803,24 @@ int ckmc_verify_signature(const char *public_key_alias,
  * @retval #CKMC_ERROR_INVALID_FORMAT       The format of certificate is not valid
  * @retval #CKMC_ERROR_PERMISSION_DENIED    Failed to access key manager
  * @retval #CKMC_ERROR_AUTHENTICATION_FAILED
- *                                          Decryption failed because password is incorrect.
+ *                                          Decryption failed because password is incorrect
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_get_cert_chain_with_alias())
  * @see ckmc_cert_list_all_free()
+ * @see #ckmc_cert_list_s
  */
 int ckmc_get_cert_chain(const ckmc_cert_s *cert,
                         const ckmc_cert_list_s *untrustedcerts,
                         ckmc_cert_list_s **ppcert_chain_list);
 
 /**
+ * @deprecated Deprecated since 2.4. [Use ckmc_get_cert_chain() instead]
  * @brief Verifies a certificate chain using an alias list of untrusted certificates and return that
  *        chain.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
@@ -745,15 +828,15 @@ int ckmc_get_cert_chain(const ckmc_cert_s *cert,
  *          storage.
  * @remarks You must destroy the newly created @a ppcert_chain_list by calling
  *          ckmc_cert_list_all_free() if it is no longer needed.
+ * @remarks @a untrustedcerts shouldn't be protected with optional password.
  *
- * @param[in] cert               The certificate to be verified
- * @param[in] untrustedcerts     The alias list of untrusted CA certificates stored in key manager
+ * @param[in]  cert              The certificate to be verified
+ * @param[in]  untrustedcerts    The alias list of untrusted CA certificates stored in key manager
  *                               to be used in verifying a certificate chain
  * @param[out] ppcert_chain_list The pointer to a newly created certificate chain's handle \n
- *                               If an error occurs, @a *ppcert_chain_list will be null.
+ *                               If an error occurs, @a *ppcert_chain_list will be null
  *
- * @return @c 0 on success and the signature is valid,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success and the signature is valid, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE                 Successful
  * @retval #CKMC_ERROR_VERIFICATION_FAILED  The certificate chain is not valid
@@ -766,32 +849,111 @@ int ckmc_get_cert_chain(const ckmc_cert_s *cert,
  * @retval #CKMC_ERROR_PERMISSION_DENIED    Failed to access key manager
  * @retval #CKMC_ERROR_AUTHENTICATION_FAILED
  *                                          Some certificates were encrypted with password and could not
- *                                          be used.
+ *                                          be used
  *
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_get_cert_chain()
  * @see ckmc_cert_list_all_free()
+ * @see #ckmc_cert_s
+ * @see #ckmc_alias_list_s
+ * @see #ckmc_cert_list_s
  */
 int ckmc_get_cert_chain_with_alias(const ckmc_cert_s *cert,
                                    const ckmc_alias_list_s *untrustedcerts,
                                    ckmc_cert_list_s **ppcert_chain_list);
 
+/**
+ * @brief Verifies a certificate chain and returns that chain using user entered trusted and
+ *        untrusted CA certificates.
+ *
+ * @since_tizen 2.4
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/keymanager
+ *
+ * @remarks If the trusted root certificates are provided as a user input, these certificates do not
+ *          need to exist in the system's certificate storage.
+ * @remarks You must destroy the newly created @a ppcert_chain_list by calling
+ *          ckmc_cert_list_all_free() if it is no longer needed.
+ *
+ * @param[in] cert                    The certificate to be verified
+ * @param[in] untrustedcerts          The untrusted CA certificates to be used in verifying a
+ *                                    certificate chain
+ * @param[in] trustedcerts            The trusted CA certificates to be used in verifying a
+ *                                    certificate chain
+ * @param[in] use_trustedsystemcerts  The flag indicating the use of the trusted root certificates
+ *                                    in the system's certificate storage
+ * @param[out] ppcert_chain_list      The pointer to a newly created certificate chain's handle \n
+ *                                    If an error occurs, @a *ppcert_chain_list will be null
+ *
+ * @return #CKMC_ERROR_NONE on success and the signature is valid, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE                 Successful
+ * @retval #CKMC_ERROR_VERIFICATION_FAILED  The certificate chain is not valid
+ * @retval #CKMC_ERROR_INVALID_PARAMETER    Input parameter is invalid
+ * @retval #CKMC_ERROR_DB_LOCKED            A user key is not loaded in memory (a user is not logged
+ *                                          in)
+ * @retval #CKMC_ERROR_DB_ERROR             Failed due to the error with unknown reason
+ * @retval #CKMC_ERROR_INVALID_FORMAT       The format of certificate is not valid
+ * @retval #CKMC_ERROR_PERMISSION_DENIED    Failed to access key manager
+ *
+ * @pre User is already logged in and the user key is already loaded into memory in plain text form.
+ *
+ * @see ckmc_cert_list_all_free()
+ * @see #ckmc_cert_s
+ * @see #ckmc_cert_list_s
+ */
+int ckmc_get_cert_chain_with_trustedcert(const ckmc_cert_s *cert,
+                                         const ckmc_cert_list_s *untrustedcerts,
+                                         const ckmc_cert_list_s *trustedcerts,
+                                         const bool use_trustedsystemcerts,
+                                         ckmc_cert_list_s **ppcert_chain_list);
+
+/**
+ * @brief Perform OCSP which checks certificate is whether revoked or not.
+ *
+ * @since_tizen 2.4
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/keymanager
+ *
+ * @param[in]  pcert_chain_list  Valid certificate chain to perform OCSP check
+ * @param[out] ocsp_status       The pointer to status result of OCSP check
+ *
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE                 Successful
+ * @retval #CKMC_ERROR_INVALID_PARAMETER    Input parameter is invalid
+ * @retval #CKMC_ERROR_PERMISSION_DENIED    Failed to access key manager
+ * @retval #CKMC_ERROR_NOT_SUPPORTED        Device needed to run API is not supported
+ *
+ * @pre User is already logged in and the user key is already loaded into memory in plain text form.
+ * @pre @a pcert_chain_list is created with ckmc_get_certificate_chain() or
+ *      ckmc_get_certificate_chain_with_alias().
+ *
+ * @see ckmc_get_cert_chain()
+ * @see ckmc_get_cert_chain_with_alias()
+ * @see ckmc_get_cert_chain_with_trustedcert()
+ * @see ckmc_cert_list_all_free()
+ * @see #ckmc_cert_list_s
+ * @see #ckmc_ocsp_status_e
+ */
+int ckmc_ocsp_check(const ckmc_cert_list_s *pcert_chain_list, ckmc_ocsp_status_e *ocsp_status);
 
 /**
- * @brief Allows another application to access client's application data
+ * @deprecated Deprecated since 2.4. [Use ckmc_set_permission() instead]
+ * @brief Allows another application to access client's application data.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
- * @remarks Data identified by @a alias should exist
+ * @remarks Data identified by @a alias should exist.
  *
  * @param[in] alias       Data alias for which access will be granted
  * @param[in] accessor    Package id of the application that will gain access rights
  * @param[in] granted     Rights granted for @a accessor application
  *
- * @return @c 0 on success, otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE                 Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER    Input parameter is invalid
@@ -804,24 +966,56 @@ int ckmc_get_cert_chain_with_alias(const ckmc_cert_s *cert,
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_deny_access()
+ * @see ckmc_set_permission()
+ * @see #ckmc_access_right_e
  */
 int ckmc_allow_access(const char *alias, const char *accessor, ckmc_access_right_e granted);
 
+/**
+ * @brief Allows another application to access client's application data.
+ *
+ * @since_tizen 2.4
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/keymanager
+ *
+ * @remarks Data identified by @a alias should exist.
+ *
+ * @param[in] alias       Data alias for which access will be granted
+ * @param[in] accessor    Package id of the application that will gain access rights
+ * @param[in] permissions Mask of #ckmc_permission_e granted for @a accessor application \n
+ *                        Previous permission mask will be replaced with the new mask value
+ *
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE                 Successful
+ * @retval #CKMC_ERROR_INVALID_PARAMETER    Input parameter is invalid
+ * @retval #CKMC_ERROR_DB_LOCKED            A user key is not loaded in memory (a user is not logged
+ *                                          in)
+ * @retval #CKMC_ERROR_DB_ERROR             Failed due to the error with unknown reason
+ * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN     Alias does not exist
+ * @retval #CKMC_ERROR_PERMISSION_DENIED    Failed to access key manager
+ *
+ * @pre User is already logged in and the user key is already loaded into memory in plain text form.
+ *
+ * @see #ckmc_permission_e
+ */
+int ckmc_set_permission(const char *alias, const char *accessor, int permissions);
 
 /**
- * @brief Revokes another application's access to client's application data
+ * @deprecated Deprecated since 2.4. [Use ckmc_set_permission() instead]
+ * @brief Revokes another application's access to client's application data.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  * @privlevel public
  * @privilege %http://tizen.org/privilege/keymanager
  *
- * @remarks Data identified by @a alias should exist
- * @remarks Only access previously granted with ckmc_allow_access can be revoked.
+ * @remarks Data identified by @a alias should exist.
+ * @remarks Only access previously granted with ckmc_allow_access() can be revoked.
  *
  * @param[in] alias       Data alias for which access will be revoked
  * @param[in] accessor    Package id of the application that will lose access rights
  *
- * @return @c 0 on success, otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE                 Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER    Input parameter is invalid or the @a accessor doesn't
@@ -835,9 +1029,44 @@ int ckmc_allow_access(const char *alias, const char *accessor, ckmc_access_right
  * @pre User is already logged in and the user key is already loaded into memory in plain text form.
  *
  * @see ckmc_allow_access()
+ * @see ckmc_set_permission()
  */
 int ckmc_deny_access(const char *alias, const char *accessor);
 
+/**
+ * @brief Removes a an entry (no matter of type) from the key manager.
+ *
+ * @since_tizen 2.4
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/keymanager
+ *
+ * @remarks To remove item, client must have remove permission to the specified item.
+ * @remarks The item owner can remove by default.
+ *
+ * @param[in] alias Item alias to be removed
+ *
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE              Successful
+ * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid
+ * @retval #CKMC_ERROR_DB_LOCKED         A user key is not loaded in memory (a user is not logged
+ *                                       in)
+ * @retval #CKMC_ERROR_DB_ERROR          Failed due to a database error
+ * @retval #CKMC_ERROR_DB_ALIAS_UNKNOWN  Alias does not exist
+ * @retval #CKMC_ERROR_PERMISSION_DENIED Failed to access key manager
+ *
+ * @pre User is already logged in and the user key is already loaded into memory in plain text form.
+ *
+ * @see ckmc_save_key()
+ * @see ckmc_save_cert()
+ * @see ckmc_save_data()
+ * @see ckmc_save_pkcs12()
+ * @see ckmc_create_key_pair_rsa()
+ * @see ckmc_create_key_pair_dsa()
+ * @see ckmc_create_key_pair_ecdsa()
+ */
+int ckmc_remove_alias(const char *alias);
+
 #ifdef __cplusplus
 }
 #endif
index ef9cc7c..ad0100e 100644 (file)
@@ -15,7 +15,7 @@
  *
  *
  * @file        ckmc-type.h
- * @version     1.0
+ * @version     1.2
  * @brief       Definitions of struct for the Key Manager's CAPI and their utility functions.
  */
 
@@ -23,7 +23,7 @@
 #define __TIZEN_CORE_CKMC_TYPE_H
 
 #include <stddef.h>
-#include <ckmc/ckmc-error.h>
+#include <stdbool.h>
 
 #define KEY_MANAGER_CAPI __attribute__((visibility("default")))
 
@@ -38,18 +38,20 @@ extern "C" {
  */
 
 /**
- * alias can be provided as an alias alone, or together with label - in this
- * case, separator " " (space bar) is used to separate label and alias.
+ * @brief Sperator between alias and label.
+ * @since_tizen 2.3
+ * @remarks Alias can be provided as an alias alone, or together with label - in this
+ *          case, separator " " (space bar) is used to separate label and alias.
  * @see key-manager_doc.h
  */
 KEY_MANAGER_CAPI extern char const * const ckmc_label_name_separator;
 
 /**
  * @brief Enumeration for key types of key manager.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef enum __ckmc_key_type {
-    CKMC_KEY_NONE = 0,       /**< key type not specified */
+    CKMC_KEY_NONE = 0,       /**< Key type not specified */
     CKMC_KEY_RSA_PUBLIC,     /**< RSA public key */
     CKMC_KEY_RSA_PRIVATE,    /**< RSA private key */
     CKMC_KEY_ECDSA_PUBLIC,   /**< ECDSA public key */
@@ -61,7 +63,7 @@ typedef enum __ckmc_key_type {
 
 /**
  * @brief Enumeration for data format.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef enum __ckmc_data_format {
     CKMC_FORM_DER_BASE64 = 0,  /**< DER format base64 encoded data */
@@ -72,7 +74,7 @@ typedef enum __ckmc_data_format {
 
 /**
  * @brief Enumeration for elliptic curve.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef enum __ckmc_ec_type {
     CKMC_EC_PRIME192V1 = 0, /**< Elliptic curve domain "secp192r1" listed in "SEC 2" recommended
@@ -84,7 +86,7 @@ typedef enum __ckmc_ec_type {
 
 /**
  * @brief Enumeration for hash algorithm.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef enum __ckmc_hash_algo {
     CKMC_HASH_NONE = 0, /**< No Hash Algorithm  */
@@ -96,7 +98,7 @@ typedef enum __ckmc_hash_algo {
 
 /**
  * @brief Enumeration for RSA padding algorithm.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef enum __ckmc_rsa_padding_algo {
     CKMC_NONE_PADDING = 0,  /**< No Padding */
@@ -105,17 +107,28 @@ typedef enum __ckmc_rsa_padding_algo {
 } ckmc_rsa_padding_algo_e;
 
 /**
+ * @deprecated Deprecated since 2.4. [Use ckmc_permission_e() instead]
  * @brief Enumeration for database access rights.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef enum __ckmc_access_right{
-    CKMC_AR_READ = 0,       /**< access right for read*/
-    CKMC_AR_READ_REMOVE     /**< access right for read and remove*/
+    CKMC_AR_READ = 0,       /**< Access right for read*/
+    CKMC_AR_READ_REMOVE     /**< Access right for read and remove*/
 } ckmc_access_right_e;
 
 /**
+ * @brief Enumeration for permissions to access/modify alias.
+ * @since_tizen 2.4
+ */
+typedef enum __ckmc_permission{
+    CKMC_PERMISSION_NONE        = 0x00, /**< Clear permissions */
+    CKMC_PERMISSION_READ        = 0x01, /**< Eead allowed */
+    CKMC_PERMISSION_REMOVE      = 0x02  /**< Remove allowed */
+} ckmc_permission_e;
+
+/**
  * @brief the structure for binary buffer used in key manager CAPI.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef struct __ckmc_raw_buff {
     unsigned char* data; /**< Byte array containing binary data */
@@ -124,7 +137,7 @@ typedef struct __ckmc_raw_buff {
 
 /**
  * @brief The structure for a policy for storing key/certificate/binary data.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef struct __ckmc_policy {
     char* password;   /**< Byte array used to encrypt data inside CKM. If it is not null, the data
@@ -135,7 +148,7 @@ typedef struct __ckmc_policy {
 
 /**
  * @brief The structure for key used in key manager CAPI.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef struct __ckmc_key {
     unsigned char* raw_key;   /**< Byte array of key. raw_key may be encrypted with password */
@@ -146,7 +159,7 @@ typedef struct __ckmc_key {
 
 /**
  * @brief The structure for certificate used in key manager CAPI.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef struct __ckmc_cert {
     unsigned char* raw_cert;  /**< Byte array of certificate */
@@ -156,7 +169,7 @@ typedef struct __ckmc_cert {
 
 /**
  * @brief The structure for linked list of alias.
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  */
 typedef struct __ckmc_alias_list {
     char *alias;  /**< The name of key, certificate or data stored in key manager */
@@ -164,35 +177,59 @@ typedef struct __ckmc_alias_list {
 } ckmc_alias_list_s;
 
 /**
- * @brief The structure for linked list of ckmc_cert_s
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @brief The structure for linked list of #ckmc_cert_s.
+ * @since_tizen 2.3
  */
 typedef struct __ckmc_cert_list {
-    ckmc_cert_s *cert; /**< The pointer of ckmc_cert_s */
-    struct __ckmc_cert_list *next; /**< The pointer pointing to the next ckmc_cert_list_s */
+    ckmc_cert_s *cert; /**< The pointer of #ckmc_cert_s */
+    struct __ckmc_cert_list *next; /**< The pointer pointing to the next #ckmc_cert_list_s */
 } ckmc_cert_list_s;
 
+/**
+ * @brief Enumeration for OCSP status.
+ * @since_tizen 2.4
+ */
+typedef enum __ckmc_ocsp_status {
+    CKMC_OCSP_STATUS_GOOD = 0,          /**< OCSP status is good */
+    CKMC_OCSP_STATUS_REVOKED,           /**< The certificate is revoked */
+    CKMC_OCSP_STATUS_UNKNOWN,           /**< Unknown error */
+    CKMC_OCSP_ERROR_UNSUPPORTED,        /**< The certificate does not provide OCSP extension */
+    CKMC_OCSP_ERROR_INVALID_URL,        /**< The invalid URL in certificate OCSP extension */
+    CKMC_OCSP_ERROR_INVALID_RESPONSE,   /**< The invalid response from OCSP server */
+    CKMC_OCSP_ERROR_REMOTE,             /**< OCSP remote server error */
+    CKMC_OCSP_ERROR_NET,                /**< Network connection error */
+    CKMC_OCSP_ERROR_INTERNAL            /**< OpenSSL API error */
+} ckmc_ocsp_status_e;
 
 /**
- * @internal
- * @brief Creates a new @a ckmc_key_s handle and returns it.
+ * @brief The structure for PKCS12 used in key manager CAPI.
+ * @since_tizen 2.4
+ */
+typedef struct __ckmc_pkcs12 {
+    ckmc_key_s  *priv_key;      /**< The private key, may be null */
+    ckmc_cert_s *cert;          /**< The certificate, may be null */
+    ckmc_cert_list_s *ca_chain; /**< The chain certificate list, may be null */
+} ckmc_pkcs12_s;
+
+
+/**
+ * @brief Creates a new #ckmc_key_s handle and returns it.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks You must destroy the newly created @a ckmc_key_s by calling ckmc_key_free() if it is no
- *          longer needed.
+ * @remarks You must destroy the newly created @a ppkey by calling ckmc_key_free()
+ *          if it is no longer needed.
  *
- * @param[in] raw_key  The byte array of key \n
- *                     @a raw_key may be encrypted with password.
+ * @param[in] raw_key  The byte array of key @a raw_key may be encrypted with password
  * @param[in] key_size The byte size of @a raw_key
  * @param[in] key_type The @a raw_key's type
  * @param[in] password The byte array used to decrypt @a raw_key inside key manager \n
- *                     If @a raw_key is not encrypted, @a password can be null.
- * @param[out] ppkey   The pointer to a newly created @a ckmc_key_s handle
+ *                     If @a raw_key is not encrypted, @a password can be null
+ * @param[out] ppkey   The pointer to a newly created #ckmc_key_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
+ * @retval #CKMC_ERROR_NONE              Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid
  * @retval #CKMC_ERROR_OUT_OF_MEMORY     Not enough memory
  *
@@ -202,75 +239,74 @@ typedef struct __ckmc_cert_list {
 int ckmc_key_new(unsigned char *raw_key,
                  size_t key_size,
                  ckmc_key_type_e key_type,
-                 char *password, ckmc_key_s **ppkey);
+                 char *password,
+                 ckmc_key_s **ppkey);
 
 /**
- * @brief Destroys the @a ckmc_key_s handle and releases all its resources.
+ * @brief Destroys the #ckmc_key_s handle and releases all its resources.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  *
- * @param[in] key The @a ckmc_key_s handle to destroy
+ * @param[in] key The #ckmc_key_s handle to destroy
  *
  */
 void ckmc_key_free(ckmc_key_s *key);
 
 /**
- * @internal
- * @brief Creates a new @a ckmc_raw_buffer_s handle and returns it.
+ * @brief Creates a new #ckmc_raw_buffer_s handle and returns it.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks You must destroy the newly created @a ckmc_raw_buffer_s by calling ckmc_buffer_free() if
- *          it is no longer needed.
+ * @remarks You must destroy the newly created @a ppbuffer by calling ckmc_buffer_free()
+ *          if it is no longer needed.
  *
  * @param[in]  data      The byte array of buffer
  * @param[in]  size      The byte size of buffer
- * @param[out] ppbuffer  The pointer to a newly created @a ckmc_buffer_s handle
+ * @param[out] ppbuffer  The pointer to a newly created #ckmc_buffer_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
+ * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
  * @retval #CKMC_ERROR_OUT_OF_MEMORY      Not enough memory
  *
  * @see ckmc_buffer_free()
  * @see #ckmc_raw_buffer_s
  */
-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);
 
 /**
- * @brief Destroys the @a ckmc_raw_buffer_s handle and releases all its resources.
+ * @brief Destroys the #ckmc_raw_buffer_s handle and releases all its resources.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  *
- * @param[in] buffer The @a ckmc_raw_buffer_s handle to destroy
+ * @param[in] buffer The #ckmc_raw_buffer_s structure to destroy
  *
  */
 void ckmc_buffer_free(ckmc_raw_buffer_s *buffer);
 
 /**
- * @internal
- * @brief Creates a new @a ckmc_cert_s handle and returns it.
+ * @brief Creates a new #ckmc_cert_s handle and returns it.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks You must destroy the newly created @a ckmc_cert_s by calling ckmc_cert_free() if it is
- *          no longer needed.
+ * @remarks You must destroy the newly created @a ppcert by calling ckmc_cert_free()
+ *          if it is no longer needed.
  *
  * @param[in]  raw_cert     The byte array of certificate
  * @param[in]  cert_size    The byte size of raw_cert
  * @param[in]  data_format  The encoding format of raw_cert
- * @param[out] ppcert       The pointer to a newly created @a ckmc_cert_s handle
+ * @param[out] ppcert       The pointer to a newly created #ckmc_cert_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
+ * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
  * @retval #CKMC_ERROR_OUT_OF_MEMORY      Not enough memory
  *
  * @see ckmc_cert_free()
  * @see ckmc_load_cert_from_file()
- * @see ckmc_load_from_pkcs12_file()
+ * @see #ckmc_data_format_e
  * @see #ckmc_cert_s
  */
 int ckmc_cert_new(unsigned char *raw_cert,
@@ -279,31 +315,31 @@ int ckmc_cert_new(unsigned char *raw_cert,
                   ckmc_cert_s **ppcert);
 
 /**
- * @brief Destroys the @a ckmc_cert handle and releases all its resources.
+ * @brief Destroys the #ckmc_cert handle and releases all its resources.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  *
- * @param[in] cert The @a ckmc_cert_s handle to destroy
+ * @param[in] cert The #ckmc_cert_s handle to destroy
  *
  * @see ckmc_load_cert_from_file()
  * @see ckmc_load_from_pkcs12_file()
+ * @see #ckmc_cert_s
  */
 void ckmc_cert_free(ckmc_cert_s *cert);
 
 /**
- * @brief Creates a new @a ckmc_cert_s handle from a given file and returns it.
+ * @brief Creates a new #ckmc_cert_s handle from a given file and returns it.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  *
- * @remarks You must destroy the newly created @a ckmc_cert_s by calling ckmc_cert_free() if it is
- *          no longer needed.
+ * @remarks You must destroy the newly created @a cert by calling ckmc_cert_free()
+ *          if it is no longer needed.
  *
  * @param[in]  file_path  The path of certificate file to be loaded \n
- *                        The only DER or PEM encoded certificate file is supported.
- * @param[out] cert       The pointer of newly created @a ckmc_cert_s handle
+ *                        The only DER or PEM encoded certificate file is supported
+ * @param[out] cert       The pointer of newly created #ckmc_cert_s handle
  *
- * @return #CKMC_ERROR_NONE on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE                Successful
  * @retval #CKMC_ERROR_OUT_OF_MEMORY       Not enough memory space
@@ -311,39 +347,75 @@ void ckmc_cert_free(ckmc_cert_s *cert);
  * @retval #CKMC_ERROR_FILE_ACCESS_DENIED  Provided file does not exist or cannot be accessed
  *
  * @see ckmc_cert_free()
- * @see ckmc_load_from_pkcs12_file()
  * @see #ckmc_cert_s
  */
 int ckmc_load_cert_from_file(const char *file_path, ckmc_cert_s **cert);
 
 /**
- * @brief Creates a new @a ckmc_key_s(private key), @a ckmc_cert_s(certificate), and
- *        @a ckmc_cert_list_s(CA certificates) handle from a given PKCS#12 file and returns them.
+ * @brief Creates a new #ckmc_pkcs12_s handle and returns it.
+ *
+ * @since_tizen 2.4
+ *
+ * @remarks You must destroy the newly created @a pkcs12_bundle by calling ckmc_pkcs12_free()
+ *          if it is no longer needed.
+ * @remarks On success, @a private_key, @a cert and @a ca_cert_list ownership is transferred
+ *          into newly returned #ckmc_pkcs12_s.
+ *
+ * @param[in]  private_key      #ckmc_key_s handle to the private key (optional)
+ * @param[in]  cert             #ckmc_cert_s handle to the certificate (optional)
+ * @param[in]  ca_cert_list     #ckmc_cert_list_s list of chain certificate handles (optional)
+ * @param[out] pkcs12_bundle    The pointer to a newly created #ckmc_pkcs12_s handle
+ *
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE               Successful
+ * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid or @a private_key, @a cert
+ *                                        and @a ca_cert_list all are null
+ * @retval #CKMC_ERROR_OUT_OF_MEMORY      Not enough memory
+ *
+ * @see ckmc_pkcs12_free()
+ * @see ckmc_load_from_pkcs12_file()
+ * @see ckmc_pkcs12_load()
+ * @see #ckmc_key_s
+ * @see #ckmc_cert_s
+ * @see #ckmc_cert_list_s
+ * @see #ckmc_pkcs12_s
+ */
+int ckmc_pkcs12_new(ckmc_key_s *private_key,
+                    ckmc_cert_s *cert,
+                    ckmc_cert_list_s *ca_cert_list,
+                    ckmc_pkcs12_s **pkcs12_bundle);
+
+/**
+ * @deprecated Deprecated since 2.4. [Use ckmc_pkcs12_load() instead]
+ * @brief Creates a new @a private_key, @a cert and @a ca_cert_list handle from a given
+ *        PKCS12 file and returns them.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  *
- * @remarks You must destroy the newly created @a ckmc_key_s, @a ckmc_cert_s, and
- *          @a ckmc_cert_list_s by calling ckmc_key_free(), ckmc_cert_free(), and
+ * @remarks You must destroy the newly created @a private_key, @a cert and
+ *          @a ca_cert_list by calling ckmc_key_free(), ckmc_cert_free() and
  *          ckmc_cert_list_all_free() if they are no longer needed.
  *
  * @param[in]  file_path    The path of PKCS12 file to be loaded
  * @param[in]  passphrase   The passphrase used to decrypt the PCKS12 file \n
- *                          If PKCS12 file is not encrypted, passphrase can be null.
- * @param[out] private_key  The pointer of newly created @a ckmc_key_s handle for a private key
- * @param[out] cert         The pointer of newly created @a ckmc_cert_s handle for a certificate \n
- *                          It is null if the PKCS12 file does not contain a certificate.
- * @param[out] ca_cert_list The pointer of newly created @a ckmc_cert_list_s handle for CA
+ *                          If PKCS12 file is not encrypted, passphrase can be null
+ * @param[out] private_key  The pointer of newly created #ckmc_key_s handle for a private key
+ * @param[out] cert         The pointer of newly created #ckmc_cert_s handle for a certificate \n
+ *                          It is null if the PKCS12 file does not contain a certificate
+ * @param[out] ca_cert_list The pointer of newly created #ckmc_cert_list_s handle for CA
  *                          certificates \n
- *                          It is null if the PKCS12 file does not contain CA certificates.
+ *                          It is null if the PKCS12 file does not contain CA certificates
  *
- * @return #CKMC_ERROR_NONE on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
  * @retval #CKMC_ERROR_NONE                Successful
  * @retval #CKMC_ERROR_OUT_OF_MEMORY       Not enough memory space
  * @retval #CKMC_ERROR_INVALID_FORMAT      Invalid PKCS12 file format
  * @retval #CKMC_ERROR_FILE_ACCESS_DENIED  Provided file does not exist or cannot be accessed
  *
+ * @see ckmc_pkcs12_new()
+ * @see ckmc_pkcs12_load()
  * @see ckmc_key_free()
  * @see ckmc_cert_free()
  * @see ckmc_cert_list_all_free()
@@ -353,27 +425,67 @@ int ckmc_load_cert_from_file(const char *file_path, ckmc_cert_s **cert);
  */
 int ckmc_load_from_pkcs12_file(const char *file_path,
                                const char *passphrase,
-                               ckmc_key_s **private_key, ckmc_cert_s **cert,
+                               ckmc_key_s **private_key,
+                               ckmc_cert_s **cert,
                                ckmc_cert_list_s **ca_cert_list);
 
 /**
- * @internal
- * @brief Creates a new @a ckmc_alias_list_s handle and returns it.
- *        The alias pointer in the returned @a ckmc_alias_list_s handle points to the provided
+ * @brief Creates a new #ckmc_pkcs12_s handle from a given PKCS#12 file and returns it.
+ *
+ * @since_tizen 2.4
+ *
+ * @remarks You must destroy the newly created @a pkcs12_bundle by calling ckmc_pkcs12_free() if
+ *          they are no longer needed.
+ *
+ * @param[in]  file_path     The path of PKCS12 file to be loaded
+ * @param[in]  passphrase    The passphrase used to decrypt the PCKS12 file \n
+ *                           If PKCS12 file is not encrypted, passphrase can be null
+ * @param[out] pkcs12_bundle The pointer of newly created #ckmc_cert_list_s handle for CA
+ *                           certificates \n
+ *                           It is null if the PKCS12 file does not contain CA certificates
+ *
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
+ *
+ * @retval #CKMC_ERROR_NONE                Successful
+ * @retval #CKMC_ERROR_OUT_OF_MEMORY       Not enough memory space
+ * @retval #CKMC_ERROR_INVALID_FORMAT      Invalid PKCS12 file format
+ * @retval #CKMC_ERROR_FILE_ACCESS_DENIED  Provided file does not exist or cannot be accessed
+ *
+ * @see ckmc_pkcs12_free()
+ * @see #ckmc_pkcs12_s
+ */
+int ckmc_pkcs12_load(const char *file_path,
+                     const char *passphrase,
+                     ckmc_pkcs12_s **pkcs12_bundle);
+
+/**
+ * @brief Destroys the #ckmc_pkcs12_s handle and releases all its resources.
+ *
+ * @since_tizen 2.4
+ *
+ * @param[in] pkcs12 The #ckmc_pkcs12_s handle to destroy
+ *
+ * @see ckmc_pkcs12_new()
+ * @see ckmc_pkcs12_load()
+ */
+void ckmc_pkcs12_free(ckmc_pkcs12_s *pkcs12);
+
+/**
+ * @brief Creates a new #ckmc_alias_list_s handle and returns it.
+ *        The alias pointer in the returned #ckmc_alias_list_s handle points to the provided
  *        characters and next is null.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks You must destroy the newly created @a ckmc_alias_list_s
- *          by calling ckmc_alias_list_free() or ckmc_alias_list_all_free() if it is no longer
- *          needed.
+ * @remarks You must destroy the newly created @a ppalias_list by calling ckmc_alias_list_free()
+ *          or ckmc_alias_list_all_free() if it is no longer needed.
  *
- * @param[in]  alias        The first item to be set in the newly created @a ckmc_alias_list_s
- * @param[out] ppalias_list The pointer to a newly created @a ckmc_alias_list_s handle
+ * @param[in]  alias        The first item to be set in the newly created #ckmc_alias_list_s
+ * @param[out] ppalias_list The pointer to a newly created #ckmc_alias_list_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
+ * @retval #CKMC_ERROR_NONE              Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER Input parameter is invalid
  * @retval #CKMC_ERROR_OUT_OF_MEMORY     Not enough memory
  *
@@ -383,21 +495,20 @@ int ckmc_load_from_pkcs12_file(const char *file_path,
 int ckmc_alias_list_new(char *alias, ckmc_alias_list_s **ppalias_list);
 
 /**
- * @internal
- * @brief Creates a new @a ckmc_alias_list_s handle, adds it to a previous @a ckmc_alias_list_s and
- *        returns it. The alias pointer in the returned @a ckmc_alias_list_s handle points to the
+ * @brief Creates a new #ckmc_alias_list_s handle, adds it to a @a previous and returns it.
+ *        The alias pointer in the returned #ckmc_alias_list_s handle points to the
  *        provided characters and next is null.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @param[in]  previous  The last @a ckmc_alias_list_s handle to which a newly created
- *                       @a ckmc_alias_list_s is added
- * @param[in]  alias     The item to be set in the newly created @a ckmc_alias_list_s
- * @param[out] pplast    The pointer to a newly created and added @a ckmc_alias_list_s handle
+ * @param[in]  previous  The last #ckmc_alias_list_s handle to which a newly created
+ *                       #ckmc_alias_list_s is added
+ * @param[in]  alias     The item to be set in the newly created #ckmc_alias_list_s
+ * @param[out] pplast    The pointer to a newly created and added #ckmc_alias_list_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
+ * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
  * @retval #CKMC_ERROR_OUT_OF_MEMORY      Not enough memory
  *
@@ -409,15 +520,14 @@ int ckmc_alias_list_add(ckmc_alias_list_s *previous,
                         ckmc_alias_list_s **pplast);
 
 /**
- * @internal
- * @brief Destroys the @a ckmc_alias_list_s handle and releases resources of @a ckmc_alias_list_s
- *        from the provided first handle cascadingly.
+ * @brief Destroys the #ckmc_alias_list_s handle and releases resources from the provided
+ *        @a first handle cascadingly.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks It does not destroy an alias itself in @a ckmc_alias_list_s.
+ * @remarks It does not destroy an alias itself in #ckmc_alias_list_s.
  *
- * @param[in] first The first @a ckmc_alias_list_s handle to destroy
+ * @param[in] first The first #ckmc_alias_list_s handle to destroy
  *
  * @see ckmc_alias_list_all_free()
  * @see #ckmc_alias_list_s
@@ -425,36 +535,36 @@ int ckmc_alias_list_add(ckmc_alias_list_s *previous,
 void ckmc_alias_list_free(ckmc_alias_list_s *first);
 
 /**
- * @brief Destroys the @a ckmc_alias_list_s handle and releases all its resources from the provided
- *        first handle cascadingly.
+ * @brief Destroys the #ckmc_alias_list_s handle and releases all its resources from the provided
+ *        @a first handle cascadingly.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks It also destroys the alias in @a ckmc_alias_list_s.
+ * @remarks It also destroys the alias in #ckmc_alias_list_s.
  *
- * @param[in] first The first @a ckmc_alias_list_s handle to destroy
+ * @param[in] first The first #ckmc_alias_list_s handle to destroy
  *
+ * @see ckmc_alias_list_free()
  * @see #ckmc_alias_list_s
  */
 void ckmc_alias_list_all_free(ckmc_alias_list_s *first);
 
 /**
- * @internal
- * @brief Creates a new @a ckmc_cert_list_s handle and returns it.
- *        The cert pointer in the returned @a ckmc_cert_list_s handle points to the provided
- *        @a ckmc_cert_s and next is null.
+ * @brief Creates a new #ckmc_cert_list_s handle and returns it.
+ *        The cert pointer in the returned #ckmc_cert_list_s handle points to the provided
+ *        #ckmc_cert_s and next is null.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks You must destroy the newly created @a ckmc_cert_list_s by calling ckmc_cert_list_free()
+ * @remarks You must destroy the newly created @a ppalias_list by calling ckmc_cert_list_free()
  *          or ckmc_cert_list_all_free() if it is no longer needed.
  *
- * @param[in]  cert          The first item to be set in the newly created @a ckmc_cert_list_s
- * @param[out] ppalias_list  The pointer to a newly created @a ckmc_alias_list_s handle
+ * @param[in]  cert          The first item to be set in the newly created #ckmc_cert_list_s
+ * @param[out] ppalias_list  The pointer to a newly created #ckmc_alias_list_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
+ * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
  * @retval #CKMC_ERROR_OUT_OF_MEMORY      Not enough memory
  *
@@ -464,21 +574,20 @@ void ckmc_alias_list_all_free(ckmc_alias_list_s *first);
 int ckmc_cert_list_new(ckmc_cert_s *cert, ckmc_cert_list_s **ppalias_list);
 
 /**
- * @internal
- * @brief Creates a new @a ckmc_cert_list_s handle, adds it to a previous @a ckmc_cert_list_s and
- *        returns it. The cert pointer in the returned @a ckmc_alias_list_s handle points to the
- *        provided @a ckmc_cert_s and next is null.
+ * @brief Creates a new #ckmc_cert_list_s handle, adds it to a previous #ckmc_cert_list_s and
+ *        returns it. The cert pointer in the returned #ckmc_alias_list_s handle points to the
+ *        provided #ckmc_cert_s and next is null.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @param[in]  previous  The last @a ckmc_cert_list_s handle to which a newly created
- *                       @a ckmc_cert_list_s is added
- * @param[in]  cert      The item to be set in the newly created @a ckmc_cert_list_s
- * @param[out] pplast    The pointer to a newly created and added @a ckmc_alias_list_s handle
+ * @param[in]  previous  The last #ckmc_cert_list_s handle to which a newly created
+ *                       #ckmc_cert_list_s is added
+ * @param[in]  cert      The item to be set in the newly created #ckmc_cert_list_s
+ * @param[out] pplast    The pointer to a newly created and added #ckmc_alias_list_s handle
  *
- * @return @c 0 on success,
- *         otherwise a negative error value
+ * @return #CKMC_ERROR_NONE on success, otherwise a negative error value
  *
+ * @retval #CKMC_ERROR_NONE               Successful
  * @retval #CKMC_ERROR_INVALID_PARAMETER  Input parameter is invalid
  * @retval #CKMC_ERROR_OUT_OF_MEMORY      Not enough memory
  *
@@ -488,15 +597,14 @@ int ckmc_cert_list_new(ckmc_cert_s *cert, ckmc_cert_list_s **ppalias_list);
 int ckmc_cert_list_add(ckmc_cert_list_s *previous, ckmc_cert_s *cert, ckmc_cert_list_s **pplast);
 
 /**
- * @internal
- * @brief Destroys the @a ckmc_cert_list_s handle and releases resources of @a ckmc_cert_list_s
- *        from the provided first handle cascadingly.
+ * @brief Destroys the #ckmc_cert_list_s handle and releases resources from the provided
+ *        @a first handle cascadingly.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.4
  *
- * @remarks It does not destroy @a ckmc_cert_s itself in @a ckmc_cert_list_s.
+ * @remarks It does not destroy #ckmc_cert_s itself in #ckmc_cert_list_s.
  *
- * @param[in] first The first @a ckmc_cert_list_s handle to destroy
+ * @param[in] first The first #ckmc_cert_list_s handle to destroy
  *
  * @see ckmc_cert_list_all_free()
  * @see #ckmc_cert_list_s
@@ -504,15 +612,16 @@ int ckmc_cert_list_add(ckmc_cert_list_s *previous, ckmc_cert_s *cert, ckmc_cert_
 void ckmc_cert_list_free(ckmc_cert_list_s *first);
 
 /**
- * @brief Destroys the @a ckmc_cert_list_s handle and releases all its resources from the provided
- *        first handle cascadingly.
+ * @brief Destroys the #ckmc_cert_list_s handle and releases all its resources from the provided
+ *        @a first handle cascadingly.
  *
- * @since_tizen @if MOBILE 2.3 @elseif WEARABLE 2.3.1 @endif
+ * @since_tizen 2.3
  *
- * @remarks It also destroys @a ckmc_cert_s in ckmc_cert_list_s.
+ * @remarks It also destroys #ckmc_cert_s in #ckmc_cert_list_s.
  *
- * @param[in] first The first @a ckmc_cert_list_s handle to destroy
+ * @param[in] first The first #ckmc_cert_list_s handle to destroy
  *
+ * @see ckmc_cert_list_free()
  * @see #ckmc_cert_list_s
  */
 void ckmc_cert_list_all_free(ckmc_cert_list_s *first);
diff --git a/src/listener/CMakeLists.txt b/src/listener/CMakeLists.txt
deleted file mode 100644 (file)
index 25be929..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-PKG_CHECK_MODULES(LISTENER_DEP
-    REQUIRED
-    dlog
-    glib-2.0
-    capi-appfw-package-manager
-    libsystemd-daemon
-    )
-
-SET(LISTENER_SOURCES ${PROJECT_SOURCE_DIR}/src/listener/listener-daemon.cpp)
-
-# fPIE flag is added for ASLR
-SET_SOURCE_FILES_PROPERTIES(
-    ${LISTENER_SOURCES}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fvisibility=hidden -fPIE")
-
-INCLUDE_DIRECTORIES(
-    ${PROJECT_SOURCE_DIR}/src/include
-    ${LISTENER_DEP_INCLUDE_DIRS}
-    )
-
-ADD_EXECUTABLE(${TARGET_LISTENER} ${LISTENER_SOURCES})
-
-# pie flag is added for ASLR
-TARGET_LINK_LIBRARIES(
-    ${TARGET_LISTENER}
-    ${LISTENER_DEP_LIBRARIES}
-    ${TARGET_KEY_MANAGER_CLIENT}
-    ${TARGET_KEY_MANAGER_CONTROL_CLIENT}
-    -pie
-    )
-
-INSTALL(TARGETS ${TARGET_LISTENER} DESTINATION bin)
diff --git a/src/listener/listener-daemon.cpp b/src/listener/listener-daemon.cpp
deleted file mode 100644 (file)
index b86ffcf..0000000
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2014 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        listener-daemon.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Listener daemon handle some events for key-manager
- */
-#include <fcntl.h>
-#include <unistd.h>
-
-#include <glib.h>
-#include <package_manager.h>
-#include <ckm/ckm-control.h>
-#include <ckm/ckm-type.h>
-#include <dlog.h>
-
-#define CKM_LISTENER_TAG "CKM_LISTENER"
-
-namespace {
-const char* const CKM_LOCK = "/var/run/key-manager.pid";
-};
-
-bool isCkmRunning()
-{
-    int lock = TEMP_FAILURE_RETRY(open(CKM_LOCK, O_RDWR));
-    if (lock == -1)
-        return false;
-
-    int ret = lockf(lock, F_TEST, 0);
-    close(lock);
-
-    // if lock test fails because of an error assume ckm is running
-    return (0 != ret);
-}
-
-void packageUninstalledEventCallback(
-    const char *type,
-    const char *package,
-    package_manager_event_type_e eventType,
-    package_manager_event_state_e eventState,
-    int progress,
-    package_manager_error_e error,
-    void *userData)
-{
-    (void) type;
-    (void) progress;
-    (void) error;
-    (void) userData;
-
-    if (eventType != PACKAGE_MANAGER_EVENT_TYPE_UNINSTALL ||
-            eventState != PACKAGE_MANAGER_EVENT_STATE_STARTED ||
-            package == NULL) {
-        SLOG(LOG_DEBUG, CKM_LISTENER_TAG, "PackageUninstalled Callback error of Invalid Param");
-    }
-    else {
-        SLOG(LOG_DEBUG, CKM_LISTENER_TAG, "PackageUninstalled Callback. Uninstalation of: %s", package);
-        auto control = CKM::Control::create();
-        int ret = 0;
-        if ( CKM_API_SUCCESS != (ret = control->removeApplicationData(std::string(package))) ) {
-            SLOG(LOG_ERROR, CKM_LISTENER_TAG, "CKM::Control::removeApplicationData error. ret : %d\n", ret);
-        }
-        else {
-            SLOG(LOG_DEBUG, CKM_LISTENER_TAG,
-                "CKM::Control::removeApplicationData success. Uninstallation package : %s\n", package);
-        }
-    }
-}
-
-int main(void)
-{
-    SLOG(LOG_DEBUG, CKM_LISTENER_TAG, "%s", "Start!");
-
-    // Let's start to listen
-    GMainLoop *main_loop = g_main_loop_new(NULL, FALSE);
-
-    package_manager_h manager;
-
-    while (true) {
-        if (PACKAGE_MANAGER_ERROR_NONE != package_manager_create(&manager)) {
-            SLOG(LOG_ERROR, CKM_LISTENER_TAG, "%s", "Error in create package_manager");
-
-            sleep(5);
-            continue;
-        }
-
-        if (PACKAGE_MANAGER_ERROR_NONE != package_manager_set_event_cb(manager, packageUninstalledEventCallback, NULL)) {
-            SLOG(LOG_ERROR, CKM_LISTENER_TAG, "%s", "Error in package_manager_set_event_cb");
-            package_manager_destroy(manager);
-
-            sleep(5);
-            continue;
-        }
-
-        break;
-    }
-
-    g_main_loop_run(main_loop);
-
-    package_manager_destroy(manager);
-
-    return 0;
-}
-
index a50d7b7..1e92e40 100644 (file)
@@ -1,8 +1,6 @@
 PKG_CHECK_MODULES(COMMON_DEP
     REQUIRED
     dlog
-    openssl
-    libsmack
     libcrypto
     libsystemd-journal
     )
@@ -20,6 +18,7 @@ SET(COMMON_SOURCES
     ${COMMON_PATH}/common/certificate-impl.cpp
     ${COMMON_PATH}/common/key-impl.cpp
     ${COMMON_PATH}/common/pkcs12-impl.cpp
+    ${COMMON_PATH}/common/client-info-impl.cpp
     ${COMMON_PATH}/common/log-setup.cpp
     ${COMMON_PATH}/dpl/log/src/abstract_log_provider.cpp
     ${COMMON_PATH}/dpl/log/src/dlog_log_provider.cpp
@@ -35,17 +34,12 @@ SET(COMMON_SOURCES
     ${COMMON_PATH}/dpl/core/src/errno_string.cpp
     )
 
-INCLUDE_DIRECTORIES(SYSTEM
-    ${COMMON_DEP_INCLUDE_DIRS}
-    )
-
 INCLUDE_DIRECTORIES(
+    SYSTEM
+    ${COMMON_DEP_INCLUDE_DIRS}
     ${COMMON_PATH}/common
     ${COMMON_PATH}/dpl/core/include
     ${COMMON_PATH}/dpl/log/include
-    ${COMMON_PATH}/dpl/db/include
-    ${COMMON_PATH}/sqlcipher
-       ${COMMON_PATH}/service
     )
 
 ADD_LIBRARY(${TARGET_KEY_MANAGER_COMMON} SHARED ${COMMON_SOURCES})
@@ -62,8 +56,4 @@ TARGET_LINK_LIBRARIES(${TARGET_KEY_MANAGER_COMMON}
     ${COMMON_DEP_LIBRARIES}
     )
 
-##########################################################################
-
 INSTALL(TARGETS ${TARGET_KEY_MANAGER_COMMON} DESTINATION ${LIB_INSTALL_DIR})
-
-
index 997cf02..5caf087 100644 (file)
@@ -14,7 +14,7 @@
  *  limitations under the License
  *
  *
- * @file        ckmc-control.h
+ * @file        ckmc-control.cpp
  * @author      Yuseok Jeon(yuseok.jeon@samsung.com)
  * @version     1.0
  * @brief       provides conversion methods to C from C++ for key-manager control functions.
@@ -34,20 +34,13 @@ CKM::Password _toPasswordStr(const char *str)
     return CKM::Password(str);
 }
 
-int _ckmc_set_permission_by_adm(uid_t user, const char *alias, const char *accessor, int permissions)
-{
-    if (!alias || !accessor)
-        return CKMC_ERROR_INVALID_PARAMETER;
-
-    auto control = CKM::Control::create();
-    return to_ckmc_error(control->setPermission(user, alias, accessor, permissions));
-}
-
 KEY_MANAGER_CAPI
 int ckmc_unlock_user_key(uid_t user, const char *password)
 {
     auto control = CKM::Control::create();
-    int ret = control->unlockUserKey(user, _toPasswordStr(password));
+    int ret = control->unlockUserKey(
+                CKM::ClientInfo(user),
+                _toPasswordStr(password));
     return to_ckmc_error(ret);
 }
 
@@ -55,7 +48,7 @@ KEY_MANAGER_CAPI
 int ckmc_lock_user_key(uid_t user)
 {
     auto control = CKM::Control::create();
-    int ret = control->lockUserKey(user);
+    int ret = control->lockUserKey(CKM::ClientInfo(user));
     return to_ckmc_error(ret);
 }
 
@@ -63,7 +56,7 @@ KEY_MANAGER_CAPI
 int ckmc_remove_user_data(uid_t user)
 {
     auto control = CKM::Control::create();
-    int ret = control->removeUserData(user);
+    int ret = control->removeUserData(CKM::ClientInfo(user));
     return to_ckmc_error(ret);
 }
 
@@ -71,9 +64,10 @@ KEY_MANAGER_CAPI
 int ckmc_change_user_password(uid_t user, const char *oldPassword, const char *newPassword)
 {
     auto control = CKM::Control::create();
-    int ret = control->changeUserPassword(user,
-                                          _toPasswordStr(oldPassword),
-                                          _toPasswordStr(newPassword));
+    int ret = control->changeUserPassword(
+                CKM::ClientInfo(user),
+                _toPasswordStr(oldPassword),
+                _toPasswordStr(newPassword));
     return to_ckmc_error(ret);
 }
 
@@ -81,7 +75,9 @@ KEY_MANAGER_CAPI
 int ckmc_reset_user_password(uid_t user, const char *newPassword)
 {
     auto control = CKM::Control::create();
-    int ret = control->resetUserPassword(user, _toPasswordStr(newPassword));
+    int ret = control->resetUserPassword(
+                CKM::ClientInfo(user),
+                _toPasswordStr(newPassword));
     return to_ckmc_error(ret);
 }
 
@@ -97,7 +93,21 @@ int ckmc_allow_access_by_adm(uid_t user, const char* owner, const char *alias, c
         return ec;
 
     // if label given twice, service will return an error
-    return _ckmc_set_permission_by_adm(user, CKM::AliasSupport::merge(CKM::Label(owner), CKM::Name(alias)).c_str(), accessor, permissionMask);
+    return ckmc_set_permission_by_adm(user, CKM::AliasSupport::merge(CKM::Label(owner), CKM::Name(alias)).c_str(), accessor, permissionMask);
+}
+
+KEY_MANAGER_CAPI
+int ckmc_set_permission_by_adm(uid_t user, const char *alias, const char *accessor, int permissions)
+{
+    if (!alias || !accessor)
+        return CKMC_ERROR_INVALID_PARAMETER;
+
+    auto control = CKM::Control::create();
+    return to_ckmc_error(control->setPermission(
+                CKM::ClientInfo(user),
+                alias,
+                accessor,
+                permissions));
 }
 
 KEY_MANAGER_CAPI
@@ -109,8 +119,9 @@ int ckmc_deny_access_by_adm(uid_t user, const char* owner, const char *alias, co
     // if label given twice, service will return an error
     auto control = CKM::Control::create();
     return to_ckmc_error(control->setPermission(
-                                user,
-                                CKM::AliasSupport::merge(CKM::Label(owner), CKM::Name(alias)).c_str(),
-                                accessor,
-                                CKM::Permission::NONE));
+                CKM::ClientInfo(user),
+                CKM::AliasSupport::merge(CKM::Label(owner),
+                CKM::Name(alias)).c_str(),
+                accessor,
+                CKM::Permission::NONE));
 }
index 1f3da2f..65bc9aa 100644 (file)
  *  limitations under the License
  *
  *
- * @file        ckmc-control.h
+ * @file        ckmc-manager.cpp
  * @author      Yuseok Jeon(yuseok.jeon@samsung.com)
  * @version     1.0
- * @brief       provides conversion methods to C from C++ for key-manager control functions.
+ * @brief       provides conversion methods to C from C++ for key-manager storage functions.
  */
 
 #include <ckm/ckm-type.h>
@@ -27,7 +27,6 @@
 #include <ckmc/ckmc-error.h>
 #include <ckmc-type-converter.h>
 #include <client-common.h>
-#include <iostream>
 #include <string.h>
 
 namespace
@@ -117,25 +116,6 @@ ckmc_cert_list_s *_toNewCkmCertList(const CKM::CertificateShPtrVector &certVecto
     return start;
 }
 
-int _ckmc_remove_alias(const char *alias)
-{
-    if(!alias)
-        return CKMC_ERROR_INVALID_PARAMETER;
-
-    CKM::ManagerShPtr mgr = CKM::Manager::create();
-    int ret =  mgr->removeAlias(alias);
-    return to_ckmc_error(ret);
-}
-
-int _ckmc_set_permission(const char *alias, const char *accessor, int permissions)
-{
-    if (!alias || !accessor)
-        return CKMC_ERROR_INVALID_PARAMETER;
-
-    CKM::ManagerShPtr mgr = CKM::Manager::create();
-    return to_ckmc_error(mgr->setPermission(alias, accessor, permissions));
-}
-
 }
 
 
@@ -169,7 +149,7 @@ int ckmc_save_key(const char *alias, const ckmc_key_s key, const ckmc_policy_s p
 KEY_MANAGER_CAPI
 int ckmc_remove_key(const char *alias)
 {
-    return _ckmc_remove_alias(alias);
+    return ckmc_remove_alias(alias);
 }
 
 KEY_MANAGER_CAPI
@@ -264,7 +244,7 @@ int ckmc_save_cert(const char *alias, const ckmc_cert_s cert, const ckmc_policy_
 KEY_MANAGER_CAPI
 int ckmc_remove_cert(const char *alias)
 {
-    return _ckmc_remove_alias(alias);
+    return ckmc_remove_alias(alias);
 }
 
 KEY_MANAGER_CAPI
@@ -331,6 +311,95 @@ int ckmc_get_cert_alias_list(ckmc_alias_list_s** alias_list) {
 }
 
 KEY_MANAGER_CAPI
+int ckmc_save_pkcs12(const char *alias, const ckmc_pkcs12_s *ppkcs, const ckmc_policy_s key_policy, const ckmc_policy_s cert_policy)
+{
+    CKM::KeyShPtr private_key;
+    CKM::CertificateShPtr cert;
+    CKM::CertificateShPtrVector ca_cert_list;
+
+    if(alias==NULL || ppkcs==NULL) {
+        return CKMC_ERROR_INVALID_PARAMETER;
+    }
+    CKM::Alias ckmAlias(alias);
+    private_key = _toCkmKey(ppkcs->priv_key);
+    cert = _toCkmCertificate(ppkcs->cert);
+    ca_cert_list = _toCkmCertificateVector(ppkcs->ca_chain);
+
+    CKM::Policy keyPolicy(_tostring(key_policy.password), key_policy.extractable);
+    CKM::Policy certPolicy(_tostring(cert_policy.password), cert_policy.extractable);
+
+    CKM::PKCS12ShPtr pkcs12(new CKM::PKCS12Impl(private_key, cert, ca_cert_list));
+
+    CKM::ManagerShPtr mgr = CKM::Manager::create();
+    int ret = mgr->savePKCS12(ckmAlias, pkcs12, keyPolicy, certPolicy);
+
+    return to_ckmc_error(ret);
+}
+
+KEY_MANAGER_CAPI
+int ckmc_get_pkcs12(const char *alias, const char *key_password, const char *cert_password, ckmc_pkcs12_s **pkcs12)
+{
+    int ret;
+    CKM::PKCS12ShPtr pkcs;
+    CKM::Password keyPass, certPass;
+    ckmc_key_s *private_key = NULL;
+    ckmc_cert_s *cert = NULL;
+    ckmc_cert_list_s *ca_cert_list = 0;
+
+    if(!alias || !pkcs12) {
+        return CKMC_ERROR_INVALID_PARAMETER;
+    }
+
+    if (key_password)
+        keyPass = key_password;
+
+    if (cert_password)
+        certPass = cert_password;
+
+    auto mgr = CKM::Manager::create();
+
+    if((ret = mgr->getPKCS12(alias, keyPass, certPass, pkcs)) != CKM_API_SUCCESS) {
+        return to_ckmc_error(ret);
+    }
+
+    if(!pkcs)
+        return CKMC_ERROR_BAD_RESPONSE;
+
+    auto pkcsKey = pkcs->getKey();
+    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)
+            return ret;
+    }
+
+    auto pkcsCert = pkcs->getCertificate();
+    if(pkcsCert)
+    {
+        CKM::RawBuffer buffer = pkcsCert->getDER();
+        ret = ckmc_cert_new(buffer.data(), buffer.size(), CKMC_FORM_DER, &cert);
+        if(ret != CKMC_ERROR_NONE) {
+            ckmc_key_free(private_key);
+            return ret;
+        }
+    }
+
+    ca_cert_list = _toNewCkmCertList(pkcs->getCaCertificateShPtrVector());
+
+    ret = ckmc_pkcs12_new(private_key, cert, ca_cert_list, pkcs12);
+    if(ret != CKMC_ERROR_NONE)
+    {
+        ckmc_key_free(private_key);
+        ckmc_cert_free(cert);
+        ckmc_cert_list_free(ca_cert_list);
+    }
+    return ret;
+}
+
+
+KEY_MANAGER_CAPI
 int ckmc_save_data(const char *alias, ckmc_raw_buffer_s data, const ckmc_policy_s policy)
 {
     if(alias == NULL) {
@@ -354,7 +423,7 @@ int ckmc_save_data(const char *alias, ckmc_raw_buffer_s data, const ckmc_policy_
 KEY_MANAGER_CAPI
 int ckmc_remove_data(const char *alias)
 {
-    return _ckmc_remove_alias(alias);
+    return ckmc_remove_alias(alias);
 }
 
 KEY_MANAGER_CAPI
@@ -616,6 +685,64 @@ int ckmc_get_cert_chain_with_alias(const ckmc_cert_s *cert, const ckmc_alias_lis
 }
 
 KEY_MANAGER_CAPI
+int ckmc_get_cert_chain_with_trustedcert(const ckmc_cert_s* cert,
+                                         const ckmc_cert_list_s* untrustedcerts,
+                                         const ckmc_cert_list_s* trustedcerts,
+                                         const bool sys_certs,
+                                         ckmc_cert_list_s** ppcert_chain_list)
+{
+    int ret;
+    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) {
+        return CKMC_ERROR_INVALID_PARAMETER;
+    }
+    CKM::CertificateShPtr ckm_cert = _toCkmCertificate(cert);
+
+    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) {
+        return to_ckmc_error(ret);
+    }
+
+    *ppcert_chain_list = _toNewCkmCertList(ckm_cert_chain);
+
+    return CKMC_ERROR_NONE;
+}
+
+KEY_MANAGER_CAPI
+int ckmc_ocsp_check(const ckmc_cert_list_s *pcert_chain_list, ckmc_ocsp_status_e *ocsp_status)
+{
+    if (pcert_chain_list == NULL
+        || pcert_chain_list->cert == NULL
+        || pcert_chain_list->cert->raw_cert == NULL
+        || pcert_chain_list->cert->cert_size <= 0
+        || ocsp_status == NULL) {
+        return CKMC_ERROR_INVALID_PARAMETER;
+    }
+
+    int ret = CKMC_ERROR_UNKNOWN;
+    int tmpOcspStatus = -1;
+    CKM::ManagerShPtr mgr = CKM::Manager::create();
+    CKM::CertificateShPtrVector ckmCertChain = _toCkmCertificateVector(pcert_chain_list);
+
+    if (ckmCertChain.size() < 2) {
+        return CKMC_ERROR_INVALID_PARAMETER;
+    }
+
+    ret = mgr->ocspCheck(ckmCertChain, tmpOcspStatus);
+    *ocsp_status = to_ckmc_ocsp_status(tmpOcspStatus);
+    return to_ckmc_error(ret);
+}
+
+KEY_MANAGER_CAPI
 int ckmc_allow_access(const char *alias, const char *accessor, ckmc_access_right_e granted)
 {
     int ec, permissionMask;
@@ -623,7 +750,17 @@ int ckmc_allow_access(const char *alias, const char *accessor, ckmc_access_right
     if(ec != CKMC_ERROR_NONE)
         return ec;
 
-    return _ckmc_set_permission(alias, accessor, permissionMask);
+    return ckmc_set_permission(alias, accessor, permissionMask);
+}
+
+KEY_MANAGER_CAPI
+int ckmc_set_permission(const char *alias, const char *accessor, int permissions)
+{
+    if (!alias || !accessor)
+        return CKMC_ERROR_INVALID_PARAMETER;
+
+    CKM::ManagerShPtr mgr = CKM::Manager::create();
+    return to_ckmc_error(mgr->setPermission(alias, accessor, permissions));
 }
 
 KEY_MANAGER_CAPI
@@ -635,3 +772,14 @@ int ckmc_deny_access(const char *alias, const char *accessor)
     CKM::ManagerShPtr mgr = CKM::Manager::create();
     return to_ckmc_error(mgr->setPermission(alias, accessor, CKM::Permission::NONE));
 }
+
+KEY_MANAGER_CAPI
+int ckmc_remove_alias(const char *alias)
+{
+    if(!alias)
+        return CKMC_ERROR_INVALID_PARAMETER;
+
+    CKM::ManagerShPtr mgr = CKM::Manager::create();
+    int ret =  mgr->removeAlias(alias);
+    return to_ckmc_error(ret);
+}
index 479e327..97fcfe7 100644 (file)
 #include <ckmc/ckmc-type.h>
 #include <ckmc-type-converter.h>
 
-typedef enum __ckmc_permission{
-    CKMC_PERMISSION_NONE        = 0x00, /**< clear permissions */
-    CKMC_PERMISSION_READ        = 0x01, /**< read allowed */
-    CKMC_PERMISSION_REMOVE      = 0x02  /**< remove allowed */
-} ckmc_permission_e;
-
 int to_ckm_error(int ckmc_error) {
     switch(ckmc_error) {
     case CKMC_ERROR_NONE:                  return CKM_API_SUCCESS;
@@ -52,9 +46,10 @@ int to_ckm_error(int ckmc_error) {
     case CKMC_ERROR_FILE_ACCESS_DENIED:    return CKM_API_ERROR_FILE_ACCESS_DENIED;
     case CKMC_ERROR_NOT_EXPORTABLE:        return CKM_API_ERROR_NOT_EXPORTABLE;
     case CKMC_ERROR_FILE_SYSTEM:           return CKM_API_ERROR_FILE_SYSTEM;
+    case CKMC_ERROR_NOT_SUPPORTED:         return CKM_API_ERROR_NOT_SUPPORTED;
     case CKMC_ERROR_UNKNOWN:               return CKM_API_ERROR_UNKNOWN;
     }
-    return CKMC_ERROR_UNKNOWN;
+    return CKM_API_ERROR_UNKNOWN;
 }
 
 int to_ckmc_error(int ckm_error) {
@@ -80,11 +75,26 @@ int to_ckmc_error(int ckm_error) {
     case CKM_API_ERROR_FILE_ACCESS_DENIED:    return CKMC_ERROR_FILE_ACCESS_DENIED;
     case CKM_API_ERROR_NOT_EXPORTABLE:        return CKMC_ERROR_NOT_EXPORTABLE;
     case CKM_API_ERROR_FILE_SYSTEM:           return CKMC_ERROR_FILE_SYSTEM;
+    case CKM_API_ERROR_NOT_SUPPORTED:         return CKMC_ERROR_NOT_SUPPORTED;
     case CKM_API_ERROR_UNKNOWN:               return CKMC_ERROR_UNKNOWN;
     }
     return CKMC_ERROR_UNKNOWN;
 }
 
+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;
+    case CKM_API_OCSP_STATUS_NET_ERROR:        return CKMC_OCSP_ERROR_NET;
+    case CKM_API_OCSP_STATUS_INVALID_URL:      return CKMC_OCSP_ERROR_INVALID_URL;
+    case CKM_API_OCSP_STATUS_INVALID_RESPONSE: return CKMC_OCSP_ERROR_INVALID_RESPONSE;
+    case CKM_API_OCSP_STATUS_REMOTE_ERROR:     return CKMC_OCSP_ERROR_REMOTE;
+    case CKM_API_OCSP_STATUS_INTERNAL_ERROR:   return CKMC_OCSP_ERROR_INTERNAL;
+    default:                                   return CKMC_OCSP_STATUS_UNKNOWN;
+    }
+}
+
 int access_to_permission_mask(ckmc_access_right_e ar, int & permissionMask)
 {
     switch(ar)
index 20dbb1c..1de3325 100644 (file)
@@ -33,6 +33,7 @@ extern "C" {
 
 int to_ckmc_error(int ckm_error);
 int to_ckm_error(int ckmc_error);
+ckmc_ocsp_status_e to_ckmc_ocsp_status(int ckm_ocsp_status);
 int access_to_permission_mask(ckmc_access_right_e ar, int & permissionMask);
 
 #ifdef __cplusplus
index 41c718a..5775929 100644 (file)
@@ -202,6 +202,30 @@ void ckmc_cert_free(ckmc_cert_s *cert)
 }
 
 KEY_MANAGER_CAPI
+int ckmc_pkcs12_new(ckmc_key_s *private_key, ckmc_cert_s *cert,
+        ckmc_cert_list_s *ca_cert_list, ckmc_pkcs12_s **pkcs12_bundle)
+{
+    ckmc_pkcs12_s *pkcs12;
+
+    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) {
+        return CKMC_ERROR_OUT_OF_MEMORY;
+    }
+    // ownership is transferred into pkcs12 - mentioned in the docs
+    pkcs12->priv_key = private_key;
+    pkcs12->cert = cert;
+    pkcs12->ca_chain = ca_cert_list;
+
+    *pkcs12_bundle = pkcs12;
+    return CKMC_ERROR_NONE;
+}
+
+KEY_MANAGER_CAPI
 int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ckmc_key_s **private_key, ckmc_cert_s **ckmcert, ckmc_cert_list_s **ca_cert_list)
 {
     class Pkcs12Converter {
@@ -368,6 +392,45 @@ int ckmc_load_from_pkcs12_file(const char *file_path, const char *passphrase, ck
 }
 
 KEY_MANAGER_CAPI
+int ckmc_pkcs12_load(const char *file_path, const char *passphrase, ckmc_pkcs12_s **pkcs12_bundle)
+{
+    int ec;
+    ckmc_key_s *private_key = 0;
+    ckmc_cert_s *cert = 0;
+    ckmc_cert_list_s *ca_cert_list = 0;
+
+    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)
+        return ec;
+
+    ec = ckmc_pkcs12_new(private_key, cert, ca_cert_list, pkcs12_bundle);
+    if(ec != CKMC_ERROR_NONE)
+    {
+        ckmc_key_free(private_key);
+        ckmc_cert_free(cert);
+        ckmc_cert_list_free(ca_cert_list);
+        return ec;
+    }
+
+    return CKMC_ERROR_NONE;
+}
+
+KEY_MANAGER_CAPI
+void ckmc_pkcs12_free(ckmc_pkcs12_s *pkcs12)
+{
+    if(pkcs12 == NULL)
+        return;
+
+    ckmc_key_free(pkcs12->priv_key);
+    ckmc_cert_free(pkcs12->cert);
+    ckmc_cert_list_all_free(pkcs12->ca_chain);
+    free(pkcs12);
+}
+
+KEY_MANAGER_CAPI
 int ckmc_alias_list_new(char *alias, ckmc_alias_list_s **ppalias_list)
 {
     ckmc_alias_list_s *previous = NULL;
index 37cbf66..f29ba0a 100644 (file)
  *  See the License for the specific language governing permissions and
  *  limitations under the License
  *
- * @file        client-common.cpp
+ * @file        client-control.cpp
  * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
  * @version     1.0
- * @brief       This file is implementation of client-common functions.
+ * @brief       This file is implementation of client-control functions.
  */
 #include <dpl/log/log.h>
 
@@ -38,15 +38,15 @@ public:
     ControlImpl& operator=(const ControlImpl &) = delete;
     ControlImpl& operator=(ControlImpl &&) = delete;
 
-    virtual int unlockUserKey(uid_t user, const Password &password) {
+    virtual int unlockUserKey(const ClientInfo &clientInfo, const Password &password) {
         return try_catch([&] {
-            if((int)user < 0) {
+            if((int)clientInfo.getUID() < 0) {
                 return CKM_API_ERROR_INPUT_PARAM;
             }
 
             MessageBuffer recv;
             auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::UNLOCK_USER_KEY),
-                                                 user,
+                                                 clientInfo.getClientID(),
                                                  password);
 
             int retCode = m_controlConnection.processRequest(send.Pop(), recv);
@@ -59,14 +59,15 @@ public:
         });
     }
 
-    virtual int lockUserKey(uid_t user) {
+    virtual int lockUserKey(const ClientInfo &clientInfo) {
         return try_catch([&] {
-            if((int)user < 0) {
+            if((int)clientInfo.getUID() < 0) {
                 return CKM_API_ERROR_INPUT_PARAM;
             }
 
             MessageBuffer recv;
-            auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::LOCK_USER_KEY), user);
+            auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::LOCK_USER_KEY),
+                                                 clientInfo.getClientID());
 
             int retCode = m_controlConnection.processRequest(send.Pop(), recv);
             if (CKM_API_SUCCESS != retCode)
@@ -77,15 +78,15 @@ public:
             return retCode;
         });
     }
-
-    virtual int removeUserData(uid_t user) {
+    virtual int removeUserData(const ClientInfo &clientInfo) {
         return try_catch([&] {
-            if((int)user < 0) {
+            if((int)clientInfo.getUID() < 0) {
                 return CKM_API_ERROR_INPUT_PARAM;
             }
 
             MessageBuffer recv;
-            auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::REMOVE_USER_DATA), user);
+            auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::REMOVE_USER_DATA),
+                                                 clientInfo.getClientID());
 
             int retCode = m_controlConnection.processRequest(send.Pop(), recv);
             if (CKM_API_SUCCESS != retCode)
@@ -96,17 +97,16 @@ public:
             return retCode;
         });
     }
-
-    virtual int changeUserPassword(uid_t user, const Password &oldPassword, const Password &newPassword) {
+    virtual int changeUserPassword(const ClientInfo &clientInfo, const Password &oldPassword, const Password &newPassword) {
         return try_catch([&] {
-            if((int)user < 0) {
+            if((int)clientInfo.getUID() < 0) {
                 return CKM_API_ERROR_INPUT_PARAM;
             }
 
             MessageBuffer recv;
             auto send = MessageBuffer::Serialize(
                     static_cast<int>(ControlCommand::CHANGE_USER_PASSWORD),
-                    user,
+                    clientInfo.getClientID(),
                     oldPassword,
                     newPassword);
 
@@ -120,16 +120,16 @@ public:
         });
     }
 
-    virtual int resetUserPassword(uid_t user, const Password &newPassword) {
+    virtual int resetUserPassword(const ClientInfo &clientInfo, const Password &newPassword) {
         return try_catch([&] {
-            if((int)user < 0) {
+            if((int)clientInfo.getUID() < 0) {
                 return CKM_API_ERROR_INPUT_PARAM;
             }
 
             MessageBuffer recv;
             auto send = MessageBuffer::Serialize(
                     static_cast<int>(ControlCommand::RESET_USER_PASSWORD),
-                    user,
+                    clientInfo.getClientID(),
                     newPassword);
 
             int retCode = m_controlConnection.processRequest(send.Pop(), recv);
@@ -142,14 +142,16 @@ public:
         });
     }
 
-    virtual int removeApplicationData(const Label &smackLabel) {
+    virtual int removeApplicationData(const std::string &zone, const Label &smackLabel) {
         return try_catch([&] {
             if (smackLabel.empty()) {
                 return CKM_API_ERROR_INPUT_PARAM;
             }
 
             MessageBuffer recv;
-            auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::REMOVE_APP_DATA), smackLabel);
+            auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::REMOVE_APP_DATA),
+                                                 zone,
+                                                 smackLabel);
 
             int retCode = m_controlConnection.processRequest(send.Pop(), recv);
             if (CKM_API_SUCCESS != retCode)
@@ -176,7 +178,7 @@ public:
         });
     }
 
-    virtual int setPermission(uid_t user,
+    virtual int setPermission(const ClientInfo &clientInfo,
                               const Alias &alias,
                               const Label &accessor,
                               PermissionMask permissionMask)
@@ -185,7 +187,7 @@ public:
             MessageBuffer recv;
             AliasSupport helper(alias);
             auto send = MessageBuffer::Serialize(static_cast<int>(ControlCommand::SET_PERMISSION),
-                                                 static_cast<int>(user),
+                                                 clientInfo.getClientID(),
                                                  helper.getName(),
                                                  helper.getLabel(),
                                                  accessor,
index b27e180..cae0973 100644 (file)
@@ -33,9 +33,8 @@
 
 namespace CKM {
 
-namespace {
 template <class T>
-int getCertChain(
+int ManagerImpl::getCertChain(
     ServiceConnection & serviceConnection,
     LogicCommand command,
     int counter,
@@ -61,8 +60,11 @@ int getCertChain(
 
         int retCommand;
         int retCounter;
+        bool retCCModeState;
         RawBufferVector rawBufferVector;
-        recv.Deserialize(retCommand, retCounter, retCode, rawBufferVector);
+        recv.Deserialize(retCommand, retCounter, retCode, rawBufferVector, retCCModeState);
+
+        LogDebug("CCModeState[" << (retCCModeState ? "TRUE" : "FALSE") << "]");
 
         if ((counter != retCounter) || (static_cast<int>(command) != retCommand)) {
             return CKM_API_ERROR_UNKNOWN;
@@ -79,12 +81,19 @@ int getCertChain(
             certificateChainVector.push_back(cert);
         }
 
+        if (retCCModeState) {
+            int ocspStatus;
+            retCode = ocspCheck(certificateChainVector, ocspStatus);
+
+            if ((retCode == CKM_API_SUCCESS) && (ocspStatus != CKM_API_OCSP_STATUS_GOOD)) {
+                retCode = CKM_API_ERROR_VERIFICATION_FAILED;
+            }
+        }
+
         return retCode;
     });
 }
 
-} // namespace anonymous
-
 ManagerImpl::ManagerImpl()
   : m_counter(0), m_storageConnection(SERVICE_SOCKET_CKM_STORAGE), m_ocspConnection(SERVICE_SOCKET_OCSP)
 {
index 8111150..ff70fdf 100644 (file)
@@ -90,6 +90,7 @@ public:
         bool useTrustedSystemCertificates,
         CertificateShPtrVector &certificateChainVector);
 
+
     int createSignature(
         const Alias &privateKeyAlias,
         const Password &password,           // password for private_key
@@ -136,6 +137,17 @@ protected:
         const Policy &policyPrivateKey,
         const Policy &policyPublicKey);
 
+    template <class T>
+    int getCertChain(
+        ServiceConnection & serviceConnection,
+        LogicCommand command,
+        int counter,
+        const CertificateShPtr &certificate,
+        const T &untrustedVector,
+        const T &trustedVector,
+        bool useTrustedSystemCertificates,
+        CertificateShPtrVector &certificateChainVector);
+
     int m_counter;
     CKM::ServiceConnection m_storageConnection;
     CKM::ServiceConnection m_ocspConnection;
diff --git a/src/manager/common/client-info-impl.cpp b/src/manager/common/client-info-impl.cpp
new file mode 100644 (file)
index 0000000..e5b268e
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ *
+ * @file        client-info-impl.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       ClientInfo implementation.
+ */
+
+#include <ckm/ckm-client-info.h>
+
+namespace CKM {
+       const std::string ClientInfo::ZONE_DEFAULT = "host";
+       const std::string ClientInfo::DELIMITER = "-";
+
+
+uid_t ClientInfo::getUID() const
+{
+    return m_uid;
+}
+
+ClientInfo::~ClientInfo()
+{
+}
+
+ClientInfo::ClientInfo(const std::string &zone, const uid_t uid)
+  : m_zone(zone), m_uid(uid)
+{
+}
+
+ClientInfo::ClientInfo(const uid_t uid)
+  : m_zone(ZONE_DEFAULT), m_uid(uid)
+{
+}
+
+ClientID ClientInfo::getClientID() const
+{
+#ifdef DB_PER_ZONE_ENABLE
+    return ClientID(m_zone
+        + DELIMITER
+        + std::to_string(m_uid));
+#else
+    return ClientID(std::to_string(m_uid));
+#endif
+}
+
+std::string ClientInfo::getZone() const
+{
+    return m_zone;
+}
+
+} // namespace CKM
index 47bc69b..ae70dbb 100644 (file)
@@ -98,12 +98,12 @@ KeyImpl::KeyImpl(const KeyImpl &second) {
     m_type = second.m_type;
 }
 
-KeyImpl &KeyImpl::operator=(const KeyImpl &second)
-{
-    if (&second != this) {
-        m_pkey = second.getEvpShPtr();
-        m_type = second.getType();
-    }
+KeyImpl &KeyImpl::operator=(const KeyImpl &second) {
+    if (this == &second)
+        return *this;
+
+    m_pkey = second.m_pkey;
+    m_type = second.m_type;
 
     return *this;
 }
index 1360627..826ca4f 100644 (file)
@@ -36,7 +36,6 @@ public:
     KeyImpl();
     KeyImpl(const KeyImpl &second);
     KeyImpl &operator=(const KeyImpl &second);
-
     KeyImpl(const RawBuffer& buffer, const Password &password = Password());
     KeyImpl(EvpShPtr pkey, KeyType type);
 
index e86e180..aa4a273 100644 (file)
@@ -34,62 +34,29 @@ char const * const SERVICE_SOCKET_CKM_STORAGE = "/tmp/.central-key-manager-api-s
 char const * const SERVICE_SOCKET_OCSP = "/tmp/.central-key-manager-api-ocsp.sock";
 char const * const LABEL_NAME_SEPARATOR = " ";
 
-PolicySerializable::PolicySerializable()
-{}
-
-
+PolicySerializable::PolicySerializable() {}
+PolicySerializable::~PolicySerializable() {}
 PolicySerializable::PolicySerializable(const Policy &policy)
   : Policy(policy)
 {}
 
-PolicySerializable::PolicySerializable(IStream &stream) {
-    Deserialization::Deserialize(stream, password);
-    Deserialization::Deserialize(stream, extractable);
-}
-
 void PolicySerializable::Serialize(IStream &stream) const {
     Serialization::Serialize(stream, password);
     Serialization::Serialize(stream, extractable);
 }
 
+void PolicySerializable::Deserialize(IStream &stream) {
+    Deserialization::Deserialize(stream, password);
+    Deserialization::Deserialize(stream, extractable);
+}
+
 
 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) {
-        int keyType;
-        RawBuffer keyData;
-        Deserialization::Deserialize(stream, keyType);
-        Deserialization::Deserialize(stream, keyData);
-        m_pkey = CKM::Key::create(keyData);
-    }
-
-    // cert
-    size_t numCerts;
-    Deserialization::Deserialize(stream, numCerts);
-    if(numCerts > 0) {
-        RawBuffer certData;
-        Deserialization::Deserialize(stream, certData);
-        m_cert = CKM::Certificate::create(certData, DataFormat::FORM_DER);
-    }
-
-    // CA chain
-    size_t num_CA;
-    Deserialization::Deserialize(stream, num_CA);
-    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;
@@ -123,7 +90,40 @@ void PKCS12Serializable::Serialize(IStream &stream) const
     Serialization::Serialize(stream, getCaCertificateShPtrVector().size());
     for(auto it : getCaCertificateShPtrVector())
         Serialization::Serialize(stream, it->getDER());
-};
+}
+
+void PKCS12Serializable::Deserialize(IStream &stream)
+{
+    // key
+    size_t numKeys;
+    Deserialization::Deserialize(stream, numKeys);
+    if(numKeys > 0) {
+        int keyType;
+        RawBuffer keyData;
+        Deserialization::Deserialize(stream, keyType);
+        Deserialization::Deserialize(stream, keyData);
+        m_pkey = CKM::Key::create(keyData);
+    }
+
+    // cert
+    size_t numCerts;
+    Deserialization::Deserialize(stream, numCerts);
+    if(numCerts > 0) {
+        RawBuffer certData;
+        Deserialization::Deserialize(stream, certData);
+        m_cert = CKM::Certificate::create(certData, DataFormat::FORM_DER);
+    }
+
+    // CA chain
+    size_t num_CA;
+    Deserialization::Deserialize(stream, num_CA);
+    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));
+    }
+}
 
 } // namespace CKM
 
index 302ff54..2de2443 100644 (file)
@@ -247,20 +247,22 @@ class IStream;
 
 struct COMMON_API PolicySerializable : public Policy, ISerializable {
     PolicySerializable();
+    ~PolicySerializable();
     explicit PolicySerializable(const Policy &);
-    explicit PolicySerializable(IStream &);
     void Serialize(IStream &) const;
+    void Deserialize(IStream &);
 };
 
 struct COMMON_API PKCS12Serializable : public PKCS12Impl, ISerializable {
     PKCS12Serializable();
+    ~PKCS12Serializable();
     explicit PKCS12Serializable(const PKCS12 &);
-    explicit PKCS12Serializable(IStream &);
     PKCS12Serializable(
             const KeyShPtr &privKey,
             const CertificateShPtr &cert,
             const CertificateShPtrVector &chainCerts);
     void Serialize(IStream &) const;
+    void Deserialize(IStream &);
 };
 
 } // namespace CKM
index 581fedd..078607d 100644 (file)
@@ -47,6 +47,7 @@ class ISerializable
     /*    ISerializable(){};
      *    ISerializable(IStream&){}; */
     virtual void Serialize(IStream &) const = 0;
+    virtual void Deserialize(IStream &) = 0;
     virtual ~ISerializable(){}
 };
 
@@ -253,12 +254,12 @@ struct Deserialization {
     template <typename T>
     static void Deserialize(IStream& stream, T& object)
     {
-        object = T(stream);
+        object.Deserialize(stream);
     }
     template <typename T>
     static void Deserialize(IStream& stream, T*& object)
     {
-        object = new T(stream);
+        object->Deserialize(stream);
     }
 
     // char
index 32d6024..792c97f 100644 (file)
@@ -22,6 +22,7 @@
 #include <stddef.h>
 #include <dpl/exception.h>
 #include <dpl/log/log.h>
+#include <cstdio>
 
 namespace CKM {
 Exception* Exception::m_lastException = NULL;
@@ -30,6 +31,9 @@ void (*Exception::m_terminateHandler)() = NULL;
 
 void LogUnhandledException(const std::string &str)
 {
+    // Logging to console
+    printf("%s\n", str.c_str());
+
     // Logging to dlog
     LogPedantic(str);
 }
@@ -39,6 +43,13 @@ void LogUnhandledException(const std::string &str,
                            int line,
                            const char *function)
 {
+    // Logging to console
+    std::ostringstream msg;
+    msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " <<
+    function << " ===\033[m";
+    msg << str;
+    printf("%s\n", msg.str().c_str());
+
     // Logging to dlog
     CKM::Log::LogSystemSingleton::Instance().Log(CKM::Log::AbstractLogProvider::LogLevel::Error,
                                                  str.c_str(),
index e71918d..7214a73 100644 (file)
@@ -629,13 +629,13 @@ boost::optional<RawBuffer> SqlConnection::DataCommand::GetColumnOptionalBlob(
     }
     const unsigned char *value = reinterpret_cast<const unsigned char*>(
             sqlcipher3_column_blob(m_stmt, column));
+    if (!value) {
+        return boost::optional<RawBuffer>();
+    }
 
     int length = sqlcipher3_column_bytes(m_stmt, column);
     LogPedantic("Got blob of length: " << length);
 
-    if (!value)
-        return boost::optional<RawBuffer>();
-
     RawBuffer temp(value, value + length);
     return boost::optional<RawBuffer>(temp);
 }
index 1707ebe..d460871 100644 (file)
@@ -53,9 +53,7 @@ const char * const CONSOLE =  "CONSOLE";
 const char * const DLOG =     "DLOG";
 const char * const JOURNALD = "JOURNALD";
 
-const char * DEFAULT_PROVIDER = "DLOG";
-const char * DEFAULT_LEVEL = "1";
-
+const char * const NO_ENV_SET = "NO_ENV_VARIABLE";
 } // namespace anonymous
 
 LogSystem::LogSystem() : m_providerCtor({
@@ -66,19 +64,17 @@ LogSystem::LogSystem() : m_providerCtor({
             { JOURNALD, []{ return static_cast<AbstractLogProvider*>(new JournalLogProvider()); } }
     })
 {
-    const char *env_level = getenv(CKM_LOG_LEVEL);
-    if (!env_level)
-        env_level = DEFAULT_LEVEL;
-
-    SetLogLevel(env_level);
+    const char* logLevel = getenv(CKM_LOG_LEVEL);
+    if(logLevel == NULL)
+        logLevel = NO_ENV_SET; // To solve a prevent issue
+    SetLogLevel(logLevel);
 
     AbstractLogProvider* prv = NULL;
+    const char* logProvider = getenv(CKM_LOG_PROVIDER);
+    if(logProvider == NULL)
+        logProvider = NO_ENV_SET; // To solve a prevent issue
     try {
-        const char *env_provider = getenv(CKM_LOG_PROVIDER);
-        if (!env_provider)
-            env_provider = DEFAULT_PROVIDER;
-
-        prv = m_providerCtor.at(env_provider)();
+        prv = m_providerCtor.at(logProvider)();
     } catch(const std::exception&) {
         prv = m_providerCtor[DLOG]();
     }
diff --git a/src/manager/listener/listener-thread.cpp b/src/manager/listener/listener-thread.cpp
new file mode 100644 (file)
index 0000000..9722e65
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+ *  Copyright (c) 2000 - 2014 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        listener-daemon.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Listener daemon handle some events for key-manager.
+ */
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <thread>
+#include <glib.h>
+#include <ckm/ckm-control.h>
+#include <ckm/ckm-type.h>
+#include <dlog.h>
+#include <listener-thread.h>
+
+
+#include <map>
+#include <utility>
+#include <string>
+#include <package-manager-zone.h>
+
+#define CKM_LISTENER_TAG "CKM_LISTENER"
+
+#define LISTENER_SLOGD(format, arg...) SLOG(LOG_DEBUG, CKM_LISTENER_TAG, format, ##arg)
+#define LISTENER_SLOGE(format, arg...) SLOG(LOG_ERROR, CKM_LISTENER_TAG, format, ##arg)
+
+namespace { // anonymous namespace
+const char *const ZONE_DEFAULT = "host";
+typedef std::pair<std::string, CKM::Label> PkgmgrEvent;
+typedef std::map<const int, PkgmgrEvent> EventMap;
+
+int _pkgmgr_event_callback(
+    int req_id,
+    const char *pkg_type,
+    const char *pkgid,
+    const char *key,
+    const char *val,
+    const void *pmsg,
+    void *data,
+    const char *zone)
+{
+    (void) pmsg;
+    EventMap *eventMap = static_cast<EventMap *>(data);
+
+    LISTENER_SLOGD(
+        "req_id(%d), pkg_type(%s), pkgid(%s), key(%s), val(%s)",
+        req_id, pkg_type, pkgid, key, val);
+
+    // uninstall package start event
+    if (strncmp(key, "start", strlen(key)) == 0
+     && strncmp(val, "uninstall", strlen(val)) == 0) {
+        if (zone) {
+            eventMap->insert(
+                std::pair<const int, PkgmgrEvent>(
+                    req_id,
+                    PkgmgrEvent(std::string(zone), CKM::Label(pkgid))
+                )
+            );
+        }
+        else {
+            eventMap->insert(
+                std::pair<const int, PkgmgrEvent>(
+                    req_id,
+                    PkgmgrEvent(std::string(ZONE_DEFAULT), CKM::Label(pkgid))
+                )
+            );
+        }
+        return 0;
+    }
+    // uninstall package success event
+    else if (strncmp(key, "end", strlen(key)) == 0
+          && strncmp(val, "ok", strlen(val)) == 0) {
+        EventMap::iterator it;
+        it = eventMap->find(req_id);
+
+        if (it == eventMap->end()) {
+            LISTENER_SLOGE("cannot find req_id(%d) in eventMap. Maybe not in case of uninstallation.", req_id);
+        }
+        else {
+            LISTENER_SLOGD("Uninstallation success. pkgid(%s)", pkgid);
+
+            auto control = CKM::Control::create();
+            int ret = control->removeApplicationData(std::get<0>(it->second), std::get<1>(it->second));
+            if (ret != CKM_API_SUCCESS) {
+                LISTENER_SLOGE("removeApplicationData error. ret(%d)", ret);
+            }
+            eventMap->erase(it);
+        }
+    }
+
+    // zone can be "personal", "knox" or "host".
+    LISTENER_SLOGD("zone_name is (%s)", zone);
+
+    return 0;
+}
+
+int listener_main(GMainLoop *main_loop) {
+    LISTENER_SLOGD("Start!");
+
+    EventMap eventMap;
+    int req_id = 0;
+    pkgmgr_client *client = pkgmgr_client_new(PC_LISTENING);
+    if (client == NULL) {
+        LISTENER_SLOGE("Error in pkgmgr client creation");
+        return -1;
+    }
+
+    req_id = pkgmgr_client_listen_status_with_zone(client, _pkgmgr_event_callback, &eventMap);
+    if (req_id < 0) {
+        LISTENER_SLOGE("Error in pkgmgr callback registeration req_id(%d)", req_id);
+        pkgmgr_client_free(client);
+        return -1;
+    }
+
+    LISTENER_SLOGD("Ready to listen!");
+    g_main_loop_run(main_loop);
+    SLOG(LOG_ERROR, CKM_LISTENER_TAG, "%s", "Listener main loop ended.");
+    return 0;
+}
+
+} // namespace  anonymous
+
+namespace CKM {
+
+ListenerThread::ListenerThread()
+{
+    main_loop = g_main_loop_new(NULL, FALSE);
+}
+
+void ListenerThread::start()
+{
+    SLOG(LOG_INFO, CKM_LISTENER_TAG, "%s", "Listener will start!");
+    std::thread thread(listener_main, main_loop);
+    thread.detach();
+}
+
+ListenerThread::~ListenerThread()
+{
+}
+
+
+} // namespace CKM
similarity index 50%
rename from src/manager/main/smack-check.h
rename to src/manager/listener/listener-thread.h
index 942578b..657279e 100644 (file)
@@ -1,9 +1,5 @@
 /*
- *  ckm-manager
- *
- *  Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Contact: Bumjin Im <bj.im@samsung.com>
+ *  Copyright (c) 2014 Samsung Electronics Co.
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
  *  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        listener-thread.h
+ * @author      Dongseon Lee(ds72.lee@samsung.com)
+ * @version     1.0
+ * @brief       Listener thread header file.
  */
+#pragma once
+
+#include <glib.h>
 
-#ifndef _SMACK_CHECK_H_
-#define _SMACK_CHECK_H_
 
 namespace CKM {
 
-/*
- * A very simple runtime check for SMACK on the platform
- * Returns 1 if SMACK is present, 0 otherwise
- */
+class ListenerThread
+{
+public:
+    ListenerThread();
+    ListenerThread(const ListenerThread &) = delete;
+    ListenerThread(ListenerThread &&) = delete;
+    ListenerThread& operator=(const ListenerThread &) = delete;
+    ListenerThread& operator=(ListenerThread &&) = delete;
+    virtual ~ListenerThread();
 
-int smack_runtime_check(void);
+    virtual void start();
 
-/*
- * A very simple runtime check for SMACK on the platform
- * Returns 1 if SMACK is present, 0 otherwise. If SMACK_ENABLED is not defined
- * It returns 0.
- */
-int smack_check(void);
+private:
+    GMainLoop *main_loop;
+};
 
 } // namespace CKM
-
-#endif // _SMACK_CHECK_H_
index 5d1521e..abd6260 100644 (file)
@@ -45,7 +45,7 @@ namespace CKM {
 typedef int InterfaceID;
 
 struct Credentials {
-    uid_t uid;
+    ClientID clientID;
     Label smackLabel;
 };
 
index a92f8d3..930e053 100644 (file)
@@ -38,6 +38,7 @@
 #include <key-provider.h>
 #include <CryptoService.h>
 #include <file-system.h>
+#include <listener-thread.h>
 
 #define REGISTER_SOCKET_SERVICE(manager, service) \
     registerSocketService<service>(manager, #service)
@@ -97,12 +98,18 @@ int main(void) {
         CKM::CryptoService::initialize();
 
         {
-            LogInfo("Start!");
+            LogInfo("Register socket services!");
             CKM::SocketManager manager;
 
             REGISTER_SOCKET_SERVICE(manager, CKM::CKMService);
             REGISTER_SOCKET_SERVICE(manager, CKM::OCSPService);
 
+            // Start listener thread for listening app unstall events and vconf key change event
+            LogInfo("Start app event listening!");
+            CKM::ListenerThread listener;
+            listener.start();
+
+            LogInfo("Start socket services!");
             manager.MainLoop();
         }
         // Manager has been destroyed and we may close external libraries.
diff --git a/src/manager/main/smack-check.cpp b/src/manager/main/smack-check.cpp
deleted file mode 100644 (file)
index ce7899a..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-#include <smack-check.h>
-
-#include <stdlib.h>
-#include <sys/smack.h>
-
-#include <dpl/log/log.h>
-
-namespace CKM {
-
-int smack_runtime_check(void)
-{
-    static int smack_present = -1;
-    if (-1 == smack_present) {
-        if (NULL == smack_smackfs_path()) {
-            LogDebug("no smack found on device");
-            smack_present = 0;
-        } else {
-            LogDebug("found smack on device");
-            smack_present = 1;
-        }
-    }
-    return smack_present;
-}
-
-int smack_check(void)
-{
-#ifndef SMACK_ENABLED
-    return 0;
-#else
-    return smack_runtime_check();
-#endif
-}
-
-} // namespace CKM
index 405add5..30acc9f 100644 (file)
 #include <sys/signalfd.h>
 #include <sys/types.h>
 #include <sys/socket.h>
-#include <sys/smack.h>
 #include <sys/un.h>
 #include <sys/stat.h>
 #include <unistd.h>
-#include <fcntl.h>
 #include <signal.h>
 #include <errno.h>
 #include <time.h>
 #include <dpl/log/log.h>
 #include <dpl/assert.h>
 
-#include <smack-check.h>
+#include <ckm/ckm-client-info.h>
 #include <socket-manager.h>
 
 namespace {
-
 const time_t SOCKET_TIMEOUT = 1000;
 
-int getCredentialsFromSocket(int sock, CKM::Credentials &cred) {
-    CKM::Credentials credentials;
+int getCredentialsFromSocket(int sock, CKM::Credentials &cred, vsm_context_h &vsmCtx)
+{
     std::vector<char> result(1);
     socklen_t length = 1;
     ucred peerCred;
@@ -80,10 +77,42 @@ int getCredentialsFromSocket(int sock, CKM::Credentials &cred) {
 
     result.push_back('\0');
     cred.smackLabel = result.data();
-    cred.uid = peerCred.uid;
+    if (!vsmCtx) {
+        CKM::ClientInfo clientInfo(peerCred.uid);
+        cred.clientID = clientInfo.getClientID();
+        LogError("vsmCtx == NULL. ClientID[" << cred.clientID << "]");
+    } else {
+        vsm_zone_h _vsm_zone = vsm_lookup_zone_by_pid(vsmCtx, peerCred.pid);
+        if (!_vsm_zone) {
+            if (0 > vsm_cleanup_context(vsmCtx)) {
+                LogError("Failed to vsm_cleanup_context.");
+            } else if (!(vsmCtx = vsm_create_context())) {
+                LogError("Failed to vsm_create_context.");
+                return -1;
+            }
+            LogDebug("Recreate vsm context Success. vsm_lookup_zone_by_pid:[" << peerCred.pid << "] returned NULL");
+            _vsm_zone = vsm_lookup_zone_by_pid(vsmCtx, peerCred.pid);
+
+            if (!_vsm_zone) {
+                LogError("Failed. vsm_zone lookedup by pid:[" << peerCred.pid << "]");
+                vsm_cleanup_context(vsmCtx);
+                vsmCtx = NULL;
+                return -1;
+            }
+            LogDebug("Success. vsm_lookup_zone_by_pid:[" << peerCred.pid << "]");
+        }
+
+        // construct clientInfo with default zone
+        CKM::ClientInfo clientInfo(peerCred.uid);
+
+        if (!vsm_is_host_zone(_vsm_zone))
+            clientInfo = CKM::ClientInfo(std::string(vsm_get_zone_name(_vsm_zone)), peerCred.uid);
+
+        cred.clientID = clientInfo.getClientID();
+        LogDebug("sock[" << sock << "] clientID[" << cred.clientID << "]");
+    }
     return 0;
 }
-
 } // namespace anonymous
 
 namespace CKM {
@@ -172,6 +201,7 @@ SocketManager::CreateDefaultReadSocketDescription(int sock, bool timeout)
 SocketManager::SocketManager()
   : m_maxDesc(0)
   , m_counter(0)
+  , m_vsmCtx(NULL)
 {
     FD_ZERO(&m_readSet);
     FD_ZERO(&m_writeSet);
@@ -202,6 +232,8 @@ SocketManager::SocketManager()
         desc2.service = signalService;
         LogInfo("SignalService mounted on " << filefd << " descriptor");
     }
+    m_vsmCtx = vsm_create_context();
+    // TODO: handle error
 }
 
 SocketManager::~SocketManager() {
@@ -239,7 +271,7 @@ void SocketManager::ReadyForAccept(int sock) {
     }
 
     Credentials peerCred;
-    if (0 > getCredentialsFromSocket(client, peerCred)) {
+    if (0 > getCredentialsFromSocket(client, peerCred, m_vsmCtx)) {
         LogDebug("Error in getCredentialsFromSocket. Socket closed.");
         TEMP_FAILURE_RETRY(close(client));
         return;
@@ -464,78 +496,20 @@ int SocketManager::GetSocketFromSystemD(
         ThrowMsg(Exception::InitFailed, "Error in sd_listend_fds");
     }
 
-    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))
-        {
+    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)) {
             LogInfo("Useable socket " << desc.serviceHandlerPath <<
                 " was passed by SystemD under descriptor " << fd);
+            if (m_vsmCtx) {
+                int ret = vsm_declare_link(m_vsmCtx, desc.serviceHandlerPath.c_str(), desc.serviceHandlerPath.c_str());
+                if (ret)
+                    LogError("Failed to socket declare link: " << desc.serviceHandlerPath.c_str());
+            }
             return fd;
         }
     }
-    LogError("No useable sockets were passed by systemd.");
-    return -1;
-}
-
-int SocketManager::CreateDomainSocketHelp(
-    const GenericSocketService::ServiceDescription &desc)
-{
-    int sockfd;
-
-    if (-1 == (sockfd = socket(AF_UNIX, SOCK_STREAM, 0))) {
-        int err = errno;
-        LogError("Error in socket: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in socket: " << GetErrnoString(err));
-    }
 
-    if (smack_check()) {
-        LogInfo("Set up smack label: " << desc.smackLabel);
-
-        if (0 != smack_fsetlabel(sockfd, desc.smackLabel.c_str(), SMACK_LABEL_IPIN)) {
-            LogError("Error in smack_fsetlabel");
-            ThrowMsg(Exception::InitFailed, "Error in smack_fsetlabel");
-        }
-    } else {
-        LogInfo("No smack on platform. Socket won't be securied with smack label!");
-    }
-
-    int flags;
-    if (-1 == (flags = fcntl(sockfd, F_GETFL, 0)))
-        flags = 0;
-
-    if (-1 == fcntl(sockfd, F_SETFL, flags | O_NONBLOCK)) {
-        int err = errno;
-        close(sockfd);
-        LogError("Error in fcntl: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in fcntl: " << GetErrnoString(err));
-    }
-
-    sockaddr_un serverAddress;
-    memset(&serverAddress, 0, sizeof(serverAddress));
-    serverAddress.sun_family = AF_UNIX;
-    strcpy(serverAddress.sun_path, desc.serviceHandlerPath.c_str());
-    unlink(serverAddress.sun_path);
-
-    mode_t originalUmask;
-    originalUmask = umask(0);
-
-    if (-1 == bind(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) {
-        int err = errno;
-        close(sockfd);
-        LogError("Error in bind: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in bind: " << GetErrnoString(err));
-    }
-
-    umask(originalUmask);
-
-    if (-1 == listen(sockfd, 5)) {
-        int err = errno;
-        close(sockfd);
-        LogError("Error in listen: " << GetErrnoString(err));
-        ThrowMsg(Exception::InitFailed, "Error in listen: " << GetErrnoString(err));
-    }
-
-    return sockfd;
+    ThrowMsg(Exception::GetSystemdSocketFailed, "No useable sockets were passed by systemd.");
 }
 
 void SocketManager::CreateDomainSocket(
@@ -543,8 +517,6 @@ void SocketManager::CreateDomainSocket(
     const GenericSocketService::ServiceDescription &desc)
 {
     int sockfd = GetSocketFromSystemD(desc);
-    if (-1 == sockfd)
-        sockfd = CreateDomainSocketHelp(desc);
 
     auto &description = CreateDefaultReadSocketDescription(sockfd, false);
 
@@ -556,7 +528,9 @@ void SocketManager::CreateDomainSocket(
         " Handler: " << desc.serviceHandlerPath.c_str());
 }
 
-void SocketManager::RegisterSocketService(GenericSocketService *service) {
+void SocketManager::RegisterSocketService(
+    GenericSocketService *service)
+{
     service->SetSocketManager(this);
     auto serviceVector = service->GetServiceDescription();
     Try {
index 978dbee..230a182 100644 (file)
@@ -32,8 +32,9 @@
 #include <mutex>
 #include <thread>
 
-#include <dpl/exception.h>
+#include <vasum.h>
 
+#include <dpl/exception.h>
 #include <generic-socket-manager.h>
 
 namespace CKM {
@@ -44,6 +45,7 @@ public:
     public:
         DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
         DECLARE_EXCEPTION_TYPE(Base, InitFailed)
+        DECLARE_EXCEPTION_TYPE(Base, GetSystemdSocketFailed)
     };
     SocketManager();
     virtual ~SocketManager();
@@ -58,8 +60,6 @@ protected:
     void CreateDomainSocket(
         GenericSocketService *service,
         const GenericSocketService::ServiceDescription &desc);
-    int CreateDomainSocketHelp(
-        const GenericSocketService::ServiceDescription &desc);
     int GetSocketFromSystemD(
         const GenericSocketService::ServiceDescription &desc);
 
@@ -119,6 +119,7 @@ protected:
     int m_notifyMe[2];
     int m_counter;
     std::priority_queue<Timeout> m_timeoutQueue;
+    vsm_context_h m_vsmCtx;
 };
 
 } // namespace CKM
index c57c840..15f5081 100644 (file)
@@ -28,6 +28,8 @@
 #define OPENSSL_SUCCESS 1       // DO NOTCHANGE THIS VALUE
 #define OPENSSL_FAIL    0       // DO NOTCHANGE THIS VALUE
 
+#define RAND_READ_BYTES 32
+
 namespace CKM {
 
 CryptoService::CryptoService(){
@@ -38,30 +40,22 @@ CryptoService::~CryptoService(){
 
 
 
-int CryptoService::initialize() {
-    int hw_rand_ret = 0;
-    int u_rand_ret = 0;
-
+void CryptoService::initialize() {
     // try to initialize using ERR_load_crypto_strings and OpenSSL_add_all_algorithms
     ERR_load_crypto_strings();
     OpenSSL_add_all_algorithms();
 
     // initialize entropy
     std::ifstream ifile(DEV_HW_RANDOM_FILE);
-    if(ifile.is_open()) {
-        u_rand_ret= RAND_load_file(DEV_HW_RANDOM_FILE, 32);
-    }
-    if(u_rand_ret != 32 ){
-        LogError("Error in HW_RAND file load");
-        hw_rand_ret = RAND_load_file(DEV_URANDOM_FILE, 32);
 
-        if(hw_rand_ret != 32) {
-            LogError("Error in U_RAND_file_load");
-            ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in U_RAND_file_load");
-        }
-    }
-
-    return CKM_CRYPTO_INIT_SUCCESS;
+    if (ifile.is_open()
+        && (RAND_READ_BYTES == RAND_load_file(DEV_HW_RANDOM_FILE, RAND_READ_BYTES)))
+        LogDebug("Success to read from [" << DEV_HW_RANDOM_FILE << "]");
+    else if (RAND_READ_BYTES == RAND_load_file(DEV_URANDOM_FILE, RAND_READ_BYTES))
+        LogDebug("Success to read from [" << DEV_URANDOM_FILE << "]");
+    else
+        ThrowMsg(CryptoService::Exception::Crypto_internal,
+            "Error in U_RAND_file_load");
 }
 
 const EVP_MD *CryptoService::getMdAlgo(const HashAlgorithm hashAlgo) {
@@ -188,111 +182,111 @@ int CryptoService::createKeyPairRSA(const int size, // size in bits [1024, 2048,
 
 
 int CryptoService::createKeyPairDSA(const int size, // size in bits [1024, 2048, 3072, 4096]
-               KeyImpl &createdPrivateKey,  // returned value
-               KeyImpl &createdPublicKey)  // returned value
+        KeyImpl &createdPrivateKey,  // returned value
+        KeyImpl &createdPublicKey)  // returned value
 {
-       EVP_PKEY_CTX *pctx = NULL;
-       EVP_PKEY_CTX *kctx = NULL;
-       EVP_PKEY *pkey = NULL;
-       EVP_PKEY *pparam = NULL;
-
-       // check the parameters of functions
-       if(size != 1024 && size !=2048 && size !=3072 && size != 4096) {
-               LogError("Error in DSA input size");
-               ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in DSA input size");
-       }
-
-       // check the parameters of functions
-       if(&createdPrivateKey == NULL) {
-               LogError("Error in createdPrivateKey value");
-               ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in createdPrivateKey value");
-       }
-
-       // check the parameters of functions
-       if(&createdPublicKey == NULL) {
-               LogError("Error in createdPrivateKey value");
-               ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in createdPublicKey value");
-       }
-
-       Try {
-               /* Create the context for generating the parameters */
-               if(!(pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, NULL))) {
-                       LogError("Error in EVP_PKEY_CTX_new_id function");
-                       ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_CTX_new_id function");
-               }
-
-               if(EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx)) {
-                       LogError("Error in EVP_PKEY_paramgen_init function");
-                       ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_paramgen_init function");
-               }
-
-               if(EVP_SUCCESS != EVP_PKEY_CTX_set_dsa_paramgen_bits(pctx, size)) {
-                       LogError("Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(" << size << ") function");
-                       ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(" << size << ") function");
-               }
-
-               /* Generate parameters */
-               if(EVP_SUCCESS != EVP_PKEY_paramgen(pctx, &pparam)) {
-                       LogError("Error in EVP_PKEY_paramgen function");
-                       ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_paramgen function");
-               }
-
-               // Start to generate key
-               if(!(kctx = EVP_PKEY_CTX_new(pparam, NULL))) {
-                       LogError("Error in EVP_PKEY_CTX_new function");
-                       ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_CTX_new function");
-               }
-
-               if(EVP_SUCCESS != EVP_PKEY_keygen_init(kctx)) {
-                       LogError("Error in EVP_PKEY_keygen_init function");
-                       ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_keygen_init function");
-               }
-
-               /* Generate the key */
-               if(EVP_SUCCESS != EVP_PKEY_keygen(kctx, &pkey)) {
-                       LogError("Error in EVP_PKEY_keygen function");
-                       ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_keygen function");
-               }
-       }
-       Catch(CryptoService::Exception::opensslError)
-       {
-               if(pkey) {
-                       EVP_PKEY_free(pkey);
-               }
-
-               if(pparam) {
-                       EVP_PKEY_free(pparam);
-               }
-
-               if(pctx) {
-                       EVP_PKEY_CTX_free(pctx);
-               }
-
-               if(kctx) {
-                       EVP_PKEY_CTX_free(kctx);
-               }
-
-               ReThrowMsg(CryptoService::Exception::opensslError,"Error in openssl function !!");
-       }
-
-       KeyImpl::EvpShPtr ptr(pkey, EVP_PKEY_free); // shared ptr will free pkey
-
-       createdPrivateKey = KeyImpl(ptr, KeyType::KEY_DSA_PRIVATE);
-       createdPublicKey = KeyImpl(ptr, KeyType::KEY_DSA_PUBLIC);
-
-       if(pparam) {
-               EVP_PKEY_free(pparam);
-       }
-
-       if(pctx) {
-               EVP_PKEY_CTX_free(pctx);
-       }
-
-       if(kctx) {
-               EVP_PKEY_CTX_free(kctx);
-       }
-
-       return CKM_CRYPTO_CREATEKEY_SUCCESS;
+    EVP_PKEY_CTX *pctx = NULL;
+    EVP_PKEY_CTX *kctx = NULL;
+    EVP_PKEY *pkey = NULL;
+    EVP_PKEY *pparam = NULL;
+
+    // check the parameters of functions
+    if(size != 1024 && size !=2048 && size !=3072 && size != 4096) {
+        LogError("Error in DSA input size");
+        ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in DSA input size");
+    }
+
+    // check the parameters of functions
+    if(&createdPrivateKey == NULL) {
+        LogError("Error in createdPrivateKey value");
+        ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in createdPrivateKey value");
+    }
+
+    // check the parameters of functions
+    if(&createdPublicKey == NULL) {
+        LogError("Error in createdPrivateKey value");
+        ThrowMsg(CryptoService::Exception::Crypto_internal, "Error in createdPublicKey value");
+    }
+
+    Try {
+        /* Create the context for generating the parameters */
+        if(!(pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, NULL))) {
+            LogError("Error in EVP_PKEY_CTX_new_id function");
+            ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_CTX_new_id function");
+        }
+
+        if(EVP_SUCCESS != EVP_PKEY_paramgen_init(pctx)) {
+            LogError("Error in EVP_PKEY_paramgen_init function");
+            ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_paramgen_init function");
+        }
+
+        if(EVP_SUCCESS != EVP_PKEY_CTX_set_dsa_paramgen_bits(pctx, size)) {
+            LogError("Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(" << size << ") function");
+            ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_CTX_set_dsa_paramgen_bits(" << size << ") function");
+        }
+
+        /* Generate parameters */
+        if(EVP_SUCCESS != EVP_PKEY_paramgen(pctx, &pparam)) {
+            LogError("Error in EVP_PKEY_paramgen function");
+            ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_paramgen function");
+        }
+
+        // Start to generate key
+        if(!(kctx = EVP_PKEY_CTX_new(pparam, NULL))) {
+            LogError("Error in EVP_PKEY_CTX_new function");
+            ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_CTX_new function");
+        }
+
+        if(EVP_SUCCESS != EVP_PKEY_keygen_init(kctx)) {
+            LogError("Error in EVP_PKEY_keygen_init function");
+            ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_keygen_init function");
+        }
+
+        /* Generate the key */
+        if(EVP_SUCCESS != EVP_PKEY_keygen(kctx, &pkey)) {
+            LogError("Error in EVP_PKEY_keygen function");
+            ThrowMsg(CryptoService::Exception::opensslError, "Error in EVP_PKEY_keygen function");
+        }
+    }
+    Catch(CryptoService::Exception::opensslError)
+    {
+        if(pkey) {
+            EVP_PKEY_free(pkey);
+        }
+
+        if(pparam) {
+            EVP_PKEY_free(pparam);
+        }
+
+        if(pctx) {
+            EVP_PKEY_CTX_free(pctx);
+        }
+
+        if(kctx) {
+            EVP_PKEY_CTX_free(kctx);
+        }
+
+        ReThrowMsg(CryptoService::Exception::opensslError,"Error in openssl function !!");
+    }
+
+    KeyImpl::EvpShPtr ptr(pkey, EVP_PKEY_free); // shared ptr will free pkey
+
+    createdPrivateKey = KeyImpl(ptr, KeyType::KEY_DSA_PRIVATE);
+    createdPublicKey = KeyImpl(ptr, KeyType::KEY_DSA_PUBLIC);
+
+    if(pparam) {
+        EVP_PKEY_free(pparam);
+    }
+
+    if(pctx) {
+        EVP_PKEY_CTX_free(pctx);
+    }
+
+    if(kctx) {
+        EVP_PKEY_CTX_free(kctx);
+    }
+
+    return CKM_CRYPTO_CREATEKEY_SUCCESS;
 }
 
 
index 6828ddb..3ab24c2 100644 (file)
@@ -23,7 +23,6 @@
 #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
 #define CKM_VERIFY_CHAIN_SUCCESS 5
 #define NOT_DEFINED -1
@@ -48,7 +47,7 @@ public:
     // And system certificates are loaded in the memory during initialization.
     //    FIPS_MODE - ON, OFF(Default)
     //    antropy source - /dev/random,/dev/urandom(Default)
-    static int initialize();
+    static void initialize();
 
     static int createKeyPairRSA(const int size,      // size in bits [1024, 2048, 4096]
                         KeyImpl &createdPrivateKey,  // returned value ==> Key &createdPrivateKey,
index 009e7f6..356cd97 100644 (file)
@@ -30,9 +30,7 @@ namespace CKM {
 void AccessControl::updateCCMode() {
     int fipsModeStatus = 0;
     int rc = 0;
-    bool newMode;
-
-    newMode = false;
+    bool newMode = false;
 
     if (newMode == m_ccMode)
         return;
@@ -41,17 +39,17 @@ void AccessControl::updateCCMode() {
 
     fipsModeStatus = FIPS_mode();
 
-    if(m_ccMode) {
-        if(fipsModeStatus == 0) { // If FIPS mode off
+    if (m_ccMode) {
+        if (fipsModeStatus == 0) { // If FIPS mode off
             rc = FIPS_mode_set(1); // Change FIPS_mode from off to on
-            if(rc == 0) {
+            if (rc == 0) {
                 LogError("Error in FIPS_mode_set function");
             }
         }
     } else {
-        if(fipsModeStatus == 1) { // If FIPS mode on
+        if (fipsModeStatus == 1) { // If FIPS mode on
             rc = FIPS_mode_set(0); // Change FIPS_mode from on to off
-            if(rc == 0) {
+            if (rc == 0) {
                 LogError("Error in FIPS_mode_set function");
             }
         }
index 565f4fd..47e0be6 100644 (file)
@@ -111,6 +111,8 @@ int CertificateStore::verifyCertificate(
 
     switch (result) {
     case 0:
+        ret = X509_STORE_CTX_get_error(csc.get());
+        LogError("verify error[" << ret << "]: " << X509_verify_cert_error_string(ret));
         return CKM_API_ERROR_VERIFICATION_FAILED;
     case 1:
         return CKM_API_SUCCESS;
index b324a20..e3b4544 100644 (file)
@@ -60,20 +60,40 @@ CKMLogic::CKMLogic()
 
 CKMLogic::~CKMLogic(){}
 
-void CKMLogic::loadDKEKFile(uid_t user, const Password &password, bool apiReq) {
-    auto &handle = m_userDataMap[user];
+void CKMLogic::loadDKEKFile(
+    const ClientID &clientID,
+    const Password &password,
+    bool apiReq)
+{
+    auto &handle = m_userDataMap[clientID];
 
-    FileSystem fs(user);
+    FileSystem fs(clientID);
 
     auto wrappedDKEKMain = fs.getDKEK();
     auto wrappedDKEKBackup = fs.getDKEKBackup();
 
+#ifdef PASSWORD_PROTECTION_DISABLE
+    if (wrappedDKEKMain.empty()) {
+        wrappedDKEKMain = KeyProvider::generateDomainKEK(clientID, Password(""));
+        fs.saveDKEK(wrappedDKEKMain);
+    }
+
+    try{
+        chooseDKEKFile(handle, Password(""), wrappedDKEKMain, wrappedDKEKBackup);
+    } catch (const KeyProvider::Exception::Base &e) {
+        chooseDKEKFile(handle, password, wrappedDKEKMain, wrappedDKEKBackup);
+        fs.saveDKEK(handle.keyProvider.getWrappedDomainKEK(Password("")));
+        handle.isMainDKEK = true;
+        LogInfo("Password Protected DB was migrated to Password Protection Disabled DB.");
+    }
+#else
     if (wrappedDKEKMain.empty()) {
-        wrappedDKEKMain = KeyProvider::generateDomainKEK(std::to_string(user), password);
+        wrappedDKEKMain = KeyProvider::generateDomainKEK(clientID, password);
         fs.saveDKEK(wrappedDKEKMain);
     }
 
     chooseDKEKFile(handle, password, wrappedDKEKMain, wrappedDKEKBackup);
+#endif
 
     if (!password.empty() || apiReq) {
         handle.isDKEKConfirmed = true;
@@ -103,10 +123,10 @@ void CKMLogic::chooseDKEKFile(
     }
 }
 
-void CKMLogic::saveDKEKFile(uid_t user, const Password &password) {
-    auto &handle = m_userDataMap[user];
+void CKMLogic::saveDKEKFile(const ClientID &clientID, const Password &password) {
+    auto &handle = m_userDataMap[clientID];
 
-    FileSystem fs(user);
+    FileSystem fs(clientID);
     if (handle.isMainDKEK)
         fs.createDKEKBackup();
 
@@ -116,20 +136,24 @@ void CKMLogic::saveDKEKFile(uid_t user, const Password &password) {
     handle.isDKEKConfirmed = false;
 }
 
-RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password, bool apiRequest) {
+RawBuffer CKMLogic::unlockUserKey(
+    const ClientID &clientID,
+    const Password &password,
+    bool apiRequest)
+{
     int retCode = CKM_API_SUCCESS;
 
     try {
-        if (0 == m_userDataMap.count(user) || !(m_userDataMap[user].keyProvider.isInitialized())) {
-            auto &handle = m_userDataMap[user];
-            FileSystem fs(user);
+        if (0 == m_userDataMap.count(clientID) || !(m_userDataMap[clientID].keyProvider.isInitialized())) {
+            auto &handle = m_userDataMap[clientID];
+            FileSystem fs(clientID);
 
-            loadDKEKFile(user, password, apiRequest);
+            loadDKEKFile(clientID, password, apiRequest);
 
             auto wrappedDatabaseDEK = fs.getDBDEK();
 
             if (wrappedDatabaseDEK.empty()) {
-                wrappedDatabaseDEK = handle.keyProvider.generateDEK(std::to_string(user));
+                wrappedDatabaseDEK = handle.keyProvider.generateDEK(clientID);
                 fs.saveDBDEK(wrappedDatabaseDEK);
             }
 
@@ -140,11 +164,12 @@ RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password, bool api
             // remove data of removed apps during locked state
             AppLabelVector removedApps = fs.clearRemovedsApps();
             for(auto& appSmackLabel : removedApps) {
+                handle.crypto.removeKey(appSmackLabel);
                 handle.database.deleteKey(appSmackLabel);
             }
-        } else if (apiRequest == true && m_userDataMap[user].isDKEKConfirmed == false) {
+        } else if (apiRequest == true && m_userDataMap[clientID].isDKEKConfirmed == false) {
             // now we will try to choose the DKEK key and remove old one
-            loadDKEKFile(user, password, apiRequest);
+            loadDKEKFile(clientID, password, apiRequest);
         }
     } catch (const KeyProvider::Exception::PassWordError &e) {
         LogError("Incorrect Password " << e.GetMessage());
@@ -166,7 +191,7 @@ RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password, bool api
     if(retCode != CKM_API_SUCCESS) {
         // When not successful, UserData in m_userDataMap should be erased.
         // Because other operations make decision based on the existence of UserData in m_userDataMap.
-        m_userDataMap.erase(user);
+        m_userDataMap.erase(clientID);
     }
 
     return MessageBuffer::Serialize(retCode).Pop();
@@ -177,35 +202,47 @@ RawBuffer CKMLogic::updateCCMode() {
     return MessageBuffer::Serialize(CKM_API_SUCCESS).Pop();
 }
 
-RawBuffer CKMLogic::lockUserKey(uid_t user) {
+RawBuffer CKMLogic::lockUserKey(const ClientID &clientID) {
     int retCode = CKM_API_SUCCESS;
     // TODO try catch for all errors that should be supported by error code
-    m_userDataMap.erase(user);
+
+#ifdef PASSWORD_PROTECTION_DISABLE
+    (void) clientID;
+#else
+    m_userDataMap.erase(clientID);
+#endif
 
     return MessageBuffer::Serialize(retCode).Pop();
 
 }
 
-RawBuffer CKMLogic::removeUserData(uid_t user) {
+RawBuffer CKMLogic::removeUserData(const ClientID &clientID) {
     int retCode = CKM_API_SUCCESS;
     // TODO try catch for all errors that should be supported by error code
-    m_userDataMap.erase(user);
 
-    FileSystem fs(user);
+    m_userDataMap.erase(clientID);
+
+    FileSystem fs(clientID);
     fs.removeUserData();
 
     return MessageBuffer::Serialize(retCode).Pop();
 }
 
 RawBuffer CKMLogic::changeUserPassword(
-    uid_t user,
+    const ClientID &clientID,
     const Password &oldPassword,
     const Password &newPassword)
 {
     int retCode = CKM_API_SUCCESS;
+
+#ifdef PASSWORD_PROTECTION_DISABLE
+    (void) clientID;
+    (void) oldPassword;
+    (void) newPassword;
+#else
     try {
-        loadDKEKFile(user, oldPassword, true);
-        saveDKEKFile(user, newPassword);
+        loadDKEKFile(clientID, oldPassword, true);
+        saveDKEKFile(clientID, newPassword);
     } catch (const KeyProvider::Exception::PassWordError &e) {
         LogError("Incorrect Password " << e.GetMessage());
         retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
@@ -219,25 +256,29 @@ RawBuffer CKMLogic::changeUserPassword(
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
     }
+#endif
 
     return MessageBuffer::Serialize(retCode).Pop();
 }
 
 RawBuffer CKMLogic::resetUserPassword(
-    uid_t user,
+    const ClientID &clientID,
     const Password &newPassword)
 {
     int retCode = CKM_API_SUCCESS;
-
+#ifdef PASSWORD_PROTECTION_DISABLE
+    (void) clientID;
+    (void) newPassword;
+#else
     try {
-        if (0 == m_userDataMap.count(user)) {
+        if (0 == m_userDataMap.count(clientID)) {
             // Check if key exists. If exists we must return error
-            FileSystem fs(user);
+            FileSystem fs(clientID);
             auto wrappedDKEKMain = fs.getDKEK();
             if (!wrappedDKEKMain.empty())
                 retCode = CKM_API_ERROR_BAD_REQUEST;
         } else {
-            saveDKEKFile(user, newPassword);
+            saveDKEKFile(clientID, newPassword);
         }
     } catch (const FileSystem::Exception::Base &e) {
         LogError("Error in FileSystem " << e.GetMessage());
@@ -246,30 +287,30 @@ RawBuffer CKMLogic::resetUserPassword(
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
     }
+#endif
 
     return MessageBuffer::Serialize(retCode).Pop();
 }
 
-RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) {
+RawBuffer CKMLogic::removeApplicationData(const std::string &zone, const Label &smackLabel) {
     int retCode = CKM_API_SUCCESS;
 
     try {
-
         if (smackLabel.empty()) {
             retCode = CKM_API_ERROR_INPUT_PARAM;
         } else {
-            UidVector uids = FileSystem::getUIDsFromDBFile();
-            for (auto userId : uids) {
-                if (0 == m_userDataMap.count(userId)) {
-                    FileSystem fs(userId);
+            ClientIDVector clientIDVec = FileSystem::getClientIDsFromDBFile(zone);
+            for (auto clientID : clientIDVec) {
+                if (0 == m_userDataMap.count(clientID)) {
+                    FileSystem fs(clientID);
                     fs.addRemovedApp(smackLabel);
                 } else {
-                    auto &handle = m_userDataMap[userId];
+                    auto &handle = m_userDataMap[clientID];
+                    handle.crypto.removeKey(smackLabel);
                     handle.database.deleteKey(smackLabel);
                 }
             }
         }
-
     } catch (const DB::Crypto::Exception::InternalError &e) {
         LogError("DB::Crypto couldn't remove data: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
@@ -298,7 +339,6 @@ int CKMLogic::checkSaveConditions(
         LogWarning("Invalid parameter passed to key-manager");
         return CKM_API_ERROR_INPUT_PARAM;
     }
-
     // check if allowed to save using ownerLabel
     int access_ec = m_accessControl.canSave(ownerLabel, cred.smackLabel);
     if(access_ec != CKM_API_SUCCESS)
@@ -387,7 +427,7 @@ RawBuffer CKMLogic::saveData(
     const PolicySerializable &policy)
 {
     int retCode;
-    if (0 == m_userDataMap.count(cred.uid))
+    if (0 == m_userDataMap.count(cred.clientID))
         retCode = CKM_API_ERROR_DB_LOCKED;
     else
     {
@@ -481,7 +521,7 @@ RawBuffer CKMLogic::savePKCS12(
     const PolicySerializable &certPolicy)
 {
     int retCode;
-    if (0 == m_userDataMap.count(cred.uid))
+    if (0 == m_userDataMap.count(cred.clientID))
         retCode = CKM_API_ERROR_DB_LOCKED;
     else
     {
@@ -517,7 +557,7 @@ int CKMLogic::removeDataHelper(
         const Name &name,
         const Label &ownerLabel)
 {
-    if (0 == m_userDataMap.count(cred.uid))
+    if (0 == m_userDataMap.count(cred.clientID))
         return CKM_API_ERROR_DB_LOCKED;
 
     if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
@@ -525,7 +565,7 @@ int CKMLogic::removeDataHelper(
         return CKM_API_ERROR_INPUT_PARAM;
     }
 
-    auto &database = m_userDataMap[cred.uid].database;
+    auto &database = m_userDataMap[cred.clientID].database;
     DB::Crypto::Transaction transaction(&database);
 
     // read and check permissions
@@ -584,14 +624,14 @@ int CKMLogic::readSingleRow(const Name &name,
     {
         // read all key types
         row_optional = database.getRow(name,
-                                         ownerLabel,
-                                         DataType::DB_KEY_FIRST,
-                                         DataType::DB_KEY_LAST);
+                                       ownerLabel,
+                                       DataType::DB_KEY_FIRST,
+                                       DataType::DB_KEY_LAST);
     } else {
         // read anything else
         row_optional = database.getRow(name,
-                                         ownerLabel,
-                                         dataType);
+                                       ownerLabel,
+                                       dataType);
     }
 
     if(!row_optional) {
@@ -604,7 +644,6 @@ int CKMLogic::readSingleRow(const Name &name,
     return CKM_API_SUCCESS;
 }
 
-
 int CKMLogic::readMultiRow(const Name &name,
                            const Label &ownerLabel,
                            DataType dataType,
@@ -615,31 +654,35 @@ int CKMLogic::readMultiRow(const Name &name,
     {
         // read all key types
         database.getRows(name,
-                          ownerLabel,
-                          DataType::DB_KEY_FIRST,
-                          DataType::DB_KEY_LAST,
-                          output);
+                         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);
+                         ownerLabel,
+                         DataType::DB_CHAIN_FIRST,
+                         DataType::DB_CHAIN_LAST,
+                         output);
     }
     else
     {
         // read anything else
         database.getRows(name,
-                          ownerLabel,
-                          dataType,
-                          output);
+                         ownerLabel,
+                         dataType,
+                         output);
     }
 
     if(!output.size()) {
-        LogError("No row for given name, label and type");
+        /*
+         *  readMultiRow is only used to get row which cannot exist
+         *  So, it shouldn't print error log
+         */
+        LogDebug("No row for given name, label and type");
         return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
     }
 
@@ -670,7 +713,7 @@ int CKMLogic::readDataHelper(
     const Password &password,
     DB::RowVector &rows)
 {
-    if (0 == m_userDataMap.count(cred.uid))
+    if (0 == m_userDataMap.count(cred.clientID))
         return CKM_API_ERROR_DB_LOCKED;
 
     // use client label if not explicitly provided
@@ -679,7 +722,7 @@ int CKMLogic::readDataHelper(
     if (!isNameValid(name) || !isLabelValid(ownerLabel))
         return CKM_API_ERROR_INPUT_PARAM;
 
-    auto &handler = m_userDataMap[cred.uid];
+    auto &handler = m_userDataMap[cred.clientID];
 
     // read rows
     DB::Crypto::Transaction transaction(&handler.database);
@@ -722,7 +765,7 @@ int CKMLogic::readDataHelper(
     const Password &password,
     DB::Row &row)
 {
-    if (0 == m_userDataMap.count(cred.uid))
+    if (0 == m_userDataMap.count(cred.clientID))
         return CKM_API_ERROR_DB_LOCKED;
 
     // use client label if not explicitly provided
@@ -731,7 +774,7 @@ int CKMLogic::readDataHelper(
     if (!isNameValid(name) || !isLabelValid(ownerLabel))
         return CKM_API_ERROR_INPUT_PARAM;
 
-    auto &handler = m_userDataMap[cred.uid];
+    auto &handler = m_userDataMap[cred.clientID];
 
     // read row
     DB::Crypto::Transaction transaction(&handler.database);
@@ -900,8 +943,8 @@ RawBuffer CKMLogic::getDataList(
     int retCode = CKM_API_SUCCESS;
     LabelNameVector labelNameVector;
 
-    if (0 < m_userDataMap.count(cred.uid)) {
-        auto &database = m_userDataMap[cred.uid].database;
+    if (0 < m_userDataMap.count(cred.clientID)) {
+        auto &database = m_userDataMap[cred.clientID].database;
 
         Try {
             if (dataType.isKey()) {
@@ -941,7 +984,7 @@ int CKMLogic::saveDataHelper(
     const RawBuffer &data,
     const PolicySerializable &policy)
 {
-    auto &handler = m_userDataMap[cred.uid];
+    auto &handler = m_userDataMap[cred.clientID];
 
     // use client label if not explicitly provided
     const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
@@ -968,7 +1011,7 @@ int CKMLogic::saveDataHelper(
     const PolicySerializable &keyPolicy,
     const PolicySerializable &certPolicy)
 {
-    auto &handler = m_userDataMap[cred.uid];
+    auto &handler = m_userDataMap[cred.clientID];
 
     // use client label if not explicitly provided
     const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
@@ -1004,7 +1047,7 @@ int CKMLogic::createKeyPairHelper(
     const PolicySerializable &policyPrivate,
     const PolicySerializable &policyPublic)
 {
-    if (0 == m_userDataMap.count(cred.uid))
+    if (0 == m_userDataMap.count(cred.clientID))
         return CKM_API_ERROR_DB_LOCKED;
 
     KeyImpl prv, pub;
@@ -1036,7 +1079,7 @@ int CKMLogic::createKeyPairHelper(
         return CKM_API_ERROR_SERVER_ERROR; // TODO error code
     }
 
-    auto &database = m_userDataMap[cred.uid].database;
+    auto &database = m_userDataMap[cred.clientID].database;
     DB::Crypto::Transaction transaction(&database);
 
     retCode = saveDataHelper(cred,
@@ -1249,7 +1292,8 @@ RawBuffer CKMLogic::getCertificateChain(
     auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET_CHAIN_CERT),
                                              commandId,
                                              retCode,
-                                             chainRawVector);
+                                             chainRawVector,
+                                             m_accessControl.isCCMode());
     return response.Pop();
 }
 
@@ -1290,7 +1334,8 @@ RawBuffer CKMLogic::getCertificateChain(
     auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET_CHAIN_ALIAS),
                                              commandId,
                                              retCode,
-                                             chainRawVector);
+                                             chainRawVector,
+                                             m_accessControl.isCCMode());
     return response.Pop();
 }
 
@@ -1360,22 +1405,46 @@ RawBuffer CKMLogic::verifySignature(
     try {
         do {
             CryptoService cs;
+            DB::RowVector rowVec;
             DB::Row row;
             KeyImpl key;
 
             // try certificate first - looking for a public key.
             // in case of PKCS, pub key from certificate will be found first
             // rather than private key from the same PKCS.
-            retCode = readDataHelper(false, cred, DataType::CERTIFICATE, publicKeyOrCertName, ownerLabel, password, row);
-            if (retCode == CKM_API_SUCCESS) {
-                CertificateImpl cert(row.data, DataFormat::FORM_DER);
+            retCode = readDataHelper(
+                    false,
+                    cred,
+                    DataType::CERTIFICATE,
+                    publicKeyOrCertName,
+                    ownerLabel,
+                    password,
+                    rowVec);
+
+            // output cannot be more than 1
+            if (rowVec.size() > 1) {
+                ThrowMsg(CKM::Exception,
+                    "More than one certificate mapped to a label[" << ownerLabel << "]");
+            }
+            else if (retCode == CKM_API_SUCCESS && rowVec.size() == 1) {
+                CertificateImpl cert(rowVec[0].data, DataFormat::FORM_DER);
                 key = cert.getKeyImpl();
-            } else if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
-                retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, publicKeyOrCertName, ownerLabel, password, row);
+            }
+            else if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN && rowVec.size() == 0) {
+                retCode = readDataHelper(
+                        false,
+                        cred,
+                        DataType::DB_KEY_FIRST,
+                        publicKeyOrCertName,
+                        ownerLabel,
+                        password,
+                        row);
+
                 if (retCode != CKM_API_SUCCESS)
                     break;
                 key = KeyImpl(row.data);
-            } else {
+            }
+            else {
                 break;
             }
 
@@ -1441,11 +1510,10 @@ int CKMLogic::setPermissionHelper(
     int access_ec = m_accessControl.canModify(ownerLabel, cred.smackLabel);
     if(access_ec != CKM_API_SUCCESS)
         return access_ec;
-
-    if (0 == m_userDataMap.count(cred.uid))
+    if (0 == m_userDataMap.count(cred.clientID))
         return CKM_API_ERROR_DB_LOCKED;
 
-    auto &database = m_userDataMap[cred.uid].database;
+    auto &database = m_userDataMap[cred.clientID].database;
     DB::Crypto::Transaction transaction(&database);
 
     if( !database.isNameLabelPresent(name, ownerLabel) )
index 912f44c..dc66322 100644 (file)
@@ -59,22 +59,23 @@ public:
     CKMLogic& operator=(CKMLogic &&) = delete;
     virtual ~CKMLogic();
 
-    RawBuffer unlockUserKey(uid_t user, const Password &password, bool apiRequest = true);
+    RawBuffer unlockUserKey(const ClientID &clientID, const Password &password, bool apiRequest = true);
 
-    RawBuffer lockUserKey(uid_t user);
+    RawBuffer lockUserKey(const ClientID &clientID);
 
-    RawBuffer removeUserData(uid_t user);
+    RawBuffer removeUserData(const ClientID &clientID);
 
     RawBuffer changeUserPassword(
-        uid_t user,
+        const ClientID &clientID,
         const Password &oldPassword,
         const Password &newPassword);
 
     RawBuffer resetUserPassword(
-        uid_t user,
+        const ClientID &clientID,
         const Password &newPassword);
 
     RawBuffer removeApplicationData(
+        const std::string &zone,
         const Label &smackLabel);
 
     RawBuffer saveData(
@@ -185,7 +186,7 @@ public:
 private:
 
     void loadDKEKFile(
-        uid_t user,
+        const ClientID &clientID,
         const Password &password,
         bool apiReq);
 
@@ -196,7 +197,7 @@ private:
         const RawBuffer &second);
 
     void saveDKEKFile(
-        uid_t user,
+        const ClientID &clientID,
         const Password &password);
 
     int verifyBinaryData(
@@ -335,7 +336,7 @@ private:
         const PermissionMask permissionMask);
 
 
-    std::map<uid_t, UserData> m_userDataMap;
+    std::map<ClientID, UserData> m_userDataMap;
     AccessControl m_accessControl;
     //FileLock m_lock;
 };
index 79c08d7..6c99c36 100644 (file)
@@ -111,7 +111,7 @@ bool CKMService::processOne(
 
 RawBuffer CKMService::processControl(MessageBuffer &buffer) {
     int command = 0;
-    uid_t user = 0;
+    ClientID clientID;
     ControlCommand cc;
     Password newPass, oldPass;
     Label smackLabel;
@@ -124,25 +124,26 @@ RawBuffer CKMService::processControl(MessageBuffer &buffer) {
 
     switch(cc) {
     case ControlCommand::UNLOCK_USER_KEY:
-        buffer.Deserialize(user, newPass);
-        return m_logic->unlockUserKey(user, newPass);
+        buffer.Deserialize(clientID, newPass);
+        return m_logic->unlockUserKey(clientID, newPass);
     case ControlCommand::LOCK_USER_KEY:
-        buffer.Deserialize(user);
-        return m_logic->lockUserKey(user);
+        buffer.Deserialize(clientID);
+        return m_logic->lockUserKey(clientID);
     case ControlCommand::REMOVE_USER_DATA:
-        buffer.Deserialize(user);
-        return m_logic->removeUserData(user);
+        buffer.Deserialize(clientID);
+        return m_logic->removeUserData(clientID);
     case ControlCommand::CHANGE_USER_PASSWORD:
-        buffer.Deserialize(user, oldPass, newPass);
-        return m_logic->changeUserPassword(user, oldPass, newPass);
+        buffer.Deserialize(clientID, oldPass, newPass);
+        return m_logic->changeUserPassword(clientID, oldPass, newPass);
     case ControlCommand::RESET_USER_PASSWORD:
-        buffer.Deserialize(user, newPass);
-        return m_logic->resetUserPassword(user, newPass);
+        buffer.Deserialize(clientID, newPass);
+        return m_logic->resetUserPassword(clientID, newPass);
     case ControlCommand::REMOVE_APP_DATA:
-        buffer.Deserialize(smackLabel);
-        return m_logic->removeApplicationData(smackLabel);
-    case ControlCommand::UPDATE_CC_MODE:
-        return m_logic->updateCCMode();
+    {
+        std::string zone;
+        buffer.Deserialize(zone, smackLabel);
+        return m_logic->removeApplicationData(zone, smackLabel);
+    }
     case ControlCommand::SET_PERMISSION:
     {
         Name name;
@@ -150,8 +151,8 @@ RawBuffer CKMService::processControl(MessageBuffer &buffer) {
         Label accessorLabel;
         PermissionMask permissionMask = 0;
 
-        buffer.Deserialize(user, name, label, accessorLabel, permissionMask);
-        Credentials cred = { user, label };
+        buffer.Deserialize(clientID, name, label, accessorLabel, permissionMask);
+        Credentials cred = { clientID, label };
         return m_logic->setPermission(
             cred,
             command,
@@ -161,6 +162,8 @@ RawBuffer CKMService::processControl(MessageBuffer &buffer) {
             accessorLabel,
             permissionMask);
     }
+    case ControlCommand::UPDATE_CC_MODE:
+        return m_logic->updateCCMode();
     default:
         Throw(Exception::BrokenProtocol);
     }
@@ -173,7 +176,6 @@ RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer)
     int tmpDataType = 0;
     Name name;
     Label label, accessorLabel;
-    std::string user;
 
     buffer.Deserialize(command);
     buffer.Deserialize(msgID);
@@ -184,7 +186,7 @@ RawBuffer CKMService::processStorage(Credentials &cred, MessageBuffer &buffer)
     // So, to unlock user data when lock type is None, key-manager always try to unlock user data with null password.
     // Even if the result is fail, it will be ignored.
     Password nullPassword("");
-    m_logic->unlockUserKey(cred.uid, nullPassword, false);
+    m_logic->unlockUserKey(cred.clientID, nullPassword, false);
 
     LogDebug("Process storage. Command: " << command);
 
index d6eb241..5f0e778 100644 (file)
@@ -75,6 +75,11 @@ void CryptoLogic::pushKey(const Label &smackLabel,
     m_keyMap[smackLabel] = applicationKey;
 }
 
+void CryptoLogic::removeKey(const Label &smackLabel)
+{
+    m_keyMap.erase(smackLabel);
+}
+
 RawBuffer CryptoLogic::encryptDataAesCbc(
     const RawBuffer &data,
     const RawBuffer &key,
index ceda146..43e4b9c 100644 (file)
@@ -54,6 +54,7 @@ public:
     bool haveKey(const Label &smackLabel);
     void pushKey(const Label &smackLabel,
                  const RawBuffer &applicationKey);
+    void removeKey(const Label &smackLabel);
 
 private:
        static const int ENCR_BASE64 =   1 << 0;
index 04f4022..1fcf77a 100644 (file)
@@ -63,7 +63,7 @@ namespace {
             "   VALUES(?101, ?103);";
 
     const char *DB_CMD_SCHEMA_GET =
-            "SELECT * FROM SCHEMA_INFO WHERE name=?101;";
+            "SELECT * FROM SCHEMA_INFO WHERE name IS ?101;";
 
     const char *DB_SCHEMA_VERSION_FIELD = "schema_version";
 
@@ -74,13 +74,13 @@ namespace {
             "   VALUES(?101, ?102);";
 
     const char *DB_CMD_NAME_COUNT_ROWS =
-            "SELECT COUNT(idx) FROM NAMES WHERE name=?101 AND label=?102;";
+            "SELECT COUNT(idx) FROM NAMES WHERE name IS ?101 AND label IS ?102;";
 
     const char *DB_CMD_NAME_DELETE =
-            "DELETE FROM NAMES WHERE name=?101 AND label=?102;";
+            "DELETE FROM NAMES WHERE name IS ?101 AND label IS ?102;";
 
     const char *DB_CMD_NAME_DELETE_BY_LABEL =
-            "DELETE FROM NAMES WHERE label=?102;";
+            "DELETE FROM NAMES WHERE label IS ?102;";
 
 
     const char *DB_CMD_OBJECT_INSERT =
@@ -90,35 +90,35 @@ namespace {
             "   iv, dataSize, data, tag, idx) "
             "   VALUES(?001, ?002, ?003, ?004, ?005, "
             "          ?006, ?007, ?008,"
-            "          (SELECT idx FROM NAMES WHERE name=?101 and label=?102)"
+            "          (SELECT idx FROM NAMES WHERE name IS ?101 and label IS ?102)"
             "         );";
 
     const char *DB_CMD_OBJECT_SELECT_BY_NAME_AND_LABEL =
             "SELECT * FROM [join_name_object_tables] "
             " WHERE (dataType BETWEEN ?001 AND ?002) "
-            " AND name=?101 and label=?102;";
+            " AND name IS ?101 and label IS ?102;";
 
 
     const char *DB_CMD_KEY_INSERT =
             "INSERT INTO KEYS(label, key) VALUES (?, ?);";
     const char *DB_CMD_KEY_SELECT =
-            "SELECT key FROM KEYS WHERE label=?;";
+            "SELECT key FROM KEYS WHERE label IS ?;";
     const char *DB_CMD_KEY_DELETE =
-            "DELETE FROM KEYS WHERE label=?";
+            "DELETE FROM KEYS WHERE label IS ?;";
 
 
     const char *DB_CMD_PERMISSION_SET = // SQLite does not support updating views
             "REPLACE INTO PERMISSIONS(permissionLabel, permissionMask, idx) "
-            " VALUES (?104, ?105, (SELECT idx FROM NAMES WHERE name=?101 and label=?102));";
+            " VALUES (?104, ?105, (SELECT idx FROM NAMES WHERE name IS ?101 and label IS ?102));";
 
     const char *DB_CMD_PERMISSION_SELECT =
             "SELECT permissionMask FROM [join_name_permission_tables] "
-            " WHERE permissionLabel=?104 "
-            " AND name=?101 and label=?102;";
+            " WHERE permissionLabel IS ?104 "
+            " AND name IS ?101 AND label IS ?102;";
 
     const char *DB_CMD_PERMISSION_DELETE = // SQLite does not support updating views
-            "DELETE FROM PERMISSIONS WHERE permissionLabel=?104 AND "
-            " idx=(SELECT idx FROM NAMES WHERE name=?101 and label=?102);";
+            "DELETE FROM PERMISSIONS WHERE permissionLabel IS ?104 AND "
+            " idx IS (SELECT idx FROM NAMES WHERE name IS ?101 AND label IS ?102);";
 
 
     /*
@@ -129,8 +129,8 @@ namespace {
      */
     const char *DB_CMD_NAME_SELECT_BY_TYPE_AND_PERMISSION =
             "SELECT label, name FROM [join_all_tables] "
-            " WHERE dataType>=?001 AND dataType<=?002 "
-            " AND permissionLabel=?104 AND permissionMask&?004!=0 GROUP BY idx;";
+            " WHERE (dataType BETWEEN ?001 AND ?002) "
+            " AND permissionLabel IS ?104 AND permissionMask&?004 IS NOT 0 GROUP BY idx;";
 }
 
 namespace CKM {
@@ -217,26 +217,37 @@ namespace DB {
     bool Crypto::getDBVersion(int & schemaVersion)
     {
         SchemaInfo SchemaInfo(this);
-        if(SchemaInfo.getVersionInfo(schemaVersion)) {
+
+        /*
+         *  SCHEMA_INFO (o)
+         *  SCHEMA_INFO exists from schema version 3
+         */
+        if (m_connection->CheckTableExist("SCHEMA_INFO")
+           && SchemaInfo.getVersionInfo(schemaVersion)) {
             LogDebug("Current DB version: " << schemaVersion);
             return true;
         }
-        else
-        {
-            LogDebug("No DB version known or DB not present");
 
-            // special case: old CKM_TABLE exists
-            if(m_connection->CheckTableExist("CKM_TABLE")) {
-                schemaVersion = DB_VERSION_1;
-                return true;
-            }
+        /*
+         *  SCHEMA_INFO (x) / CKM_TABLE (o)
+         *  CKM_TABLE exists only in schema version 1
+         *  -> schema version 1
+         */
+        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")) {
-                schemaVersion = DB_VERSION_2;
-                return true;
-            }
+        /*
+         *  SCHEMA_INFO (x) / CKM_TABLE (x) / NAME_TABLE (o)
+         *  NAME_TABLE exists only in schema version 2
+         *  -> schema version 2
+         */
+        if (m_connection->CheckTableExist("NAME_TABLE")) {
+            schemaVersion = DB_VERSION_2;
+            return true;
         }
+
         // not recognized - proceed with an empty DBs
         return false;
     }
index 681c16b..0bec6fc 100644 (file)
@@ -47,11 +47,8 @@ void Digest::reset()
 
     m_initialized = false;
     m_finalized = false;
-
     m_ctx = EVP_MD_CTX_create();
-    if (!m_ctx) {
-        ThrowMsg(Exception::InternalError,
-                 "Failed to memory allocation on EVP_MD_CTX");
+    if (m_ctx == nullptr) {
     }
 
     ret = EVP_DigestInit_ex(m_ctx, m_md, NULL);
index 6c77098..445e239 100644 (file)
@@ -21,6 +21,8 @@
 
 #include "file-lock.h"
 
+#include <dpl/errno_string.h>
+
 #include <fcntl.h>
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -48,30 +50,28 @@ std::runtime_error io_exception(const Args&... args)
 
 FileLock::FileLock(const char* const file)
 {
-    char errbuf[512] = {0, };
-
     // Open lock file
     m_lockFd = TEMP_FAILURE_RETRY(creat(file, 0644));
     if (m_lockFd == -1) {
-        throw io_exception("Cannot open lock file. Errno: ", strerror_r(errno, errbuf, sizeof(errbuf)));
+        throw io_exception("Cannot open lock file. Errno: ", GetErrnoString(errno));
     }
 
     if (-1 == lockf(m_lockFd, F_TLOCK, 0)) {
         if (errno == EACCES || errno == EAGAIN)
             throw io_exception("Can't acquire lock. Another instance must be running.");
         else
-            throw io_exception("Can't acquire lock. Errno: ", strerror_r(errno, errbuf, sizeof(errbuf)));
+            throw io_exception("Can't acquire lock. Errno: ", GetErrnoString(errno));
     }
 
     std::string pid = std::to_string(getpid());
 
     ssize_t written = TEMP_FAILURE_RETRY(write(m_lockFd, pid.c_str(), pid.size()));
     if (-1 == written || static_cast<ssize_t>(pid.size()) > written)
-        throw io_exception("Can't write file lock. Errno: ", strerror_r(errno, errbuf, sizeof(errbuf)));
+        throw io_exception("Can't write file lock. Errno: ", GetErrnoString(errno));
 
     int ret = fsync(m_lockFd);
     if (-1 == ret)
-        throw io_exception("Fsync failed. Errno: ", strerror_r(errno, errbuf, sizeof(errbuf)));
+        throw io_exception("Fsync failed. Errno: ", GetErrnoString(errno));
 }
 
 FileLock::~FileLock()
index 7a02fe1..e2b953a 100644 (file)
@@ -47,44 +47,44 @@ const std::string CKM_KEY_BACKUP_PREFIX = "key-backup-";
 const std::string CKM_DB_KEY_PREFIX = "db-key-";
 const std::string CKM_DB_PREFIX = "db-";
 const std::string CKM_REMOVED_APP_PREFIX = "removed-app-";
-const std::string CKM_LOCK_FILE = "/var/run/key-manager.pid";
+const std::string CKM_LOCK_FILE = "/run/key-manager.pid";
 
 } // namespace anonymous
 
 namespace CKM {
 
-FileSystem::FileSystem(uid_t uid)
-  : m_uid(uid)
+FileSystem::FileSystem(const ClientID &clientID)
+  : m_clientID(clientID)
 {}
 
 std::string FileSystem::getDBPath() const
 {
     std::stringstream ss;
-    ss << CKM_DATA_PATH << CKM_DB_PREFIX << m_uid;
+    ss << CKM_DATA_PATH << CKM_DB_PREFIX << m_clientID;
     return ss.str();
 }
 
 std::string FileSystem::getDKEKPath() const {
     std::stringstream ss;
-    ss << CKM_DATA_PATH << CKM_KEY_PREFIX << m_uid;
+    ss << CKM_DATA_PATH << CKM_KEY_PREFIX << m_clientID;
     return ss.str();
 }
 
 std::string FileSystem::getDKEKBackupPath() const {
     std::stringstream ss;
-    ss << CKM_DATA_PATH << CKM_KEY_BACKUP_PREFIX << m_uid;
+    ss << CKM_DATA_PATH << CKM_KEY_BACKUP_PREFIX << m_clientID;
     return ss.str();
 }
 
 std::string FileSystem::getDBDEKPath() const {
     std::stringstream ss;
-    ss << CKM_DATA_PATH << CKM_DB_KEY_PREFIX << m_uid;
+    ss << CKM_DATA_PATH << CKM_DB_KEY_PREFIX << m_clientID;
     return ss.str();
 }
 
 std::string FileSystem::getRemovedAppsPath() const {
     std::stringstream ss;
-    ss << CKM_DATA_PATH << CKM_REMOVED_APP_PREFIX << m_uid;
+    ss << CKM_DATA_PATH << CKM_REMOVED_APP_PREFIX << m_clientID;
     return ss.str();
 }
 
@@ -217,15 +217,15 @@ int FileSystem::init() {
     return 0;
 }
 
-UidVector FileSystem::getUIDsFromDBFile() {
-    UidVector uids;
+ClientIDVector FileSystem::getClientIDsFromDBFile(const std::string zone) {
+    ClientIDVector clientIDVec;
     std::unique_ptr<DIR, std::function<int(DIR*)>>
         dirp(::opendir(CKM_DATA_PATH.c_str()), ::closedir);
 
     if (!dirp.get()) {
         int err = errno;
         LogError("Error in opendir. Data directory could not be read. Error: " << GetErrnoString(err));
-        return UidVector();
+        return ClientIDVector();
     }
 
     size_t len = offsetof(struct dirent, d_name) + pathconf(CKM_DATA_PATH.c_str(), _PC_NAME_MAX) + 1;
@@ -234,20 +234,31 @@ UidVector FileSystem::getUIDsFromDBFile() {
 
     if (!pEntry.get()) {
         LogError("Memory allocation failed.");
-        return UidVector();
+        return ClientIDVector();
     }
 
     struct dirent* pDirEntry = NULL;
 
     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())) {
+            LogDebug("Not DomainKEK file.");
             continue;
         }
-
-        // We find database. Let's extract user id.
+#ifdef DB_PER_ZONE_ENABLE
+        if (strlen(pDirEntry->d_name + CKM_KEY_PREFIX.size()) <= zone.size()) {
+            LogError("Should not happen. "
+                "Key file[" << pDirEntry->d_name << "] clientID(zone + uid) length should be longer than zone name size");
+            continue;
+        }
+        if (strncmp(pDirEntry->d_name + CKM_KEY_PREFIX.size(), zone.c_str(), zone.size())) {
+            LogDebug("Another zone's DomainKEK file.");
+            continue;
+        }
+#else
+        (void) zone;
+#endif
         try {
-            uids.push_back(static_cast<uid_t>(std::stoi((pDirEntry->d_name)+CKM_KEY_PREFIX.size())));
+            clientIDVec.push_back(pDirEntry->d_name + CKM_KEY_PREFIX.size());
         } catch (const std::invalid_argument) {
             LogError("Error in extracting uid from db file. Error=std::invalid_argument."
                 "This will be ignored.File=" << pDirEntry->d_name << "");
@@ -256,49 +267,38 @@ UidVector FileSystem::getUIDsFromDBFile() {
                 "This will be ignored. File="<< pDirEntry->d_name << "");
         }
     }
-
-    return uids;
+    return clientIDVec;
 }
 
 int FileSystem::removeUserData() const {
-    int err, retCode = 0;
 
-    if (unlink(getDBPath().c_str())) {
-        retCode = -1;
-        err = errno;
-        LogError("Error in unlink user database: " << getDBPath()
-            << "Errno: " << errno << " " << GetErrnoString(err));
-    }
+    if (removeFile(getDBPath())
+        || removeFile(getDKEKPath())
+        || removeFile(getDKEKBackupPath())
+        || removeFile(getDBDEKPath())
+        || removeFile(getRemovedAppsPath())) {
 
-    if (unlink(getDKEKPath().c_str())) {
-        retCode = -1;
-        err = errno;
-        LogError("Error in unlink user DKEK: " << getDKEKPath()
-            << "Errno: " << errno << " " << GetErrnoString(err));
+        return -1;
     }
 
-    if (unlink(getDKEKBackupPath().c_str())) {
-        retCode = -1;
-        err = errno;
-        LogDebug("Unlink user backup DKEK failed (file probably does not exists): " << getDKEKBackupPath()
-            << "Errno: " << errno << " " << GetErrnoString(err));
-    }
+    return 0;
+}
 
-    if (unlink(getDBDEKPath().c_str())) {
-        retCode = -1;
-        err = errno;
-        LogError("Error in unlink user DBDEK: " << getDBDEKPath()
-            << "Errno: " << errno << " " << GetErrnoString(err));
-    }
+int FileSystem::removeFile(const std::string &path) const
+{
+    if (access(path.c_str(), F_OK) == 0
+        && unlink(path.c_str()) != 0) {
 
-    if (unlink(getRemovedAppsPath().c_str())) {
-        retCode = -1;
-        err = errno;
-        LogError("Error in unlink user's Removed Apps File: " << getRemovedAppsPath()
-            << "Errno: " << errno << " " << GetErrnoString(err));
+        int err = errno;
+
+        LogError("Unlink Path[" << path
+            << "] Errno[" << errno
+            << "] ErrnoString[" << GetErrnoString(err) << "]");
+
+       return -1;
     }
 
-    return retCode;
+    return 0;
 }
 
 FileLock FileSystem::lock()
index 9058c42..2e7767f 100644 (file)
  */
 #pragma once
 
-#include <ckm/ckm-type.h>
 #include <string>
+#include <ckm/ckm-type.h>
 #include <file-lock.h>
 
 namespace CKM {
 
 typedef std::vector<std::string> AppLabelVector;
-typedef std::vector<uid_t> UidVector;
+typedef std::vector<ClientID> ClientIDVector;
 
 class FileSystem {
 public:
@@ -40,7 +40,7 @@ public:
         DECLARE_EXCEPTION_TYPE(Base, RenameFailed)
     };
 
-    FileSystem(uid_t uid);
+    FileSystem(const ClientID &clientID);
 
     std::string getDBPath() const;
 
@@ -65,7 +65,7 @@ public:
     AppLabelVector clearRemovedsApps() const;
 
     static int init();
-    static UidVector getUIDsFromDBFile();
+    static ClientIDVector getClientIDsFromDBFile(std::string zone);
     static FileLock lock();
 
     virtual ~FileSystem(){}
@@ -77,8 +77,9 @@ protected:
     void saveFile(const std::string &path, const RawBuffer &buffer) const;
     std::string getRemovedAppsPath() const;
     void moveFile(const std::string &from, const std::string &to) const;
+    int removeFile(const std::string &path) const;
 
-    uid_t m_uid;
+    ClientID m_clientID;
 };
 
 } // namespace CKM
index a50e5b2..6da61dd 100644 (file)
@@ -49,6 +49,23 @@ CKM::RawBuffer toRawBuffer(T *)
     return CKM::RawBuffer();
 }
 
+int cleanMemory(void *targetPtr, size_t targetSize)
+{
+    char *ptr = reinterpret_cast<char *>(targetPtr);
+
+    // overwrite ptr
+    for (size_t size = 0; size < targetSize; ++size)
+        ptr[size] = 0;
+
+    // verification
+    for (size_t size = 0; size < targetSize; ++size) {
+        if (0 != ptr[size]) {
+            return -1; // fail
+        }
+    }
+    return 0; // success
+}
+
 } // anonymous namespace
 
 using namespace CKM;
@@ -59,6 +76,25 @@ WrappedKeyAndInfoContainer::WrappedKeyAndInfoContainer()
     memset(wrappedKeyAndInfo, 0, sizeof(WrappedKeyAndInfo));
 }
 
+WrappedKeyAndInfoContainer::WrappedKeyAndInfoContainer(const WrappedKeyAndInfoContainer &second)
+{
+    wrappedKeyAndInfo = new WrappedKeyAndInfo;
+    memcpy(wrappedKeyAndInfo, second.wrappedKeyAndInfo, sizeof(WrappedKeyAndInfo));
+}
+
+WrappedKeyAndInfoContainer &WrappedKeyAndInfoContainer::operator=(const WrappedKeyAndInfoContainer &second)
+{
+    if (this == &second)
+        return *this;
+
+    if (wrappedKeyAndInfo)
+        delete wrappedKeyAndInfo;
+
+    wrappedKeyAndInfo = new WrappedKeyAndInfo;
+    memcpy(wrappedKeyAndInfo, second.wrappedKeyAndInfo, sizeof(WrappedKeyAndInfo));
+    return *this;
+}
+
 WrappedKeyAndInfoContainer::WrappedKeyAndInfoContainer(const unsigned char *data)
 {
     wrappedKeyAndInfo = new WrappedKeyAndInfo;
@@ -113,6 +149,31 @@ KeyAndInfoContainer::KeyAndInfoContainer()
     memset(keyAndInfo, 0, sizeof(KeyAndInfo));
 }
 
+KeyAndInfoContainer::KeyAndInfoContainer(const KeyAndInfoContainer &second)
+{
+    keyAndInfo = new KeyAndInfo;
+    memcpy(keyAndInfo, second.keyAndInfo, sizeof(KeyAndInfo));
+}
+
+KeyAndInfoContainer &KeyAndInfoContainer::operator=(const KeyAndInfoContainer &second)
+{
+    if (this == &second)
+        return *this;
+
+    if (keyAndInfo) {
+        if (cleanMemory(keyAndInfo, sizeof(KeyAndInfo))) {
+            delete keyAndInfo;
+            ThrowMsg(Exception::Base,
+                     "KeyAndInfo in KeyAndInfoContainer was not destroyed!");
+        }
+        delete keyAndInfo;
+    }
+
+    keyAndInfo = new KeyAndInfo;
+    memcpy(keyAndInfo, second.keyAndInfo, sizeof(KeyAndInfo));
+    return *this;
+}
+
 KeyAndInfoContainer::KeyAndInfoContainer(const unsigned char *data)
 {
     keyAndInfo = new KeyAndInfo;
@@ -136,18 +197,13 @@ void KeyAndInfoContainer::setKeyInfo(const KeyComponentsInfo *keyComponentsInfo)
 
 KeyAndInfoContainer::~KeyAndInfoContainer()
 {
-    // overwrite key
-    char *ptr = reinterpret_cast<char*>(keyAndInfo);
-    for (size_t size = 0; size < sizeof(KeyAndInfo); ++size)
-        ptr[size] = 0;
-    // verification
-    for (size_t size = 0; size < sizeof(KeyAndInfo); ++size) {
-        if (0 != ptr[size]) {
-            delete keyAndInfo;
-            ThrowMsg(Exception::Base, "KeyAndInfo in KeyAndInfoContainer "
-                "was not destroyed!");
-        }
+    if (cleanMemory(keyAndInfo, sizeof(KeyAndInfo))) {
+        // destroy verification failed.
+        delete keyAndInfo;
+        ThrowMsg(Exception::Base,
+                 "KeyAndInfo in KeyAndInfoContainer was not destroyed!");
     }
+
     delete keyAndInfo;
 }
 
@@ -165,19 +221,20 @@ KeyProvider::KeyProvider(
     , m_isInitialized(true)
 {
     if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
-        LogError("input size:" << domainKEKInWrapForm.size()
-            << " Expected: " << sizeof(WrappedKeyAndInfo));
-        ThrowMsg(Exception::InputParamError, "buffer doesn't have proper size to store WrappedKeyAndInfo in KeyProvider Constructor");
+        ThrowMsg(Exception::InputParamError,
+            "domainKEKInWrapForm "
+            "input size:" << domainKEKInWrapForm.size() <<
+            " Expected:" << sizeof(WrappedKeyAndInfo));
     }
 
-    WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer(domainKEKInWrapForm.data());
+    WrappedKeyAndInfoContainer wkmcDKEK(domainKEKInWrapForm.data());
 
     char *concat_user_pass = NULL;
     uint8_t PKEK1[MAX_KEY_SIZE];
 
     concat_user_pass = concat_password_user(
         wkmcDKEK.getWrappedKeyAndInfo().keyInfo.label,
-        password.c_str());
+        getConvertedStr(password));
 
     if (!PKCS5_PBKDF2_HMAC_SHA1(
         concat_user_pass,
@@ -204,7 +261,8 @@ KeyProvider::KeyProvider(
         wkmcDKEK.getWrappedKeyAndInfo().keyInfo.iv,
         m_kmcDKEK->getKeyAndInfo().key))) {
 
-        ThrowMsg(Exception::PassWordError, "VerifyDomainKEK failed in KeyProvider Constructor");
+        ThrowMsg(Exception::PassWordError,
+            "VerifyDomainKEK failed in KeyProvider Constructor");
     }
 
     m_kmcDKEK->setKeyInfo(&(wkmcDKEK.getWrappedKeyAndInfo().keyInfo));
@@ -243,7 +301,9 @@ RawBuffer KeyProvider::getPureDomainKEK()
         ThrowMsg(Exception::InitFailed, "Object not initialized!");
     }
 
-    return RawBuffer(m_kmcDKEK->getKeyAndInfo().key, (m_kmcDKEK->getKeyAndInfo().key) + m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength);
+    return RawBuffer(m_kmcDKEK->getKeyAndInfo().key,
+            (m_kmcDKEK->getKeyAndInfo().key)
+                + m_kmcDKEK->getKeyAndInfo().keyInfo.keyLength);
 }
 
 RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
@@ -252,14 +312,14 @@ RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
         ThrowMsg(Exception::InitFailed, "Object not initialized!");
     }
 
-    WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer();
+    WrappedKeyAndInfoContainer wkmcDKEK;
 
     char *concat_user_pass = NULL;
     uint8_t PKEK1[MAX_KEY_SIZE];
 
     concat_user_pass = concat_password_user(
         m_kmcDKEK->getKeyAndInfo().keyInfo.label,
-        password.c_str());
+        getConvertedStr(password));
 
     if (!PKCS5_PBKDF2_HMAC_SHA1(
         concat_user_pass,
@@ -305,15 +365,14 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
     }
 
     if (DEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)){
-        LogError("input size:" << DEKInWrapForm.size()
-                  << " Expected: " << sizeof(WrappedKeyAndInfo));
         ThrowMsg(Exception::InputParamError,
-                "buffer doesn't have proper size to store "
-                "WrappedKeyAndInfo in KeyProvider::getPureDEK");
+            "DEKInWrapForm "
+            "input size:" << DEKInWrapForm.size() <<
+            " Expected:" << sizeof(WrappedKeyAndInfo));
     }
 
-    KeyAndInfoContainer kmcDEK = KeyAndInfoContainer();
-    WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer(DEKInWrapForm.data());
+    KeyAndInfoContainer kmcDEK;
+    WrappedKeyAndInfoContainer wkmcDEK(DEKInWrapForm.data());
 
     uint8_t PKEK2[MAX_KEY_SIZE];
     int keyLength;
@@ -347,7 +406,8 @@ RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
     LogDebug("getPureDEK SUCCESS");
     return RawBuffer(
         kmcDEK.getKeyAndInfo().key,
-        (kmcDEK.getKeyAndInfo().key) + kmcDEK.getKeyAndInfo().keyInfo.keyLength);
+        (kmcDEK.getKeyAndInfo().key)
+            + kmcDEK.getKeyAndInfo().keyInfo.keyLength);
 }
 
 RawBuffer KeyProvider::generateDEK(const std::string &smackLabel)
@@ -357,7 +417,7 @@ RawBuffer KeyProvider::generateDEK(const std::string &smackLabel)
                 "Object not initialized!");
     }
 
-    WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer();
+    WrappedKeyAndInfoContainer wkmcDEK;
     std::string resized_smackLabel;
 
     if (smackLabel.length() < APP_LABEL_SIZE)
@@ -413,16 +473,15 @@ RawBuffer KeyProvider::reencrypt(
     const Password &newPass)
 {
     if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
-        LogError("input size:" << domainKEKInWrapForm.size()
-                  << " Expected: " << sizeof(WrappedKeyAndInfo));
         ThrowMsg(Exception::InputParamError,
-                "buffer doesn't have proper size to store "
-                "WrappedKeyAndInfo in KeyProvider::reencrypt");
+            "domainKEKInWrapForm "
+            "input size:" << domainKEKInWrapForm.size() <<
+            " Expected:" << sizeof(WrappedKeyAndInfo));
     }
 
-    WrappedKeyAndInfoContainer wkmcOldDKEK = WrappedKeyAndInfoContainer(domainKEKInWrapForm.data());
-    WrappedKeyAndInfoContainer wkmcNewDKEK = WrappedKeyAndInfoContainer();
-    KeyAndInfoContainer kmcDKEK = KeyAndInfoContainer();
+    WrappedKeyAndInfoContainer wkmcOldDKEK(domainKEKInWrapForm.data());
+    WrappedKeyAndInfoContainer wkmcNewDKEK;
+    KeyAndInfoContainer kmcDKEK;
 
     char *concat_user_pass = NULL;
     uint8_t PKEK1[MAX_KEY_SIZE];
@@ -431,7 +490,7 @@ RawBuffer KeyProvider::reencrypt(
 
     concat_user_pass = concat_password_user(
         wkmcOldDKEK.getWrappedKeyAndInfo().keyInfo.label,
-        oldPass.c_str());
+        getConvertedStr(oldPass));
 
     if (!PKCS5_PBKDF2_HMAC_SHA1(
         concat_user_pass,
@@ -464,7 +523,7 @@ RawBuffer KeyProvider::reencrypt(
 
     concat_user_pass = concat_password_user(
         kmcDKEK.getKeyAndInfo().keyInfo.label,
-        newPass.c_str());
+        getConvertedStr(newPass));
 
     if (!PKCS5_PBKDF2_HMAC_SHA1(
         concat_user_pass,
@@ -507,7 +566,7 @@ RawBuffer KeyProvider::generateDomainKEK(
     const std::string &user,
     const Password &userPassword)
 {
-    WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer();
+    WrappedKeyAndInfoContainer wkmcDKEK;
     uint8_t key[MAX_KEY_SIZE], PKEK1[MAX_KEY_SIZE];
 
     if (!RAND_bytes(wkmcDKEK.getWrappedKeyAndInfo().keyInfo.salt, MAX_SALT_SIZE) ||
@@ -517,7 +576,7 @@ RawBuffer KeyProvider::generateDomainKEK(
 
     int wrappedKeyLength;
     char *concat_user_pass = NULL;
-    concat_user_pass = concat_password_user(user.c_str(), userPassword.c_str());
+    concat_user_pass = concat_password_user(user.c_str(), getConvertedStr(userPassword));
     if (!PKCS5_PBKDF2_HMAC_SHA1(
         concat_user_pass,
         strlen(concat_user_pass),
@@ -569,7 +628,12 @@ KeyProvider::~KeyProvider()
     LogDebug("KeyProvider Destructor");
 }
 
-int KeyProvider::encryptAes256Gcm(const unsigned char *plaintext, int plaintext_len, const unsigned char *key, const unsigned char *iv, unsigned char *ciphertext, unsigned char *tag)
+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;
@@ -611,7 +675,12 @@ int KeyProvider::encryptAes256Gcm(const unsigned char *plaintext, int plaintext_
     return ciphertext_len;
 }
 
-int KeyProvider::decryptAes256Gcm(const unsigned char *ciphertext, int ciphertext_len, unsigned char *tag, const unsigned char *key, const unsigned char *iv, unsigned char *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;
@@ -679,9 +748,14 @@ char * KeyProvider::concat_password_user(const char *user, const char *password)
 
     memset(concat_user_pass, '\0', concat_user_pass_len);
     memcpy(concat_user_pass, password, strlen(password));
-    memcpy(&(concat_user_pass[strlen(password)]), user, strlen(user));
+    memcpy(&(concat_user_pass[strlen(password)]), resized_user, strlen(resized_user));
     concat_user_pass[strlen(resized_user) + strlen(password)] = '\0';
 
     delete[] resized_user;
     return concat_user_pass;
 }
+
+const char* KeyProvider::getConvertedStr(const Password &password)
+{
+    return password.c_str();
+}
index 612dcd3..8e08c8a 100644 (file)
@@ -85,6 +85,10 @@ typedef struct WrappedKeyAndInfo_ {
 class WrappedKeyAndInfoContainer{
 public:
     WrappedKeyAndInfoContainer();
+
+    WrappedKeyAndInfoContainer(const WrappedKeyAndInfoContainer &);
+    WrappedKeyAndInfoContainer &operator=(const WrappedKeyAndInfoContainer &);
+
     WrappedKeyAndInfoContainer(const unsigned char*);
     WrappedKeyAndInfo& getWrappedKeyAndInfo();
     void setKeyInfoKeyLength(const unsigned int);
@@ -103,6 +107,10 @@ public:
         DECLARE_EXCEPTION_TYPE(CKM::Exception, Base)
     };
     KeyAndInfoContainer();
+
+    KeyAndInfoContainer(const KeyAndInfoContainer &);
+    KeyAndInfoContainer &operator=(const KeyAndInfoContainer &);
+
     KeyAndInfoContainer(const unsigned char*);
     KeyAndInfo& getKeyAndInfo();
     void setKeyInfoKeyLength(const unsigned int);
@@ -172,6 +180,7 @@ public:
     static int closeLibrary();
 
     virtual ~KeyProvider();
+
 private:
     // KeyAndInfoContainer class
     std::shared_ptr<KeyAndInfoContainer> m_kmcDKEK;
@@ -197,6 +206,7 @@ private:
         const char *user,
         const char *password);
 
+    static const char* getConvertedStr(const Password &password);
 };
 
 } // namespace CKM
index bd62d2c..61433fd 100644 (file)
 #include <ocsp-logic.h>
 #include <ocsp.h>
 
+#include <system_info.h>
+
+#define FEATURE_WIFI         "tizen.org/feature/network.internet"
+#define FEATURE_TELEPHONY    "tizen.org/feature/network.telephony"
+#define FEATURE_TETHERING_BT "tizen.org/feature/network.tethering.bluetooth"
+#define FEATURE_ETHERNET     "tizen.org/feature/network.ethernet"
+
 namespace CKM {
 
+namespace {
+
+bool isFeatureOn(const char *feature)
+{
+    bool value = false;
+
+    if (SYSTEM_INFO_ERROR_NONE != system_info_get_platform_bool(feature, &value)) {
+        // system info capi error.
+        return false;
+    }
+
+    return value;
+}
+
+} // namespace anonymous
+
+
+OCSPLogic::OCSPLogic()
+  : m_isNetAvailable(false)
+{
+    setNetAvailable();
+}
+
+void OCSPLogic::setNetAvailable()
+{
+    if (isFeatureOn(FEATURE_WIFI)
+        || isFeatureOn(FEATURE_TELEPHONY)
+        || isFeatureOn(FEATURE_TETHERING_BT)
+        || isFeatureOn(FEATURE_ETHERNET)) {
+        m_isNetAvailable = true;
+    }
+    else {
+        m_isNetAvailable = false;
+    }
+}
+
 RawBuffer OCSPLogic::ocspCheck(int commandId, const RawBufferVector &rawChain) {
     CertificateImplVector certChain;
     OCSPModule ocsp;
     int retCode = CKM_API_SUCCESS;
     int ocspStatus = CKM_API_OCSP_STATUS_INTERNAL_ERROR;
 
-    for (auto &e: rawChain) {
-        certChain.push_back(CertificateImpl(e, DataFormat::FORM_DER));
-        if (certChain.rbegin()->empty()) {
-            LogDebug("Error in parsing certificates!");
-            retCode = CKM_API_ERROR_INPUT_PARAM;
-            break;
-        }
+
+    if (!m_isNetAvailable) {
+        // try again for in case of system-info error
+        setNetAvailable();
+    }
+
+    if (!m_isNetAvailable) {
+        retCode = CKM_API_ERROR_NOT_SUPPORTED;
     }
+    else {
+       for (auto &e: rawChain) {
+           certChain.push_back(CertificateImpl(e, DataFormat::FORM_DER));
+           if (certChain.rbegin()->empty()) {
+               LogDebug("Error in parsing certificates!");
+               retCode = CKM_API_ERROR_INPUT_PARAM;
+               break;
+           }
+        }
 
-    if (retCode == CKM_API_SUCCESS)
-        ocspStatus = ocsp.verify(certChain);
+        if (certChain.size() < 2)
+            retCode = CKM_API_ERROR_INPUT_PARAM;
+        else if (retCode == CKM_API_SUCCESS)
+            ocspStatus = ocsp.verify(certChain);
+    }
 
     return MessageBuffer::Serialize(commandId, retCode, ocspStatus).Pop();
 }
index f0dcab4..725e757 100644 (file)
@@ -27,7 +27,7 @@ namespace CKM {
 
 class OCSPLogic {
 public:
-    OCSPLogic(){}
+    OCSPLogic();
     OCSPLogic(const OCSPLogic &) = delete;
     OCSPLogic(OCSPLogic &&) = delete;
     OCSPLogic& operator=(const OCSPLogic &) = delete;
@@ -35,6 +35,10 @@ public:
 
     RawBuffer ocspCheck(int commandId, const RawBufferVector &rawChain);
     virtual ~OCSPLogic(){}
+private:
+    void setNetAvailable();
+
+    bool m_isNetAvailable;
 };
 
 
index 4f4477e..22b8b25 100644 (file)
@@ -71,14 +71,13 @@ int OCSPModule::verify(const CertificateImplVector &certificateChain) {
     // create trusted store
     X509_STACK_PTR trustedCerts = create_x509_stack();
 
-    // skip first 2 certificates
-    for (auto it=certificateChain.cbegin()+2; it != certificateChain.cend(); it++)
-    {
-        if (it->empty()) {
+    for (unsigned int i=1; i < certificateChain.size(); i++) { // except leaf certificate
+        if (certificateChain[i].empty()) {
             LogError("Error. Broken certificate chain.");
             return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
         }
-        sk_X509_push(trustedCerts.get(), it->getX509());
+        sk_X509_push(trustedCerts.get(), certificateChain[i].getX509());
+        // these trusted certs will be changed while verifying ocsp status.
     }
 
     for (unsigned int i=0; i < certificateChain.size() -1; i++) {// except root certificate
@@ -183,7 +182,7 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer
     }
 
     if (BIO_do_connect(cbio) <= 0) {
-        LogDebug("Error in BIO_do_connect.");
+        LogError("Error in BIO_do_connect.");
         ERR_print_errors(bioLogger.get());
         /* report error */
 
@@ -217,17 +216,17 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer
     req = OCSP_REQUEST_new();
 
     if(req == NULL) {
-        LogDebug("Error in OCPS_REQUEST_new");
+        LogError("Error in OCPS_REQUEST_new");
         return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
     }
     certid = OCSP_cert_to_id(NULL, cert, issuer);
     if(certid == NULL)  {
-        LogDebug("Error in OCSP_cert_to_id");
+        LogError("Error in OCSP_cert_to_id");
         return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
     }
 
     if(OCSP_request_add0_id(req, certid) == NULL) {
-        LogDebug("Error in OCSP_request_add0_id");
+        LogError("Error in OCSP_request_add0_id");
         return CKM_API_OCSP_STATUS_INTERNAL_ERROR;
     }
 
@@ -284,7 +283,7 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer
         OCSP_REQUEST_free(req);
         OCSP_RESPONSE_free(resp);
 
-        LogDebug("Error in OCSP_response_get1_basic");
+        LogError("Error in OCSP_response_get1_basic");
         return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
     }
 
@@ -317,7 +316,7 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer
             OCSP_RESPONSE_free(resp);
             OCSP_BASICRESP_free(bs);
             X509_STORE_free(trustedStore);
-            LogDebug("Error in OCSP_check_nonce");
+            LogError("Error in OCSP_check_nonce");
             return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
         }
     }
@@ -333,7 +332,7 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer
         OCSP_BASICRESP_free(bs);
         X509_STORE_free(trustedStore);
 
-        LogDebug("Error in OCSP_resp_find_status");
+        LogError("Error in OCSP_resp_find_status");
         return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
     }
 
@@ -350,7 +349,7 @@ int OCSPModule::ocsp_verify(X509 *cert, X509 *issuer, STACK_OF(X509) *trustedCer
         OCSP_BASICRESP_free(bs);
         X509_STORE_free(trustedStore);
 
-        LogDebug("Error in OCSP_check_validity");
+        LogError("Error in OCSP_check_validity");
         return CKM_API_OCSP_STATUS_INVALID_RESPONSE;
     }
 
index f40a67e..92e26bc 100644 (file)
@@ -13384,7 +13384,7 @@ int sqlcipher_codec_ctx_set_pass(codec_ctx *ctx, const void *zKey, int nKey, int
   c_ctx->derive_key = 1;
 
   if(for_ctx == 2)
-    if((rc = sqlcipher_cipher_ctx_copy(ctx->read_ctx, c_ctx)) != SQLCIPHER_OK) 
+    if((rc = sqlcipher_cipher_ctx_copy(ctx->read_ctx, c_ctx)) != SQLCIPHER_OK)
       return rc; 
 
   return SQLCIPHER_OK;
@@ -13595,7 +13595,7 @@ int sqlcipher_page_hmac(cipher_ctx *ctx, Pgno pgno, unsigned char *in, int in_sz
 int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int page_sz, unsigned char *in, unsigned char *out) {
   cipher_ctx *c_ctx = for_ctx ? ctx->write_ctx : ctx->read_ctx;
   unsigned char *iv_in, *iv_out, *hmac_in, *hmac_out, *out_start;
-  int tmp_csz, csz, size;
+  int tmp_csz, csz, size, rc;
 
   /* calculate some required positions into various buffers */
   size = page_sz - c_ctx->reserve_sz; /* adjust size to useable size and memset reserve at end of page */
@@ -13642,13 +13642,15 @@ int sqlcipher_page_cipher(codec_ctx *ctx, int for_ctx, Pgno pgno, int mode, int
     }
   } 
 
-  EVP_CipherInit(&c_ctx->ectx, c_ctx->evp_cipher, NULL, NULL, mode);
+  rc = EVP_CipherInit(&c_ctx->ectx, c_ctx->evp_cipher, NULL, NULL, mode);
   EVP_CIPHER_CTX_set_padding(&c_ctx->ectx, 0);
-  EVP_CipherInit(&c_ctx->ectx, NULL, c_ctx->key, iv_out, mode);
-  EVP_CipherUpdate(&c_ctx->ectx, out, &tmp_csz, in, size);
+  rc = EVP_CipherInit(&c_ctx->ectx, NULL, c_ctx->key, iv_out, mode);
+  rc = EVP_CipherUpdate(&c_ctx->ectx, out, &tmp_csz, in, size);
   csz = tmp_csz;  
   out += tmp_csz;
-  EVP_CipherFinal(&c_ctx->ectx, out, &tmp_csz);
+  rc = EVP_CipherFinal(&c_ctx->ectx, out, &tmp_csz);
+  // patch to fix unchecked return value warning from prevent
+  (void) rc;
   csz += tmp_csz;
   EVP_CIPHER_CTX_cleanup(&c_ctx->ectx);
   assert(size == csz);
@@ -20302,7 +20304,10 @@ SQLCIPHER_API sqlcipher3_int64 sqlcipher3_soft_heap_limit64(sqlcipher3_int64 n){
   sqlcipher3_int64 priorLimit;
   sqlcipher3_int64 excess;
 #ifndef SQLCIPHER_OMIT_AUTOINIT
-  sqlcipher3_initialize();
+  // patch to fix unchecked return value warning from prevent
+  // sqlcipher3_initialize();
+  int rc = sqlcipher3_initialize();
+  (void) rc;
 #endif
   sqlcipher3_mutex_enter(mem0.mutex);
   priorLimit = mem0.alarmThreshold;
@@ -28548,7 +28553,10 @@ static int dotlockLock(sqlcipher3_file *id, int eFileLock) {
 #ifdef HAVE_UTIME
     utime(zLockFile, NULL);
 #else
-    utimes(zLockFile, NULL);
+    // patch to fix unchecked return value warning from prevent
+    // 0 on success, -1 on error. But it doesn't affect on any feature on program.
+    int rcTimeUpdate = utimes(zLockFile, NULL);
+    (void) rcTimeUpdate;
 #endif
     return SQLCIPHER_OK;
   }
@@ -28627,13 +28635,16 @@ static int dotlockUnlock(sqlcipher3_file *id, int eFileLock) {
 ** Close a file.  Make sure the lock has been released before closing.
 */
 static int dotlockClose(sqlcipher3_file *id) {
-  int rc;
+  int rc = SQLCIPHER_INTERNAL;
   if( id ){
     unixFile *pFile = (unixFile*)id;
     dotlockUnlock(id, NO_LOCK);
     sqlcipher3_free(pFile->lockingContext);
+
+    // patch to fix dereference pointer without null checking
+    rc = closeUnixFile(id);
   }
-  rc = closeUnixFile(id);
+  // rc = closeUnixFile(id);
   return rc;
 }
 /****************** End of the dot-file lock implementation *******************
@@ -30595,9 +30606,8 @@ static int unixShmMap(
       void *pMem;
       if( pShmNode->h>=0 ){
         pMem = mmap(0, szRegion,
-            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
-            MAP_SHARED, pShmNode->h, ((off_t)(pShmNode->nRegion))*szRegion
-        );
+            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
+            MAP_SHARED, pShmNode->h, ((off_t)(pShmNode->nRegion))*szRegion);
         if( pMem==MAP_FAILED ){
           rc = unixLogError(SQLCIPHER_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
           goto shmpage_out;
@@ -31894,7 +31904,12 @@ static void unixDlError(sqlcipher3_vfs *NotUsed, int nBuf, char *zBufOut){
   const char *zErr;
   UNUSED_PARAMETER(NotUsed);
   unixEnterMutex();
-  zErr = dlerror();
+  /*
+   * Tizen patch. disable dlerror because of prevent defect.
+   * zErr = dlerror();
+   * fix error code for dlerror case.
+   */
+  zErr = "[Tizen] dlfcn function error occured";
   if( zErr ){
     sqlcipher3_snprintf(nBuf, zBufOut, "%s", zErr);
   }
@@ -42588,7 +42603,7 @@ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
   */
   if( pSavepoint ){
     u32 ii;            /* Loop counter */
-    i64 offset = ((i64)(pSavepoint->iSubRec))*(4+pPager->pageSize);
+    i64 offset = pSavepoint->iSubRec*((i64)(4+pPager->pageSize));
 
     if( pagerUseWal(pPager) ){
       rc = sqlcipher3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
@@ -43435,7 +43450,7 @@ static int subjournalPage(PgHdr *pPg){
     ** write the journal record into the file.  */
     if( rc==SQLCIPHER_OK ){
       void *pData = pPg->pData;
-      i64 offset = ((i64)(pPager->nSubRec))*(4+pPager->pageSize);
+      i64 offset = pPager->nSubRec*((i64)(4+pPager->pageSize));
       char *pData2;
   
       CODEC2(pPager, pData, pPg->pgno, 7, return SQLCIPHER_NOMEM, pData2);
@@ -62333,7 +62348,7 @@ SQLCIPHER_PRIVATE u32 sqlcipher3VdbeSerialGet(
       return 3;
     }
     case 4: { /* 4-byte signed integer */
-      pMem->u.i = (((signed char)buf[0])<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
+      pMem->u.i = (i64)(buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
       pMem->flags = MEM_Int;
       return 4;
     }
@@ -63387,7 +63402,10 @@ SQLCIPHER_API void *sqlcipher3_aggregate_context(sqlcipher3_context *p, int nByt
       pMem->flags = MEM_Null;
       pMem->z = 0;
     }else{
-      sqlcipher3VdbeMemGrow(pMem, nByte, 0);
+      // patch to fix unchecked return value warning from prevent
+      int rc = sqlcipher3VdbeMemGrow(pMem, nByte, 0);
+      (void) rc;
+
       pMem->flags = MEM_Agg;
       pMem->u.pDef = p->pFunc;
       if( pMem->z ){
@@ -73596,6 +73614,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       const char *zId;            /* The function name. */
       FuncDef *pDef;              /* Information about the function */
       u8 enc = ENC(pParse->db);   /* The database encoding */
+      int rc;                     // patch to fix unchecked return value warning from prevent
 
       testcase( pExpr->op==TK_CONST_FUNC );
       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
@@ -73643,7 +73662,9 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         pNC->hasAgg = 1;
       }
       if( is_agg ) pNC->allowAgg = 0;
-      sqlcipher3WalkExprList(pWalker, pList);
+      // patch to fix unchecked return value warning from prevent
+      rc = sqlcipher3WalkExprList(pWalker, pList);
+      (void) rc;
       if( is_agg ) pNC->allowAgg = 1;
       /* FIX ME:  Compute pExpr->affinity based on the expected return
       ** type of the function 
@@ -82497,6 +82518,7 @@ SQLCIPHER_PRIVATE void sqlcipher3CreateView(
   DbFixer sFix;
   Token *pName = 0;
   int iDb;
+  int rc;            // patch to fix unchecked return value warning from prevent
   sqlcipher3 *db = pParse->db;
 
   if( pParse->nVar>0 ){
@@ -82510,7 +82532,10 @@ SQLCIPHER_PRIVATE void sqlcipher3CreateView(
     sqlcipher3SelectDelete(db, pSelect);
     return;
   }
-  sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
+  rc = sqlcipher3TwoPartName(pParse, pName1, pName2, &pName);
+  // patch to fix unchecked return value warning from prevent
+  (void) rc;
+
   iDb = sqlcipher3SchemaToIndex(db, p->pSchema);
   if( sqlcipher3FixInit(&sFix, pParse, iDb, "view", pName)
     && sqlcipher3FixSelect(&sFix, pSelect)
@@ -87848,6 +87873,7 @@ static void fkScanChildren(
   NameContext sNameContext;       /* Context used to resolve WHERE clause */
   WhereInfo *pWInfo;              /* Context used by sqlcipher3WhereXXX() */
   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
+  int rc;                         // patch to fix unchecked return value warning from prevent
   Vdbe *v = sqlcipher3GetVdbe(pParse);
 
   assert( !pIdx || pIdx->pTable==pTab );
@@ -87920,7 +87946,9 @@ static void fkScanChildren(
   memset(&sNameContext, 0, sizeof(NameContext));
   sNameContext.pSrcList = pSrc;
   sNameContext.pParse = pParse;
-  sqlcipher3ResolveExprNames(&sNameContext, pWhere);
+  rc = sqlcipher3ResolveExprNames(&sNameContext, pWhere);
+  // patch to fix unchecked return value warning from prevent
+  (void) rc;
 
   /* Create VDBE to loop through the entries in pSrc that match the WHERE
   ** clause. If the constraint is not deferred, throw an exception for
@@ -93219,12 +93247,12 @@ SQLCIPHER_PRIVATE void sqlcipher3Pragma(
 #if defined(SQLCIPHER_HAS_CODEC) || defined(SQLCIPHER_ENABLE_CEROD)
   if( sqlcipher3StrICmp(zLeft, "activate_extensions")==0 ){
 #ifdef SQLCIPHER_HAS_CODEC
-    if( sqlcipher3StrNICmp(zRight, "see-", 4)==0 ){
+    if( zRight && sqlcipher3StrNICmp(zRight, "see-", 4)==0 ){
       sqlcipher3_activate_see(&zRight[4]);
     }
 #endif
 #ifdef SQLCIPHER_ENABLE_CEROD
-    if( sqlcipher3StrNICmp(zRight, "cerod-", 6)==0 ){
+    if( zRight && sqlcipher3StrNICmp(zRight, "cerod-", 6)==0 ){
       sqlcipher3_activate_cerod(&zRight[6]);
     }
 #endif
@@ -93330,15 +93358,17 @@ SQLCIPHER_PRIVATE int sqlcipher3InitCallback(void *pInit, int argc, char **argv,
     */
     int rc;
     sqlcipher3_stmt *pStmt;
-    TESTONLY(int rcp);            /* Return code from sqlcipher3_prepare() */
+    int rcp;            /* Return code from sqlcipher3_prepare() */
 
     assert( db->init.busy );
     db->init.iDb = iDb;
     db->init.newTnum = sqlcipher3Atoi(argv[1]);
     db->init.orphanTrigger = 0;
-    TESTONLY(rcp = ) sqlcipher3_prepare(db, argv[2], -1, &pStmt, 0);
+    rcp = sqlcipher3_prepare(db, argv[2], -1, &pStmt, 0);
     rc = db->errCode;
     assert( (rc&0xFF)==(rcp&0xFF) );
+    (void) rcp;
+
     db->init.iDb = 0;
     if( SQLCIPHER_OK!=rc ){
       if( db->init.orphanTrigger ){
@@ -96946,7 +96976,12 @@ static int flattenSubquery(
 
   /* Authorize the subquery */
   pParse->zAuthContext = pSubitem->zName;
-  sqlcipher3AuthCheck(pParse, SQLCIPHER_SELECT, 0, 0, 0);
+
+  // patch for unchecked return value warning from prevent
+  // sqlcipher3AuthCheck(pParse, SQLCIPHER_SELECT, 0, 0, 0);
+  int authResult = sqlcipher3AuthCheck(pParse, SQLCIPHER_SELECT, 0, 0, 0);
+  (void) authResult;
+
   pParse->zAuthContext = zSavedAuthContext;
 
   /* If the sub-query is a compound SELECT statement, then (by restrictions
@@ -101357,8 +101392,10 @@ SQLCIPHER_PRIVATE void sqlcipher3VtabBeginParse(
   ** The second call, to obtain permission to create the table, is made now.
   */
   if( pTable->azModuleArg ){
-    sqlcipher3AuthCheck(pParse, SQLCIPHER_CREATE_VTABLE, pTable->zName, 
+    int rc = sqlcipher3AuthCheck(pParse, SQLCIPHER_CREATE_VTABLE, pTable->zName,
             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
+    // patch to fix unchecked return value warning from prevent
+    (void) rc;
   }
 #endif
 }
@@ -104288,7 +104325,12 @@ static sqlcipher3_index_info *allocateIndexInfo(
     testcase( pTerm->eOperator==WO_IN );
     testcase( pTerm->eOperator==WO_ISNULL );
     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
+
+    // patch to fix dead code warning from prevent
+    // TERM_VNULL is always 0 if SQLCIPHER_ENABLE_STAT3 feature is not defined.
+#ifdef SQLCIPHER_ENABLE_STAT3
     if( pTerm->wtFlags & TERM_VNULL ) continue;
+#endif
     nTerm++;
   }
 
@@ -104339,7 +104381,12 @@ static sqlcipher3_index_info *allocateIndexInfo(
     testcase( pTerm->eOperator==WO_IN );
     testcase( pTerm->eOperator==WO_ISNULL );
     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
+
+    // patch to fix dead code warning from prevent
+    // TERM_VNULL is always 0 if SQLCIPHER_ENABLE_STAT3 feature is not defined.
+#ifdef SQLCIPHER_ENABLE_STAT3
     if( pTerm->wtFlags & TERM_VNULL ) continue;
+#endif
     pIdxCons[j].iColumn = pTerm->u.leftColumn;
     pIdxCons[j].iTermOffset = i;
     pIdxCons[j].op = (u8)pTerm->eOperator;
index 988de24..5d42f9a 100644 (file)
@@ -19,6 +19,7 @@
  */
 #include <security-server-plugin-api.h>
 
+#include <ckm/ckm-client-info.h>
 #include <ckm/ckm-control.h>
 #include <ckm/ckm-type.h>
 
@@ -31,78 +32,99 @@ namespace SecurityServer {
 
 class KEY_MANAGER_API Plugin : public PasswordPlugin {
 public:
-    Plugin();
-    virtual int changeUserPassword(uid_t user, const std::string &oldPass, const std::string &newPass);
-    virtual int login(uid_t user, const std::string &password);
-    virtual int logout(uid_t user);
-    virtual int resetUserPassword(uid_t user, const std::string &newPass);
-    virtual int removeUserData(uid_t user);
-    virtual ~Plugin(){}
+    Plugin() {}
+    virtual int changeUserPassword(const std::string &zone, uid_t user, const std::string &oldPass, const std::string &newPass);
+    virtual int login(const std::string &zone, uid_t user, const std::string &password);
+    virtual int logout(const std::string &zone, uid_t user);
+    virtual int resetUserPassword(const std::string &zone, uid_t user, const std::string &newPass);
+    virtual int removeUserData(const std::string &zone, uid_t user);
+    virtual ~Plugin() {}
 private:
-    CKM::ControlShPtr m_control;
+    CKM::ClientInfo getClientInfo(const std::string &zone, uid_t user);
 };
 
-Plugin::Plugin() {
-    m_control = CKM::Control::create();
+CKM::ClientInfo Plugin::getClientInfo(const std::string &zone, uid_t user)
+{
+    return CKM::ClientInfo(zone, user);
 }
 
-int Plugin::changeUserPassword(uid_t user, const std::string &oldPass, const std::string &newPass) {
+int Plugin::changeUserPassword(
+    const std::string &zone,
+    uid_t user,
+    const std::string &oldPass,
+    const std::string &newPass)
+{
+    auto control = CKM::Control::create();
+    if (!control)
+        return SECURITY_SERVER_PLUGIN_FAIL;
+
     CKM::Password oldPwd(oldPass.begin(), oldPass.end());
     CKM::Password newPwd(newPass.begin(), newPass.end());
-
-    if (!m_control)
-        return SECURITY_SERVER_PLUGIN_FAIL;
+    CKM::ClientInfo clientInfo = getClientInfo(zone, user);
 
     // CKM does not allow to change user password if database does
     // not exists. We must create database before change password.
-    if (CKM_API_SUCCESS != m_control->unlockUserKey(user, oldPwd))
+    if (CKM_API_SUCCESS != control->unlockUserKey(clientInfo, oldPwd))
         return SECURITY_SERVER_PLUGIN_FAIL;
-
-    if (CKM_API_SUCCESS != m_control->changeUserPassword(user, oldPwd, newPwd))
+    if (CKM_API_SUCCESS != control->changeUserPassword(clientInfo, oldPwd, newPwd))
         return SECURITY_SERVER_PLUGIN_FAIL;
 
     return SECURITY_SERVER_PLUGIN_SUCCESS;
 }
 
-int Plugin::login(uid_t user, const std::string &password) {
-    CKM::Password pwd(password.begin(), password.end());
-
-    if (!m_control)
+int Plugin::login(
+    const std::string &zone,
+    uid_t user,
+    const std::string &password)
+{
+    auto control = CKM::Control::create();
+    if (!control)
         return SECURITY_SERVER_PLUGIN_FAIL;
 
-    if (CKM_API_SUCCESS != m_control->unlockUserKey(user, pwd))
+    CKM::Password pwd(password.begin(), password.end());
+
+    if (CKM_API_SUCCESS != control->unlockUserKey(getClientInfo(zone, user), pwd))
         return SECURITY_SERVER_PLUGIN_FAIL;
 
     return SECURITY_SERVER_PLUGIN_SUCCESS;
 }
 
-int Plugin::logout(uid_t user) {
-    if (!m_control)
+int Plugin::logout(const std::string &zone, uid_t user)
+{
+    auto control = CKM::Control::create();
+    if (!control)
         return SECURITY_SERVER_PLUGIN_FAIL;
 
-    if (CKM_API_SUCCESS != m_control->lockUserKey(user))
+    if (CKM_API_SUCCESS != control->lockUserKey(getClientInfo(zone, user)))
         return SECURITY_SERVER_PLUGIN_FAIL;
 
     return SECURITY_SERVER_PLUGIN_SUCCESS;
 }
 
-int Plugin::resetUserPassword(uid_t user, const std::string &newPass) {
-    CKM::Password pwd(newPass.begin(), newPass.end());
-
-    if (!m_control)
+int Plugin::resetUserPassword(
+    const std::string &zone,
+    uid_t user,
+    const std::string &newPass)
+{
+    auto control = CKM::Control::create();
+    if (!control)
         return SECURITY_SERVER_PLUGIN_FAIL;
 
-    if (CKM_API_SUCCESS != m_control->resetUserPassword(user, pwd))
+    CKM::Password pwd(newPass.begin(), newPass.end());
+
+    if (CKM_API_SUCCESS != control->resetUserPassword(getClientInfo(zone, user), pwd))
         return SECURITY_SERVER_PLUGIN_FAIL;
 
     return SECURITY_SERVER_PLUGIN_SUCCESS;
 }
 
-int Plugin::removeUserData(uid_t user) {
-    if (!m_control)
+int Plugin::removeUserData(const std::string &zone, uid_t user)
+{
+    auto control = CKM::Control::create();
+    if (!control)
         return SECURITY_SERVER_PLUGIN_FAIL;
 
-    if (CKM_API_SUCCESS != m_control->removeUserData(user))
+    if (CKM_API_SUCCESS != control->removeUserData(getClientInfo(zone, user)))
         return SECURITY_SERVER_PLUGIN_FAIL;
 
     return SECURITY_SERVER_PLUGIN_SUCCESS;
@@ -119,5 +141,3 @@ KEY_MANAGER_API
 void destroy(SecurityServer::PasswordPlugin *obj) {
     delete obj;
 }
-
-
index f9005e7..070106a 100644 (file)
@@ -3,8 +3,6 @@ CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/systemd/central-key-manager.service.in
 
 INSTALL(FILES
     ${CMAKE_SOURCE_DIR}/systemd/central-key-manager.service
-    ${CMAKE_SOURCE_DIR}/systemd/central-key-manager.target
-    ${CMAKE_SOURCE_DIR}/systemd/central-key-manager-listener.service
     ${CMAKE_SOURCE_DIR}/systemd/central-key-manager-api-control.socket
     ${CMAKE_SOURCE_DIR}/systemd/central-key-manager-api-storage.socket
     ${CMAKE_SOURCE_DIR}/systemd/central-key-manager-api-ocsp.socket
index 7c132a6..0f76e14 100644 (file)
@@ -1,14 +1,15 @@
+[Unit]
+Description=key manager socket for control API
+Before=central-key-manager.service
+
 [Socket]
+SocketUser=system
+SocketGroup=system
 ListenStream=/tmp/.central-key-manager-api-control.sock
+Service=central-key-manager.service
 SocketMode=0777
 SmackLabelIPIn=key-manager::api-control
 SmackLabelIPOut=@
 
-Service=central-key-manager.service
-
-[Unit]
-Wants=central-key-manager.target
-Before=central-key-manager.target
-
 [Install]
 WantedBy=sockets.target
index b20e7e7..f5d55a1 100644 (file)
@@ -1,14 +1,15 @@
+[Unit]
+Description=key manager socket for ocsp API
+Before=central-key-manager.service
+
 [Socket]
+SocketUser=system
+SocketGroup=system
 ListenStream=/tmp/.central-key-manager-api-ocsp.sock
+Service=central-key-manager.service
 SocketMode=0777
 SmackLabelIPIn=key-manager::api-ocsp
 SmackLabelIPOut=@
 
-Service=central-key-manager.service
-
-[Unit]
-Wants=central-key-manager.target
-Before=central-key-manager.target
-
 [Install]
 WantedBy=sockets.target
index 7bc5350..fc725d5 100644 (file)
@@ -1,14 +1,15 @@
+[Unit]
+Description=key manager socket for storage API
+Before=central-key-manager.service
+
 [Socket]
+SocketUser=system
+SocketGroup=system
 ListenStream=/tmp/.central-key-manager-api-storage.sock
+Service=central-key-manager.service
 SocketMode=0777
 SmackLabelIPIn=key-manager::api-storage
 SmackLabelIPOut=@
 
-Service=central-key-manager.service
-
-[Unit]
-Wants=central-key-manager.target
-Before=central-key-manager.target
-
 [Install]
 WantedBy=sockets.target
diff --git a/systemd/central-key-manager-listener.service b/systemd/central-key-manager-listener.service
deleted file mode 100644 (file)
index ba2b8bc..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-[Unit]
-Description=Start the Central Key Manager Listener
-Requires=dbus.service
-After=central-key-manager.service
-
-[Service]
-Type=simple
-ExecStart=/usr/bin/key-manager-listener
-
-[Install]
-WantedBy=multi-user.target
index 469db7a..5455de7 100644 (file)
@@ -1,8 +1,11 @@
 [Unit]
 Description=Start the Central Key Manager
-DefaultDependencies=no
+Requires=central-key-manager-api-storage.socket central-key-manager-api-control.socket central-key-manager-api-ocsp.socket
 
 [Service]
+User=system
+Group=system
+SmackProcessLabel=key-manager
 Type=notify
 ExecStart=/usr/bin/key-manager
 Sockets=central-key-manager-api-storage.socket
diff --git a/systemd/central-key-manager.target b/systemd/central-key-manager.target
deleted file mode 100644 (file)
index 01eaa8e..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-[Unit]
-Description=Central Key Manager sockets
-DefaultDependencies=true
-
index e3d39af..5d84ba1 100644 (file)
@@ -17,6 +17,7 @@ INCLUDE_DIRECTORIES(
     ${KEY_MANAGER_PATH}/service
     ${KEY_MANAGER_PATH}/common/
     ${KEY_MANAGER_PATH}/client-async/
+    ${KEY_MANAGER_PATH}/client-capi/
     ${KEY_MANAGER_SRC_PATH}/include
     ${KEY_MANAGER_TEST_MERGED_SRC}/
     )
@@ -51,3 +52,38 @@ TARGET_LINK_LIBRARIES(${TARGET_TEST_MERGED}
     )
 
 INSTALL(TARGETS ${TARGET_TEST_MERGED} DESTINATION bin)
+
+################################################################################
+PKG_CHECK_MODULES(KEY_MANAGER_TEST_LCOV_DEP
+    REQUIRED
+    openssl
+    )
+
+
+SET(KEY_MANAGER_TEST_LCOV_SRC ${PROJECT_SOURCE_DIR}/tests)
+
+SET(TEST_LCOV_SOURCES
+    ${KEY_MANAGER_TEST_LCOV_SRC}/main_lcov.cpp
+    ${KEY_MANAGER_TEST_LCOV_SRC}/test_common.cpp
+    ${KEY_MANAGER_TEST_LCOV_SRC}/colour_log_formatter.cpp
+    ${KEY_MANAGER_TEST_LCOV_SRC}/test_lcov_certificate-impl.cpp
+    ${KEY_MANAGER_TEST_LCOV_SRC}/test_lcov_ckmc-type-converter.cpp
+    ${KEY_MANAGER_TEST_LCOV_SRC}/test_lcov_client-error.cpp
+    ${KEY_MANAGER_TEST_LCOV_SRC}/test_lcov_key-impl.cpp
+    ${KEY_MANAGER_PATH}/client/client-error.cpp
+    ${KEY_MANAGER_PATH}/client-capi/ckmc-type-converter.cpp
+    ${KEY_MANAGER_PATH}/dpl/core/src/assert.cpp
+    ${KEY_MANAGER_PATH}/dpl/core/src/colors.cpp
+    )
+
+ADD_EXECUTABLE(${TARGET_TEST_LCOV} ${TEST_LCOV_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_TEST_LCOV}
+    ${TARGET_KEY_MANAGER_COMMON}
+    ${CMAKE_THREAD_LIBS_INIT}
+    ${KEY_MANAGER_TEST_LCOV_DEP_LIBRARIES}
+    boost_unit_test_framework
+    -ldl
+    )
+
+INSTALL(TARGETS ${TARGET_TEST_LCOV} DESTINATION bin)
diff --git a/tests/main_lcov.cpp b/tests/main_lcov.cpp
new file mode 100644 (file)
index 0000000..9dd21f0
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ *  Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/*
+ * @file       main.cpp
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version    1.0
+ */
+
+#define BOOST_TEST_MODULE CKM_TEST_LCOV_INTERNAL
+#define BOOST_TEST_MAIN
+
+
+#include <iostream>
+#include <key-provider.h>
+#include <boost/test/unit_test.hpp>
+#include <boost/test/unit_test_log.hpp>
+#include <boost/test/results_reporter.hpp>
+#include <colour_log_formatter.h>
+#include <dpl/log/log.h>
+
+struct TestConfig {
+    TestConfig() {
+        boost::unit_test::unit_test_log.set_threshold_level( boost::unit_test::log_test_units);
+        boost::unit_test::results_reporter::set_level(boost::unit_test::SHORT_REPORT);
+        boost::unit_test::unit_test_log.set_formatter(new CKM::colour_log_formatter);
+    }
+    ~TestConfig(){
+    }
+};
+
+bool isLibInitialized = false;
+
+struct KeyProviderLib {
+    KeyProviderLib() {
+    }
+    ~KeyProviderLib() {
+    }
+};
+
+struct LogSetup {
+    LogSetup() {
+        CKM::Singleton<CKM::Log::LogSystem>::Instance().SetTag("CKM_INTERNAL_TESTS");
+    }
+    ~LogSetup() {}
+};
+
+BOOST_GLOBAL_FIXTURE(KeyProviderLib)
+BOOST_GLOBAL_FIXTURE(TestConfig)
+BOOST_GLOBAL_FIXTURE(LogSetup)
+
index 93c70ad..785e5d8 100644 (file)
@@ -39,6 +39,7 @@ int getRandom()
 
     return randVal;
 }
+
 } // namespace anonymous
 
 BOOST_FIXTURE_TEST_SUITE(DBCRYPTO_TEST, DBFixture)
diff --git a/tests/test_lcov_certificate-impl.cpp b/tests/test_lcov_certificate-impl.cpp
new file mode 100644 (file)
index 0000000..56f89f7
--- /dev/null
@@ -0,0 +1,89 @@
+#include <boost/test/unit_test.hpp>
+#include <test_common.h>
+
+#include <certificate-impl.h>
+#include <base64.h>
+#include <openssl/x509.h>
+
+#include <string>
+
+
+using namespace CKM;
+
+BOOST_AUTO_TEST_SUITE(CKM_CERTIFICATE_IMPL_TEST)
+
+
+BOOST_AUTO_TEST_CASE(CKM_CERTIFICATE_IMPL_TESTS) {
+    std::string certStr = 
+        "MIIDOzCCAiOgAwIBAgIBADANBgkqhkiG9w0BAQUFADBYMRowGAYDVQQKDBFUaXpl\n"
+        "biBBc3NvY2lhdGlvbjEaMBgGA1UECwwRVGl6ZW4gQXNzb2NpYXRpb24xHjAcBgNV\n"
+        "BAMMFVRpemVuIERldmVsb3BlcnMgUm9vdDAeFw0xMjAxMDEwMDAwMDBaFw0zMjAx\n"
+        "MDEwMDAwMDBaMFgxGjAYBgNVBAoMEVRpemVuIEFzc29jaWF0aW9uMRowGAYDVQQL\n"
+        "DBFUaXplbiBBc3NvY2lhdGlvbjEeMBwGA1UEAwwVVGl6ZW4gRGV2ZWxvcGVycyBS\n"
+        "b290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp2rCwXTYh28vcagX\n"
+        "WLIeVtEvXA5EeTR9UnL4Dzyd7hIq8rkxLbIMMOcCrXMTc7bEH2twFaTuXxyKXMW/\n"
+        "2c+id3m3Z1B5caCqwSPr72oKPSI4jSkvrAC5W7EHx16M818aG4tQkXIUBhDrtSmH\n"
+        "6dFOdt8zGq2fanj1sETfUmXAeLGE7OQYcEb2SoWGXR75Ytfp1LAw/L3luuG/kbzB\n"
+        "crZt1Cv05jfCP575eope6p5p80Gl0tieXyPYhSLVTLwhEdWx18CMaC7IXQo2Bm+J\n"
+        "djDH0Ruh/vTRnjFtmVB+nBOZNVzMHNOPUVFKSgysX/+PlM4jBTvbaTnPCZUkC/O7\n"
+        "5tYIpwIDAQABoxAwDjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBw\n"
+        "95ibcuAiKpAEqBMyTZtOf0okhSi9NYfs/AFIPLH5REnhtQkPmKsvDp21OSdzrFEL\n"
+        "42rV94K98QChD9tGO6Mwp1ZHM3No7/PLC3EelOwmn4dr3KPGdjvQNSwKRblGh0Hj\n"
+        "n4fI+studFLLv6ldCLIpA/Ssgf9GuUbcjTC8OWBYPVUQ6YoXAcuHbfhr6a2IXRTj\n"
+        "lJUCt3qWyciP2H/R+oNBSjtlq13ZT+D9AQMmIG/5w1tK0HzDRhORfWlKCo5JKn0A\n"
+        "iQq2fwtoB0JQEHRKCKZYWghG41HuKc82xLf6H7x24XWOAlXb0SpvVENT1i89XNrj\n"
+        "XS4modIY545rYjI1amfL\n";
+
+    CertificateImpl cert(RawBuffer(certStr.begin(),certStr.end()), DataFormat::FORM_DER_BASE64);
+    X509* certX509 = cert.getX509();
+
+    CertificateImpl cert2(certX509, true);
+
+    CertificateImpl cert3(cert);
+    CertificateImpl cert4(CertificateImpl(cert));
+
+    CertificateImpl cert5 = cert;
+    CertificateImpl cert6 = CertificateImpl(cert);
+
+    KeyImpl::EvpShPtr certEvpShPtr = cert.getEvpShPtr();
+
+    KeyImpl keyImpl = cert.getKeyImpl();
+
+    std::string issuer = cert.getOneLine(CertificateFieldId::ISSUER);
+    std::string subject = cert.getOneLine(CertificateFieldId::SUBJECT);
+
+    std::string issuerCommonNameField = cert.getField(CertificateFieldId::ISSUER, NID_commonName);
+
+    std::string commonName = cert.getCommonName(CertificateFieldId::SUBJECT);
+    std::string country = cert.getCountryName(CertificateFieldId::SUBJECT);
+    std::string state = cert.getStateOrProvinceName(CertificateFieldId::SUBJECT);
+    std::string locality = cert.getLocalityName(CertificateFieldId::SUBJECT);
+    std::string organization = cert.getOrganizationName(CertificateFieldId::SUBJECT);
+    std::string ouName = cert.getOrganizationalUnitName(CertificateFieldId::SUBJECT);
+    std::string email = cert.getEmailAddres(CertificateFieldId::SUBJECT);
+    std::string ocspUrl = cert.getOCSPURL();
+}
+
+BOOST_AUTO_TEST_CASE(CKM_BASE64_TESTS) {
+    std::string origStr = "test data";
+    RawBuffer origBuffer(origStr.begin(), origStr.end());
+
+    Base64Encoder encoder;
+    encoder.reset();
+    encoder.append(origBuffer);
+    encoder.finalize();
+    RawBuffer base64 = encoder.get();
+
+    Base64Decoder decoder; 
+    decoder.reset();
+    decoder.append(base64);
+    decoder.finalize();
+    RawBuffer decoded = decoder.get();
+
+    std::string decodedStr = std::string(decoded.begin(), decoded.end());
+
+    BOOST_REQUIRE_MESSAGE(origStr.compare(decodedStr) == 0, "Base64 encoding/decoding returned a wrong value");
+}
+
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/tests/test_lcov_ckmc-type-converter.cpp b/tests/test_lcov_ckmc-type-converter.cpp
new file mode 100644 (file)
index 0000000..642e43c
--- /dev/null
@@ -0,0 +1,215 @@
+#include <boost/test/unit_test.hpp>
+#include <test_common.h>
+
+#include <ckmc/ckmc-type.h>
+#include <ckmc-type-converter.h>
+
+
+#include <string>
+
+
+using namespace CKM;
+
+BOOST_AUTO_TEST_SUITE(CKMC_TYPE_CONVERTER_TEST)
+
+
+BOOST_AUTO_TEST_CASE(CKMC_TYPE_CONVERTER_to_ckm_error) {
+    int ckm_error = -1;
+
+    ckm_error = to_ckm_error(CKMC_ERROR_NONE);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_SUCCESS, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_SOCKET);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_SOCKET, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_BAD_REQUEST);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_BAD_REQUEST, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_BAD_RESPONSE);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_BAD_RESPONSE, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_SEND_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_SEND_FAILED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_RECV_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_RECV_FAILED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_AUTHENTICATION_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_AUTHENTICATION_FAILED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_INVALID_PARAMETER);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_INPUT_PARAM, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_BUFFER_TOO_SMALL);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_BUFFER_TOO_SMALL, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_OUT_OF_MEMORY);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_OUT_OF_MEMORY, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_PERMISSION_DENIED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_ACCESS_DENIED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_SERVER_ERROR);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_SERVER_ERROR, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_DB_LOCKED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_DB_LOCKED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_DB_ERROR);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_DB_ERROR, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_DB_ALIAS_EXISTS);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_DB_ALIAS_EXISTS, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_DB_ALIAS_UNKNOWN);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_DB_ALIAS_UNKNOWN, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_VERIFICATION_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_VERIFICATION_FAILED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_INVALID_FORMAT);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_INVALID_FORMAT, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_FILE_ACCESS_DENIED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_FILE_ACCESS_DENIED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_NOT_EXPORTABLE);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_NOT_EXPORTABLE, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_FILE_SYSTEM);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_FILE_SYSTEM, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_NOT_SUPPORTED);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_NOT_SUPPORTED, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(CKMC_ERROR_UNKNOWN);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_UNKNOWN, "invalid ckm error returned");
+
+    ckm_error = to_ckm_error(-99999);
+    BOOST_REQUIRE_MESSAGE( ckm_error == CKM_API_ERROR_UNKNOWN, "invalid ckm error returned");
+}
+
+
+BOOST_AUTO_TEST_CASE(CKMC_TYPE_CONVERTER_to_ckmc_error) {
+    int ckmc_error = -1;
+
+    ckmc_error = to_ckmc_error(CKM_API_SUCCESS);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_NONE, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_SOCKET);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_SOCKET, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_BAD_REQUEST);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_BAD_REQUEST, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_BAD_RESPONSE);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_BAD_RESPONSE, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_SEND_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_SEND_FAILED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_RECV_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_RECV_FAILED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_AUTHENTICATION_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_AUTHENTICATION_FAILED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_INPUT_PARAM);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_INVALID_PARAMETER, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_BUFFER_TOO_SMALL);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_BUFFER_TOO_SMALL, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_OUT_OF_MEMORY);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_OUT_OF_MEMORY, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_ACCESS_DENIED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_PERMISSION_DENIED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_SERVER_ERROR);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_SERVER_ERROR, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_DB_LOCKED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_DB_LOCKED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_DB_ERROR);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_DB_ERROR, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_DB_ALIAS_EXISTS);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_DB_ALIAS_EXISTS, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_DB_ALIAS_UNKNOWN);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_DB_ALIAS_UNKNOWN, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_VERIFICATION_FAILED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_VERIFICATION_FAILED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_INVALID_FORMAT);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_INVALID_FORMAT, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_FILE_ACCESS_DENIED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_FILE_ACCESS_DENIED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_NOT_EXPORTABLE);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_NOT_EXPORTABLE, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_FILE_SYSTEM);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_FILE_SYSTEM, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_NOT_SUPPORTED);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_NOT_SUPPORTED, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(CKM_API_ERROR_UNKNOWN);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_UNKNOWN, "invalid ckmc error returned");
+
+    ckmc_error = to_ckmc_error(-9999);
+    BOOST_REQUIRE_MESSAGE( ckmc_error == CKMC_ERROR_UNKNOWN, "invalid ckmc error returned");
+}
+
+BOOST_AUTO_TEST_CASE(CKMC_TYPE_CONVERTER_to_ckmc_ocsp_status) {
+    int ckmc_ocsp= -1;
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_GOOD);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_STATUS_GOOD, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_UNSUPPORTED);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_ERROR_UNSUPPORTED, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_REVOKED);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_STATUS_REVOKED, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_NET_ERROR);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_ERROR_NET, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_INVALID_URL);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_ERROR_INVALID_URL, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_INVALID_RESPONSE);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_ERROR_INVALID_RESPONSE, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_REMOTE_ERROR);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_ERROR_REMOTE, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(CKM_API_OCSP_STATUS_INTERNAL_ERROR);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_ERROR_INTERNAL, "invalid ckmc ocsp status returned");
+
+    ckmc_ocsp = to_ckmc_ocsp_status(-9999);
+    BOOST_REQUIRE_MESSAGE( ckmc_ocsp == CKMC_OCSP_STATUS_UNKNOWN, "invalid ckmc ocsp status returned");
+}
+
+
+BOOST_AUTO_TEST_CASE(CKMC_TYPE_CONVERTER_to_permission_mask) {
+    int ret = -1;
+    int permissionMask = -1;
+
+    ret = access_to_permission_mask(CKMC_AR_READ, permissionMask);
+    BOOST_REQUIRE_MESSAGE( ret == CKMC_ERROR_NONE , "error returned");
+    BOOST_REQUIRE_MESSAGE( permissionMask == CKMC_PERMISSION_READ, "invalid permission mask returned");
+
+    ret = access_to_permission_mask(CKMC_AR_READ_REMOVE, permissionMask);
+    BOOST_REQUIRE_MESSAGE( ret == CKMC_ERROR_NONE , "error returned");
+    BOOST_REQUIRE_MESSAGE( permissionMask == (CKMC_PERMISSION_READ | CKMC_PERMISSION_REMOVE),
+                           "invalid permission mask returned");
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/tests/test_lcov_client-error.cpp b/tests/test_lcov_client-error.cpp
new file mode 100644 (file)
index 0000000..36cc2bf
--- /dev/null
@@ -0,0 +1,89 @@
+#include <boost/test/unit_test.hpp>
+#include <test_common.h>
+
+#include <ckm/ckm-type.h>
+#include <ckm/ckm-error.h>
+
+#include <string>
+
+
+using namespace CKM;
+
+BOOST_AUTO_TEST_SUITE(CKM_ERROR_TEST)
+
+
+BOOST_AUTO_TEST_CASE(CKM_ERROR_ErrorToString) {
+    std::string errString;
+
+    errString = std::string(ErrorToString(CKM_API_SUCCESS));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_SUCCESS") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_SOCKET));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_SOCKET") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_BAD_REQUEST));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_BAD_REQUEST") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_BAD_RESPONSE));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_BAD_RESPONSE") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_SEND_FAILED));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_SEND_FAILED") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_RECV_FAILED));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_RECV_FAILED") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_AUTHENTICATION_FAILED));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_AUTHENTICATION_FAILED") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_INPUT_PARAM));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_INPUT_PARAM") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_BUFFER_TOO_SMALL));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_BUFFER_TOO_SMALL") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_OUT_OF_MEMORY));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_OUT_OF_MEMORY") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_ACCESS_DENIED));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_ACCESS_DENIED") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_SERVER_ERROR));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_SERVER_ERROR") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_DB_LOCKED));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_DB_LOCKED") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_DB_ERROR));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_DB_ERROR") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_DB_ALIAS_EXISTS));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_DB_ALIAS_EXISTS") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_DB_ALIAS_UNKNOWN));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_DB_ALIAS_UNKNOWN") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_VERIFICATION_FAILED));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_VERIFICATION_FAILED") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_INVALID_FORMAT));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_INVALID_FORMAT") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_FILE_ACCESS_DENIED));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_FILE_ACCESS_DENIED") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_NOT_EXPORTABLE));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_NOT_EXPORTABLE") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_FILE_SYSTEM));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_FILE_SYSTEM") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(CKM_API_ERROR_UNKNOWN));
+    BOOST_REQUIRE_MESSAGE(errString.compare("CKM_API_ERROR_UNKNOWN") == 0, "Invalid Error String");
+
+    errString = std::string(ErrorToString(-99999));
+    BOOST_REQUIRE_MESSAGE(errString.compare("Error not defined") == 0, "Invalid Error String");
+}
+
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/tests/test_lcov_key-impl.cpp b/tests/test_lcov_key-impl.cpp
new file mode 100644 (file)
index 0000000..c72421d
--- /dev/null
@@ -0,0 +1,43 @@
+#include <boost/test/unit_test.hpp>
+#include <test_common.h>
+
+#include <key-impl.h>
+#include <ckm/ckm-type.h>
+
+#include <string>
+
+
+using namespace CKM;
+
+BOOST_AUTO_TEST_SUITE(CKM_KEY_IMPL_TEST)
+
+
+BOOST_AUTO_TEST_CASE(CKM_KEY_IMPL_TESTS) {
+
+    std::string keyPem = "-----BEGIN PUBLIC KEY-----\n"
+        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2b1bXDa+S8/MGWnMkru4\n"
+        "T4tUddtZNi0NVjQn9RFH1NMa220GsRhRO56F77FlSVFKfSfVZKIiWg6C+DVCkcLf\n"
+        "zXJ/Z0pvwOQYBAqVMFjV6efQGN0JzJ1Unu7pPRiZl7RKGEI+cyzzrcDyrLLrQ2W7\n"
+        "0ZySkNEOv6Frx9JgC5NExuYY4lk2fQQa38JXiZkfyzif2em0px7mXbyf5LjccsKq\n"
+        "v1e+XLtMsL0ZefRcqsP++NzQAI8fKX7WBT+qK0HJDLiHrKOTWYzx6CwJ66LD/vvf\n"
+        "j55xtsKDLVDbsotvf8/m6VLMab+vqKk11TP4tq6yo0mwyTADvgl1zowQEO9I1W6o\n"
+        "zQIDAQAB\n"
+        "-----END PUBLIC KEY-----";
+
+    CKM::RawBuffer buffer(keyPem.begin(), keyPem.end());
+    KeyImpl key(buffer, CKM::Password());
+
+    KeyImpl key2(key);
+    KeyImpl key3 = key2;
+
+    KeyImpl::EvpShPtr keyEvpShPtr = key3.getEvpShPtr();
+    ElipticCurve curve = key.getCurve();
+    int size = key.getSize();
+
+    BOOST_REQUIRE_MESSAGE(keyEvpShPtr != NULL, "Null Key Pointer");
+    BOOST_REQUIRE_MESSAGE(curve == ElipticCurve::prime192v1, "Invalid Curve");
+    BOOST_REQUIRE_MESSAGE(size >= 0, "Invalid Key Size");
+}
+
+
+BOOST_AUTO_TEST_SUITE_END()
index a39adb6..2af4d06 100644 (file)
@@ -94,12 +94,27 @@ int main(int argc, char* argv[])
     string so_path(argv[3]);
     string symbol(argv[4]);
 
+    /*
+     *  perform sanity check of user input string
+     *  which will be used for dlopen
+     */
+    if (so_path.compare(so_path.size() - 3, 3, ".so")
+        && so_path.compare(so_path.size() - 5, 3, ".so")
+        && so_path.compare(so_path.size() - 9, 3, ".so")) {
+        cerr << "[" << so_path << "] doesn't has .so postfix." << endl;
+        return -1;
+    }
+    if (access(so_path.c_str(), R_OK)) {
+        cerr << "cannot read [" << so_path << "]" << endl;
+        return -1;
+    }
+
     cout << "dlopen[us];dlsym[us]" << endl;
     for (int cnt = 0 ; cnt < repeats; cnt++)
     {
         /*
-         * It has to be a different process each time. Glibc somehow caches the library information
-         * and consecutive calls are faster
+         *  It has to be a different process each time. Glibc somehow caches the library information
+         *  and consecutive calls are faster
          */
         pid_t pid = fork();
         if (pid < 0) {