From 6d176c7d47d8af075826c6c1dfca01b7021ba1fb Mon Sep 17 00:00:00 2001 From: "jk7744.park" Date: Sun, 1 Feb 2015 13:51:12 +0900 Subject: tizen 2.3 release --- CMakeLists.txt | 45 +- NOTICE | 0 TC/_export_env.sh | 10 + TC/_export_target_env.sh | 9 + TC/build.sh | 8 +- TC/clean.sh | 11 + TC/execute.sh | 19 - TC/push.sh | 13 + TC/run.sh | 15 + TC/scenario1/tslist | 5 - TC/scenario1/utc_SecurityFW_ssm_delete_file_func.c | 137 --- TC/scenario1/utc_SecurityFW_ssm_getinfo_func.c | 144 --- TC/scenario1/utc_SecurityFW_ssm_read_func.c | 187 ---- .../utc_SecurityFW_ssm_write_buffer_func.c | 155 ---- TC/scenario1/utc_SecurityFW_ssm_write_file_func.c | 147 ---- TC/testcase/tslist | 2 + TC/testcase/utc_secure_storage | Bin 0 -> 40807 bytes TC/testcase/utc_secure_storage.c | 399 +++++++++ TC/tet_code | 12 - TC/tet_scen | 2 +- TC/tetbuild.cfg | 9 +- TC/tetclean.cfg | 8 +- TC/tetexec.cfg | 8 +- client/include/ss_client_intf.h | 75 -- client/include/ss_client_ipc.h | 32 - client/non-tz/include/ss_client_intf.h | 78 ++ client/non-tz/include/ss_client_ipc.h | 32 + client/non-tz/src/ss_client_intf.c | 576 ++++++++++++ client/non-tz/src/ss_client_ipc.c | 102 +++ client/non-tz/src/ss_manager.c | 586 +++++++++++++ client/src/ss_client_intf.c | 587 ------------- client/src/ss_client_ipc.c | 103 --- client/src/ss_manager.c | 316 ------- debian/changelog | 35 - doc/secure_storage_doc.h | 28 + image/SLP_secure-storage_PG_image001.png | Bin 0 -> 98945 bytes image/SLP_secure-storage_PG_image002.png | Bin 0 -> 20603 bytes include/SLP_secure-storage_PG.h | 520 +++++++++++ include/secure_storage.h | 194 +++-- include/ss_manager.h | 639 +++++++------- libss-client.manifest | 1 + packaging/non-tz-secure-storage.service | 12 + packaging/secure-storage.service | 14 + packaging/secure-storage.spec | 53 +- packaging/ss-server.socket | 10 + prng/include/ss_prng.h | 69 ++ prng/include/ss_prng_impl.h | 108 +++ prng/src/ss_prng.c | 349 ++++++++ res/salt | Bin 0 -> 400 bytes secure-storage.pc.in | 2 +- server/include/ss_server_ipc.h | 30 - server/include/ss_server_main.h | 77 -- server/non-tz/include/ss_server_ipc.h | 31 + server/non-tz/include/ss_server_main.h | 31 + server/non-tz/src/ss_server_ipc.c | 567 ++++++++++++ server/non-tz/src/ss_server_main.c | 969 +++++++++++++++++++++ server/src/ss_server_ipc.c | 459 ---------- server/src/ss_server_main.c | 849 ------------------ ss-server.manifest | 14 +- systemd/secure-storage.service | 11 - systemd/secure-storage.socket | 6 - testcases/ss_test.c | 243 ++++++ testcases/test_manager.c | 138 +++ testcases/unit_test.c | 487 +++++++++++ 64 files changed, 5944 insertions(+), 3834 deletions(-) mode change 100644 => 100755 CMakeLists.txt mode change 100755 => 100644 NOTICE create mode 100755 TC/_export_env.sh create mode 100755 TC/_export_target_env.sh create mode 100755 TC/clean.sh delete mode 100755 TC/execute.sh create mode 100755 TC/push.sh create mode 100755 TC/run.sh delete mode 100755 TC/scenario1/tslist delete mode 100755 TC/scenario1/utc_SecurityFW_ssm_delete_file_func.c delete mode 100755 TC/scenario1/utc_SecurityFW_ssm_getinfo_func.c delete mode 100755 TC/scenario1/utc_SecurityFW_ssm_read_func.c delete mode 100755 TC/scenario1/utc_SecurityFW_ssm_write_buffer_func.c delete mode 100755 TC/scenario1/utc_SecurityFW_ssm_write_file_func.c create mode 100755 TC/testcase/tslist create mode 100755 TC/testcase/utc_secure_storage create mode 100644 TC/testcase/utc_secure_storage.c delete mode 100755 TC/tet_code mode change 100755 => 100644 TC/tet_scen mode change 100755 => 100644 TC/tetbuild.cfg mode change 100755 => 100644 TC/tetclean.cfg mode change 100755 => 100644 TC/tetexec.cfg delete mode 100755 client/include/ss_client_intf.h delete mode 100644 client/include/ss_client_ipc.h create mode 100755 client/non-tz/include/ss_client_intf.h create mode 100644 client/non-tz/include/ss_client_ipc.h create mode 100755 client/non-tz/src/ss_client_intf.c create mode 100644 client/non-tz/src/ss_client_ipc.c create mode 100755 client/non-tz/src/ss_manager.c delete mode 100755 client/src/ss_client_intf.c delete mode 100644 client/src/ss_client_ipc.c delete mode 100755 client/src/ss_manager.c create mode 100644 doc/secure_storage_doc.h create mode 100755 image/SLP_secure-storage_PG_image001.png create mode 100755 image/SLP_secure-storage_PG_image002.png create mode 100755 include/SLP_secure-storage_PG.h mode change 100755 => 100644 include/secure_storage.h create mode 100755 packaging/non-tz-secure-storage.service create mode 100755 packaging/secure-storage.service mode change 100644 => 100755 packaging/secure-storage.spec create mode 100644 packaging/ss-server.socket create mode 100755 prng/include/ss_prng.h create mode 100755 prng/include/ss_prng_impl.h create mode 100755 prng/src/ss_prng.c create mode 100755 res/salt delete mode 100644 server/include/ss_server_ipc.h delete mode 100755 server/include/ss_server_main.h create mode 100644 server/non-tz/include/ss_server_ipc.h create mode 100755 server/non-tz/include/ss_server_main.h create mode 100755 server/non-tz/src/ss_server_ipc.c create mode 100755 server/non-tz/src/ss_server_main.c delete mode 100755 server/src/ss_server_ipc.c delete mode 100755 server/src/ss_server_main.c mode change 100755 => 100644 ss-server.manifest delete mode 100644 systemd/secure-storage.service delete mode 100644 systemd/secure-storage.socket create mode 100644 testcases/ss_test.c create mode 100644 testcases/test_manager.c create mode 100644 testcases/unit_test.c diff --git a/CMakeLists.txt b/CMakeLists.txt old mode 100644 new mode 100755 index d6c395d..c52a954 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,17 +3,18 @@ PROJECT(secure-storage C) SET(PREFIX ${CMAKE_INSTALL_PREFIX}) SET(EXEC_PREFIX "\${prefix}") +SET(LIBDIR "\${prefix}/lib") SET(INCLUDEDIR "\${prefix}/include") SET(VERSION_MAJOR 1) SET(VERSION ${VERSION_MAJOR}.0.0) -#Verbose -#SET(CMAKE_VERBOSE_MAKEFILE ON) - -INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include) +INCLUDE_DIRECTORIES( + ${CMAKE_SOURCE_DIR}/include + /usr/include + ) INCLUDE(FindPkgConfig) -pkg_check_modules(pkgs REQUIRED dukgenerator libsystemd-daemon) +pkg_check_modules(pkgs REQUIRED openssl dlog vconf dukgenerator capi-base-common) FOREACH(flag ${pkgs_CFLAGS}) SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}") @@ -21,19 +22,18 @@ ENDFOREACH(flag) SET(ss_dir "./") SET(ss_include_dir "./include") -SET(ss_client_dir "./client/src") -SET(ss_client_include_dir "./client/include") -SET(ss_server_dir "./server/src") -SET(ss_server_include_dir "./server/include") +SET(ss_client_dir "./client/non-tz/src") +SET(ss_client_include_dir "./client/non-tz/include") +SET(ss_server_dir "./server/non-tz/src") +SET(ss_server_include_dir "./server/non-tz/include") + +SET(ss_prng_dir "./prng/src") +SET(ss_prng_include_dir "./prng/include") SET(ss_test_dir "./testcases") ## About debug -#SET(debug_type "") # for debug - use no debugging -#SET(debug_type "-DSS_CONSOLE_USE") # for debug - use console window SET(debug_type "-DSS_DLOG_USE") # for debug - use dlog -#SET(debug_type "") # for debug - DO NOT use SET(use_key "-DUSE_KEY_FILE") # for private key - use key file -#SET(use_key "-DUSE_NOT") # for private key - use no private key, key will be fixed SET(smack_groupid "-DSMACK_GROUP_ID") # for group id sharing with smack label SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fvisibility=hidden") @@ -43,7 +43,7 @@ SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}") ## for libss-client.so (library) SET(libss-client_SOURCES ${ss_client_dir}/ss_client_intf.c ${ss_client_dir}/ss_client_ipc.c ${ss_client_dir}/ss_manager.c) SET(libss-client_LDFLAGS " -module -avoid-version ${OPENSSL_LIBS}") -SET(libss-client_CFLAGS " ${CFLAGS} -fPIC -I${ss_client_include_dir} -I${ss_include_dir} ${OPENSSL_CFLAGS} ${debug_type} ") +SET(libss-client_CFLAGS " ${CFLAGS} -fPIC -I${ss_client_include_dir} -I${ss_include_dir} ${OPENSSL_CFLAGS} ${debug_type}") #SET(libss-client_LIBADD " ${OPENSSL_LIBS} ") ADD_LIBRARY(ss-client SHARED ${libss-client_SOURCES}) @@ -55,22 +55,25 @@ SET_TARGET_PROPERTIES(ss-client PROPERTIES COMPILE_FLAGS "${libss-client_CFLAGS} ################################################################################################### ## for ss-server (binary) -SET(ss-server_SOURCES ${ss_server_dir}/ss_server_ipc.c ${ss_server_dir}/ss_server_main.c) -SET(ss-server_CFLAGS " -I. -I${ss_include_dir} -I${ss_server_include_dir} ${debug_type} ${use_key} ${OPENSSL_CFLAGS} ${smack_groupid} -D_GNU_SOURCE ") +SET(ss-server_SOURCES ${ss_server_dir}/ss_server_ipc.c ${ss_server_dir}/ss_server_main.c ${ss_prng_dir}/ss_prng.c) +SET(ss-server_CFLAGS " -I. -I${ss_include_dir} -I${ss_server_include_dir} -I${ss_prng_include_dir} ${debug_type} ${use_key} ${OPENSSL_CFLAGS} ${smack_groupid} -D_GNU_SOURCE -D_TRUST_ZONE_") SET(ss-server_LDFLAGS ${pkgs_LDFLAGS}) +#ADD PKG_CHECK_MODULES +PKG_CHECK_MODULES(server_pkg REQUIRED libsystemd-daemon cryptsvc) + ADD_EXECUTABLE(ss-server ${ss-server_SOURCES}) -TARGET_LINK_LIBRARIES(ss-server ${pkgs_LDFLAGS} -lsecurity-server-client ) +TARGET_LINK_LIBRARIES(ss-server ${pkgs_LDFLAGS} ${server_pkg_LIBRARIES} -lsecurity-server-client -ldl) + SET_TARGET_PROPERTIES(ss-server PROPERTIES COMPILE_FLAGS "${ss-server_CFLAGS}") #################################################################################################### CONFIGURE_FILE(secure-storage.pc.in secure-storage.pc @ONLY) CONFIGURE_FILE(config.in config @ONLY) -INSTALL(TARGETS ss-client DESTINATION ${LIB_INSTALL_DIR}) +INSTALL(TARGETS ss-client DESTINATION lib) INSTALL(PROGRAMS ${CMAKE_BINARY_DIR}/ss-server DESTINATION bin) -INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/secure-storage.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/secure-storage.pc DESTINATION lib/pkgconfig) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/res/salt DESTINATION ../opt/share/secure-storage/salt/) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/config DESTINATION share/secure-storage/) INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/include/ss_manager.h DESTINATION include) -INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/systemd/secure-storage.service DESTINATION /usr/lib/systemd/system) -INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/systemd/secure-storage.socket DESTINATION /usr/lib/systemd/system) diff --git a/NOTICE b/NOTICE old mode 100755 new mode 100644 diff --git a/TC/_export_env.sh b/TC/_export_env.sh new file mode 100755 index 0000000..7a317f8 --- /dev/null +++ b/TC/_export_env.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +source ./config + +export TET_INSTALL_PATH=$TET_INSTALL_HOST_PATH # tetware root path +#export TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-simulator # tetware target path +export TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-target # tetware target path +export PATH=$TET_TARGET_PATH/bin:$PATH +export LD_LIBRARY_PATH=$TET_TARGET_PATH/lib/tet3:$LD_LIBRARY_PATH +export TET_ROOT=$TET_TARGET_PATH diff --git a/TC/_export_target_env.sh b/TC/_export_target_env.sh new file mode 100755 index 0000000..3fd8e3f --- /dev/null +++ b/TC/_export_target_env.sh @@ -0,0 +1,9 @@ +#!/bin/sh +. ./config + +export TET_INSTALL_PATH=$TET_INSTALL_TARGET_PATH # path to path +#export TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-simulator +export TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-target +export PATH=$TET_TARGET_PATH/bin:$PATH +export LD_LIBRARY_PATH=$TET_TARGET_PATH/lib/tet3:$LD_LIBRARY_PATH +export TET_ROOT=$TET_TARGET_PATH diff --git a/TC/build.sh b/TC/build.sh index 91656c9..72aad6c 100755 --- a/TC/build.sh +++ b/TC/build.sh @@ -1,10 +1,6 @@ #!/bin/sh -export TET_INSTALL_PATH=$HOME/work/TETware # local tetware path -export TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-target -export PATH=$TET_TARGET_PATH/bin:$PATH -export LD_LIBRARY_PATH=$TET_TARGET_PATH/lib/tet3:$LD_LIBRARY_PATH -export TET_ROOT=$TET_TARGET_PATH +. ./_export_env.sh # setting environment variables export TET_SUITE_ROOT=`pwd` FILE_NAME_EXTENSION=`date +%s` @@ -17,4 +13,4 @@ mkdir -p $RESULT_DIR tcc -c -p ./ tcc -b -j $JOURNAL_RESULT -p ./ -grw -c 3 -f chtml -o $HTML_RESULT $JOURNAL_RESULT +grw -c 7 -f chtml -o $HTML_RESULT $JOURNAL_RESULT diff --git a/TC/clean.sh b/TC/clean.sh new file mode 100755 index 0000000..29743e0 --- /dev/null +++ b/TC/clean.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +. ./_export_env.sh # setting environment variables + +export TET_SUITE_ROOT=`pwd` +RESULT_DIR=results + +tcc -c -p ./ # executing tcc, with clean option (-c) +rm -r $RESULT_DIR +rm -r tet_tmp_dir +rm testcase/tet_captured diff --git a/TC/execute.sh b/TC/execute.sh deleted file mode 100755 index e2c742e..0000000 --- a/TC/execute.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -export TET_INSTALL_PATH=/mnt/nfs/TETware -export TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-target -export PATH=$TET_TARGET_PATH/bin:$PATH -export LD_LIBRARY_PATH=$TET_TARGET_PATH/lib/tet3:$LD_LIBRARY_PATH - -export TET_ROOT=$TET_TARGET_PATH - -export TET_SUITE_ROOT=`pwd` -FILE_NAME_EXTENSION=`date +%s` - -RESULT_DIR=results -HTML_RESULT=$RESULT_DIR/exec-tar-result-$FILE_NAME_EXTENSION.html -JOURNAL_RESULT=$RESULT_DIR/exec-tar-result-$FILE_NAME_EXTENSION.journal - -mkdir -p $RESULT_DIR - -tcc -e -j $JOURNAL_RESULT -p ./ -grw -c 3 -f chtml -o $HTML_RESULT $JOURNAL_RESULT diff --git a/TC/push.sh b/TC/push.sh new file mode 100755 index 0000000..5eb9510 --- /dev/null +++ b/TC/push.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +. ./config + +TC_PATH=/opt/home/$PKG_NAME + +echo $TC_PATH + +sdb shell "mkdir -p $TC_PATH" + +sdb push . $TC_PATH + + diff --git a/TC/run.sh b/TC/run.sh new file mode 100755 index 0000000..cec5778 --- /dev/null +++ b/TC/run.sh @@ -0,0 +1,15 @@ +#!/bin/sh + +source ./_export_target_env.sh + +export TET_SUITE_ROOT=`pwd` +FILE_NAME_EXTENSION=`date +%s` + +RESULT_DIR=results +HTML_RESULT=$RESULT_DIR/exec-tar-result-$FILE_NAME_EXTENSION.html +JOURNAL_RESULT=$RESULT_DIR/exec-tar-result-$FILE_NAME_EXTENSION.journal + +mkdir -p $RESULT_DIR + +tcc -e -j $JOURNAL_RESULT -p ./ +grw -c 7 -f chtml -o $HTML_RESULT $JOURNAL_RESULT diff --git a/TC/scenario1/tslist b/TC/scenario1/tslist deleted file mode 100755 index c04c3f0..0000000 --- a/TC/scenario1/tslist +++ /dev/null @@ -1,5 +0,0 @@ -/scenario1/utc_SecurityFW_ssm_write_file_func -/scenario1/utc_SecurityFW_ssm_write_buffer_func -/scenario1/utc_SecurityFW_ssm_read_func -/scenario1/utc_SecurityFW_ssm_getinfo_func -/scenario1/utc_SecurityFW_ssm_delete_file_func diff --git a/TC/scenario1/utc_SecurityFW_ssm_delete_file_func.c b/TC/scenario1/utc_SecurityFW_ssm_delete_file_func.c deleted file mode 100755 index 88f782c..0000000 --- a/TC/scenario1/utc_SecurityFW_ssm_delete_file_func.c +++ /dev/null @@ -1,137 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include - -#include -#include - -static void startup(void); -static void cleanup(void); - -void (*tet_startup)(void) = startup; -void (*tet_cleanup)(void) = cleanup; - -static void utc_SecurityFW_ssm_delete_file_func_01(void); -static void utc_SecurityFW_ssm_delete_file_func_02(void); - -enum { - POSITIVE_TC_IDX = 0x01, - NEGATIVE_TC_IDX, -}; - -struct tet_testlist tet_testlist[] = { - { utc_SecurityFW_ssm_delete_file_func_01, POSITIVE_TC_IDX }, - { utc_SecurityFW_ssm_delete_file_func_02, NEGATIVE_TC_IDX }, - { NULL, 0 } -}; - -static void startup(void) -{ - printf("Make temporary directory - /opt/secure-storage/test/\n"); - system("mkdir -p /opt/secure-storage/test"); - printf("Make temporary file\n"); - system("touch /opt/secure-storage/test/input.txt"); - system("echo \"abcdefghij\" > /opt/secure-storage/test/input.txt"); - system("cp /opt/secure-storage/test/input.txt /opt/secure-storage/test/input2.txt"); -} - -static void cleanup(void) -{ - printf("Remove tamporary file and directory\n"); - system("rm -rf /opt/secure-storage/test"); -} - -/** - * @brief Positive test case of ssm_delete_file() - */ -static void utc_SecurityFW_ssm_delete_file_func_01(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_delete_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - - /* write file to secure-storage */ - ret = ssm_write_file(filepath, flag, group_id); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto error; - } - - /* delete file */ - ret = ssm_delete_file(filepath, flag, group_id); - if(ret == 0) - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} - -/** - * @brief Negative test case of ssm_delete_file() - */ -static void utc_SecurityFW_ssm_delete_file_func_02(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_delete_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input2.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - - printf("[%s] checkpoint1\n", __func__); - - /* write file to secure-storage */ - ret = ssm_write_file(filepath, flag, group_id); - printf("[%s] checkpoint2 [%d]\n", __func__, ret); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto error; - } - - /* delete file */ - ret = ssm_delete_file(NULL, flag, group_id); - printf("[%s] checkpoint3 [%d]\n", __func__, ret); - if(ret != 0) - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - - /* delete encrypted file */ - ret = ssm_delete_file(filepath, flag, group_id); - printf("[%s] checkpoint4 [%d]\n", __func__, ret); - if(ret != 0) - tetResult = TET_UNINITIATED; - -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} diff --git a/TC/scenario1/utc_SecurityFW_ssm_getinfo_func.c b/TC/scenario1/utc_SecurityFW_ssm_getinfo_func.c deleted file mode 100755 index fb6064f..0000000 --- a/TC/scenario1/utc_SecurityFW_ssm_getinfo_func.c +++ /dev/null @@ -1,144 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include - -#include -#include - -static void startup(void); -static void cleanup(void); - -void (*tet_startup)(void) = startup; -void (*tet_cleanup)(void) = cleanup; - -static void utc_SecurityFW_ssm_getinfo_func_01(void); -static void utc_SecurityFW_ssm_getinfo_func_02(void); - -enum { - POSITIVE_TC_IDX = 0x01, - NEGATIVE_TC_IDX, -}; - -struct tet_testlist tet_testlist[] = { - { utc_SecurityFW_ssm_getinfo_func_01, POSITIVE_TC_IDX }, - { utc_SecurityFW_ssm_getinfo_func_02, NEGATIVE_TC_IDX }, - { NULL, 0 } -}; - -static void startup(void) -{ - printf("Make temporary directory - /opt/secure-storage/test/\n"); - system("mkdir -p /opt/secure-storage/test"); - printf("Make temporary file\n"); - system("touch /opt/secure-storage/test/input.txt"); - system("echo \"abcdefghij\" > /opt/secure-storage/test/input.txt"); - system("cp /opt/secure-storage/test/input.txt /opt/secure-storage/test/input2.txt"); -} - -static void cleanup(void) -{ - printf("Remove tamporary file and directory\n"); - system("rm -rf /opt/secure-storage/test"); -} - -/** - * @brief Positive test case of ssm_getinfo() - */ -static void utc_SecurityFW_ssm_getinfo_func_01(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - ssm_file_info_t sfi; - - /* write file to secure-storage */ - ret = ssm_write_file(filepath, flag, group_id); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto error; - } - - /* get information */ - ret = ssm_getinfo(filepath, &sfi, flag, group_id); - if(ret == 0) // success - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - - /* delete encrypted file */ - ret = ssm_delete_file(filepath, flag, group_id); - if(ret != 0) - tetResult = TET_UNINITIATED; - -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} - -/** - * @brief Negative test case of ssm_getinfo() - */ -static void utc_SecurityFW_ssm_getinfo_func_02(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input2.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - ssm_file_info_t sfi; - - printf("[%s] checkpoint1\n", __func__); - - /* write file to secure-storage */ - ret = ssm_write_file(filepath, flag, group_id); - printf("[%s] checkpoint2 [%d]\n", __func__, ret); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto error; - } - - /* get information */ - ret = ssm_getinfo(NULL, &sfi, flag, group_id); - printf("[%s] checkpoint3 [%d]\n", __func__, ret); - if(ret == 0) // success - tetResult = TET_FAIL; - else - tetResult = TET_PASS; - - /* delete encrypted file */ - ret = ssm_delete_file(filepath, flag, group_id); - printf("[%s] checkpoint4 [%d]\n", __func__, ret); - if(ret != 0) - tetResult = TET_UNINITIATED; - -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} diff --git a/TC/scenario1/utc_SecurityFW_ssm_read_func.c b/TC/scenario1/utc_SecurityFW_ssm_read_func.c deleted file mode 100755 index e976f06..0000000 --- a/TC/scenario1/utc_SecurityFW_ssm_read_func.c +++ /dev/null @@ -1,187 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include - -#include -#include - -static void startup(void); -static void cleanup(void); - -void (*tet_startup)(void) = startup; -void (*tet_cleanup)(void) = cleanup; - -static void utc_SecurityFW_ssm_read_func_01(void); -static void utc_SecurityFW_ssm_read_func_02(void); - -enum { - POSITIVE_TC_IDX = 0x01, - NEGATIVE_TC_IDX, -}; - -struct tet_testlist tet_testlist[] = { - { utc_SecurityFW_ssm_read_func_01, POSITIVE_TC_IDX }, - { utc_SecurityFW_ssm_read_func_02, NEGATIVE_TC_IDX }, - { NULL, 0 } -}; - -static void startup(void) -{ - printf("Make temporary directory - /opt/secure-storage/test/\n"); - system("mkdir -p /opt/secure-storage/test"); - printf("Make temporary file\n"); - system("touch /opt/secure-storage/test/input.txt"); - system("echo \"abcdefghij\" > /opt/secure-storage/test/input.txt"); - system("cp /opt/secure-storage/test/input.txt /opt/secure-storage/test/input2.txt"); -} - -static void cleanup(void) -{ - printf("Remove tamporary file and directory\n"); - system("rm -rf /opt/secure-storage/test"); -} - -/** - * @brief Positive test case of ssm_read() - */ -static void utc_SecurityFW_ssm_read_func_01(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - - /* variables for ssm_read */ - FILE* fp_original = NULL; - char buf[20]; - char* retbuf = NULL; - int readlen = 0; - ssm_file_info_t sfi; - - /* get original file content. after encrypting, original file will be deleted */ - memset(buf, 0x00, 20); - fp_original = fopen(filepath, "r"); - fgets(buf, 20, fp_original); - fclose(fp_original); - - /* write file to secure-storage */ - ret = ssm_write_file(filepath, flag, group_id); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto error; - } - - /* read and compare */ - ssm_getinfo(filepath, &sfi, flag, group_id); - retbuf = (char*)malloc(sizeof(char) * (sfi.originSize + 1)); - memset(retbuf, 0x00, (sfi.originSize + 1)); - ret = ssm_read(filepath, retbuf, sfi.originSize, &readlen, flag, group_id); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto free_error; - } - - if(tetResult != TET_UNINITIATED) - { - if(!memcmp(buf, retbuf, strlen(retbuf))) // if same - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - } - - /* delete encrypted file */ - ret = ssm_delete_file(filepath, flag, group_id); - if(ret != 0) - tetResult = TET_UNINITIATED; - -free_error: - free(retbuf); -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} - -/** - * @brief Negative test case of ssm_read() - */ -static void utc_SecurityFW_ssm_read_func_02(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input2.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - - /* variables for ssm_read */ - FILE* fp_original = NULL; - char buf[20]; - char* retbuf = NULL; - int readlen = 0; - ssm_file_info_t sfi; - - /* get original file content. after encrypting, original file will be deleted */ - memset(buf, 0x00, 20); - fp_original = fopen(filepath, "r"); - fgets(buf, 20, fp_original); - fclose(fp_original); - - printf("[%s] checkpoint1\n", __func__); - - /* write file to secure-storage */ - ret = ssm_write_file(filepath, flag, group_id); - printf("[%s] checkpoint2 [%d]\n", __func__, ret); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto error; - } - - /* read and compare */ - ret = ssm_getinfo(filepath, &sfi, flag, group_id); - printf("[%s] checkpoint3 [%d]\n", __func__, ret); - retbuf = (char*)malloc(sizeof(char) * (sfi.originSize + 1)); - memset(retbuf, 0x00, (sfi.originSize + 1)); - ret = ssm_read(NULL, retbuf, sfi.originSize, &readlen, flag, group_id); - printf("[%s] checkpoint4 [%d]\n", __func__, ret); - if(ret != 0) // if fail, - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - - /* delete encrypted file */ - ret = ssm_delete_file(filepath, flag, group_id); - printf("[%s] checkpoint5 [%d]\n", __func__, ret); - if(ret != 0) - tetResult = TET_UNINITIATED; - - free(retbuf); -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} diff --git a/TC/scenario1/utc_SecurityFW_ssm_write_buffer_func.c b/TC/scenario1/utc_SecurityFW_ssm_write_buffer_func.c deleted file mode 100755 index 50faf2c..0000000 --- a/TC/scenario1/utc_SecurityFW_ssm_write_buffer_func.c +++ /dev/null @@ -1,155 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include - -#include -#include - -static void startup(void); -static void cleanup(void); - -void (*tet_startup)(void) = startup; -void (*tet_cleanup)(void) = cleanup; - -static void utc_SecurityFW_ssm_write_buffer_func_01(void); -static void utc_SecurityFW_ssm_write_buffer_func_02(void); - -enum { - POSITIVE_TC_IDX = 0x01, - NEGATIVE_TC_IDX, -}; - -struct tet_testlist tet_testlist[] = { - { utc_SecurityFW_ssm_write_buffer_func_01, POSITIVE_TC_IDX }, - { utc_SecurityFW_ssm_write_buffer_func_02, NEGATIVE_TC_IDX }, - { NULL, 0 } -}; - -static void startup(void) -{ - printf("Make temporary directory - /opt/secure-storage/test/\n"); - system("mkdir -p /opt/secure-storage/test"); - printf("Make temporary file\n"); - system("touch /opt/secure-storage/test/input.txt"); - system("echo \"abcdefghij\" > /opt/secure-storage/test/input.txt"); -} - -static void cleanup(void) -{ - printf("Remove tamporary file and directory\n"); - system("rm -rf /opt/secure-storage/test"); -} - -/** - * @brief Positive test case of ssm_write_buffer() - */ -static void utc_SecurityFW_ssm_write_buffer_func_01(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_buffer */ - int ret = -1; - char oribuf[20]; - ssm_flag flag = SSM_FLAG_SECRET_OPERATION; - char* group_id = NULL; - char* filename = "write_buffer.txt"; - int buflen = 0; - - /* variables for ssm_read */ - char buf[20]; - char* retbuf = NULL; - int readlen = 0; - ssm_file_info_t sfi; - - /* set contents in buffers */ - memset(oribuf, 0x00, 20); - memset(buf, 0x00, 20); - strncpy(oribuf, "abcdefghij", 10); // original buffer - strncpy(buf, "abcdefghij", 10); // encrypting - - buflen = strlen(buf); - - /* write file to secure-storage */ - ret = ssm_write_buffer(buf, buflen, filename, flag, group_id); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto error; - } - - /* read and compare */ - ssm_getinfo(filename, &sfi, flag, group_id); - retbuf = (char*)malloc(sizeof(char) * (sfi.originSize + 1)); - memset(retbuf, 0x00, (sfi.originSize + 1)); - - ret = ssm_read(filename, retbuf, sfi.originSize, &readlen, flag, group_id); - if(ret != 0) // if fail, - { - tetResult = TET_UNINITIATED; - goto free_error; - } - - if(tetResult != TET_UNINITIATED) - { - if(!memcmp(oribuf, retbuf, strlen(retbuf))) // if same - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - } - - /* delete encrypted file */ - ret = ssm_delete_file(filename, flag, group_id); - if(ret != 0) - tetResult = TET_UNINITIATED; - -free_error: - free(retbuf); -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} - -/** - * @brief Negative test case of ssm_write_buffer() - */ -static void utc_SecurityFW_ssm_write_buffer_func_02(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_buffer */ - int ret = -1; - char* filename = "write_buffer.txt"; - ssm_flag flag = SSM_FLAG_SECRET_OPERATION; - char buf[20]; - int buflen = 0; - char* group_id = NULL; - - /* write file to secure-storage */ - ret = ssm_write_buffer(NULL, buflen, filename, flag, group_id); - if(ret != 0) // if fail, - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} diff --git a/TC/scenario1/utc_SecurityFW_ssm_write_file_func.c b/TC/scenario1/utc_SecurityFW_ssm_write_file_func.c deleted file mode 100755 index a502992..0000000 --- a/TC/scenario1/utc_SecurityFW_ssm_write_file_func.c +++ /dev/null @@ -1,147 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include - -#include -#include - -static void startup(void); -static void cleanup(void); - -void (*tet_startup)(void) = startup; -void (*tet_cleanup)(void) = cleanup; - -static void utc_SecurityFW_ssm_write_file_func_01(void); -static void utc_SecurityFW_ssm_write_file_func_02(void); - -enum { - POSITIVE_TC_IDX = 0x01, - NEGATIVE_TC_IDX, -}; - -struct tet_testlist tet_testlist[] = { - { utc_SecurityFW_ssm_write_file_func_01, POSITIVE_TC_IDX }, - { utc_SecurityFW_ssm_write_file_func_02, NEGATIVE_TC_IDX }, - { NULL, 0 } -}; - -static void startup(void) -{ - printf("Make temporary directory - /opt/secure-storage/test/\n"); - system("mkdir -p /opt/secure-storage/test"); - printf("Make temporary file\n"); - system("touch /opt/secure-storage/test/input.txt"); - system("echo \"abcdefghij\" > /opt/secure-storage/test/input.txt"); -} - -static void cleanup(void) -{ - printf("Remove tamporary file and directory\n"); - system("rm -rf /opt/secure-storage/test"); -} - -/** - * @brief Positive test case of ssm_write_file() - */ -static void utc_SecurityFW_ssm_write_file_func_01(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - - /* variables for ssm_read */ - FILE* fp_original = NULL; - char buf[20]; - char* retbuf = NULL; - int readlen = 0; - ssm_file_info_t sfi; - - /* get original file content. after encrypting, original file will be deleted */ - memset(buf, 0x00, 20); - fp_original = fopen(filepath, "r"); - fgets(buf, 20, fp_original); - fclose(fp_original); - - /* write file to secure-storage */ - ret = ssm_write_file(filepath, flag, group_id); - if(ret != 0) { // if fail, - tetResult = TET_UNINITIATED; - goto error; - } - - /* read and compare */ - ssm_getinfo(filepath, &sfi, flag, group_id); - retbuf = (char*)malloc(sizeof(char) * (sfi.originSize + 1)); - memset(retbuf, 0x00, (sfi.originSize + 1)); - ret = ssm_read(filepath, retbuf, sfi.originSize, &readlen, flag, group_id); - if(ret != 0) { // if fail, - tetResult = TET_UNINITIATED; - goto free_error; - } - - if(tetResult != TET_UNINITIATED) - { - if(!memcmp(buf, retbuf, strlen(retbuf))) // if same - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - } - - /* delete encrypted file */ - ret = ssm_delete_file(filepath, flag, group_id); - if(ret != 0) - tetResult = TET_UNINITIATED; - -free_error: - free(retbuf); -error: - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} - -/** - * @brief Negative test case of ssm_write_file() - */ -static void utc_SecurityFW_ssm_write_file_func_02(void) -{ - int tetResult = TET_FAIL; - /* variables for ssm_write_file */ - int ret = -1; - char* filepath = "/opt/secure-storage/test/input.txt"; - ssm_flag flag = SSM_FLAG_DATA; - char* group_id = NULL; - - /* write file to secure-storage */ - ret = ssm_write_file(NULL, flag, group_id); - if(ret != 0) // if fail, - tetResult = TET_PASS; - else - tetResult = TET_FAIL; - - printf("[%d] [%s]\n", tetResult, __FILE__); - tet_result(tetResult); -} diff --git a/TC/testcase/tslist b/TC/testcase/tslist new file mode 100755 index 0000000..0d96058 --- /dev/null +++ b/TC/testcase/tslist @@ -0,0 +1,2 @@ +/testcase/utc_secure_storage + diff --git a/TC/testcase/utc_secure_storage b/TC/testcase/utc_secure_storage new file mode 100755 index 0000000..205852a Binary files /dev/null and b/TC/testcase/utc_secure_storage differ diff --git a/TC/testcase/utc_secure_storage.c b/TC/testcase/utc_secure_storage.c new file mode 100644 index 0000000..3ddce19 --- /dev/null +++ b/TC/testcase/utc_secure_storage.c @@ -0,0 +1,399 @@ +/* + * Copyright (c) 2011 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. + */ + + +#include +#include +#include + +#define MAX_DATA_NAME 256 +#define MAX_BUFFER_LEN 4096 +#define MAX_GROUP_ID_LEN 32 +#define MAX_PASSWORD_LEN 32 + +#define SSA_TEST_RESULT_SUCCESS 0 +enum { + POSITIVE_TC_IDX = 0x01, + NEGATIVE_TC_IDX, +}; + +static void startup(void); +static void cleanup(void); + +void (*tet_startup)(void) = startup; +void (*tet_cleanup)(void) = cleanup; + +// positive +static void utc_secure_stroage_ssa_put_p01(void); +static void utc_secure_stroage_ssa_put_p02(void); +static void utc_secure_stroage_ssa_put_p03(void); +static void utc_secure_stroage_ssa_put_p04(void); +static void utc_secure_stroage_ssa_put_p05(void); +static void utc_secure_stroage_ssa_get_p01(void); +static void utc_secure_stroage_ssa_delete_p01(void); +static void utc_secure_stroage_ssa_encrypt_p01(void); +static void utc_secure_stroage_ssa_encrypt_p02(void); +static void utc_secure_stroage_ssa_decrypt_p01(void); +// negative +static void utc_secure_stroage_ssa_put_n01(void); +static void utc_secure_stroage_ssa_get_n01(void); +static void utc_secure_stroage_ssa_encrypt_n01(void); +static void utc_secure_stroage_ssa_decrypt_n01(void); +static void utc_secure_stroage_ssa_delete_n01(void); + +struct tet_testlist tet_testlist[] = { + { utc_secure_stroage_ssa_put_p01, POSITIVE_TC_IDX }, + { utc_secure_stroage_ssa_put_p02, POSITIVE_TC_IDX }, + { utc_secure_stroage_ssa_put_p03, POSITIVE_TC_IDX }, + { utc_secure_stroage_ssa_put_p04, POSITIVE_TC_IDX }, + { utc_secure_stroage_ssa_put_p05, POSITIVE_TC_IDX }, +// { utc_secure_stroage_ssa_get_p01, POSITIVE_TC_IDX }, + { utc_secure_stroage_ssa_delete_p01, POSITIVE_TC_IDX }, + { utc_secure_stroage_ssa_encrypt_p01, POSITIVE_TC_IDX }, + { utc_secure_stroage_ssa_encrypt_p02, POSITIVE_TC_IDX }, +// { utc_secure_stroage_ssa_decrypt_p01, POSITIVE_TC_IDX }, + + { utc_secure_stroage_ssa_put_n01, NEGATIVE_TC_IDX }, +// { utc_secure_stroage_ssa_get_n01, NEGATIVE_TC_IDX }, + { utc_secure_stroage_ssa_encrypt_n01, NEGATIVE_TC_IDX }, + { utc_secure_stroage_ssa_decrypt_n01, NEGATIVE_TC_IDX }, + { utc_secure_stroage_ssa_delete_n01, NEGATIVE_TC_IDX }, + { NULL, 0 }, +}; + +static void startup(void) +{ + /* start of TC */ + tet_printf("\n Secure Storage Agnet TC start"); +} + + +static void cleanup(void) +{ + /* end of TC */ + tet_printf("\n Secure Storage Agent TC end"); +} + + +static void MakeLongBuffer(char* buffer, int length) +{ + int i = 0; + for(i=0; i 0 && encrypted_buffer != NULL) + { + int res = SsaCheckEncrypt(encrypted_buffer, len, password, test_buffer); + dts_check_gt("ssa_encrypt", res, 0, "Failed to verifying ssa_encrypt err : %d", res); + free(encrypted_buffer); + } +} + + +static void utc_secure_stroage_ssa_encrypt_p02(void) +{ + char test_buffer[MAX_BUFFER_LEN] = {0,}; + const char* password = "1234"; + char* encrypted_buffer = NULL; + + MakeLongBuffer(test_buffer, MAX_BUFFER_LEN-60); + int len = ssa_encrypt(test_buffer, strlen(test_buffer), &encrypted_buffer, password); + dts_check_gt("ssa_encrypt", len, 0, "Failed to encrypt err : %d", len); + + if(len > 0 && encrypted_buffer != NULL) + { + int res = SsaCheckEncrypt(encrypted_buffer, len, password, test_buffer); + dts_check_gt("ssa_encrypt", res, 0, "Failed to verifying ssa_encrypt err : %d", res); + free(encrypted_buffer); + } +} + + +static void utc_secure_stroage_ssa_decrypt_p01(void) +{ +} + +// Negative + +static void utc_secure_stroage_ssa_put_n01(void) +{ + const char* test_buffer = "this is nagative ssa_put test buffer.\n"; + const char* data_name = "nagative_test_data_name"; + const char* group_id = "test"; + const char* password = "qwer"; + + // NULL data name + int len = ssa_put(NULL, test_buffer, strlen(test_buffer), NULL, NULL); + dts_check_lt("ssa_put Negative", len, 0, "Failed to test NULL data name data_name : %s , err : %d", data_name, len); + + // NULL data buffer + len = ssa_put(data_name, NULL, strlen(test_buffer), NULL, NULL); + dts_check_lt("ssa_put Negative", len, 0, "Failed to test NULL data buffer data_name : %s , err : %d", data_name, len); + + // zero data length + len = ssa_put(data_name, test_buffer, 0, NULL, NULL); + dts_check_lt("ssa_put Negative", len, 0, "Failed to test 0 data length put data_name : %s , err : %d", data_name, len); + + // ununiformed group_id + len = ssa_put(data_name, test_buffer, strlen(test_buffer), "ununiformaed group_id", NULL); + dts_check_lt("ssa_put Negative", len, 0, "Failed to test group_id data_name : %s , err : %d", data_name, len); + + // invalid password. ss password : 32, sss MAX_PW_LEN : 64 + char invalidPassword[128] = {0,}; + MakeLongBuffer(invalidPassword, 128); + len = ssa_put(data_name, test_buffer, strlen(test_buffer), NULL, invalidPassword); + dts_check_lt("ssa_put Negative", len, 0, "Failed to test invalid password data_name : %s , err : %d", data_name, len); +} + +static void utc_secure_stroage_ssa_get_n01(void) +{ +} + +static void utc_secure_stroage_ssa_encrypt_n01(void) +{ + const char* test_buffer = "this is test buffer for ssa_put.\n 1234567890 \n abcdefghijklmni \n !@#$%^&*()_+|"; + const char* password = "1234"; + char* encrypted_buffer = NULL; + + // null input buffer + int len = ssa_encrypt(NULL, strlen(test_buffer), &encrypted_buffer, password); + dts_check_lt("ssa_encrypt Negative", len, 0, "Failed to test null buffer err : %d",len); + dts_check_gt("ssa_encrypt Negative", encrypted_buffer, NULL, "Failed to encrypt err : %d", len); + + // zero buffer length + len = ssa_encrypt(test_buffer, 0, &encrypted_buffer, password); + dts_check_lt("ssa_encrypt Negative", len, 0, "Failed to test zero length err : %d",len); + + // over size of input buffer + char max_buffer[5500] = {0,}; + MakeLongBuffer(max_buffer, 5500); + len = ssa_encrypt(max_buffer, strlen(max_buffer), &encrypted_buffer, password); + dts_check_lt("ssa_encrypt Negative", len, 0, "Failed to test over size buffer err : %d", len); + + // over size of password + char max_passwd[80] = {0,}; + MakeLongBuffer(max_passwd, 80); + len = ssa_encrypt(test_buffer, strlen(test_buffer), &encrypted_buffer, max_passwd); + dts_check_lt("ssa_encrypt Negative", len, 0, "Failed to test invalid password err : %d", len); +} + + +static void utc_secure_stroage_ssa_decrypt_n01(void) +{ + const char* test_buffer = "this is test buffer for ssa_put.\n 1234567890 \n abcdefghijklmni \n !@#$%^&*()_+|"; + const char* password = "1234"; + char* encrypted_buffer = NULL; + + int len = ssa_encrypt(test_buffer, strlen(test_buffer), &encrypted_buffer, password); + dts_check_gt("ssa_decrypt Negative", len, 0, "Failed to encrypt err : %d", len); + dts_check_gt("ssa_decrypt Negative", encrypted_buffer, NULL, "Failed to encrypt err : %d", len); + + char* decrypted_buffer = NULL; + // NULL input buffer + len = ssa_decrypt(NULL, len, &decrypted_buffer, NULL); + dts_check_lt("ssa_decrypt Negative", len, 0, "Failed to test NULL input buffer err : %d", len); + free(decrypted_buffer); + + // zero length + len = ssa_decrypt(encrypted_buffer, 0, &decrypted_buffer, NULL); + dts_check_lt("ssa_decrypt Negative", len, 0, "Failed to test NULL zero length err : %d", len); + free(encrypted_buffer); +} + +static void utc_secure_stroage_ssa_delete_n01(void) +{ + const char* test_buffer = "this is test buffer for ssa_put.\n 1234567890 \n abcdefghijklmni \n !@#$%^&*()_+|"; + const char* data_name = "nagative_delete_test"; + const char* group_id = NULL; + const char* password = "1234"; + + // no data_name + int check = ssa_delete(data_name, NULL); + dts_check_lt("ssa_delete Negative", check, 0, "Failed to test invalid data name data_name : %s , err : %d", data_name, check); + + // NULL data name + check = ssa_delete(NULL, group_id); + dts_check_lt("ssa_delete Negative", check, 0, "Failed to test NULL data name data_name : %s , err : %d", data_name, check); +} diff --git a/TC/tet_code b/TC/tet_code deleted file mode 100755 index a2cf6c1..0000000 --- a/TC/tet_code +++ /dev/null @@ -1,12 +0,0 @@ -# TET reserved codes -0 "PASS" -1 "FAIL" -2 "UNRESOLVED" -3 "NOTINUSE" -4 "UNSUPPORTED" -5 "UNTESTED" -6 "UNINITIATED" -7 "NORESULT" - -# Test suite additional codes -33 "INSPECT" diff --git a/TC/tet_scen b/TC/tet_scen old mode 100755 new mode 100644 index c63a380..03f029a --- a/TC/tet_scen +++ b/TC/tet_scen @@ -4,4 +4,4 @@ all # Test scenario TEST - :include:/scenario1/tslist + :include:/testcase/tslist diff --git a/TC/tetbuild.cfg b/TC/tetbuild.cfg old mode 100755 new mode 100644 index 1f80874..f7eda55 --- a/TC/tetbuild.cfg +++ b/TC/tetbuild.cfg @@ -1,4 +1,5 @@ -TET_OUTPUT_CAPTURE=False -TET_BUILD_TOOL=make -TET_PASS_TC_NAME=True -TET_API_COMPLIANT=True +TET_OUTPUT_CAPTURE=True # capture option for build operation checking +TET_BUILD_TOOL=make # build with using make command +TET_BUILD_FILE=-f Makefile # execution file (Makefile) for build +TET_API_COMPLIANT=True # use TET API in Test Case ? +TET_PASS_TC_NAME=True # report passed TC name in Journal file? diff --git a/TC/tetclean.cfg b/TC/tetclean.cfg old mode 100755 new mode 100644 index 55ef6b5..02d7030 --- a/TC/tetclean.cfg +++ b/TC/tetclean.cfg @@ -1,3 +1,5 @@ -TET_OUTPUT_CAPTURE=False -TET_CLEAN_TOOL=make clean -TET_API_COMPLIANT=True +TET_OUTPUT_CAPTURE=True # capture option +TET_CLEAN_TOOL= make clean # clean tool +TET_CLEAN_FILE= Makefile # file for clean +TET_API_COMPLIANT=True # TET API useage +TET_PASS_TC_NAME=True # showing name , passed TC diff --git a/TC/tetexec.cfg b/TC/tetexec.cfg old mode 100755 new mode 100644 index eb4f0d3..ef3e452 --- a/TC/tetexec.cfg +++ b/TC/tetexec.cfg @@ -1,3 +1,5 @@ -TET_OUTPUT_CAPTURE=True -TET_API_COMPLIANT=True -TET_PASS_TC_NAME=True +TET_OUTPUT_CAPTURE=True # capturing execution or not +TET_EXEC_TOOL= # ex) exec : execution tool set up/ Optional +TET_EXEC_FILE= # ex) exectool : execution file/ Optional +TET_API_COMPLIANT=True # Test case or Tool usesTET API? +TET_PASS_TC_NAME=True # showing Passed TC name ? diff --git a/client/include/ss_client_intf.h b/client/include/ss_client_intf.h deleted file mode 100755 index 88a54ea..0000000 --- a/client/include/ss_client_intf.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * 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 __SS_MANAGER__ -#include "ss_manager.h" -#endif - -/* - * Declare new function - * - * @name: SsClientDataStore - * @parameter - * - filepath: [in] - * - flag: [in] - * @return type: int - * - 1: success - * - <1: error - */ -int SsClientDataStoreFromFile(const char* filepath, ssm_flag flag, const char* group_id); -int SsClientDataStoreFromBuffer(char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* group_id); - -/* - * Declare new function - * - * @name: SsClientDataRead - * @parameter - * - filepath: [in] - * - pRetBuf: [out] - * - bufLen: [in] - * - readLen: [out] - * @return type: int - * - 1: success - * - <1: error - */ -int SsClientDataRead(const char* filepath, char* pRetBuf, size_t bufLen, size_t *readLen, ssm_flag flag, const char* group_id); - -/* - * Declare new function - * - * @name: SsClientGetInfo - * @parameter - * - filepath: [in] - * - sfi: [out] - * @return type: int - * - 1: success - * - <1: error - */ -int SsClientGetInfo(const char* filepath, ssm_file_info_t* sfi, ssm_flag flag, const char* group_id); - -int SsClientDeleteFile(const char* pFilePath, ssm_flag flag, const char* group_id); - -int SsClientEncrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen); - -int SsClientDecrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen); - -int SsClientEncryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen); -int SsClientDecryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pEncryptedBufLen); diff --git a/client/include/ss_client_ipc.h b/client/include/ss_client_ipc.h deleted file mode 100644 index 036d49b..0000000 --- a/client/include/ss_client_ipc.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * 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. - * - */ - -/* - * Declare new function - * - * @name: SsClientComm - * @parameter: client_data - * @return type: RspData_t - */ - -#include "secure_storage.h" - -RspData_t SsClientComm(ReqData_t* client_data); diff --git a/client/non-tz/include/ss_client_intf.h b/client/non-tz/include/ss_client_intf.h new file mode 100755 index 0000000..f59d448 --- /dev/null +++ b/client/non-tz/include/ss_client_intf.h @@ -0,0 +1,78 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * 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 __SS_MANAGER__ +#include "ss_manager.h" +#endif + +/* + * Declare new function + * + * @name: SsClientDataStore + * @parameter + * - filepath: [in] + * - flag: [in] + * @return type: int + * - 1: success + * - <1: error + */ +int SsClientDataStoreFromFile(const char* filepath, ssm_flag flag, const char* group_id); +int SsClientDataStoreFromBuffer(char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* group_id); + +/* + * Declare new function + * + * @name: SsClientDataRead + * @parameter + * - filepath: [in] + * - pRetBuf: [out] + * - bufLen: [in] + * - readLen: [out] + * @return type: int + * - 1: success + * - <1: error + */ +int SsClientDataRead(const char* filepath, char* pRetBuf, size_t bufLen, size_t *readLen, ssm_flag flag, const char* group_id); + +/* + * Declare new function + * + * @name: SsClientGetInfo + * @parameter + * - filepath: [in] + * - sfi: [out] + * @return type: int + * - 1: success + * - <1: error + */ +int SsClientGetInfo(const char* filepath, ssm_file_info_t* sfi, ssm_flag flag, const char* group_id); + +int SsClientDeleteFile(const char* pFilePath, ssm_flag flag, const char* group_id); + +int SsClientEncryptApplication(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** pEncryptedBuffer, int* pEncryptedBufLen); + +int SsClientDecryptApplication(const char* pBuffer, int bufLen, char** pDecryptedBuffer, int* pDecryptedBufLen); + +int SsClientEncryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen); + +int SsClientDecryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pEncryptedBufLen); + +int DoCipher(const char* pInputBuf, int inputLen, char** ppOutBuf, int* pOutBufLen, char* pKey, int encryption); diff --git a/client/non-tz/include/ss_client_ipc.h b/client/non-tz/include/ss_client_ipc.h new file mode 100644 index 0000000..036d49b --- /dev/null +++ b/client/non-tz/include/ss_client_ipc.h @@ -0,0 +1,32 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * 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. + * + */ + +/* + * Declare new function + * + * @name: SsClientComm + * @parameter: client_data + * @return type: RspData_t + */ + +#include "secure_storage.h" + +RspData_t SsClientComm(ReqData_t* client_data); diff --git a/client/non-tz/src/ss_client_intf.c b/client/non-tz/src/ss_client_intf.c new file mode 100755 index 0000000..6464a0d --- /dev/null +++ b/client/non-tz/src/ss_client_intf.c @@ -0,0 +1,576 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include +#include +#include +#include + +#include "secure_storage.h" +#include "ss_client_intf.h" +#include "ss_client_ipc.h" +#include "ss_manager.h" + +int SsClientDataStoreFromFile(const char* filepath, ssm_flag flag, const char* group_id) +{ + ReqData_t* send_data = NULL; + RspData_t recv_data; + int temp_len = 0; + + if(!filepath) + { + SLOGE("Parameter error in SsClientDataStoreFromFile..\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + + send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); + + if(!send_data) + { + SLOGE("Memory allocation fail in SsClientDataStoreFromFile..\n"); + recv_data.rsp_type = SS_MEMORY_ERROR; + goto Error; + } + + send_data->req_type = 1; // file store + send_data->enc_type = 1; // initial type + send_data->count = 0; + send_data->flag = flag; // flag + temp_len = strlen(filepath); + if(temp_len <= MAX_FILENAME_SIZE) + { + strncpy(send_data->data_infilepath, filepath, MAX_FILENAME_SIZE); + send_data->data_infilepath[temp_len] = '\0'; + } + else + { + SLOGE("filepath is too long.\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Free_and_Error; + } + memset(send_data->group_id, 0x00, MAX_GROUP_ID_SIZE+1); + if(group_id) + strncpy(send_data->group_id, group_id, MAX_GROUP_ID_SIZE); + else + strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_SIZE); + + memset(send_data->buffer, 0x00, MAX_SEND_DATA_SIZE + 1); + recv_data = SsClientComm(send_data); + +Free_and_Error: + free(send_data); +Error: + return recv_data.rsp_type; +} + +int SsClientDataStoreFromBuffer(char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* group_id) +{ + ReqData_t* send_data = NULL; + RspData_t recv_data; + int temp_len = 0; + + if(!writebuffer || !filename) + { + SLOGE("Parameter error in SsClientDataStoreFromBuffer..\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + + send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); + if(!send_data) + { + SLOGE("Memory allocation fail in SsClientDataStoreFromBuffer..\n"); + recv_data.rsp_type = SS_MEMORY_ERROR; + goto Error; + } + + send_data->req_type = 2; // buffer store + send_data->enc_type = 1; + send_data->count = bufLen; + send_data->flag = flag; + temp_len = strlen(filename); + if(temp_len <= MAX_FILENAME_SIZE) + { + strncpy(send_data->data_infilepath, filename, MAX_FILENAME_SIZE); + send_data->data_infilepath[temp_len] = '\0'; + } + else + { + SLOGE("filepath is too long.\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Free_and_Error; + } + memset(send_data->group_id, 0x00, MAX_GROUP_ID_SIZE+1); + if(group_id) + strncpy(send_data->group_id, group_id, MAX_GROUP_ID_SIZE); + else + strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_SIZE); + + memcpy(send_data->buffer, writebuffer, bufLen); + recv_data = SsClientComm(send_data); + +Free_and_Error: + free(send_data); +Error: + return recv_data.rsp_type; +} + +int SsClientDataRead(const char* filepath, char* pRetBuf, size_t bufLen, size_t *readLen, ssm_flag flag, const char* group_id) +{ + unsigned int count = (unsigned int)(bufLen / MAX_RECV_DATA_SIZE + 1); + unsigned int rest = (unsigned int)(bufLen % MAX_RECV_DATA_SIZE); + char* buffer; + ReqData_t* send_data = NULL; + RspData_t recv_data; + int temp_len = 0; + + if(!filepath) + { + SLOGE("filepath Parameter error in SsClientDataRead..\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + if(!readLen) + { + SLOGE("readLen Parameter error in SsClientDataRead..\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + + *readLen = 0; + buffer = pRetBuf; + + send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); + + if(!send_data) + { + SLOGE("Memory allocation fail in SsClientDataRead..\n"); + recv_data.rsp_type = SS_MEMORY_ERROR; + goto Error; + } + + // fill send_data + send_data->req_type = 3; // read data from storage + send_data->enc_type = 1; // initial type + send_data->count = 0; + send_data->flag = flag & 0x000000ff; //flag; + temp_len = strlen(filepath); + if(temp_len <= MAX_FILENAME_SIZE) + { + strncpy(send_data->data_infilepath, filepath, MAX_FILENAME_SIZE); + send_data->data_infilepath[temp_len] = '\0'; + } + else + { + SLOGE("filepath is too long.\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Free_and_Error; + } + memset(send_data->group_id, 0x00, MAX_GROUP_ID_SIZE+1); + if(group_id) + strncpy(send_data->group_id, group_id, MAX_GROUP_ID_SIZE); + else + strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_SIZE); + memset(send_data->buffer, 0x00, MAX_SEND_DATA_SIZE+1); + + // Call Server per 4KB data (count from 0 to ~) + for ( ; send_data->count < count; send_data->count++) + { + //receive data from server + recv_data = SsClientComm(send_data); + + // check response type + if(recv_data.rsp_type != 1) + { + SLOGE("data read error from server...\n"); + goto Free_and_Error; + } + // copy the last data (last count) + if(send_data->count == (count - 1)) + { + memcpy(buffer, recv_data.buffer, rest); + *readLen += (size_t)rest; + goto Last; + //break; + } + + memcpy(buffer, recv_data.buffer, MAX_RECV_DATA_SIZE); + *readLen += (size_t)recv_data.readLen; + buffer += recv_data.readLen; + } +Last : + if(bufLen != *readLen) + { + SLOGE("Decrypted abnormally\n"); + recv_data.rsp_type = SS_DECRYPTION_ERROR; + goto Free_and_Error; + } + + SECURE_SLOGE("Decrypted file name : %s\n", recv_data.data_filepath); +Free_and_Error: + free(send_data); +Error: + return recv_data.rsp_type; +} + +int SsClientGetInfo(const char* filepath, ssm_file_info_t* sfi, ssm_flag flag, const char* group_id) +{ + + ReqData_t* send_data = NULL; + RspData_t recv_data; + ssm_file_info_convert_t sfic; + int temp_len = 0; + + if(!filepath || !sfi) + { + SLOGE("Parameter error in SsClientGetInfo..\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + + send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); + + if(!send_data) + { + SLOGE("Memory allocation fail in SsClientGetInfo..\n"); + recv_data.rsp_type = SS_MEMORY_ERROR; + goto Error; + } + + // fill send_data + send_data->req_type = 4; // get info type + send_data->enc_type = 1; // initial type + send_data->count = 0; + send_data->flag = flag & 0x000000ff; //flag; + temp_len = strlen(filepath); + if(temp_len <= MAX_FILENAME_SIZE) + { + strncpy(send_data->data_infilepath, filepath, MAX_FILENAME_SIZE); + send_data->data_infilepath[temp_len] = '\0'; + } + else + { + SLOGE("filepath is too long.\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Free_and_Error; + } + memset(send_data->group_id, 0x00, MAX_GROUP_ID_SIZE + 1); + if(group_id) + strncpy(send_data->group_id, group_id, MAX_GROUP_ID_SIZE); + else + strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_SIZE); + memset(send_data->buffer, 0x00, MAX_SEND_DATA_SIZE + 1); + + recv_data = SsClientComm(send_data); + + memcpy(sfic.fInfoArray, recv_data.buffer, sizeof(ssm_file_info_t)); + sfi->originSize = sfic.fInfoStruct.originSize; + sfi->storedSize = sfic.fInfoStruct.storedSize; + memcpy(sfi->reserved, sfic.fInfoStruct.reserved, 8); + +Free_and_Error: + free(send_data); +Error: + return recv_data.rsp_type; +} + +int SsClientDeleteFile(const char *pFilePath, ssm_flag flag, const char* group_id) +{ + ReqData_t* send_data = NULL; + RspData_t recv_data; + int temp_len = 0; + + if(!pFilePath) + { + SLOGE("Parameter error in SsClientDeleteFile..\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + + send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); + + if(!send_data) + { + SLOGE("Memory allocation fail in SsClientDeleteFile..\n"); + recv_data.rsp_type = SS_MEMORY_ERROR; + goto Error; + } + + send_data->req_type = 10; // delete file + send_data->enc_type = 1; // initial type + send_data->count = 0; + send_data->flag = flag; // flag + temp_len = strlen(pFilePath); + if(temp_len <= MAX_FILENAME_SIZE) + { + strncpy(send_data->data_infilepath, pFilePath, MAX_FILENAME_SIZE); + send_data->data_infilepath[temp_len] = '\0'; + } + else + { + SLOGE("filepath is too long.\n"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Free_and_Error; + } + memset(send_data->group_id, 0x00, MAX_GROUP_ID_SIZE+1); + if(group_id) + strncpy(send_data->group_id, group_id, MAX_GROUP_ID_SIZE); + else + strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_SIZE); + memset(send_data->buffer, 0x00, MAX_SEND_DATA_SIZE+1); + + recv_data = SsClientComm(send_data); + +Free_and_Error: + free(send_data); + + SECURE_SLOGE("Deleted file name: %s\n", recv_data.data_filepath); + +Error: + return recv_data.rsp_type; +} + + +////////////////////////////// +__attribute__((visibility("hidden"))) +int DoCipher(const char* pInputBuf, int inputLen, char** ppOutBuf, int* pOutBufLen, char* pKey, int encryption) +{ + static const unsigned char iv[16] = {0xbd, 0xc3, 0xc5, 0xa5, 0xb8, 0xae, 0xc6, 0xbc, 0x20, 0xb3, 0xeb, 0xb0, 0xe6, 0xbf, 0xec, 0x20}; + struct evp_cipher_st* pCipherAlgorithm = NULL; + EVP_CIPHER_CTX cipherCtx; + int tempLen = 0; + int result = 0; + int finalLen = 0; + + pCipherAlgorithm = EVP_aes_256_cbc(); + tempLen = (int)((inputLen / pCipherAlgorithm->block_size + 1) * pCipherAlgorithm->block_size); + + *ppOutBuf = (char*)calloc(tempLen, 1); + EVP_CIPHER_CTX_init(&cipherCtx); + + result = EVP_CipherInit(&cipherCtx, pCipherAlgorithm, (const unsigned char*)pKey, iv, encryption); + if(result != 1) + { + SLOGE("[%d] EVP_CipherInit failed", result); + goto Error; + } + + result = EVP_CIPHER_CTX_set_padding(&cipherCtx, 1); + if(result != 1) + { + SLOGE("[%d] EVP_CIPHER_CTX_set_padding failed", result); + goto Error; + } + + //cipher update operation + result = EVP_CipherUpdate(&cipherCtx, (unsigned char*)*ppOutBuf, pOutBufLen, (const unsigned char*)pInputBuf, inputLen); + if(result != 1) + { + SLOGE("[%d] EVP_CipherUpdate failed", result); + goto Error; + } + + //cipher final operation + result = EVP_CipherFinal(&cipherCtx, (unsigned char*)*ppOutBuf + *pOutBufLen, &finalLen); + if(result != 1) + { + SLOGE("[%d] EVP_CipherFinal failed", result); + goto Error; + } + *pOutBufLen = *pOutBufLen + finalLen; + goto Last; +Error: + result = SS_ENCRYPTION_ERROR; + free(*ppOutBuf); + +Last: + EVP_CIPHER_CTX_cleanup(&cipherCtx); + if((result != 1) && (encryption != 1)) + result = SS_DECRYPTION_ERROR; + + return result; +} + +int SsClientEncryptApplication(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen) +{ + ReqData_t* send_data = NULL; + RspData_t recv_data; + static char duk[32]; + static int dukExist = 0; + + if(!pBuffer || bufLen ==0) + { + SLOGE("Parameter error"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + + if(!dukExist) + { + send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); + if(!send_data) + { + SLOGE("Memory allocation fail"); + recv_data.rsp_type = SS_MEMORY_ERROR; + goto Error; + } + + send_data->req_type = 5; //request key + send_data->enc_type = 0; + send_data->count = 0; + send_data->flag = 1; + memset(send_data->group_id, 0, MAX_GROUP_ID_SIZE+1); + memcpy(send_data->group_id, pAppId, idLen); + + recv_data = SsClientComm(send_data); + + if(recv_data.rsp_type != 1) + { + SLOGE("failed to get data from server"); + recv_data.rsp_type = SS_TZ_ERROR; + goto Free_and_Error; + } + memcpy(duk, recv_data.buffer, 32); + dukExist = 1; + } + + if(DoCipher(pBuffer, bufLen, ppEncryptedBuffer, pEncryptedBufLen, duk, 1) != 1) + { + SLOGE("failed to encrypt data"); + recv_data.rsp_type = SS_ENCRYPTION_ERROR; + goto Free_and_Error; + } + + recv_data.rsp_type = 1; + +Free_and_Error: + free(send_data); +Error: + return recv_data.rsp_type; +} + +int SsClientDecryptApplication(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen) +{ + ReqData_t* send_data = NULL; + RspData_t recv_data; + static char duk[32]; + static int dukExist = 0; + + if(!pBuffer || bufLen ==0) + { + SLOGE("Parameter error"); + recv_data.rsp_type = SS_PARAM_ERROR; + goto Error; + } + + if(!dukExist) + { + send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); + if(!send_data) + { + SLOGE("Memory allocation fail"); + recv_data.rsp_type = SS_MEMORY_ERROR; + goto Error; + } + + send_data->req_type = 5; //request key + send_data->enc_type = 0; + send_data->count = 0; + send_data->flag = 0; + + recv_data = SsClientComm(send_data); + + if(recv_data.rsp_type != 1) + { + SLOGE("Failed to get data from server"); + recv_data.rsp_type = SS_TZ_ERROR; + goto Free_and_Error; + } + memcpy(duk, recv_data.buffer, 32); + dukExist = 1; + } + + if(DoCipher(pBuffer, bufLen, ppDecryptedBuffer, pDecryptedBufLen, duk, 0) != 1) + { + SLOGE("failed to decrypt data"); + recv_data.rsp_type = SS_DECRYPTION_ERROR; + goto Free_and_Error; + } + recv_data.rsp_type = 1; + +Free_and_Error: + free(send_data); +Error: + return recv_data.rsp_type; +} + +int SsClientEncryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen) +{ + int result = 0; + char duk[36] = {0,}; + + if(!pBuffer || bufLen ==0) + { + SLOGE("Parameter error"); + result = SS_PARAM_ERROR; + goto Final; + } + + if(DoCipher(pBuffer, bufLen, ppEncryptedBuffer, pEncryptedBufLen, duk, 1) != 1) + { + SLOGE("failed to decrypt data"); + result = SS_ENCRYPTION_ERROR; + goto Final; + } + + result = 1; + +Final: + return result; +} + +int SsClientDecryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen) +{ + int result = 0; + char duk[36] = {0,}; + + if(!pBuffer || bufLen ==0) + { + SLOGE("Parameter error"); + result = SS_PARAM_ERROR; + goto Final; + } + + if(DoCipher(pBuffer, bufLen, ppDecryptedBuffer, pDecryptedBufLen, duk, 0) != 1) + { + SLOGE("failed to decrypt data"); + result = SS_DECRYPTION_ERROR; + goto Final; + } + + result = 1; + +Final: + return result; +} diff --git a/client/non-tz/src/ss_client_ipc.c b/client/non-tz/src/ss_client_ipc.c new file mode 100644 index 0000000..b986274 --- /dev/null +++ b/client/non-tz/src/ss_client_ipc.c @@ -0,0 +1,102 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ss_client_ipc.h" +#include "secure_storage.h" + +RspData_t SsClientComm(ReqData_t* client_data) +{ + int sockfd = 0; + int client_len = 0; + struct sockaddr_un clientaddr; + ReqData_t send_data = {0, }; + RspData_t recv_data = {0, }; + int temp_len_in = 0; + int temp_len_sock = 0; + int read_len = 0; + + send_data.req_type = client_data->req_type; + send_data.enc_type = client_data->enc_type; + send_data.count = client_data->count; + send_data.flag = client_data->flag; + + temp_len_in = strlen(client_data->data_infilepath); + + strncpy(send_data.data_infilepath, client_data->data_infilepath, MAX_FILENAME_SIZE); + send_data.data_infilepath[temp_len_in] = '\0'; + + strncpy(send_data.group_id, client_data->group_id, MAX_GROUP_ID_SIZE); + + memcpy(send_data.buffer, client_data->buffer, MAX_SEND_DATA_SIZE); + + if((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) + { + SLOGE("Error in function socket()..\n"); + recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_exit; + } + + temp_len_sock = strlen(SS_SOCK_PATH); + + bzero(&clientaddr, sizeof(clientaddr)); + clientaddr.sun_family = AF_UNIX; + strncpy(clientaddr.sun_path, SS_SOCK_PATH, temp_len_sock); + clientaddr.sun_path[temp_len_sock] = '\0'; + client_len = sizeof(clientaddr); + + if(connect(sockfd, (struct sockaddr*)&clientaddr, client_len) < 0) + { + SLOGE("Error in function connect()..\n"); + recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_close_exit; + } + + if(write(sockfd, (char*)&send_data, sizeof(send_data)) < 0) + { + SLOGE("Error in function write()..\n"); + recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_close_exit; + } + + read_len = read(sockfd, (char*)&recv_data, sizeof(recv_data)); + if(read_len < 0) + { + SLOGE("Error in function read()..\n"); + recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_close_exit; + } + +Error_close_exit: + close(sockfd); + +Error_exit: + return recv_data; +} diff --git a/client/non-tz/src/ss_manager.c b/client/non-tz/src/ss_manager.c new file mode 100755 index 0000000..ab2f08f --- /dev/null +++ b/client/non-tz/src/ss_manager.c @@ -0,0 +1,586 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include +#include + +#include "secure_storage.h" +#include "ss_client_intf.h" + +#ifndef SS_API +#define SS_API __attribute__((visibility("default"))) +#endif + +/***************************************************************************** + * Internal Functions + *****************************************************************************/ +SS_API +int ssm_getinfo(const char* pFilePath, ssm_file_info_t *sfi, ssm_flag flag, const char* group_id) +{ + int ret = 0; + + if(!pFilePath || !sfi) + { + SLOGE("Parameter error in ssm_getinfo()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientGetInfo(pFilePath, sfi, flag, group_id); + + if(ret == 1) + { + SLOGI("Getinfo Success.\n"); + ret = 0; // return true + } + else + SLOGE("Getinfo Fail.\n"); + +Error: + return ret; +} + +/***************************************************************************** + * Manager APIs + *****************************************************************************/ +SS_API +int ssm_write_file(const char* pFilePath, ssm_flag flag, const char* group_id) +{ + int ret = 0; + + if(!pFilePath) + { + SLOGE("Parameter error in ssm_write_file()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + if(flag <= SSM_FLAG_NONE || flag >= SSM_FLAG_MAX) + { + SLOGE("Parameter error in ssm_write_file()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientDataStoreFromFile(pFilePath, flag, group_id); + if(ret == 1) + { + if(unlink(pFilePath) != 0) // if fail + { + SLOGE("unlink fail. [%s]\n", pFilePath); + return -1; // return false + } + SLOGI("Write file Success.\n"); + return 0; // return true + } + else + SLOGE("Write file Fail.\n"); + +Error: + return ret; +} + +SS_API +int ssm_write_buffer(char* pWriteBuffer, size_t bufLen, const char* pFileName, ssm_flag flag, const char* group_id) +{ + int ret = 0; + + if(!pWriteBuffer || !pFileName) + { + SLOGE("Parameter error in ssm_write_buffer()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + if(bufLen <= 0 || bufLen > 4096) + { + SLOGE("Parameter error in ssm_write_buffer()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + if(flag <= SSM_FLAG_NONE || flag >= SSM_FLAG_MAX) + { + SLOGE("Parameter error in ssm_write_buffer()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientDataStoreFromBuffer(pWriteBuffer, bufLen, pFileName, flag, group_id); + if(ret == 1) + { + SLOGI("Write buffer Success.\n"); + return 0; // return true + } + else + SLOGE("Write buffer Fail.\n"); + +Error: + return ret; +} + +SS_API +int ssm_read(const char* pFilePath, char* pRetBuf, size_t bufLen, size_t *readLen, ssm_flag flag, const char* group_id) +{ + int ret = 0; + ssm_file_info_t sfi; + + if(!pFilePath || !pRetBuf) + { + SLOGE("Parameter error in ssm_read()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + if(!readLen) + { + SLOGE("Parameter error in ssm_read()...\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + // get info + ret = ssm_getinfo(pFilePath, &sfi, flag, group_id); + if(ret != 0) // ret != true? + { + SLOGE("getinfo error in ssm_read()..\n"); + goto Error; + } + // in case of flag mismatch... + // check flag... + // To do : + if((bufLen > sfi.originSize) || (sfi.reserved[0] != (flag & 0x000000ff))) + { + SLOGE("Flag mismatch or buffer length error in ssm_read()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientDataRead(pFilePath, pRetBuf, sfi.originSize, readLen, flag, group_id); + + if(ret == 1) + { + SLOGI("Read Success.\n"); + return 0; // return true + } + else + SLOGE("Read Fail.\n"); + +Error: + return ret; +} + +SS_API +int ssm_delete_file(const char *pFilePath, ssm_flag flag, const char* group_id) +{ + int ret = 0; + + if(!pFilePath) + { + SLOGE("Parameter error in ssm_delete_file()..\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientDeleteFile(pFilePath, flag, group_id); + + if(ret == 1) // success + { + SLOGI("Delete file Success.\n"); + return 0; + } + else // fail + SLOGE("Delete file Fail.\n"); + +Error: + return ret; +} + +SS_API +int ssm_encrypt_application(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** pEncryptedBuffer, int* pEncryptedBufLen) +{ + int ret = 0; + + if(!pBuffer || bufLen ==0 || !pAppId || idLen == 0 || idLen+1 > MAX_GROUP_ID_SIZE) + { + SLOGE("Parameter error.\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientEncryptApplication(pAppId, idLen, pBuffer, bufLen, pEncryptedBuffer, pEncryptedBufLen); + + if(ret == 1) // success + { + SLOGI("Application encryption succeeded.\n"); + return 0; + } + else // fail + SLOGE("Application encryption failed.\n"); + +Error: + return ret; +} + +SS_API +int ssm_decrypt_application(const char* pBuffer, int bufLen, char** pDecryptedBuffer, int* pDecryptedBufLen) +{ + int ret = 0; + + if(!pBuffer || bufLen ==0) + { + SLOGE("Parameter error.\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientDecryptApplication(pBuffer, bufLen, pDecryptedBuffer, pDecryptedBufLen); + + if(ret == 1) // success + { + SLOGI("Application decryption succeeded.\n"); + return 0; + } + else // fail + SLOGE("Application decryption failed.\n"); + +Error: + return ret; +} + +SS_API +int ssm_encrypt_preloaded_application(const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen) +{ + int ret = 0; + + if(!pBuffer || bufLen ==0) + { + SLOGE("Parameter error.\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientEncryptPreloadedApplication(pBuffer, bufLen, ppEncryptedBuffer, pEncryptedBufLen); + if(ret == 1) // success + { + SLOGI("Application decryption succeeded.\n"); + return 0; + } + else // fail + SLOGE("Application decryption failed.\n"); + +Error: + return ret; +} + +SS_API +int ssm_decrypt_preloaded_application(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen) +{ + int ret = 0; + + if(!pBuffer || bufLen ==0) + { + SLOGE("Parameter error.\n"); + ret = SS_PARAM_ERROR; + goto Error; + } + + ret = SsClientDecryptPreloadedApplication(pBuffer, bufLen, ppDecryptedBuffer, pDecryptedBufLen); + if(ret == 1) // success + { + SLOGI("Application decryption succeeded.\n"); + return 0; + } + else // fail + SLOGE("Application decryption failed.\n"); + +Error: + return ret; +} + + +////////////// +//agent +///////////// +// +// + +int ConvertErrorCode(int error) +{ + int convertedError = 0; + + switch(error) + { + case SS_FILE_OPEN_ERROR: + case SS_PARAM_ERROR: + convertedError = SSA_PARAM_ERROR; + break; + case SS_FILE_TYPE_ERROR: + case SS_FILE_READ_ERROR: + case SS_FILE_WRITE_ERROR: + convertedError = SSA_IO_ERROR; + break; + case SS_MEMORY_ERROR: + convertedError = SSA_UNKNOWN_ERROR; + break; + case SS_SOCKET_ERROR: + convertedError = SSA_SOCKET_ERROR; + break; + case SS_ENCRYPTION_ERROR: + case SS_DECRYPTION_ERROR: + convertedError = SSA_CIPHER_ERROR; + break; + case SS_SIZE_ERROR: + convertedError = SSA_UNKNOWN_ERROR; + break; + case SS_SECURE_STORAGE_ERROR: + convertedError = SSA_TZ_ERROR; + break; + case SS_PERMISSION_DENIED: + convertedError = SSA_PERMISSION_ERROR; + break; + case SS_TZ_ERROR: + convertedError = SSA_TZ_ERROR; + break; + default: + convertedError = SSA_UNKNOWN_ERROR; + break; + } + + SLOGE("error code = %d", convertedError); + + return convertedError; +} + + +SS_API +int ssa_put(const char* pDataName, const char* pDataBlock, size_t inDataBlockLen, const char* pGroupId, const char* pPassword) +{ + int ret = 0; + + if(pPassword && (strlen(pPassword) > MAX_PASSWORD_SIZE)) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + if(!pDataName || !pDataBlock) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + if(inDataBlockLen <= 0 || inDataBlockLen > MAX_SEND_DATA_SIZE) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + ret = ssm_write_buffer(pDataBlock, inDataBlockLen, pDataName, SSM_FLAG_SECRET_OPERATION, pGroupId); + + if(ret != 0) + { + ret = ConvertErrorCode(ret); + return ret; + } + + return inDataBlockLen; +} + +SS_API +int ssa_get(const char* pDataName, char** ppOutDataBlock, const char* pGroupId, const char* pPassword) +{ + ssm_file_info_t info; + size_t readLen = 0; + int ret = 0; + + if(pPassword && (strlen(pPassword) > MAX_PASSWORD_SIZE)) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + if(!pDataName) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + ret = ssm_getinfo(pDataName, &info, SSM_FLAG_SECRET_OPERATION, pGroupId); + if(ret != 0) + { + ret = ConvertErrorCode(ret); + return ret; + } + + *ppOutDataBlock = (char*)malloc(sizeof(char)*(info.originSize+1)); + memset(*ppOutDataBlock, 0, info.originSize+1); + + ret = ssm_read(pDataName, *ppOutDataBlock, info.originSize, &readLen, SSM_FLAG_SECRET_OPERATION, pGroupId); + if(ret != 0) + { + ret = ConvertErrorCode(ret); + free(*ppOutDataBlock); + return ret; + } + + return (int)readLen; +} + + +SS_API +int ssa_delete(const char* pDataName, const char* pGroupId) +{ + int ret = 0; + + if(!pDataName) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + ret = ssm_delete_file(pDataName, SSM_FLAG_SECRET_OPERATION, pGroupId); + if(ret != 0) + { + ret = ConvertErrorCode(ret); + } + + return ret; +} + +SS_API +int ssa_encrypt(const char* pInDataBlock, size_t inDataBlockLen, char** ppOutDataBlock, const char* pPassword) +{ + int ret = 0; + int outLen = 0; + char* pKey = "0123456789abcdef0123456789abcdef"; + + if(pPassword && (strlen(pPassword) > MAX_PASSWORD_SIZE)) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + if(!pInDataBlock || inDataBlockLen == 0 || inDataBlockLen > MAX_SEND_DATA_SIZE) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + ret = DoCipher(pInDataBlock, inDataBlockLen, ppOutDataBlock, &outLen, pKey, 1); + if(ret != 1) + { + return SSA_CIPHER_ERROR; + } + + return outLen; +} + + +SS_API +int ssa_decrypt(const char* pInDataBlock, size_t inDataBlockLen, char** ppOutDataBlock, const char* pPassword) +{ + int ret = 0; + int outLen = 0; + char* pKey = "0123456789abcdef0123456789abcdef"; + + if(pPassword && (strlen(pPassword) > MAX_PASSWORD_SIZE)) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + if(!pInDataBlock || inDataBlockLen == 0) + { + SLOGE("Invalid input argument."); + return SSA_PARAM_ERROR; + } + + ret = DoCipher(pInDataBlock, inDataBlockLen, ppOutDataBlock, &outLen, pKey, 0); + if(ret != 1) + { + return SSA_CIPHER_ERROR; + } + + return outLen; +} + +SS_API +int ssa_encrypt_web_application(const char* pAppId, int idLen, const char* pData, int dataLen, char** ppEncryptedData, int isPreloaded) +{ + int ret = 0; + int outLen = 0; + + if(isPreloaded) + { + ret = ssm_encrypt_preloaded_application(pData, dataLen, ppEncryptedData, &outLen); + if(ret != 0) + { + ret = ConvertErrorCode(ret); + return ret; + } + + return outLen; + } + + else + { + ret = ssm_encrypt_application(pAppId, idLen, pData, dataLen, ppEncryptedData, &outLen); + if(ret != 0) + { + ret = ConvertErrorCode(ret); + return ret; + } + + return outLen; + } +} + + +SS_API +int ssa_decrypt_web_application(const char* pData, int dataLen, char** ppDecryptedData, int isPreloaded) +{ + int ret = 0; + int outLen = 0; + + if(isPreloaded) + { + ret = ssm_decrypt_preloaded_application(pData, dataLen, ppDecryptedData, &outLen); + if(ret != 0) + { + ret = ConvertErrorCode(ret); + return ret; + } + + return outLen; + } + + else + { + ret = ssm_decrypt_application(pData, dataLen, ppDecryptedData, &outLen); + if(ret != 0) + { + ret = ConvertErrorCode(ret); + return ret; + } + + return outLen; + } +} diff --git a/client/src/ss_client_intf.c b/client/src/ss_client_intf.c deleted file mode 100755 index ec9beb3..0000000 --- a/client/src/ss_client_intf.c +++ /dev/null @@ -1,587 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include -#include -#include -#include - -#include "secure_storage.h" -#include "ss_client_intf.h" -#include "ss_client_ipc.h" -#include "ss_manager.h" - -#include - -int SsClientDataStoreFromFile(const char* filepath, ssm_flag flag, const char* group_id) -{ - ReqData_t* send_data = NULL; - RspData_t recv_data; - int temp_len = 0; - int cookie_size = 20; - -// cookie_size = security_server_get_cookie_size(); - char cookie_content[20] = {0, }; - -// if(security_server_request_cookie(cookie_content, cookie_size) < 0) // error while getting cookie -// { -// SLOGE("Fail to get cookie\n"); -// recv_data.rsp_type = SS_SECURE_STORAGE_ERROR; -// goto Error; -// } - - if(!filepath) - { - SLOGE("Parameter error in SsClientDataStoreFromFile..\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Error; - } - - send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); - - if(!send_data) - { - SLOGE("Memory allocation fail in SsClientDataStoreFromFile..\n"); - recv_data.rsp_type = SS_MEMORY_ERROR; - goto Error; - } - - send_data->req_type = 1; // file store - send_data->enc_type = 1; // initial type - send_data->count = 0; - send_data->flag = flag; // flag - temp_len = strlen(filepath); - if(temp_len < MAX_FILENAME_LEN) - { - strncpy(send_data->data_infilepath, filepath, MAX_FILENAME_LEN - 1); - send_data->data_infilepath[temp_len] = '\0'; - } - else - { - SLOGE("filepath is too long.\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Free_and_Error; - } - memset(send_data->cookie, 0x00, MAX_COOKIE_LEN); - memset(send_data->group_id, 0x00, MAX_GROUP_ID_LEN); - memcpy(send_data->cookie, cookie_content, cookie_size); - if(group_id) - strncpy(send_data->group_id, group_id, MAX_GROUP_ID_LEN - 1); - else - strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_LEN - 1); - - memset(send_data->buffer, 0x00, MAX_SEND_DATA_LEN + 1); - recv_data = SsClientComm(send_data); - -Free_and_Error: - free(send_data); -Error: - return recv_data.rsp_type; -} - -int SsClientDataStoreFromBuffer(char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* group_id) -{ - ReqData_t* send_data = NULL; - RspData_t recv_data; - int temp_len = 0; - int cookie_size = 20; - -// cookie_size = security_server_get_cookie_size(); - char cookie_content[20] = {0, }; - -// if(security_server_request_cookie(cookie_content, cookie_size) < 0) // error while getting cookie -// { -// SLOGE("Fail to get cookie\n"); -// recv_data.rsp_type = SS_SECURE_STORAGE_ERROR; -// goto Error; -// } - - if(!writebuffer || !filename) - { - SLOGE("Parameter error in SsClientDataStoreFromBuffer..\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Error; - } - - send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); - if(!send_data) - { - SLOGE("Memory allocation fail in SsClientDataStoreFromBuffer..\n"); - recv_data.rsp_type = SS_MEMORY_ERROR; - goto Error; - } - - send_data->req_type = 2; // buffer store - send_data->enc_type = 1; - send_data->count = bufLen; - send_data->flag = flag; - temp_len = strlen(filename); - if(temp_len < MAX_FILENAME_LEN) - { - strncpy(send_data->data_infilepath, filename, MAX_FILENAME_LEN - 1); - send_data->data_infilepath[temp_len] = '\0'; - } - else - { - SLOGE("filepath is too long.\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Free_and_Error; - } - memset(send_data->cookie, 0x00, MAX_COOKIE_LEN); - memset(send_data->group_id, 0x00, MAX_GROUP_ID_LEN); - memcpy(send_data->cookie, cookie_content, cookie_size); - if(group_id) - strncpy(send_data->group_id, group_id, MAX_GROUP_ID_LEN - 1); - else - strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_LEN - 1); - - memcpy(send_data->buffer, writebuffer, bufLen); - recv_data = SsClientComm(send_data); - -Free_and_Error: - free(send_data); -Error: - return recv_data.rsp_type; -} - -int SsClientDataRead(const char* filepath, char* pRetBuf, size_t bufLen, size_t *readLen, ssm_flag flag, const char* group_id) -{ - unsigned int count = (unsigned int)(bufLen / MAX_RECV_DATA_LEN + 1); - unsigned int rest = (unsigned int)(bufLen % MAX_RECV_DATA_LEN); - char* buffer; - ReqData_t* send_data = NULL; - RspData_t recv_data; - int temp_len = 0; - int cookie_size = 20; - -// cookie_size = security_server_get_cookie_size(); - char cookie_content[20] = {0, }; - -// if(security_server_request_cookie(cookie_content, cookie_size) < 0) // error while getting cookie -// { -// SLOGE("Fail to get cookie\n"); -// recv_data.rsp_type = SS_SECURE_STORAGE_ERROR; -// goto Error; -// } - - if(!filepath) - { - SLOGE("filepath Parameter error in SsClientDataRead..\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Error; - } - if(!readLen) - { - SLOGE("readLen Parameter error in SsClientDataRead..\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Error; - } - - *readLen = 0; - buffer = pRetBuf; - - send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); - - if(!send_data) - { - SLOGE("Memory allocation fail in SsClientDataRead..\n"); - recv_data.rsp_type = SS_MEMORY_ERROR; - goto Error; - } - - // fill send_data - send_data->req_type = 3; // read data from storage - send_data->enc_type = 1; // initial type - send_data->count = 0; - send_data->flag = flag & 0x000000ff; //flag; - temp_len = strlen(filepath); - if(temp_len < MAX_FILENAME_LEN) - { - strncpy(send_data->data_infilepath, filepath, MAX_FILENAME_LEN - 1); - send_data->data_infilepath[temp_len] = '\0'; - } - else - { - SLOGE("filepath is too long.\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Free_and_Error; - } - memset(send_data->cookie, 0x00, MAX_COOKIE_LEN); - memset(send_data->group_id, 0x00, MAX_GROUP_ID_LEN); - memcpy(send_data->cookie, cookie_content, MAX_COOKIE_LEN); - if(group_id) - strncpy(send_data->group_id, group_id, MAX_GROUP_ID_LEN - 1); - else - strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_LEN - 1); - memset(send_data->buffer, 0x00, MAX_SEND_DATA_LEN+1); - - // Call Server per 4KB data (count from 0 to ~) - for ( ; send_data->count < count; send_data->count++) - { - //receive data from server - recv_data = SsClientComm(send_data); - - // check response type - if(recv_data.rsp_type != 1) - { - SLOGE("data read error from server...\n"); - goto Free_and_Error; - } - // copy the last data (last count) - if(send_data->count == (count - 1)) - { - memcpy(buffer, recv_data.buffer, rest); - *readLen += (size_t)rest; - goto Last; - //break; - } - - memcpy(buffer, recv_data.buffer, MAX_RECV_DATA_LEN); - *readLen += (size_t)recv_data.readLen; - buffer += recv_data.readLen; - } -Last : - if(bufLen != *readLen) - { - SLOGE("Decrypted abnormally\n"); - recv_data.rsp_type = SS_DECRYPTION_ERROR; - goto Free_and_Error; - } - - SECURE_SLOGD("Decrypted file name : %s\n", recv_data.data_filepath); -Free_and_Error: - free(send_data); -Error: - return recv_data.rsp_type; -} - -int SsClientGetInfo(const char* filepath, ssm_file_info_t* sfi, ssm_flag flag, const char* group_id) -{ - - ReqData_t* send_data = NULL; - RspData_t recv_data; - ssm_file_info_convert_t sfic; - int temp_len = 0; - int cookie_size = 20; - -// cookie_size = security_server_get_cookie_size(); - char cookie_content[20] = {0, }; - -// if(security_server_request_cookie(cookie_content, cookie_size) < 0) // error while getting cookie -// { -// SLOGE("Fail to get cookie\n"); -// recv_data.rsp_type = SS_SECURE_STORAGE_ERROR; -// goto Error; -// } - - if(!filepath || !sfi) - { - SLOGE("Parameter error in SsClientGetInfo..\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Error; - } - - send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); - - if(!send_data) - { - SLOGE("Memory allocation fail in SsClientGetInfo..\n"); - recv_data.rsp_type = SS_MEMORY_ERROR; - goto Error; - } - - // fill send_data - send_data->req_type = 4; // get info type - send_data->enc_type = 1; // initial type - send_data->count = 0; - send_data->flag = flag & 0x000000ff; //flag; - temp_len = strlen(filepath); - if(temp_len < MAX_FILENAME_LEN) - { - strncpy(send_data->data_infilepath, filepath, MAX_FILENAME_LEN - 1); - send_data->data_infilepath[temp_len] = '\0'; - } - else - { - SLOGE("filepath is too long.\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Free_and_Error; - } - memset(send_data->cookie, 0x00, MAX_COOKIE_LEN); - memset(send_data->group_id, 0x00, MAX_GROUP_ID_LEN); - memcpy(send_data->cookie, cookie_content, cookie_size); - if(group_id) - strncpy(send_data->group_id, group_id, MAX_GROUP_ID_LEN - 1); - else - strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_LEN - 1); - memset(send_data->buffer, 0x00, MAX_SEND_DATA_LEN + 1); - - recv_data = SsClientComm(send_data); - - memcpy(sfic.fInfoArray, recv_data.buffer, sizeof(ssm_file_info_t)); - sfi->originSize = sfic.fInfoStruct.originSize; - sfi->storedSize = sfic.fInfoStruct.storedSize; - memcpy(sfi->reserved, sfic.fInfoStruct.reserved, 8); - -Free_and_Error: - free(send_data); -Error: - return recv_data.rsp_type; -} - -int SsClientDeleteFile(const char *pFilePath, ssm_flag flag, const char* group_id) -{ - ReqData_t* send_data = NULL; - RspData_t recv_data; - int temp_len = 0; - int cookie_size = 20; - -// cookie_size = security_server_get_cookie_size(); - char cookie_content[20] = {0, }; - -// if(security_server_request_cookie(cookie_content, cookie_size) < 0) // error while getting cookie -// { -// SLOGE("Fail to get cookie\n"); -// recv_data.rsp_type = SS_SECURE_STORAGE_ERROR; -// goto Error; -// } - - if(!pFilePath) - { - SLOGE("Parameter error in SsClientDeleteFile..\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Error; - } - - send_data = (ReqData_t*)malloc(sizeof(ReqData_t)); - - if(!send_data) - { - SLOGE("Memory allocation fail in SsClientDeleteFile..\n"); - recv_data.rsp_type = SS_MEMORY_ERROR; - goto Error; - } - - send_data->req_type = 10; // delete file - send_data->enc_type = 1; // initial type - send_data->count = 0; - send_data->flag = flag; // flag - temp_len = strlen(pFilePath); - if(temp_len < MAX_FILENAME_LEN) - { - strncpy(send_data->data_infilepath, pFilePath, MAX_FILENAME_LEN - 1); - send_data->data_infilepath[temp_len] = '\0'; - } - else - { - SLOGE("filepath is too long.\n"); - recv_data.rsp_type = SS_PARAM_ERROR; - goto Free_and_Error; - } - memset(send_data->cookie, 0x00, MAX_COOKIE_LEN); - memset(send_data->group_id, 0x00, MAX_GROUP_ID_LEN); - memcpy(send_data->cookie, cookie_content, cookie_size); - if(group_id) - strncpy(send_data->group_id, group_id, MAX_GROUP_ID_LEN - 1); - else - strncpy(send_data->group_id, "NOTUSED", MAX_GROUP_ID_LEN - 1); - memset(send_data->buffer, 0x00, MAX_SEND_DATA_LEN+1); - - recv_data = SsClientComm(send_data); - -Free_and_Error: - free(send_data); - - SECURE_SLOGD("Deleted file name: %s\n", recv_data.data_filepath); - -Error: - return recv_data.rsp_type; -} - - -////////////////////////////// -__attribute__((visibility("hidden"))) -int DoCipher(const char* pInputBuf, int inputLen, char** ppOutBuf, int* pOutBufLen, char* pKey, int encryption) -{ - static const unsigned char iv[16] = {0xbd, 0xc3, 0xc5, 0xa5, 0xb8, 0xae, 0xc6, 0xbc, 0x20, 0xb3, 0xeb, 0xb0, 0xe6, 0xbf, 0xec, 0x20}; - struct evp_cipher_st* pCipherAlgorithm = NULL; - EVP_CIPHER_CTX cipherCtx; - int tempLen = 0; - int result = 0; - int finalLen = 0; - - pCipherAlgorithm = EVP_aes_256_cbc(); - tempLen = (int)((inputLen / pCipherAlgorithm->block_size + 1) * pCipherAlgorithm->block_size); - - *ppOutBuf = (char*)calloc(tempLen, 1); - EVP_CIPHER_CTX_init(&cipherCtx); - - result = EVP_CipherInit(&cipherCtx, pCipherAlgorithm, (const unsigned char*)pKey, iv, encryption); - if(result != 1) - { - SLOGE("[%s] EVP_CipherInit failed", result); - goto Error; - } - - result = EVP_CIPHER_CTX_set_padding(&cipherCtx, 1); - if(result != 1) - { - SLOGE("[%d] EVP_CIPHER_CTX_set_padding failed", result); - goto Error; - } - - //cipher update operation - result = EVP_CipherUpdate(&cipherCtx, (unsigned char*)*ppOutBuf, pOutBufLen, (const unsigned char*)pInputBuf, inputLen); - if(result != 1) - { - SLOGE("[%d] EVP_CipherUpdate failed", result); - goto Error; - } - - //cipher final operation - result = EVP_CipherFinal(&cipherCtx, (unsigned char*)*ppOutBuf + *pOutBufLen, &finalLen); - if(result != 1) - { - SLOGE("[%d] EVP_CipherFinal failed", result); - goto Error; - } - *pOutBufLen = *pOutBufLen + finalLen; - goto Last; -Error: - result = SS_ENCRYPTION_ERROR; - free(*ppOutBuf); - -Last: - EVP_CIPHER_CTX_cleanup(&cipherCtx); - if((result != 1) && (encryption != 1)) - result = SS_DECRYPTION_ERROR; - - return result; -} - -int SsClientEncrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen) -{ - int result = 1; - char* pDuk = NULL; - - if(!pAppId || idLen == 0 || !pBuffer || bufLen ==0) - { - SLOGE("Parameter error in SsClientEncrypt"); - result = SS_PARAM_ERROR; - goto Error; - } - - pDuk = GetDeviceUniqueKey(pAppId, idLen, 32); - - if(DoCipher(pBuffer, bufLen, ppEncryptedBuffer, pEncryptedBufLen, pDuk, 1) != 1) - { - SLOGE("failed to encrypt data"); - result = SS_ENCRYPTION_ERROR; - goto Error; - } - - result = 1; - -Error: - if(pDuk) - free(pDuk); - return result; -} - -int SsClientDecrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen) -{ - int result = 1; - char* pDuk = NULL; - - if(!pAppId || idLen == 0 || !pBuffer || bufLen ==0) - { - SLOGE("Parameter error in SsClientDecrypt"); - result = SS_PARAM_ERROR; - goto Error; - } - - pDuk = GetDeviceUniqueKey(pAppId, idLen, 32); - - if(DoCipher(pBuffer, bufLen, ppDecryptedBuffer, pDecryptedBufLen, pDuk, 0) != 1) - { - SLOGE("failed to decrypt data\n"); - result = SS_DECRYPTION_ERROR; - goto Error; - } - result = 1; - -Error: - if(pDuk) - free(pDuk); - return result; -} - -int SsClientEncryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen) -{ - int result = 0; - char duk[36] = {0,}; - - if(!pBuffer || bufLen ==0) - { - SLOGE("Parameter error"); - result = SS_PARAM_ERROR; - goto Final; - } - - if(DoCipher(pBuffer, bufLen, ppEncryptedBuffer, pEncryptedBufLen, duk, 1) != 1) - { - SLOGE("failed to decrypt data"); - result = SS_ENCRYPTION_ERROR; - goto Final; - } - - result = 1; - -Final: - return result; -} - -int SsClientDecryptPreloadedApplication(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen) -{ - int result = 0; - char duk[36] = {0,}; - - if(!pBuffer || bufLen ==0) - { - SLOGE("Parameter error"); - result = SS_PARAM_ERROR; - goto Final; - } - - if(DoCipher(pBuffer, bufLen, ppDecryptedBuffer, pDecryptedBufLen, duk, 0) != 1) - { - SLOGE("failed to decrypt data"); - result = SS_DECRYPTION_ERROR; - goto Final; - } - - result = 1; - -Final: - return result; -} diff --git a/client/src/ss_client_ipc.c b/client/src/ss_client_ipc.c deleted file mode 100644 index ec18c7d..0000000 --- a/client/src/ss_client_ipc.c +++ /dev/null @@ -1,103 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "ss_client_ipc.h" -#include "secure_storage.h" - -RspData_t SsClientComm(ReqData_t* client_data) -{ - int sockfd = 0; - int client_len = 0; - struct sockaddr_un clientaddr; - ReqData_t send_data = {0, }; - RspData_t recv_data = {0, }; - int temp_len_in = 0; - int temp_len_sock = 0; - int cookie_size = 20; - - send_data.req_type = client_data->req_type; - send_data.enc_type = client_data->enc_type; - send_data.count = client_data->count; - send_data.flag = client_data->flag; - - temp_len_in = strlen(client_data->data_infilepath); - - strncpy(send_data.data_infilepath, client_data->data_infilepath, MAX_FILENAME_LEN - 1); - send_data.data_infilepath[temp_len_in] = '\0'; - -// cookie_size = security_server_get_cookie_size(); - memcpy(send_data.cookie, client_data->cookie, cookie_size); - strncpy(send_data.group_id, client_data->group_id, MAX_GROUP_ID_LEN - 1); - - memcpy(send_data.buffer, client_data->buffer, MAX_SEND_DATA_LEN); - - if((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) - { - SLOGE("Error in function socket()..\n"); - recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_exit; - } - - temp_len_sock = strlen(SS_SOCK_PATH); - - bzero(&clientaddr, sizeof(clientaddr)); - clientaddr.sun_family = AF_UNIX; - strncpy(clientaddr.sun_path, SS_SOCK_PATH, temp_len_sock); - clientaddr.sun_path[temp_len_sock] = '\0'; - client_len = sizeof(clientaddr); - - if(connect(sockfd, (struct sockaddr*)&clientaddr, client_len) < 0) - { - SLOGE("Error in function connect()..\n"); - recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_close_exit; - } - - if(write(sockfd, (char*)&send_data, sizeof(send_data)) < 0) - { - SLOGE("Error in function write()..\n"); - recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_close_exit; - } - - if(read(sockfd, (char*)&recv_data, sizeof(recv_data)) < 0) - { - SLOGE("Error in function read()..\n"); - recv_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_close_exit; - } - -Error_close_exit: - close(sockfd); - -Error_exit: - return recv_data; -} diff --git a/client/src/ss_manager.c b/client/src/ss_manager.c deleted file mode 100755 index 2edda6f..0000000 --- a/client/src/ss_manager.c +++ /dev/null @@ -1,316 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include -#include - -#include "secure_storage.h" -#include "ss_client_intf.h" - -#ifndef SS_API -#define SS_API __attribute__((visibility("default"))) -#endif - -/***************************************************************************** - * Internal Functions - *****************************************************************************/ -SS_API -int ssm_getinfo(const char* pFilePath, ssm_file_info_t *sfi, ssm_flag flag, const char* group_id) -{ - int ret = 0; - - if(!pFilePath || !sfi) - { - SLOGE("Parameter error in ssm_getinfo()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientGetInfo(pFilePath, sfi, flag, group_id); - - if(ret == 1) - { - SLOGI("Getinfo Success.\n"); - ret = 0; // return true - } - else - SLOGE("Getinfo Fail.\n"); - -Error: - return -(ret); -} - -/***************************************************************************** - * Manager APIs - *****************************************************************************/ -SS_API -int ssm_write_file(const char* pFilePath, ssm_flag flag, const char* group_id) -{ - int ret = 0; - - if(!pFilePath) - { - SLOGE("Parameter error in ssm_write_file()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - if(flag <= SSM_FLAG_NONE || flag >= SSM_FLAG_MAX) - { - SLOGE("Parameter error in ssm_write_file()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientDataStoreFromFile(pFilePath, flag, group_id); - if(ret == 1) - { - if(unlink(pFilePath) != 0) // if fail - { - SLOGE("unlink fail. [%s]\n", pFilePath); - return -1; // return false - } - SLOGI("Write file Success.\n"); - return 0; // return true - } - else - SLOGE("Write file Fail.\n"); - -Error: - return -(ret); -} - -SS_API -int ssm_write_buffer(char* pWriteBuffer, size_t bufLen, const char* pFileName, ssm_flag flag, const char* group_id) -{ - int ret = 0; - - if(!pWriteBuffer || !pFileName || (pFileName[0] == '/')) - { - SLOGE("Parameter error in ssm_write_buffer()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - if(bufLen <= 0 || bufLen > 4096) - { - SLOGE("Parameter error in ssm_write_buffer()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - if(flag <= SSM_FLAG_NONE || flag >= SSM_FLAG_MAX) - { - SLOGE("Parameter error in ssm_write_buffer()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientDataStoreFromBuffer(pWriteBuffer, bufLen, pFileName, flag, group_id); - if(ret == 1) - { - SLOGI("Write buffer Success.\n"); - return 0; // return true - } - else - SLOGE("Write buffer Fail.\n"); - -Error: - return -(ret); -} - -SS_API -int ssm_read(const char* pFilePath, char* pRetBuf, size_t bufLen, size_t *readLen, ssm_flag flag, const char* group_id) -{ - int ret = 0; - ssm_file_info_t sfi; - - if(!pFilePath || !pRetBuf) - { - SLOGE("Parameter error in ssm_read()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - if(!readLen) - { - SLOGE("Parameter error in ssm_read()...\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - // get info - ret = ssm_getinfo(pFilePath, &sfi, flag, group_id); - if(ret != 0) // ret != true? - { - SLOGE("getinfo error in ssm_read()..\n"); - goto Error; - } - // in case of flag mismatch... - // check flag... - // To do : - if((bufLen > sfi.originSize) || (sfi.reserved[0] != (flag & 0x000000ff))) - { - SLOGE("Flag mismatch or buffer length error in ssm_read()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientDataRead(pFilePath, pRetBuf, sfi.originSize, readLen, flag, group_id); - - if(ret == 1) - { - SLOGI("Read Success.\n"); - return 0; // return true - } - else - SLOGE("Read Fail.\n"); - -Error: - return -(ret); -} - -SS_API -int ssm_delete_file(const char *pFilePath, ssm_flag flag, const char* group_id) -{ - int ret = 0; - - if(!pFilePath) - { - SLOGE("Parameter error in ssm_delete_file()..\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientDeleteFile(pFilePath, flag, group_id); - - if(ret == 1) // success - { - SLOGI("Delete file Success.\n"); - return 0; - } - else // fail - SLOGE("Delete file Fail.\n"); - -Error: - return -(ret); -} - -SS_API -int ssm_encrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen) -{ - int ret = 0; - - if(!pAppId || idLen == 0 || !pBuffer || bufLen ==0) - { - SLOGE("Parameter error.\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientEncrypt(pAppId, idLen, pBuffer, bufLen, ppEncryptedBuffer, pEncryptedBufLen); - - if(ret == 1) // success - { - SLOGI("Application encryption succeeded.\n"); - return 0; - } - else // fail - SLOGE("Application encryption failed.\n"); - -Error: - return -(ret); -} - -SS_API -int ssm_decrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen) -{ - int ret = 0; - - if(!pAppId || idLen == 0 || !pBuffer || bufLen ==0) - { - SLOGE("Parameter error.\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientDecrypt(pAppId, idLen, pBuffer, bufLen, ppDecryptedBuffer, pDecryptedBufLen); - - if(ret == 1) // success - { - SLOGI("Application decryption succeeded.\n"); - return 0; - } - else // fail - SLOGE("Application decryption failed.\n"); - -Error: - return -(ret); -} - -SS_API -int ssm_encrypt_preloaded_application(const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen) -{ - int ret = 0; - - if(!pBuffer || bufLen ==0) - { - SLOGE("Parameter error.\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientEncryptPreloadedApplication(pBuffer, bufLen, ppEncryptedBuffer, pEncryptedBufLen); - if(ret == 1) // success - { - SLOGI("Application decryption succeeded.\n"); - return 0; - } - else // fail - SLOGE("Application decryption failed.\n"); - -Error: - return -(ret); -} - -SS_API -int ssm_decrypt_preloaded_application(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen) -{ - int ret = 0; - - if(!pBuffer || bufLen ==0) - { - SLOGE("Parameter error.\n"); - ret = SS_PARAM_ERROR; - goto Error; - } - - ret = SsClientDecryptPreloadedApplication(pBuffer, bufLen, ppDecryptedBuffer, pDecryptedBufLen); - if(ret == 1) // success - { - SLOGI("Application decryption succeeded.\n"); - return 0; - } - else // fail - SLOGE("Application decryption failed.\n"); - -Error: - return -(ret); -} diff --git a/debian/changelog b/debian/changelog index fac1b78..a91caad 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,7 +1,6 @@ secure-storage (0.12.7-18) unstable; urgency=low * randomize initial vector of AES_cbc cryptographic algorithm - * Git: slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-18 -- Kidong Kim Mon, 14 May 2012 12:00:40 +0900 @@ -9,7 +8,6 @@ secure-storage (0.12.7-18) unstable; urgency=low secure-storage (0.12.7-17) unstable; urgency=low * flush and sync encrypted file - * Git: slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-17 -- Kidong Kim Tue, 08 May 2012 17:24:23 +0900 @@ -17,7 +15,6 @@ secure-storage (0.12.7-17) unstable; urgency=low secure-storage (0.12.7-16) unstable; urgency=low * sync encrypted file in order to prepare unexpected power down - * Git: slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-16 -- Kidong Kim Mon, 23 Apr 2012 16:55:36 +0900 @@ -25,7 +22,6 @@ secure-storage (0.12.7-16) unstable; urgency=low secure-storage (0.12.7-15) unstable; urgency=low * change starting order of ss-server - * Git: slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-15 -- Kidong Kim Thu, 19 Jan 2012 16:06:30 +0900 @@ -34,7 +30,6 @@ secure-storage (0.12.7-14) unstable; urgency=low * 11/12/20 * - remove systemd dependency - * Git: slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-14 -- Kidong Kim Tue, 20 Dec 2011 15:03:23 +0900 @@ -43,7 +38,6 @@ secure-storage (0.12.7-13) unstable; urgency=low * 11/12/07 * - add boiler-plate on testcases - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-13 -- Kidong Kim Wed, 07 Dec 2011 09:55:30 +0900 @@ -52,7 +46,6 @@ secure-storage (0.12.7-12) unstable; urgency=low * 11/12/02 * - change license : LGPL -> apache - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-12 -- Kidong Kim Fri, 02 Dec 2011 17:02:00 +0900 @@ -60,7 +53,6 @@ secure-storage (0.12.7-12) unstable; urgency=low secure-storage (0.12.7-11) unstable; urgency=low * fix install file - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-11 -- Kidong Kim Mon, 17 Oct 2011 13:58:06 +0900 @@ -68,7 +60,6 @@ secure-storage (0.12.7-11) unstable; urgency=low secure-storage (0.12.7-10) unstable; urgency=low * add testcases - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-10 -- Kidong Kim Fri, 14 Oct 2011 14:10:04 +0900 @@ -76,7 +67,6 @@ secure-storage (0.12.7-10) unstable; urgency=low secure-storage (0.12.7-9) unstable; urgency=low * fix boiler-plate - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-9 -- Kidong Kim Wed, 13 Jul 2011 10:23:26 +0900 @@ -84,7 +74,6 @@ secure-storage (0.12.7-9) unstable; urgency=low secure-storage (0.12.7-8) unstable; urgency=low * fix strncpy problem - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-8 -- Kidong Kim Wed, 16 Feb 2011 10:07:00 +0900 @@ -92,7 +81,6 @@ secure-storage (0.12.7-8) unstable; urgency=low secure-storage (0.12.7-7) unstable; urgency=low * fix prevent bugs - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-7 -- Kidong Kim Thu, 20 Jan 2011 16:52:02 +0900 @@ -100,7 +88,6 @@ secure-storage (0.12.7-7) unstable; urgency=low secure-storage (0.12.7-6) unstable; urgency=low * fix double free and strtoul problem - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-6 -- Kidong Kim Tue, 04 Jan 2011 15:09:08 +0900 @@ -108,7 +95,6 @@ secure-storage (0.12.7-6) unstable; urgency=low secure-storage (0.12.7-5) unstable; urgency=low * fix postinst script - * Git: 165.213.180.234:slp/pkgs/s/secure-storage * Tag: secure-storage_0.12.7-5 -- Kidong Kim Wed, 15 Dec 2010 10:15:03 +0900 @@ -116,7 +102,6 @@ secure-storage (0.12.7-5) unstable; urgency=low secure-storage (0.12.7-4) unstable; urgency=low * fix strip problem - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.7-4 -- Kidong Kim Wed, 01 Dec 2010 10:34:18 +0900 @@ -124,7 +109,6 @@ secure-storage (0.12.7-4) unstable; urgency=low secure-storage (0.12.7-3) unstable; urgency=low * add boilerplate in test codes - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.7-3 -- Kidong Kim Fri, 26 Nov 2010 15:32:47 +0900 @@ -132,7 +116,6 @@ secure-storage (0.12.7-3) unstable; urgency=low secure-storage (0.12.7-2) unstable; urgency=low * add new testcases - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.7-2 -- Kidong Kim Wed, 24 Nov 2010 15:48:28 +0900 @@ -140,7 +123,6 @@ secure-storage (0.12.7-2) unstable; urgency=low secure-storage (0.12.7-1) unstable; urgency=low * fix doxygen and add new configuration file - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.7-1 -- Kidong Kim Fri, 12 Nov 2010 18:33:40 +0900 @@ -148,7 +130,6 @@ secure-storage (0.12.7-1) unstable; urgency=low secure-storage (0.12.6-1) unstable; urgency=low * modify APIs - add new parameter 'group_id' - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.6-1 -- Kidong Kim Wed, 03 Nov 2010 09:20:55 +0900 @@ -156,7 +137,6 @@ secure-storage (0.12.6-1) unstable; urgency=low secure-storage (0.12.5-11) unstable; urgency=low * fix doxygen - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.5-11 -- Kidong Kim Wed, 27 Oct 2010 15:01:16 +0900 @@ -164,7 +144,6 @@ secure-storage (0.12.5-11) unstable; urgency=low secure-storage (0.12.5-10) unstable; urgency=low * fix bug - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.5-10 -- Kidong Kim Fri, 22 Oct 2010 18:52:59 +0900 @@ -172,7 +151,6 @@ secure-storage (0.12.5-10) unstable; urgency=low secure-storage (0.12.5-9) unstable; urgency=low * add new boiler-plate - * Git: 165.213.180.234:/git/slp/pkgs/secure-strage * Tag: secure-storage_0.12.5-9 -- Kidong Kim Fri, 22 Oct 2010 17:49:33 +0900 @@ -180,7 +158,6 @@ secure-storage (0.12.5-9) unstable; urgency=low secure-storage (0.12.5-8) unstable; urgency=low * make another symbolic link - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.5-8 -- Kidong Kim Mon, 18 Oct 2010 14:15:03 +0900 @@ -188,7 +165,6 @@ secure-storage (0.12.5-8) unstable; urgency=low secure-storage (0.12.5-7) unstable; urgency=low * delete some useless APIs - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.5-7 -- Kidong Kim Fri, 15 Oct 2010 16:58:32 +0900 @@ -196,7 +172,6 @@ secure-storage (0.12.5-7) unstable; urgency=low secure-storage (0.12.5-6) unstable; urgency=low * modify doxygen group - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.5-6 -- Kidong Kim Mon, 27 Sep 2010 18:01:20 +0900 @@ -204,7 +179,6 @@ secure-storage (0.12.5-6) unstable; urgency=low secure-storage (0.12.5-5) unstable; urgency=low * change copyright context - * Git: 165.213.180.234:/git/slp/pkgs/secure-storage * Tag: secure-storage_0.12.5-5 -- Kidong Kim Tue, 31 Aug 2010 14:14:00 +0900 @@ -212,7 +186,6 @@ secure-storage (0.12.5-5) unstable; urgency=low secure-storage (0.12.5-4) unstable; urgency=low * add new API - ssm_delete_file - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.5-4 -- Kidong Kim Sat, 12 Jun 2010 14:44:21 +0900 @@ -220,7 +193,6 @@ secure-storage (0.12.5-4) unstable; urgency=low secure-storage (0.12.5-3) unstable; urgency=low * delete deprecated values - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.5-3 -- Kidong Kim Sat, 05 Jun 2010 13:38:31 +0900 @@ -228,7 +200,6 @@ secure-storage (0.12.5-3) unstable; urgency=low secure-storage (0.12.5-2) unstable; urgency=low * modify deprecated method - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.5-2 -- Kidong Kim Mon, 24 May 2010 20:41:56 +0900 @@ -236,7 +207,6 @@ secure-storage (0.12.5-2) unstable; urgency=low secure-storage (0.12.5-1) unstable; urgency=low * change API names and data structure names - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.5-1 -- Kidong Kim Mon, 24 May 2010 18:13:20 +0900 @@ -244,7 +214,6 @@ secure-storage (0.12.5-1) unstable; urgency=low secure-storage (0.12.4-6) unstable; urgency=low * fix uploader info - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.4-6 -- Kidong Kim Wed, 19 May 2010 13:58:43 +0900 @@ -252,7 +221,6 @@ secure-storage (0.12.4-6) unstable; urgency=low secure-storage (0.12.4-5) unstable; urgency=low * give a 777permission to socket - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.4-5 -- root Wed, 19 May 2010 11:43:59 +0900 @@ -260,7 +228,6 @@ secure-storage (0.12.4-5) unstable; urgency=low secure-storage (0.12.4-4) unstable; urgency=low * fix tagging problem - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.4-4 -- Kidong Kim Mon, 19 Apr 2010 18:24:05 +0900 @@ -282,7 +249,6 @@ secure-storage (0.12.4-2) unstable; urgency=low secure-storage (0.12.4-1) unstable; urgency=low * fix problem regarding version - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.12.4-1 -- Kidong Kim Mon, 12 Apr 2010 21:35:23 +0900 @@ -320,7 +286,6 @@ secure-storage (0.12.1-1) unstable; urgency=low secure-storage (0.2.1-1) unstable; urgency=low * case of inhouse package - * Git: 165.213.180.234:/git/slp2.0/slp2.0-pkgs/secure-storage-0 * Tag: secure-storage_0.2.1-1 -- Kidong Kim Thu, 08 Apr 2010 12:07:01 +0900 diff --git a/doc/secure_storage_doc.h b/doc/secure_storage_doc.h new file mode 100644 index 0000000..7945567 --- /dev/null +++ b/doc/secure_storage_doc.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 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_LIB_SECURE_STORAGE_DOC_H__ +#define __TIZEN_CORE_LIB_SECURE_STORAGE_DOC_H__ +/** + * @ingroup StorageFW + * @defgroup CAPI_SECURE_STORAGE_MODULE Secure Storage + * @brief The Secure Storage API provides functions for encryption, decryption and putting, getting application data to secure storage + * @section CAPI_SECURE_STORAGE_MODULE_HEADER Required Header + * \#include + * @section CAPI_SECURE_STORAGE_MODULE_OVERVIEW Overview + * It provides functions for putting/getting (ssa_put(), ssa_get()) and encrypting/decrypting(ssa_encrypt()/ssa_decrypt()) application data. + */ + +#endif diff --git a/image/SLP_secure-storage_PG_image001.png b/image/SLP_secure-storage_PG_image001.png new file mode 100755 index 0000000..325dc70 Binary files /dev/null and b/image/SLP_secure-storage_PG_image001.png differ diff --git a/image/SLP_secure-storage_PG_image002.png b/image/SLP_secure-storage_PG_image002.png new file mode 100755 index 0000000..245ddcd Binary files /dev/null and b/image/SLP_secure-storage_PG_image002.png differ diff --git a/include/SLP_secure-storage_PG.h b/include/SLP_secure-storage_PG.h new file mode 100755 index 0000000..8a54815 --- /dev/null +++ b/include/SLP_secure-storage_PG.h @@ -0,0 +1,520 @@ +/** + * + * @ingroup SLP_PG + * @defgroup SecureStorage_PG Secure Storage +@{ + +

Introduction

+ +

Goal

+The purpose of the document is to explain the method to use Secure Storage for developing SLP. + +

Scope

+This document can be referenced by SCM engineers and SLP developers. + +

Introduction

+Secure storage is a kind of technology to store data securely, implemented by using cryptographic techniques. Distributed Secure storage Manager provides APIs so that other applications can tighten up security by using Secure storage Engine. +When user wants to store data, he(or she) can store data securely by using APIs provided by Secure storage. + +

Requirements

+OpenSSL +- Cryptographic APIs of Secure storage refer to the OpenSSL libraries, the OpenSSL module MUST be prepared before building Secure storage module. + - # apt-get install openssl +- OpenSSL module is included in the SDK basically. In general, you don't care about that. + +

Abbreviations

+ + + + + + + + + + +
SLPSamsung Linux Platform
  
  
+ + +

Architecture

+The Secure storage module is implemented by C language. + +

System Architecture

+@image html SLP_secure-storage_PG_image001.png +The figure shown above is the architecture of Secure Storage which now implemented in SLP. The Secure Storage is implemented as a Server/Client model, using Unix Socket communication between the Server and Client. The user application utilizes Secure Storage operation by using APIs provided by the Manager. + +

File Structure

+@image html SLP_secure-storage_PG_image002.png +The figure shown above is the structure of a file stored in Secure Storage. The file's metadata is added in a header before the actual data and is extendable. + +

Source code Architecture

+- Server + - ss_server_ipc.c : processing communication of server + - ss_server_main.c : actual cryptographic function (encrypt / decrypt) +- Client + - ss_client_ipc : processing communication of client + - ss_client_intf : processing request and reply of server + - ss_manager : the high-ranked APIs which are used by other applications + +

Result of Build

+If build of Secure storage module is success, results of build are as below: +- libss-client.so : shared library for providing manager APIs (/usr/lib) +- ss-server : executable for operating Secure storage Server (/usr/bin) +- ss_manager.h : header file for providing APIs and data structures (/usr/include + + +

APIs

+The APIs are classified by three categories - Store, Read and get information. + +

Data Store

+- Data Store 1 + + + + + + + + + + + + + + + + + + + + + + +
API Namessm_write_file()
Input Paramchar* pFilePathpath of file to be stored in Secure Storage
ssm_flag flagtype of file to be stored
const char* group_idgroup name to be shared, if not, NULL
Output ParamNone
Include Filess_manager.h
Return ValueReturn Type : INT
If 0, Success
If <0, Fail
+ - Store file in the Secure Storage. The original file will be deleted after storing. The 'pFilePath' is written in absolute path. To use data type, refer to 'Type Definition 1'. + +- Data Store 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
API Namessm_write_buffer()
Input Paramchar* pWriteBufferbuffer pointer of data to be stored in Secure storage
size_t bufLensize of buffer
char* pFileNamefile name to be used in Secure Storage
ssm_flag flagtype of file to be stored
const char* group_idgroup name to be shared, if not, NULL
Output ParamNone
Include Filess_manager.h
Return ValueReturn Type : INT
If 0, Success
If <0, Fail
+ - Encrypt buffer content and store that in the Secure Storage in the file form. The 'pFileName' is real file name which be stored in the Secure Storage and is not absolute path but single file name. For example, that is not 'mydata/abc.txt', but 'abc.txt'. The 'bufLen' has length from 0 to 4KB(4096). To use data type, refer to chapter 'Type Definition 1'. + +

Data Information

+- Data Information + + + + + + + + + + + + + + + + + + + + + + + + + +
API Namessm_getinfo()
Input Paramchar* pFilePathfile name or path to be stored in secure storage
ssm_flag flagtype of file to be stored
ssm_file_info_t* sfidata structure or information of the file
const char* group_idgroup name to be shared, if not, NULL
Output ParamNone
Include Filess_manager.h
Return ValueReturn Type : INT
If 0, Success
If <0, Fail
+ - Get information about file that you want to read. You can use 'originSize' of 'ssm_file_info_t' data structure to parameter 'bufLen' of SSM_Read() function. To use data type, refer to 'Type Definition 1'. + +

Data Read

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
API Namessm_read()
Input Paramchar* pFilePathfile name or path to be read in secure storage
size_t bufLenlength of data to be read
ssm_flag flagdata type to be read
const char* group_idgroup name to be shared, if not, NULL
Output Paramchar* pRetBufbuffer for decrypted data
size_t* readLenlength of data that this function read
Include Filess_manager.h
Return ValueReturn Type : INT
If 0, Success
If <0, Fail
+ - Read contents of file stored in Secure Storage to buffer. When coding, please note the following. + -# The 'flag' of required data MUST be same as the 'flag' of stored data. + -# The 'pFilePath' is absolute path or file name. In case of ssm_write_file(), use the absolute path, and in case of ssm_write_buffer(), use a file name. + -# The 'pRetBuf' should be a pointer of already allocated memory. (Secure Storage does not allocate memory itself.) + -# When using 'pRetBuf', do not use "string function" but "memory function". (It may include NULL bytes.) + string function : strcpy, strlen, strcat, fputs, fgets, ... + memory function : memcpy, memset, fwrite, fread, ... +@code +int ret; +size_t bufLen, readLen; +ssm_file_info_t sfi; +char* buffer = NULL; +... +ssm_getinfo("/abc/def/ghi", &sfi, SSM_FLAG_DATA); +... +buffer = (char*)malloc(sfi.originSize + 1); +bufLen = sfi.originSize; +... +ret = ssm_read("/abc/def/ghi", buffer, bufLen, &readLen, SSM_FLAG_DATA); +... +@endcode + +

Delete File

+- Delete encrypted file + + + + + + + + + + + + + + + + + + + + + + +
API Namessm_delete_file()
Input Paramchar* pFilePathpath of file to be deleted from Secure Storage
ssm_flag flagtype of file to be deleted
const char* group_idgroup name to be shared, if not, NULL
Output ParamNone
Include Filess_manager.h
Return ValueReturn Type : INT
If 0, Success
If <0, Fail
+ - Use when user want to delete file in Secure-storage. If you use the function ssm_write_file( ) or ssm_write_buffer( ) when storing in Secure-storage, you should use this function in order to delete those files. The flag MUST be identical with one which was used when storing. + +

Type Definition

+- Type Definition 1 + + + + + + + + + + + +
Type Namessm_flag
Members + typedef enum {
+     SSM_FLAG_NONE = 0x00,
+     SSM_FLAG_DATA,
+     SSM_FLAG_SECRET_PRESERVE,
+     SSM_FLAG_SECRET_OPERATION,
+     SSM_FLAG_MAX
+ } SSM_FLAG +
Include Filess_manager.h
+ - The flag for separating contents of file to be stored in Secure Storage. Secure storage API requires the flag information. + -# SSM_FLAG_DATA : general data for user. (picture, movie, memo, etc.) + -# SSM_FLAG_SECRET_PRESERVE : the secret data for preservation. + -# SSM_FLAG_SECRET_OPERATION : the secret data to be renewed. + +- Type Definition 2 + + + + + + + + + + + +
Type Namessm_file_info_t
Members + typedef struct {
+     unsigned int originSize;
+     insigned int storedSize;
+     char reserved[8];
+ } ssm_file_info_t
+
Include Filess_manager.h
+ - The data structure for storing metadata of file to be stored in Secure Storage. After encrypting, file size will be increased because of cryptographic block size. Therefore store before and after file size. 1bytes of reserved 8bytes is used for storing flag information. + +

Error Definition

+- Error Definition + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Error NameValue
HexDecimal
SS_PARAM_ERROR0x000000022
SS_FILE_TYPE_ERROR0x000000033
SS_FILE_OPEN_ERROR0x000000044
SS_FILE_READ_ERROR0x000000055
SS_FILE_WRITE_ERROR0x000000066
SS_MEMORY_ERROR0x000000077
SS_SOCKET_ERROR0x000000088
SS_ENCRYPTION_ERROR0x000000099
SS_DECRYPTION_ERROR0x0000000a10
SS_SIZE_ERROR0x0000000b11
SS_SECURE_STORAGE_ERROR0x0000000c12
SS_PERMISSION_ERROR0x0000000d13
+ - The error codes are defined in ss_manager.h. The actual return value of Secure Storage API is the negative form of the defined value. + +

File System Synchronization (Recommended)

+- When writing a file to Secure Storage using ssm_write_file() or ssm_write_buffer(), if it powers down unexpectedly, the data will not be recorded properly in the filesystem. To prevent this from happening, your application should call the sync() function. + + + + +
+ POSIX Programmer's manual
+
+ NAME
+     sync - schedule file system updates
+
+ SYNOPSIS +     #include
+
+     void sync(void);
+
+ DESCRIPTION
+     The sync() function shall cause all information in memory that updates file systems to be scheduled for writing out to all file systems.
+
+     The writing, although scheduled, is not necessarily complete upon return from sync().
+
+ RETURN VALUE
+     The sync() function shall not return a value.
+
+ ERRORS
+     No errors are defined.
+
+     The following sections are informative.
+
+ EXAMPLES
+     None
+
+ APPLICATION USAGE
+     None
+
+ RATIONALE
+     None
+
+ FUTURE DIRECTIONS
+     None
+
+ SEE ALSO
+     fsync() , the Base Definitions volume of IEEE Std 1003.1-2001,
+
+ COPYRIGHT
+     Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.open-group.org/unix/online.html.
+
+ + +

Implementation Guide

+

A note of caution when implementing

+- General particular + - The 'group_id' parameter is very important portion in Secure Storage module. + - In general cases, when an application stores some file in Secure Storage, he(or she) NEVER want to expose that file to other applications. + - Therefore, all applications should have their independent storage in Secure Storage. + - But in some cases, two or more applications should share same encrypted file. (e.g. DRM master secret key) + - The 'group_id' works in two diffrent ways - 'designated group name' or 'NULL' + - Use designated group name + - Use when two or more applications want to share same encrypted file. + - You should ask the security part to make the proper group_id. + - The storage is made in /opt/share/secure-storage/, and the directory name is group_id. (/opt/share/secure-storage/[GROUP_ID]) + - If an application wants to read the encrypted file in some specific storage, that application MUST have privilege to access the file in the storage. + - Use NULL + - In the most cases, an application writes file into it's own storage, and the privilege is given to ifself. + - The storage is made in /opt/share/secure-storage/, and the directory name is the hash value of execution path of that application. + - Each applications have it's own storage. + - Each applications CANNOT access to other's storage. (the hash value of execution path is unique.) +- Usage of tags. In Secure Storage, we have some tags, which is used to determine the kind of encrypted data. + - SSM_FLAG_DATA + - The general data. The most files are included, BUT you cannot use this flag in case of buffer encryption. + - The encrypted content will be stored in /opt/share/secure-storage/~~/. + - SSM_FLAG_SECRET_OPERATION + - If you want to encrypt buffer content, you can use this flag. The file can be encrypted, too. + - The encrypted content will be stored in /opt/share/secure-storage/~~/. + - SSM_FLAG_SECRET_PRESERVE + - This flag is reserved for special contents. The encrypted file by this flag will not be deleted regardless of any changes of binary. + - The encrypted content will be stored in directory which be specified in configuration file. + - The configuration file is /usr/share/secure-storage/config. + +

Encrypt file content and store into secure-storage

+@code +#include +#include + +int main(void) +{ + int ret = -1; // if return is 0, success + char* filepath = "/opt/secure-storage/test/input.txt"; // this file will be encrypted. MUST use absolute path. + ssm_flag flag = SSM_FLAG_DATA; // in case of file encryption, SSM_FLAG_DATA is recommended. + char* group_id = NULL; // if some applications want to share encrypted file, 'group_id' will have a value, otherwise, NULL. + + ret = ssm_write_file(filepath, flag, group_id); + // - if success, return 0. otherwise, return negative value. each value has specific meaning. see Error Definition. + // - encrypted file will be stored in /opt/share/secure-storage/[HASH_VALUE_OF_CALLER]/{ORIGINAL_FILE_NAME}_{HASH_OF_NAME}.{EXTENSION}.e + // if you use specific 'group_id', directory name is that instead of {HASH_VALUE_OF_CALLER}. + // - the original file is deleted after encrypting. + + printf("ret: [%d]\n", ret); + return 0; +} +@endcode + +

Encrypt buffer content and store into secure-storage

+@code +#include +#include + +int main(void) +{ + int ret = -1; // if return is 0, success + char buf[32]; // this buffer content will be encrypted. + ssm_flag flag = SSM_FLAG_SECRET_OPERATION; // in case of buffer encryption, SSM_FLAG_SECRET_OPERATION is recommended. + char* group_id = NULL; // if some applications want to share encrypted file, 'group_id' will have a value, otherwise, NULL. + char* filename = "write_buf_res.txt"; // file name of encrypted buffer content. this file will be stored in secure-storage. + int buflen = 0; // length of the original buffer content + + memset(buf, 0x00, 32); + strncpy(buf, "abcdefghij", 10); + + buflen = strlen(buf); + + ret = ssm_write_buf(buf, buflen, filename, flag, group_id); + // - if success, return 0. otherwise, return negative value. each value has specific meaning. see Error Definition. + // - encrypted file will be stored in /opt/share/secure-storage/[HASH_VALUE_OF_CALLER]/write_buf_res.txt + // file name is what you use as parameter. + // same as above, if you use specific 'group_id', directory name will be changed. + + printf("ret: [%d]\n", ret); + return 0; +} + +@endcode + +

Read encrypted content

+@code +#include +#include + +int main(void) +{ + int ret = -1; // if return is 0, success + char* filepath = "/opt/secure-storage/test/input.txt"; + // this 'filepath' MUST be same with the one which be used when encrypting. + // in case of buffer encryption, type JUST file name. + char* retbuf = NULL; // decrypted content is stored in this buffer. + ssm_file_info_t sfi; // information of encrypted file. this information is used in order to know original file size. + int readlen = 0; // length of reading content + ssm_flag flag = SSM_FLAG_DATA; // this 'flag' MUST be same with the one which be used when encrypting. + char* group_id = NULL; // if some applications want to share encrypted file, 'group_id' will have a value, otherwise, NULL. + + ssm_get_info(filepath, &sfi, flag, group_id); // get information of encrypted file, that information will be stored in 'sfi'. + retbuf = (char*)malloc(sizeof(char) * (sfi.originSize + 1)); // memory allocation for decrypted data + memset(retbuf, 0x00, (sfi.originSize + 1)); + + ret = ssm_read(filepath, retbuf, sfi.originSize, &readlen, flag, group_id); + // - if success, return 0. otherwise, return negative value. each value has specific meaning. see Error Definition. + // - if no error occured, decrypted data is stored in 'refbuf' buffer. + + printf("ret: [%d]\n", ret); + printf("decrypted data: [%s]\n", retbuf); + return 0; +} +@endcode + + +

Test & Etc.

+- Test + - Unit test - not supported yet. + - Integration test - not supported yet. + +- Server Action + - When testing, server program and test executable are running at the same time. Therefore two terminals are executed simultaneously. To doing this, execute server when booting. + - In /etc/rc.d/rc.sysinit script, there is code which starts secure storage (Already reflected) + +- Physical Secure storage + - The location of certificate file which be used OMA DRM is '/csa/'. But other files are stored in '/opt/share/secure-storage/'. If you want to check the file storing path, refer to 'ss_manager.h'. + - #define SSM_STORAGE_DEFAULT_PATH + +- Source code Download + - If you want to get source codes, there are two ways, + - # apt-get source libss-client-0 + +*/ + +/** + * @} + */ diff --git a/include/secure_storage.h b/include/secure_storage.h old mode 100755 new mode 100644 index 67ff3d0..def8fe0 --- a/include/secure_storage.h +++ b/include/secure_storage.h @@ -1,90 +1,104 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * 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 __SECURE_STORAGE__ -#define __SECURE_STORAGE__ - -#include "ss_manager.h" - -#define SS_SOCK_PATH "/tmp/SsSocket" - -#define MAX_FILENAME_LEN 256 // for absolute path -//#define MAX_RECV_DATA_LEN 16384 // internal buffer = 4KB -#define MAX_RECV_DATA_LEN 4096 // internal buffer = 4KB -//#define MAX_SEND_DATA_LEN 16384 // internal buffer = 4KB -#define MAX_SEND_DATA_LEN 4096 // internal buffer = 4KB -#define MAX_GROUP_ID_LEN 32 -#define MAX_COOKIE_LEN 20 - -#define SS_STORAGE_DEFAULT_PATH "/opt/share/secure-storage/" - -/* using dlog */ -#ifdef SS_DLOG_USE - -#define LOG_TAG "SECURE_STORAGE" -#include - -#elif SS_CONSOLE_USE // debug msg will be printed in console - -#define SLOGD(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) -#define SLOGV(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) -#define SLOGI(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) -#define SLOGW(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) -#define SLOGE(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) -#define SLOGF(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) - -#else // don't use logging - -#define SLOGD(FMT, ARG ...) {} -#define SLOGV(FMT, ARG ...) {} -#define SLOGI(FMT, ARG ...) {} -#define SLOGW(FMT, ARG ...) {} -#define SLOGE(FMT, ARG ...) {} -#define SLOGF(FMT, ARG ...) {} - -#endif - -#define SS_FILE_POSTFIX ".e" - -typedef union { - ssm_file_info_t fInfoStruct; - char fInfoArray[16]; -} ssm_file_info_convert_t; - -typedef struct { - int req_type; - int enc_type; - unsigned int count; // 1 count = 4KB - unsigned int flag; - char data_infilepath[MAX_FILENAME_LEN]; - char buffer[MAX_SEND_DATA_LEN+1]; - char group_id[MAX_GROUP_ID_LEN]; - char cookie[MAX_COOKIE_LEN]; -} ReqData_t; - -typedef struct { - int rsp_type; - unsigned int readLen; - char data_filepath[MAX_FILENAME_LEN]; - char buffer[MAX_RECV_DATA_LEN+1]; -} RspData_t; - -#endif +/* + * secure storage + * + * Copyright (c) 2000 - 2012 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 __SECURE_STORAGE__ +#define __SECURE_STORAGE__ + +#include "ss_manager.h" + +#define SS_SOCK_PATH "/tmp/SsSocket" + +#define MAX_FILENAME_SIZE 256 // for absolute path +#define MAX_RECV_DATA_SIZE 4096 // internal buffer = 4KB +#define MAX_SEND_DATA_SIZE 4096 // internal buffer = 4KB +#define MAX_GROUP_ID_SIZE 32 + +#define SS_STORAGE_DEFAULT_PATH "/opt/share/secure-storage/" + +#define MAX_APPID_SIZE 32 +#define MAX_PASSWORD_SIZE 32 +#define KEY_SIZE 16 +#define SALT_SIZE 400 +#define SALT_NAME "salt" +#define HASH_SIZE 20 +#define DUK_NAME "duk" +#define SALT_PATH "/opt/share/secure-storage/salt/salt" +#define DELIMITER "::" +#define DELIMITER_SIZE 2 +#define PRE_GROUP_ID "secure-storage::" + +/* using dlog */ +#ifdef SS_DLOG_USE + +#define LOG_TAG "SECURE_STORAGE" +#include + +#elif SS_CONSOLE_USE // debug msg will be printed in console + +#define SLOGD(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) +#define SLOGV(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) +#define SLOGI(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) +#define SLOGW(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) +#define SLOGE(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) +#define SLOGF(FMT, ARG ...) fprintf(stderr, FMT, ##ARG) + +#else // don't use logging + +#define SLOGD(FMT, ARG ...) {} +#define SLOGV(FMT, ARG ...) {} +#define SLOGI(FMT, ARG ...) {} +#define SLOGW(FMT, ARG ...) {} +#define SLOGE(FMT, ARG ...) {} +#define SLOGF(FMT, ARG ...) {} + +#endif + +#define SS_FILE_POSTFIX ".e" + + +typedef struct { + unsigned int originSize; + unsigned int storedSize; + char reserved[8]; +}ssm_file_info_t; + +typedef union { + ssm_file_info_t fInfoStruct; + char fInfoArray[16]; +}ssm_file_info_convert_t; + +typedef struct { + int req_type; + int enc_type; + unsigned int count; // 1 count = 4KB + unsigned int flag; + char data_infilepath[MAX_FILENAME_SIZE+1]; // string + char buffer[MAX_SEND_DATA_SIZE+1]; + char group_id[MAX_GROUP_ID_SIZE+1]; // string +} ReqData_t; + +typedef struct { + int rsp_type; + unsigned int readLen; + char data_filepath[MAX_FILENAME_SIZE+1]; // string + char buffer[MAX_RECV_DATA_SIZE]; +} RspData_t; + + +#endif // __SECURE_STORAGE__ diff --git a/include/ss_manager.h b/include/ss_manager.h index 1d14ca4..4fc6066 100755 --- a/include/ss_manager.h +++ b/include/ss_manager.h @@ -3,8 +3,6 @@ * * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved * - * Contact: Kidong Kim - * * 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 @@ -22,393 +20,434 @@ #ifndef __SS_MANAGER__ #define __SS_MANAGER__ +#include + + /** + * @addtogroup CAPI_SECURE_STORAGE_MODULE * @{ */ + /** - * @defgroup SECURE_STORAGE secure storage - * @ingroup SecurityFW - * @{ + * @brief Secure Storage default path + * @remark This path is deprecated. */ - #define SSM_STORAGE_DEFAULT_PATH "/opt/share/secure-storage/" #define DEPRECATED __attribute__((deprecated)) /** - * \name Enumeration + * @brief Enumeration for SSM data type + * @remark This enumeration is deprecated. */ typedef enum { - SSM_FLAG_NONE = 0x00, - SSM_FLAG_DATA, // normal data for user (ex> picture, video, memo, etc.) - SSM_FLAG_SECRET_PRESERVE, // for preserved operation - SSM_FLAG_SECRET_OPERATION, // for oma drm , wifi addr, divx and bt addr - SSM_FLAG_WIDGET, // for wiget encryption/decryption - SSM_FLAG_WEB_APP, - SSM_FLAG_PRELOADED_WEB_APP, + SSM_FLAG_NONE = 0x00, /**< for initial purrpose */ + SSM_FLAG_DATA, /**< normal data for user (ex> picture, video, memo, etc.) */ + SSM_FLAG_SECRET_PRESERVE, /**< for preserved operation */ + SSM_FLAG_SECRET_OPERATION, /**< for oma drm , wifi addr, divx and bt addr */ + SSM_FLAG_WIDGET, /**< for wiget encryption/decryption */ + SSM_FLAG_WEB_APP, /**< for web application encryption/decryption */ + SSM_FLAG_PRELOADED_WEB_APP, /**< for preloaded application encryption/decryption */ SSM_FLAG_MAX } ssm_flag; +/* + * @brief Enumeration for SSM data type + * @remark This enumeration is deprecated. + */ +typedef enum { + SSM_FLAG_WEB_APP_, /**< for web application */ + SSM_FLAG_PRELOADED_WEB_APP_ /**< for preloaded web application */ +} WebFlag; + + +/** + * @brief Parameter error + * @remark This Error code is deprecated. + */ +#define SS_PARAM_ERROR 0x00000002 +/** + * @brief File type error + * @remark This Error code is deprecated. + */ +#define SS_FILE_TYPE_ERROR 0x00000003 /** - * \name Type definition + * @brief File open error + * @remark This Error code is deprecated. */ -typedef struct { - unsigned int originSize; - unsigned int storedSize; - char reserved[8]; -}ssm_file_info_t; +#define SS_FILE_OPEN_ERROR 0x00000004 +/** + * @brief File read error + * @remark This Error code is deprecated. + */ +#define SS_FILE_READ_ERROR 0x00000005 /** - * \name Error codes + * @brief File write error + * @remark This Error code is deprecated. + */ +#define SS_FILE_WRITE_ERROR 0x00000006 +/** + * @brief Out of memory + * @remark This Error code is deprecated. + */ +#define SS_MEMORY_ERROR 0x00000007 +/** + * @brief Socket error + * @remark This Error code is deprecated. + */ +#define SS_SOCKET_ERROR 0x00000008 +/** + * @brief Encryption error + * @remark This Error code is deprecated. + */ +#define SS_ENCRYPTION_ERROR 0x00000009 +/** + * @brief Decryption error + * @remark This Error code is deprecated. + */ +#define SS_DECRYPTION_ERROR 0x0000000a +/** + * @brief Data block size error + * @remark This Error code is deprecated. + */ +#define SS_SIZE_ERROR 0x0000000b +/** + * @brief Secure Storage access error + * @remark This Error code is deprecated. */ -#define SS_PARAM_ERROR 0x00000002 // 2 -#define SS_FILE_TYPE_ERROR 0x00000003 // 3 -#define SS_FILE_OPEN_ERROR 0x00000004 // 4 -#define SS_FILE_READ_ERROR 0x00000005 // 5 -// -#define SS_FILE_WRITE_ERROR 0x00000006 // 6 -#define SS_MEMORY_ERROR 0x00000007 // 7 -#define SS_SOCKET_ERROR 0x00000008 // 8 -#define SS_ENCRYPTION_ERROR 0x00000009 // 9 -#define SS_DECRYPTION_ERROR 0x0000000a // 10 -// -#define SS_SIZE_ERROR 0x0000000b // 11 -#define SS_SECURE_STORAGE_ERROR 0x0000000c // 12 -#define SS_PERMISSION_DENIED 0x0000000d // 13 -#define SS_TZ_ERROR 0x0000000e // 14 +#define SS_SECURE_STORAGE_ERROR 0x0000000c +/** + * @brief Permission denied from security server + * @remark This Error code is deprecated. + */ +#define SS_PERMISSION_DENIED 0x0000000d +/** + * @brief Trust Zone error + * @remark This Error code is deprecated. + */ +#define SS_TZ_ERROR 0x0000000e + + #ifdef __cplusplus extern "C" { #endif +typedef enum +{ + SSA_PARAM_ERROR = TIZEN_ERROR_SYSTEM_CLASS | 0x01, /** < Invalid parameters */ + SSA_AUTHENTICATION_ERROR = TIZEN_ERROR_SYSTEM_CLASS | 0x02, /** < Authentication error */ + SSA_TZ_ERROR = TIZEN_ERROR_SYSTEM_CLASS | 0x03, /** < Trust zone error */ + SSA_SOCKET_ERROR = TIZEN_ERROR_CONNECTION, /** < Connection error */ + SSA_PERMISSION_ERROR = TIZEN_ERROR_PERMISSION_DENIED, /** < Permission denied */ + SSA_SECURITY_SERVER_ERROR = TIZEN_ERROR_SYSTEM_CLASS | 0x04,/** < Security server error */ + SSA_CIPHER_ERROR = TIZEN_ERROR_SYSTEM_CLASS | 0x05, /** < Encryption / Decryption error */ + SSA_IO_ERROR = TIZEN_ERROR_IO_ERROR, /** < I/O error */ + SSA_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY, /** < Out of memory */ + SSA_UNKNOWN_ERROR = TIZEN_ERROR_UNKNOWN, /** < Unknown error */ +} ssa_error_e; + /** - * \name Functions - */ -/** - * \par Description: - * Store encrypted file to secure-storage. - * - * \par Purpose: - * Encrypt file in order not to expose the contents of that file. The encrypted file is stored in specific directory and that file only be read by secure-storage server daemon. - * - * \par Typical use case: - * When user wants to store some file securely, he(or she) can use this API. + * @brief Put application data to Secure Storage by given name. + * @remark Input parameters pInDataName, pInDataBlock, pGroupId, pPassword must be static / allocated by user. Maximum used length of user password and group id are 32. * - * \par Method of function operation: - * First, encrypt the given file. Then make new file path which will be stored in secure storage. Then store new encrypted file and remove older one. + * @since_tizen 2.3 + * @param[in] pDataName Data name to be identify. + * @param[in] pInDataBlock Data block to be stored. + * @param[in] pInDataBlockLen Length of data to be put. + * @param[in] pGroupId Sharing group id. (NULL if not used) + * @param[in] pPassword User password to use for encryption. (NULL if not used) * - * \par Important Notes: - * - After encryption, original file will be deleted.\n + * @return Length of stored data block on success or an error code otherwise. + * @retval #SSA_PARAM_ERROR Invalid input parameter + * @retval #SSA_AUTHENTICATION_ERROR Non-authenticated application request + * @retval #SSA_TZ_ERROR Trust zone error + * @retval #SSA_SOCKET_ERROR Socket connection failed + * @retval #SSA_PERMISSION_ERROR Permission error + * @retval #SSA_SECURITY_SERVER_ERROR Getting smack information failed + * @retval #SSA_CIPHER_ERROR Encryption failed + * @retval #SSA_IO_ERROR I/O failed * - * \param[in] pFilePath Absolute file path of original file - * \param[in] flag Type of stored data (data or secret) - * \param[in] group_id Sharing group id(string). (NULL if not used) * - * \return Return Type (integer) \n - * - 0 - Success \n - * - <0 - Fail \n * - * \par Related functions: - * None + * @see ssa_get() * - * \par Known issues/bugs: - * None - * - * \pre None - * \post None - * \see None - * \remark None - * - * \par Sample code: - * \code + * @code * #include * * ... * - * int ret = -1; - * char* infilepath = "/opt/test/test.txt"; - * ssm_flag flag = SSM_FLAG_DATA; + * int outLen = -1; + * unsigned char dataName[32]; + * unsigned char* pDataBlock; + * unsigned int dataLen; + * unsigned char password[32]; + * unsigned char* pGroupId; + * + * // Put data name to array dataName + * // Put data block to pDataBlock and put its length to dataLen + * // Put user password to array password + * // Put group id to pGroupId if want share the data + * + * outLen = ssa_put(dataName, pDataBlock, dataLen, pGroupId, password); + * if(outLen < 0) + * { + * // Error handling + * } + * // Use dataName to read data block afterwards * - * ret = ssm_write_file(infilepath, flag, NULL); - * - * return ret; // in case of success, return 0. Or fail, return corresponding error code. - * * ... - * \endcode + * @endcode * */ -/*================================================================================================*/ -int ssm_write_file(const char* pFilePath, ssm_flag flag, const char* group_id); +int ssa_put(const char* pDataName, const char* pInDataBlock, size_t inDataBlockLen, const char* pGroupId, const char* pPassword); + /** - * \par Description: - * Store encrypted file to secure-storage (Original data is in memory buffer). - * - * \par Purpose: - * Encrypt buffer in order not to expose the contents of that buffer. The encrypted file is stored in specific directory and that file only be read by secure-storage server daemon. - * - * \par Typical use case: - * When user wants to store some buffer contents securely, he(or she) can use this API. - * - * \par Method of function operation: - * First, encrypt the given buffer contents. Then make new file path which will be stored in secure storage. Then store new encrypted file. - * - * \par Important Notes: - * None - * - * \param[in] pWriteBuffer Data buffer to be stored in secure storage - * \param[in] bufLen Data size of buffer - * \param[in] pFileName File name be used when stored. Only file name, not a path - * \param[in] flag Type of stored data (data or secret) - * \param[in] group_id Sharing group id(string). (NULL if not used) - * - * \return Return Type (integer) \n - * - 0 - Success \n - * - <0 - Fail \n - * - * \par Related functions: - * None - * - * \par Known issues/bugs: - * None - * - * \pre None - * \post None - * \see None - * \remark None - * - * \par Sample code: - * \code + * @brief Get application data from Secure Storage by given name. + * @remark Input parameters pOutataName, pGroupId, pPassword must be static / allocated by user. Maximum used length of user password and group id are 32 + * + * @since_tizen 2.3 + * @param[in] pDataName Data name to read. + * @param[out] ppOutDataBlock Containing data get from secure storage. Memory allocated for ppOutDataBlock. So must be freed by the user of this function. + * @param[in] pGroupId Sharing group id. (NULL if not used) + * @param[in] pPassword User password to use for encryption. (NULL if not used) + * + * @return Length of read data block on success or an error code otherwise. + * @retval #SSA_PARAM_ERROR Invalid input parameter or no such data by given data name + * @retval #SSA_AUTHENTICATION_ERROR Non-authenticated application request + * @retval #SSA_TZ_ERROR Trust zone error + * @retval #SSA_SOCKET_ERROR Socket connection failed + * @retval #SSA_PERMISSION_ERROR Permission error + * @retval #SSA_SECURITY_SERVER_ERROR Getting smack information failed + * @retval #SSA_CIPHER_ERROR Decryption failed + * @retval #SSA_IO_ERROR I/O failed + * + * @see ssa_put() + * + * @code * #include * * ... * - * int ret = -1; - * char buf[27] = "abcdefghijklmnopqrstuvwxyz"; - * int buflen = strlen(buf); - * char* filename = write_buf.txt; - * ssm_flag flag = SSM_FLAG_SECRET_OPERATION; - * - * ret = ssm_write_buffer(buf, buflen, filename, flag, NULL); - * - * return ret; // in case of success, return 0. Or fail, return corresponding error code. - * + * int outLen = -1; + * unsigned char dataName[32]; + * unsigned char* pOutDataBlock; + * unsigned char password[32]; + * unsigned char* pGroupId; + * + * // Put data name to array dataName + * // Put user password to array password + * // Put group id to pGroupId if want share the data + * + * outLen = ssa_get(dataName, &pOutDataBlock, pGroupId, password); + * if(outLen < 0) + * { + * // Error handling + * } + * + * free(pOutDataName); + * return; * ... - * \endcode + * @endcode * */ -/*================================================================================================*/ -int ssm_write_buffer(char* pWriteBuffer, size_t bufLen, const char* pFileName, ssm_flag flag, const char* group_id); +int ssa_get(const char* pDataName, char** ppOutDataBlock, const char* pGroupId, const char* pPassword); + /** - * \par Description: - * Decrypt encrypted file into memory buffer. - * - * \par Purpose: - * Read encrypted file which be stored in secure storage. Decrypted contents are only existed in the form of memory buffer, not file. - * - * \par Typical use case: - * When user wants to know the contents which be stored in secure storage, he(or she) can use this API. - * - * \par Method of function operation: - * First, read the file which be in secure storage. Then decrypt that file and store to memory buffer. Then return that buffer. - * - * \par Important Notes: - * - flag must be same with the one of stored data.\n - * - pFilePath can be either absolute path or file name.\n - * - pRetBuf is JUST pointer. User allocates memory buffer and passes a pointer.\n - * - not uses sting function, but uses memory function (not strcpy, strlen, ... use memcpy, memset, ...).\n - * - * \param[in] pFilePath File name or path to be read in secure storage - * \param[in] bufLen Length of data to be read - * \param[in] flag Type of stored data (data or secret) - * \param[out] readLen Length of data that this function read - * \param[out] pRetBuf Buffer for decrypted data - * \param[in] group_id Sharing group id(string). (NULL if not used) - * - * \return Return Type (integer) \n - * - 0 - Success \n - * - <0 - Fail \n - * - * \par Related functions: - * ssm_get_info() - use in order to know file size - * - * \par Known issues/bugs: - * None - * - * \pre None - * \post None - * \see None - * \remark None - * - * \par Sample code: - * \code + * @brief Delete application data from Secure Storage by given name. + * @remark Input parameters pDataName, pGroupId must be static / allocated by caller. Maximum used length of group id is 32 + * + * @since_tizen 2.3 + * @param[in] pDataName Data name to delete + * @param[in] pGroupId Sharing group id. (NULL if not used) + * + * @return Length of data block on success or an error code otherwise. + * @retval #SSA_PARAM_ERROR Invalid input parameter or no such data by given data name + * @retval #SSA_AUTHENTICATION_ERROR Non-authenticated application request + * @retval #SSA_TZ_ERROR Trust zone error + * @retval #SSA_SOCKET_ERROR Socket connection failed + * @retval #SSA_PERMISSION_ERROR Permission error + * @retval #SSA_SECURITY_SERVER_ERROR Getting smack information failed + * @retval #SSA_IO_ERROR I/O failed + * + * @pre The application data have to put before using this API by ssa_put() + * @see ssa_put() + * + * @code * #include * * ... * * int ret = -1; - * char *filepath = "/opt/test/input.txt"; - * int buflen = 128; - * ssm_flag flag = SSM_FLAG_DATA; - * char* retbuf = NULL; - * int readlen = 0; - * ssm_file_info_t sfi; - * - * ssm_getinfo(filepath, &sfi, SSM_FLAG_DATA); - * retbuf = (char*)malloc(sizeof(char) * (sfi.originSize + 1)); - * memset(retbuf, 0x00, (sfi.originSize + 1)); - * - * ret = ssm_read(filepath, retbuf, sfi.originSize, &readlen, SSM_FLAG_DATA, NULL); - * free(retbuf); - * - * return ret; // in case of success, return 0. Or fail, return corresponding error code. - * + * unsigned char dataName[32]; + * unsigned char* pGroupId; + * + * // Put data name to array dataName + * // Put group id to pGroupId if want share the data + * + * ret = ssa_delete(dataName, pGroupId); + * if(ret < 0) + * { + * // Error handling + * } + * + * return; * ... - * \endcode + * @endcode * */ -/*================================================================================================*/ -int ssm_read(const char* pFilePath, char* pRetBuf, size_t bufLen, size_t *readLen, ssm_flag flag, const char* group_id); +int ssa_delete(const char* pDataName, const char* pGroupId); + /** - * \par Description: - * Get information of data which will be read. - * - * \par Purpose: - * Use in order to know file statistic information of encrypted file, original file size and encrypted file size. - * - * \par Typical use case: - * When using ssm_read API, user should know the size of original size of encrypted file. In that case, he(or she) can use this API. - * - * \par Method of function operation: - * When encrypting some file, information regarding size of file are saved with encrypted file. In this API, returns that information. - * - * \par Important Notes: - * None - * - * \param[in] pFilePath File name or path of file - * \param[in] flag Type of stored data (data or secret) - * \param[out] sfi Structure of file information - * \param[in] group_id Sharing group id(string). (NULL if not used) - * - * \return Return Type (integer) \n - * - 0 - Success \n - * - <0 - Fail \n - * - * \par Related functions: - * ssm_read() - * - * \par Known issues/bugs: - * None - * - * \pre None - * \post None - * \see None - * \remark None - * - * \par Sample code: - * \code + * @brief Encrypt application data using Secure Storage. + * @remark Input parameters pInDataBlock, pPassword must be static / allocated by caller. Maximum used length of password is 32 + * + * @since_tizen 2.3 + * @param[in] pInDataBlock Data block to be encrypted. + * @param[in] inDataBlockLen Length of data block to be encrypted. + * @param[out] ppOutDataBlock Data block contaning encrypted data block. Memory allocated for ppOutDataBlock. So must be freed user of this function. + * @param[in] pPassword User password to use for encryption. (NULL if not used) + * + * @return Length of encrypted data block on success or an error code otherwise. + * @retval #SSA_PARAM_ERROR Invalid input parameter + * @retval #SSA_AUTHENTICATION_ERROR Non-authenticated application request + * @retval #SSA_TZ_ERROR Trust zone error + * @retval #SSA_SOCKET_ERROR Socket connection failed + * @retval #SSA_PERMISSION_ERROR Permission error + * @retval #SSA_SECURITY_SERVER_ERROR Getting smack information failed + * + * @see ssa_decrypt() + * + * @code * #include * * ... * - * int ret = -1; - * char *filepath = "/opt/secure-storage/test/input.txt"; - * ssm_flag flag = SSM_FLAG_DATA; - * ssm_file_info_t sfi; + * int len = -1; + * unsigned char* pDataBlock; + * unsigned int dataBlockLen; + * unsigned char* pOutDataBlock; + * unsigned char pPassword[32]; * - * ret = ssm_getinfo(filepath, &sfi, flag, NULL); - * - * printf(" ** original size: [%d]\n", sfi.originSize); - * printf(" ** stored size: [%d]\n", sfi.storedSize); - * printf(" ** reserved: [%s]\n", sfi.reserved); + * // Put data block to pDataBlock and put its length to dataBlockLen + * // Put user password to array pPassword + * + * len = ssa_encrypt(pDataBlock, dataBlockLen, &pOutDataBlock, pPassword); + * if(len < 0) + * { + * // Error handling + * } * - * return ret; // in case of success, return 0. Or fail, return corresponding error code. - * * ... - * \endcode + * free(pOutDataBlock); + * @endcode * */ -/*================================================================================================*/ -int ssm_getinfo(const char* pFilePath, ssm_file_info_t* sfi, ssm_flag flag, const char* group_id); +int ssa_encrypt(const char* pInDataBlock, size_t inDataBlockLen, char** ppOutDataBlock, const char* pPassword); + /** - * \par Description: - * Delete encrypted file in Secure-storage. - * - * \par Purpose: - * The Secure-storage is the special place, which only ss-server daemon can access. Therefore, in order to delete file, process requests to ss-server. - * - * \par Typical use case: - * When user wants to delete specific file, he(or she) can use this API. - * - * \par Method of function operation: - * All files in secure-storage have unique name. Process will request to delete some file, then ss-server deletes that. - * - * \par Important Notes: - * None - * - * \param[in] pFilePath File path - * \param[in] flag Type of stored data (data or secret) - * \param[in] group_id Sharing group id(string). (NULL if not used) - * - * \return Return Type (integer) \n - * - 0 - Success \n - * - <0 - Fail \n - * - * \par Related functions: - * None - * - * \par Known issues/bugs: - * None - * - * \pre None - * \post None - * \see None - * \remark None - * - * \par Sample code: - * \code + * @brief Decrypt application data using Secure Storage. + * @remark Input parameters pInDataBlock, pPassword must be static / allocated by caller. Maximum used length of password is 32 + * + * @since_tizen 2.3 + * @param[in] pInDataBlock Data block contained encrypted data from ssa_encrypt. + * @param[in] inDataBlockLen Length of data block to be decrypted. + * @param[out] ppOutDataBlock Data block contaning decrypted data block. Memory allocated for ppOutDataBlock. So must be freed user of this function. + * @param[in] pPassword User password to use for decryption. (NULL if not used) + * + * @return Length of decrypted data block on success or an error code otherwise. + * @retval #SSA_PARAM_ERROR Invalid input parameter + * @retval #SSA_AUTHENTICATION_ERROR Non-authenticated application request + * @retval #SSA_TZ_ERROR Trust zone error + * @retval #SSA_SOCKET_ERROR Socket connection failed + * @retval #SSA_PERMISSION_ERROR Permission error + * @retval #SSA_SECURITY_SERVER_ERROR Getting smack information failed + * + * @see ssa_encrypt() + * + * @code * #include * * ... * - * int ret = -1; - * char *infilepath = "res_write_buf.txt"; - * ssm_flag flag = SSM_FLAG_SECRET_OPERATION; + * int len = -1; + * unsigned char* pDataBlock; + * unsigned int dataBlockLen; + * unsigned char* pOutDataBlock; + * unsigned char pPassword[32]; * - * ret = ssm_delete_file(infilepath, flag, NULL); + * // Put data block to pDataBlock and put its length to dataBlockLen + * // Put user password to array pPassword * - * return ret; // in case of success, return 0. Or fail, return corresponding error code. + * len = ssa_decrypt(pDataBlock, dataBlockLen, &pOutDataBlock, pPassword); + * if(len < 0) + * { + * // Error handling + * } * * ... - * \endcode + * free(pOutDataBlock); + * @endcode * */ -/*================================================================================================*/ -int ssm_delete_file(const char* pFilePath, ssm_flag flag, const char* group_id); - -//for wrt installer -/*================================================================================================*/ -int ssm_encrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen); -int ssm_decrypt(const char* pAppId, int idLen, const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen); +int ssa_decrypt(const char* pInDataBlock, size_t inDataBlockLen, char** ppOutDataBlock, const char* pPassword); -int ssm_encrypt_preloaded_application(const char* pBuffer, int bufLen, char** ppEncryptedBuffer, int* pEncryptedBufLen); -int ssm_decrypt_preloaded_application(const char* pBuffer, int bufLen, char** ppDecryptedBuffer, int* pDecryptedBufLen); - - -#ifdef __cplusplus -} -#endif /** - * @} + * @brief Encrypt web application data using Secure Storage. + * + * @since_tizen 2.3 + * @param[in] pAppId The application id. + * @param[in] idLen Length of application id. + * @param[in] pData Data block to be encrypted. + * @param[in] dataLen Length of data block. + * @param[out] ppEncryptedData Data block contaning encrypted data block. Memory allocated for ppEncryptedData. So must be freed user of this function. + * @param[in] isPreloaded True if the application is preloaded else false. + * + * @return Length of encrypted data block on success or an error code otherwise. + * @retval #SSA_PARAM_ERROR Invalid input parameter + * @retval #SSA_AUTHENTICATION_ERROR Non-authenticated application request + * @retval #SSA_TZ_ERROR Trust zone error + * @retval #SSA_SOCKET_ERROR Socket connection failed + * @retval #SSA_PERMISSION_ERROR Permission error + * @retval #SSA_SECURITY_SERVER_ERROR Getting smack information failed + * + * @see ssa_decrypt_web_application() */ +int ssa_encrypt_web_application(const char* pAppId, int idLen, const char* pData, int dataLen, char** ppEncryptedData, int isPreloaded); + /** - * @} + * @brief Encrypt web application data using Secure Storage. + * + * @since_tizen 2.3 + * @param[in] pAppId The application id. + * @param[in] idLen Length of application id. + * @param[in] pData Data block to be encrypted. + * @param[in] dataLen Length of data block. + * @param[out] ppEncryptedData Data block contaning encrypted data block. Memory allocated for ppEncryptedData. So must be freed user of this function. + * @param[in] isPreloaded True if the application is preloaded else false. + * + * @return Length of encrypted data block on success or an error code otherwise. + * @retval #SSA_PARAM_ERROR Invalid input parameter + * @retval #SSA_AUTHENTICATION_ERROR Non-authenticated application request + * @retval #SSA_TZ_ERROR Trust zone error + * @retval #SSA_SOCKET_ERROR Socket connection failed + * @retval #SSA_PERMISSION_ERROR Permission error + * @retval #SSA_SECURITY_SERVER_ERROR Getting smack information failed + * + * @see ssa_decrypt_web_application() */ +int ssa_decrypt_web_application(const char* pData, int dataLen, char** ppDecryptedData, int isPreloaded); + +#ifdef __cplusplus +} +#endif #endif diff --git a/libss-client.manifest b/libss-client.manifest index 97e8c31..81ace0c 100644 --- a/libss-client.manifest +++ b/libss-client.manifest @@ -3,3 +3,4 @@ + diff --git a/packaging/non-tz-secure-storage.service b/packaging/non-tz-secure-storage.service new file mode 100755 index 0000000..066f423 --- /dev/null +++ b/packaging/non-tz-secure-storage.service @@ -0,0 +1,12 @@ +[Unit] +Description=Start the Secure Storage server +After=csa.mount +Requires=security-server.socket + +[Service] +ExecStart=/usr/bin/ss-server +Restart=always +RestartSec=0 + +[Install] +WantedBy=multi-user.target diff --git a/packaging/secure-storage.service b/packaging/secure-storage.service new file mode 100755 index 0000000..68f6c92 --- /dev/null +++ b/packaging/secure-storage.service @@ -0,0 +1,14 @@ +[Unit] +Description=Start the Secure Storage server +After=csa.mount samsung-secure-storage.service +Requires=security-server.service + +[Service] +Type=simple +ExecStart=/usr/bin/ss-server +Sockets=ss-server.socket +Restart=always +RestartSec=0 + +[Install] +WantedBy=multi-user.target diff --git a/packaging/secure-storage.spec b/packaging/secure-storage.spec old mode 100644 new mode 100755 index 9b3d37b..bae1dc3 --- a/packaging/secure-storage.spec +++ b/packaging/secure-storage.spec @@ -1,16 +1,24 @@ Name: secure-storage Summary: Secure storage -Version: 0.12.9 -Release: 4 +Version: 0.12.12 +Release: 1 Group: System/Security -License: Apache-2.0 +License: Apache 2.0 Source0: secure-storage-%{version}.tar.gz +Source1: non-tz-secure-storage.service +Source2: ss-server.socket BuildRequires: pkgconfig(openssl) BuildRequires: pkgconfig(dlog) BuildRequires: pkgconfig(libsystemd-daemon) BuildRequires: pkgconfig(security-server) BuildRequires: cmake -BuildRequires: pkgconfig(dukgenerator) +BuildRequires: libcryptsvc-devel +BuildRequires: pkgconfig(dukgenerator) +BuildRequires: pkgconfig(db-util) +BuildRequires: pkgconfig(sqlite3) +BuildRequires: pkgconfig(vconf) +BuildRequires: pkgconfig(glib-2.0) +BuildRequires: pkgconfig(capi-base-common) %description Secure storage package @@ -19,7 +27,8 @@ Secure storage package Summary: Secure storage (client) Group: Development/Libraries Provides: libss-client.so -Requires: dukgenerator +Requires(post): /sbin/ldconfig +Requires(postun): /sbin/ldconfig %description -n libss-client Secure storage package (client) @@ -40,6 +49,7 @@ Requires(post): /usr/bin/systemctl Requires(postun): /usr/bin/systemctl Requires: systemd Requires: libss-client = %{version}-%{release} +Requires: libcryptsvc %description -n ss-server Secure storage package (ss-server) @@ -49,23 +59,34 @@ Secure storage package (ss-server) %build -%cmake . + +export CFLAGS="$CFLAGS -DTIZEN_DEBUG_ENABLE" +export CXXFLAGS="$CXXFLAGS -DTIZEN_DEBUG_ENABLE" +export FFLAGS="$FFLAGS -DTIZEN_DEBUG_ENABLE" +export CFLAGS="$CFLAGS -DSECURE_STORAGE_DEBUG_ENABLE" +export CXXFLAGS="$CXXFLAGS -DSECURE_STORAGE_DEBUG_ENABLE" +export FFLAGS="$FFLAGS -DSECURE_STORAGE_DEBUG_ENABLE" + +cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} make %{?jobs:-j%jobs} %install +rm -rf %{buildroot} %make_install -mkdir -p %{buildroot}%{_prefix}/lib/systemd/system/multi-user.target.wants -mkdir -p %{buildroot}%{_prefix}/lib/systemd/system/sockets.target.wants -ln -s ../secure-storage.service %{buildroot}%{_prefix}/lib/systemd/system/multi-user.target.wants/secure-storage.service -ln -s ../secure-storage.socket %{buildroot}%{_prefix}/lib/systemd/system/sockets.target.wants/secure-storage.socket +mkdir -p %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants +mkdir -p %{buildroot}%{_libdir}/systemd/system/sockets.target.wants + +install -m 0644 %{SOURCE1} %{buildroot}%{_libdir}/systemd/system/secure-storage.service +install -m 0644 %{SOURCE2} %{buildroot}%{_libdir}/systemd/system/ +ln -s ../secure-storage.service %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants/ +ln -s ../ss-server.socket %{buildroot}%{_libdir}/systemd/system/sockets.target.wants/ mkdir -p %{buildroot}/usr/share/license cp LICENSE.APLv2 %{buildroot}/usr/share/license/ss-server cp LICENSE.APLv2 %{buildroot}/usr/share/license/libss-client -cp LICENSE.APLv2 %{buildroot}/usr/share/license/libss-client-devel %preun -n ss-server if [ $1 == 0 ]; then @@ -89,10 +110,10 @@ systemctl daemon-reload %manifest ss-server.manifest %defattr(-,root,root,-) %{_bindir}/ss-server -%{_prefix}/lib/systemd/system/secure-storage.service -%{_prefix}/lib/systemd/system/multi-user.target.wants/secure-storage.service -%{_prefix}/lib/systemd/system/secure-storage.socket -%{_prefix}/lib/systemd/system/sockets.target.wants/secure-storage.socket +%{_libdir}/systemd/system/secure-storage.service +%{_libdir}/systemd/system/ss-server.socket +%{_libdir}/systemd/system/multi-user.target.wants/secure-storage.service +%{_libdir}/systemd/system/sockets.target.wants/ss-server.socket %{_datadir}/secure-storage/config /usr/share/license/ss-server @@ -101,11 +122,11 @@ systemctl daemon-reload %defattr(-,root,root) %{_libdir}/libss-client.so.* /usr/share/license/libss-client +/opt/share/secure-storage/salt/* %files -n libss-client-devel %defattr(-,root,root,-) %{_includedir}/ss_manager.h %{_libdir}/pkgconfig/secure-storage.pc %{_libdir}/libss-client.so -/usr/share/license/libss-client-devel diff --git a/packaging/ss-server.socket b/packaging/ss-server.socket new file mode 100644 index 0000000..893926f --- /dev/null +++ b/packaging/ss-server.socket @@ -0,0 +1,10 @@ +[Socket] +ListenStream=/tmp/SsSocket +SocketMode=0777 +SmackLabelIPIn=* +SmackLabelIPOut=@ + +Service=secure-storage.service + +[Install] +WantedBy=sockets.target diff --git a/prng/include/ss_prng.h b/prng/include/ss_prng.h new file mode 100755 index 0000000..9e54712 --- /dev/null +++ b/prng/include/ss_prng.h @@ -0,0 +1,69 @@ +// +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// 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 +// +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// 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 ss_prng.h + * @brief This header file contains declarations of Pseudo Random Function based on ANSI X9.31 Appendix A.2.4. + */ + +/** + * Generate random numbers as per X9.31 specification using algorithm passed as input. + */ + +#ifndef __SS_PRNG__ +#define __SS_PRNG__ + +#define LOG_TAG "SECURE_STORAGE" +struct evp_cipher_st; + + +#define SS_PRNG_SUCCESS 0 +#define SS_PRNG_ERROR_INVALID_ARG -1 +#define SS_PRNG_ERROR_OUT_OF_MEMORY -2 +#define SS_PRNG_ERROR_SYSTEM -3 + + +#define TryCatch(condition, expr, ...) \ + if (!(condition)) { \ + SLOGE(__VA_ARGS__); \ + expr; \ + goto CATCH; \ + } \ + else {;} + +/** + * Generate random numbers as per X9.31 specification using algorithm passed as input. + * + * @return Returns pointer to byte buffer containing generated random number. + * @param[in] pAlg Pointer to algorithm used for random number generation. Supports EVP_des_ecb(), EVP_des_ede3_ecb() and EVP_AES_128_ecb(). + * @param[in] requiredLength Integer type indicating required size of random number. + */ +unsigned char* GetRandomBytesN(struct evp_cipher_st* pAlg, long requiredLength); + +#endif diff --git a/prng/include/ss_prng_impl.h b/prng/include/ss_prng_impl.h new file mode 100755 index 0000000..217d938 --- /dev/null +++ b/prng/include/ss_prng_impl.h @@ -0,0 +1,108 @@ +// +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// 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 +// +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// 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 ss_prng_impl.h + */ + +#ifndef __SS_INTERNAL_PRNG_IMPL__ +#define __SS_INTERNAL_PRNG_IMPL__ + +#include +#include "ss_prng.h" + +typedef unsigned char byte; +/** + * Defines the Prng context structure. + */ +typedef struct +{ + unsigned long lenSeed; //seed length + unsigned long blockSize; //block size + unsigned long randSize; + unsigned long curOffset; + unsigned long lenKey; //key length + byte* pKey; + byte* pSeed; + byte* pRand; //holds only reference - memory pointer by this variable to be freed by caller + struct evp_cipher_st* pAlg; //algorithm type +} PrngContext; + +typedef struct +{ + byte* pBuffer; + int bufferLen; +} PrngByteBuffer; + +/** + * Generate and fill keys in PrngContext. + * + * @return An error code. + * @param[in] prng Reference to PRNG context structure. + */ +int GenerateKey(PrngContext* prng); + +/** + * Generate and fill seed in PrngContext. + * + * @return An error code. + * @param[in] prng Reference to PRNG context. + */ +int GenerateSeed(PrngContext* prng); + +/** + * Perform XOR operation using content in in1 and in2 and store output in out. + * + * @param[in] pIn1 Pointer to input buffer 1. + * @param[in] pIn2 Pointer to input buffer 2. + * @param[in] inLen Length of input buffer. + * @param[out] pOut Pointer to out buffer to which output is stored. + */ +void PerformXor(byte* pIn1, byte* pIn2, unsigned long inLen, byte* pOut); + +/** + * Generate random number. + * + * @since 2.1 + * @return An error code. + * @param[in] prng Reference to PRNG context. + * @param[in] pSeed Pointer to byte buffer containing date factor . + */ +int GenerateRandomBytes(PrngContext* prng, PrngByteBuffer* pSeed); + +/** + * Create PRNG context. + * + * @since 2.1 + * @return Returns pointer to PRNG context on success,NULL on failure. + */ +PrngContext* CreatePrngContextN(void); + + +#endif diff --git a/prng/src/ss_prng.c b/prng/src/ss_prng.c new file mode 100755 index 0000000..46019c5 --- /dev/null +++ b/prng/src/ss_prng.c @@ -0,0 +1,349 @@ +// +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// 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 ss_prng.cpp + * @brief This file contains implementation of Pseudo Random Function based on ANSI X9.31 Appendix A.2.4. + * + */ +#include +#include +#include +#include +#include +#include "ss_prng_impl.h" + +void DestroyPrngContext(PrngContext* pPrng) +{ + if(pPrng) + { + if(pPrng->pKey) + { + free(pPrng->pKey); + pPrng->pKey = NULL; + } + if(pPrng->pSeed) + { + free(pPrng->pSeed); + pPrng->pSeed = NULL; + } + free(pPrng); + pPrng = NULL; + } +} + +byte* GetRandomBytesN(struct evp_cipher_st* pAlg, long outLen) +{ + int r = SS_PRNG_SUCCESS; + byte* pRetBuf = NULL; + if(!pAlg || outLen <= 0) + { + SLOGE("Input data are not valid."); + return NULL; + } + + PrngContext* pPrng = CreatePrngContextN(); + if(pPrng == NULL) + { + SLOGE("Allocating new PrngContext object failed."); + return NULL; + } + + byte* pOutBuf = (byte*)malloc(sizeof(byte) * outLen); + TryCatch(pOutBuf != NULL, , "Allocating new byte buffer failed"); + + // init pAlg details + pPrng->pAlg = pAlg; + pPrng->lenKey = pAlg->key_len; + pPrng->blockSize = pAlg->block_size; + pPrng->lenSeed = pPrng->blockSize; + + r = GenerateKey(pPrng); + TryCatch(r == SS_PRNG_SUCCESS, free(pOutBuf), "Failed to generate key"); + + r = GenerateSeed(pPrng); + TryCatch(r == SS_PRNG_SUCCESS, free(pOutBuf), "Failed to generate seed"); + + pPrng->pRand = pOutBuf; + pPrng->randSize = outLen; + pPrng->curOffset = 0; + + r = GenerateRandomBytes(pPrng, NULL); + TryCatch(r == SS_PRNG_SUCCESS, free(pOutBuf), "Failed to generate random bytes"); + + pRetBuf = pOutBuf; + +CATCH: + DestroyPrngContext(pPrng); + + return pRetBuf; +} + +int GenerateKey(PrngContext* prng) +{ + unsigned long index = 0; + unsigned long offset = 0; + clock_t tick = NULL; + + prng->pKey = (byte*)malloc(sizeof(byte) * prng->lenKey); + if(!prng->pKey) + { + SLOGE("Allocating new byte array failed."); + return SS_PRNG_ERROR_OUT_OF_MEMORY; // E_OUT_OF_MEMORY + } + + offset = 0; + index = sizeof(clock_t); + + while (offset < prng->lenKey) + { + if ((offset + sizeof(clock_t)) > prng->lenKey) + { + index = prng->lenKey - offset; + } + tick = clock(); + PerformXor(prng->pKey + offset, (byte*)(&tick), index, prng->pKey + offset); + offset += index; + } + + prng->lenKey = offset; + return SS_PRNG_SUCCESS; +} + +int GenerateSeed(PrngContext* prng) +{ + unsigned long offset = 0; + unsigned long index = 0; + clock_t tick = 0; + time_t miliSecond = 0; + + miliSecond = time(NULL); + + prng->pSeed = (byte*)malloc(sizeof(byte) * prng->lenSeed); + if(!prng->pSeed) + { + SLOGE("Allocating new byte array failed."); + return SS_PRNG_ERROR_OUT_OF_MEMORY; // E_OUT_OF_MEMORY + } + + offset = 0; + index = sizeof(clock_t); + + while (offset < prng->lenSeed) + { + if ((offset + sizeof(clock_t)) > prng->lenSeed) + { + index = prng->lenSeed - offset; + } + + tick = clock(); + tick = tick + miliSecond; + PerformXor(prng->pSeed + offset, (byte*)(&tick), index, prng->pSeed + offset); + offset += index; + } + + prng->lenSeed = offset; + return SS_PRNG_SUCCESS; +} + +void PerformXor(byte* pIn1, byte* pIn2, unsigned long inLen, byte* pOut) +{ + unsigned long index = 0; + + for (index = 0; index < inLen; index++) + { + pOut[index] = pIn1[index] ^ pIn2[index]; + } + +} + +int GenerateRandomBytes(PrngContext* prng, PrngByteBuffer* pSeed) +{ + int r = SS_PRNG_SUCCESS; + unsigned int ret = 0; + unsigned long tmp = 0; + unsigned long offset = 0; + unsigned long lenInterVal1 = 0; + unsigned long lenInterVal2 = 0; + unsigned long dtLen = 0; + unsigned long blockSize = prng->blockSize; + unsigned long randSize = prng->randSize; + unsigned long lenInterVal1XorBlockLen = 0; + unsigned long lenInterVal2XorInterVal1 = 0; + + byte* pBlock = NULL; + byte* pInterVal1 = NULL; + byte* pInterVal2 = NULL; + byte* pInterVal1XorBlock = NULL; + byte* pInterVal2XorInterVal1 = NULL; + + byte* pDt = NULL; + clock_t tick = NULL; + EVP_CIPHER_CTX cipherCtx; + const EVP_CIPHER* pEncryptionAlgorithm = NULL; + + EVP_CIPHER_CTX_init(&cipherCtx); + + if (pSeed != NULL) + { + pDt = (byte*)pSeed->pBuffer; + dtLen = pSeed->bufferLen; + } + + pBlock = (byte*)malloc(sizeof(byte) * blockSize); + TryCatch(pBlock != NULL, r = SS_PRNG_ERROR_OUT_OF_MEMORY, "Allocating new byte array failed."); + + pInterVal1 = (byte*)malloc(sizeof(byte) * blockSize); + TryCatch(pInterVal1 != NULL, r = SS_PRNG_ERROR_OUT_OF_MEMORY, "Allocating new byte array failed."); + + pInterVal2 = (byte*)malloc(sizeof(byte) * blockSize); + TryCatch(pInterVal2 != NULL, r = SS_PRNG_ERROR_OUT_OF_MEMORY, "Allocating new byte array failed."); + + pInterVal1XorBlock = (byte*)malloc(sizeof(byte) * blockSize); + TryCatch(pInterVal1XorBlock != NULL, r = SS_PRNG_ERROR_OUT_OF_MEMORY, "Allocating new byte array failed."); + + pInterVal2XorInterVal1 = (byte*)malloc(sizeof(byte) * blockSize); + TryCatch(pInterVal2XorInterVal1 != NULL, r = SS_PRNG_ERROR_OUT_OF_MEMORY, "Allocating new byte array failed."); + + lenInterVal1 = blockSize; + lenInterVal2 = blockSize; + lenInterVal1XorBlockLen = blockSize; + lenInterVal2XorInterVal1 = blockSize; + + while (prng->curOffset < randSize) + { + blockSize = prng->blockSize; + + if (pDt == NULL) + { + time_t sttime = NULL; + sttime = time(NULL); + + //get D and append with xor of clock tick and random value in buffer till block size is reached + memcpy(pBlock, (byte*)(&sttime), sizeof(time_t)); + + offset += sizeof(time_t); + tmp = sizeof(clock_t); + while (offset < blockSize) + { + if ((offset + sizeof(clock_t)) > blockSize) + { + tmp = blockSize - offset; + } + + tick = clock(); + PerformXor(pBlock + offset, (byte*)(&tick), tmp, pBlock + offset); + offset += tmp; + } + } + else + { + if (dtLen != blockSize) + { + r = SS_PRNG_ERROR_INVALID_ARG; + SLOGE("The seed length do not match the data block size."); + goto CATCH; + } + + memcpy(pBlock, pDt, dtLen); + } + + // Selects the encryption algorithm using prng.pAlg + pEncryptionAlgorithm = prng->pAlg; + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, prng->pKey, NULL, 0); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, pInterVal1, (int*)(&lenInterVal1), pBlock, blockSize); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + TryCatch(lenInterVal1 == blockSize, r = SS_PRNG_ERROR_INVALID_ARG, "The input and output data lengths do not match."); + + PerformXor(pInterVal1, prng->pSeed, blockSize, pInterVal1XorBlock); + lenInterVal1XorBlockLen = lenInterVal1; + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, prng->pKey, NULL, 0); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, pInterVal2, (int*)(&lenInterVal2), pInterVal1XorBlock, lenInterVal1XorBlockLen); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + TryCatch(lenInterVal2 == blockSize, r = SS_PRNG_ERROR_INVALID_ARG, "The input and output data lengths do not match."); + + PerformXor(pInterVal2, pInterVal1, blockSize, pInterVal2XorInterVal1); + lenInterVal2XorInterVal1 = blockSize; + + //Cipher init operation based on op mode + ret = EVP_CipherInit(&cipherCtx, pEncryptionAlgorithm, prng->pKey, NULL, 0); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + //if padding enabled or not + ret = EVP_CIPHER_CTX_set_padding(&cipherCtx, 0); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM, "An unexpected system error occurred."); + + //cipher update operation + ret = EVP_CipherUpdate(&cipherCtx, prng->pSeed, (int*)(&(prng->lenSeed)), pInterVal2XorInterVal1, lenInterVal2XorInterVal1); + TryCatch(ret == 1, r = SS_PRNG_ERROR_SYSTEM,"An unexpected system error occurred."); + + TryCatch(prng->lenSeed == blockSize, r = SS_PRNG_ERROR_INVALID_ARG, "The input and output data lengths do not match."); + + if ((prng->curOffset + lenInterVal2) > prng->randSize) + { + lenInterVal2 = prng->randSize - prng->curOffset; + } + + memcpy(prng->pRand + prng->curOffset, pInterVal2, lenInterVal2); + prng->curOffset += lenInterVal2; + } + +CATCH: + free(pBlock); + free(pInterVal1); + free(pInterVal2); + free(pInterVal1XorBlock); + free(pInterVal2XorInterVal1); + EVP_CIPHER_CTX_cleanup(&cipherCtx); + + return r; +} + +PrngContext* CreatePrngContextN(void) +{ + PrngContext* pPrng = NULL; + + pPrng =(PrngContext*)malloc(sizeof(PrngContext)); + if(!pPrng) + { + SLOGE("Allocating new PrngContext object failed."); + return NULL; + } + memset(pPrng, 0, sizeof(PrngContext)); + + return pPrng; +} + diff --git a/res/salt b/res/salt new file mode 100755 index 0000000..321404a Binary files /dev/null and b/res/salt differ diff --git a/secure-storage.pc.in b/secure-storage.pc.in index 7b23c7a..ae27633 100644 --- a/secure-storage.pc.in +++ b/secure-storage.pc.in @@ -1,6 +1,6 @@ prefix=@PREFIX@ exec_prefix=@EXEC_PREFIX@ -libdir=@LIB_INSTALL_DIR@ +libdir=@LIBDIR@ includedir=@INCLUDEDIR@ Name: secure-storage diff --git a/server/include/ss_server_ipc.h b/server/include/ss_server_ipc.h deleted file mode 100644 index 641c075..0000000 --- a/server/include/ss_server_ipc.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * 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. - * - */ - -/* - * Declare new function - * - * @name: SsServerComm - * @parameter: void - * @return type: void - */ -void SsServerComm(void); -char* get_key_file_path(void); diff --git a/server/include/ss_server_main.h b/server/include/ss_server_main.h deleted file mode 100755 index 52ef9ed..0000000 --- a/server/include/ss_server_main.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include "ss_manager.h" - -/* - * Declare new function - * - * @name: SsServerDataStore - * @parameter - * - sender_pid - * - filepath - * @return type: int - */ -#ifndef SMACK_GROUP_ID -int SsServerDataStoreFromFile(int sender_pid, const char* filepath, ssm_flag flag, const char* cookie, const char* group_id); -int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* cookie, const char* group_id); -#else -int SsServerDataStoreFromFile(int sender_pid, const char* filepath, ssm_flag flag, int sockfd, const char* group_id); -int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, int sockfd, const char* group_id); -#endif - -/* - * Declare new function - * - * @name: SsServerDataRead - * @parameter - * - sender_pid - * - filepath - * - pRetBuf - * - count - * - redLen - * @return type: int - */ -#ifndef SMACK_GROUP_ID -int SsServerDataRead(int sender_pid, const char* filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, const char* cookie, const char* group_id); -#else -int SsServerDataRead(int sender_pid, const char* filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, int sockfd, const char* group_id); -#endif -/* - * Declare new function - * - * @name: SsServerGetInfo - * @parameter - * - sender_pid - * - filepath - * - file_info - * @return type: int - */ - -#ifndef SMACK_GROUP_ID -int SsServerGetInfo(int sender_pid, const char* filepath, char* file_info, ssm_flag flag, const char* cookie, const char* group_id); -int SsServerDeleteFile(int sender_pid, const char* filepath, ssm_flag flag, const char* cookie, const char* group_id); -#else -int SsServerGetInfo(int sender_pid, const char* filepath, char* file_info, ssm_flag flag, int sockfd, const char* group_id); -int SsServerDeleteFile(int sender_pid, const char* filepath, ssm_flag flag, int sockfd, const char* group_id); -#endif - - diff --git a/server/non-tz/include/ss_server_ipc.h b/server/non-tz/include/ss_server_ipc.h new file mode 100644 index 0000000..4245508 --- /dev/null +++ b/server/non-tz/include/ss_server_ipc.h @@ -0,0 +1,31 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * 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. + * + */ + + +/* + * Declare new function + * + * @name: SsServerComm + * @parameter: void + * @return type: void + */ +void SsServerComm(void); +char* get_key_file_path(void); diff --git a/server/non-tz/include/ss_server_main.h b/server/non-tz/include/ss_server_main.h new file mode 100755 index 0000000..49cc7b7 --- /dev/null +++ b/server/non-tz/include/ss_server_main.h @@ -0,0 +1,31 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "ss_manager.h" + +int SsServerDataStoreFromFile(int sender_pid, const char* filepath, ssm_flag flag, int sockfd, const char* group_id); +int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, int sockfd, const char* group_id); +int SsServerDataRead(int sender_pid, const char* filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, int sockfd, const char* group_id); +int SsServerGetInfo(int sender_pid, const char* filepath, char* file_info, ssm_flag flag, int sockfd, const char* group_id); +int SsServerDeleteFile(int sender_pid, const char* filepath, ssm_flag flag, int sockfd, const char* group_id); + + +int SsServerGetDuk(int client_sockfd, char* pBuffer, unsigned int* pBufferLen, char* pAppId, unsigned int flag); diff --git a/server/non-tz/src/ss_server_ipc.c b/server/non-tz/src/ss_server_ipc.c new file mode 100755 index 0000000..0e680de --- /dev/null +++ b/server/non-tz/src/ss_server_ipc.c @@ -0,0 +1,567 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "secure_storage.h" +#include "ss_server_ipc.h" +#include "ss_server_main.h" + +#define CONF_FILE_PATH "/usr/share/secure-storage/config" +#define KEY_SIZE 16 +#define VCONF_SMACK_UPDATE_FILE_PATH_KEY_NODE "db/smack/spd_policy_filepath" +#define VCONF_UPDATE_RESULT_KEY_NODE "db/smack/spd_update_result" +#define VCONF_UPDATE_RESULT_KEY_NODE_FOR_APP "db/smack/spd_update_result2" + +static GMainLoop *event_loop; + +char* get_key_file_path() +{ + FILE* fp_conf = NULL; + char buf[128]; + char* retbuf = NULL; + char seps[] = " :\n\r\t"; + char* token = NULL; + + retbuf = (char*)malloc(sizeof(char) * 128); + if(!retbuf) + { + SLOGE("fail to allocate memory.\n"); + return NULL; + } + memset(buf, 0x00, 128); + memset(retbuf, 0x00, 128); + + if(!(fp_conf = fopen(CONF_FILE_PATH, "r"))) + { + SLOGE("Configuration file is not exist\n"); + free(retbuf); + return NULL; + } + + while(fgets(buf, 128, fp_conf)) + { + token = strtok(buf, seps); + if(token != NULL) + { + if(!strncmp(token, "MASTER_KEY_PATH", 15)) // master key path + { + token = strtok(NULL, seps); // real path + break; + } + } + token = NULL; + } + fclose(fp_conf); + + if(token) + strncpy(retbuf, token, 127); + else { + if(retbuf != NULL) + free(retbuf); + return NULL; + } + + return retbuf; +} + +int check_key_file() +{ + FILE* fp_key = NULL; + char* key_path = NULL; + + key_path = get_key_file_path(); + if(key_path == NULL) + { + SLOGE("Configuration file is not exist\n"); + return 0; + } + + if(!(fp_key = fopen(key_path, "r"))) + { + SLOGE("Secret key file is not exist, [%s]\n", key_path); + free(key_path); + return 0; + } + + free(key_path); + fclose(fp_key); + return 1; +} + +int make_key_file() +{ + FILE* fp_key = NULL; + int random_dev = -1; + int i = 0; + char tmp_key[1]; + char key[33]; + char* key_path = NULL; + int read_len = 0; + + memset(key, 0x00, 33); + + key_path = get_key_file_path(); + if(key_path == NULL) + { + SLOGE("Configuration file is not exist\n"); + return 0; + } + + if((random_dev = open("/dev/urandom", O_RDONLY)) < 0) + { + SLOGE("Random device Open error\n"); + free(key_path); + return 0; + } + + while(i < 32) + { + read_len = read(random_dev, tmp_key, 1); + if(read_len < 0) + { + SLOGE("read error from random file"); + break; + } + + if((tmp_key[0] >= '!') && (tmp_key[0] <= '~')) { + key[i] = tmp_key[0]; + i++; + } + } + + if(!(fp_key = fopen(key_path, "w"))) + { + SECURE_SLOGE("Secret key file Open error, [%s]\n", key_path); + free(key_path); + close(random_dev); + return 0; + } + + fprintf(fp_key, "%s", key); + + if(chmod(key_path, 0600)!=0) + { + SLOGE("Secret key file chmod error, [%s]\n", strerror(errno)); + free(key_path); + close(random_dev); + fclose(fp_key); + return 0; + } + + free(key_path); + fclose(fp_key); + close(random_dev); + return 1; +} + +/* for executing coverage tool (2009-04-03) */ +void SigHandler(int signo) +{ + SLOGI("Got Signal %d\n", signo); + exit(1); +} +/* end */ + + +int GetSocketFromSystemd(int* pSockfd) +{ + int n = sd_listen_fds(0); + int fd; + + for(fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) { + if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1, + SS_SOCK_PATH, 0)) + { + *pSockfd = fd; + return 1; + } + } + return 0; +} + +int CreateNewSocket(int* pSockfd) +{ + int server_sockfd = 0; + int temp_len_sock = 0; + struct sockaddr_un serveraddr; + + if((server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) + { + SLOGE("Error in function socket()..\n"); + return 0; + } + + temp_len_sock = strlen(SS_SOCK_PATH); + + bzero(&serveraddr, sizeof(serveraddr)); + serveraddr.sun_family = AF_UNIX; + strncpy(serveraddr.sun_path, SS_SOCK_PATH, temp_len_sock); + serveraddr.sun_path[temp_len_sock] = '\0'; + + if((bind(server_sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr))) < 0) + { + unlink("/tmp/SsSocket"); + if((bind(server_sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr))) < 0) + { + SLOGE("Error in function bind()..\n"); + close(server_sockfd); + return 0; // ipc error + } + } + + if(chmod(SS_SOCK_PATH, S_IRWXU | S_IRWXG | S_IRWXO) != 0) + { + close(server_sockfd); + return 0; + } + + *pSockfd = server_sockfd; + return 1; +} + + +void SsServerComm(void) +{ + int server_sockfd, client_sockfd; + int client_len; + struct sockaddr_un clientaddr, serveraddr; + + struct ucred cr; // for test client pid. 2009-03-24 + int cl = sizeof(cr); // + int temp_len_sock = 0; + int temp_len_in = 0; + + ReqData_t recv_data = {0, }; + RspData_t send_data = {0, }; + + + server_sockfd = client_sockfd = -1; + + if(!GetSocketFromSystemd(&server_sockfd)) + { + SLOGE("Failed to get sockfd from systemd"); + if(!CreateNewSocket(&server_sockfd)) + { + SLOGE("Failed to create socket"); + send_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_exit; + } + if((listen(server_sockfd, 5)) < 0) + { + SLOGE("Error in function listen()..\n"); + send_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_close_exit; + } + } + else + { + SLOGD("Get socket from systemd"); + } + + client_len = sizeof(clientaddr); + + signal(SIGINT, (void*)SigHandler); + + while(1) + { + errno = 0; + + if((client_sockfd = accept(server_sockfd, (struct sockaddr*)&clientaddr, (socklen_t*)&client_len)) < 0) + { + SLOGE("Error in function accept()..[%d, %d]\n", client_sockfd, errno); + send_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_close_exit; + } + + // for test client pid. 2009-03-24 + if(getsockopt(client_sockfd, SOL_SOCKET, SO_PEERCRED, &cr, (socklen_t*)&cl) != 0) + { + SLOGE("getsockopt() fail\n"); + } + // end + + if(read(client_sockfd, (char*)&recv_data, sizeof(recv_data)) < 0) + { + SLOGE("Error in function read()..\n"); + send_data.rsp_type = SS_SOCKET_ERROR; // ipc error + goto Error_close_exit; + } + + temp_len_in = strlen(recv_data.data_infilepath); + + switch(recv_data.req_type) + { + case 1: + send_data.rsp_type = SsServerDataStoreFromFile(cr.pid, recv_data.data_infilepath, recv_data.flag, client_sockfd, recv_data.group_id); + + if(send_data.rsp_type == 1) + { + strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_SIZE); + send_data.data_filepath[temp_len_in] = '\0'; + } + else + { + strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_SIZE); + send_data.data_filepath[15] = '\0'; + } + + write(client_sockfd, (char*)&send_data, sizeof(send_data)); + break; + case 2: + send_data.rsp_type = SsServerDataStoreFromBuffer(cr.pid, recv_data.buffer, recv_data.count, recv_data.data_infilepath, recv_data.flag, client_sockfd, recv_data.group_id); + + if(send_data.rsp_type == 1) + { + strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_SIZE); + send_data.data_filepath[temp_len_in] = '\0'; + } + else + { + strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_SIZE); + send_data.data_filepath[15] = '\0'; + } + + write(client_sockfd, (char*)&send_data, sizeof(send_data)); + break; + case 3: + send_data.rsp_type = SsServerDataRead(cr.pid, recv_data.data_infilepath, send_data.buffer, recv_data.count, &(send_data.readLen), recv_data.flag, client_sockfd, recv_data.group_id); + + if(send_data.rsp_type == 1) + { + strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_SIZE); + send_data.data_filepath[temp_len_in] = '\0'; + } + else + { + strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_SIZE); + send_data.data_filepath[15] = '\0'; + } + + write(client_sockfd, (char*)&send_data, sizeof(send_data)); + break; + case 4: + send_data.rsp_type = SsServerGetInfo(cr.pid, recv_data.data_infilepath, send_data.buffer, recv_data.flag, client_sockfd /*recv_data.cookie*/, recv_data.group_id); + + if(send_data.rsp_type == 1) + { + strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_SIZE); + send_data.data_filepath[temp_len_in] = '\0'; + } + else + { + strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_SIZE); + send_data.data_filepath[15] = '\0'; + } + + write(client_sockfd, (char*)&send_data, sizeof(send_data)); + break; + case 5: + send_data.rsp_type = SsServerGetDuk(client_sockfd, send_data.buffer, &(send_data.readLen), recv_data.group_id, recv_data.flag); + write(client_sockfd, (char*)&send_data, sizeof(send_data)); + break; + case 10: + send_data.rsp_type = SsServerDeleteFile(cr.pid, recv_data.data_infilepath, recv_data.flag, client_sockfd, recv_data.group_id); + + if(send_data.rsp_type == 1) + { + strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_SIZE); + send_data.data_filepath[temp_len_in] = '\0'; + } + else + { + strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_SIZE); + send_data.data_filepath[15] = '\0'; + } + + write(client_sockfd, (char*)&send_data, sizeof(send_data)); + break; + + default: + SLOGE("Input error..Please check request type\n"); + break; + } + close(client_sockfd); + } + +Error_close_exit: + close(server_sockfd); + +Error_exit: + strncpy(send_data.data_filepath, "error", MAX_FILENAME_SIZE); + send_data.data_filepath[5] = '\0'; + + if(client_sockfd >= 0) + { + write(client_sockfd, (char*)&send_data, sizeof(send_data)); + close(client_sockfd); + } + else + SLOGE("cannot connect to client socket.\n"); +} + +int SsServerUpdateSmackPolicy() +{ + typedef int (*SmackPolicyUpdateFuncPointer)(); + SmackPolicyUpdateFuncPointer pSmackPolicyUpdateFuncPointer = NULL; + int errCode = -1; + + void* dlHandle = dlopen("/usr/lib/libsmack-update-service.so", RTLD_LAZY); + + if (!dlHandle) + { + SLOGE("Failed to open so with reason : %s", dlerror()); + return errCode; + } + + pSmackPolicyUpdateFuncPointer = (SmackPolicyUpdateFuncPointer)dlsym(dlHandle, "spd_smack_policy_update"); + if (dlerror() != NULL) + { + SLOGE("Failed to find spd_smack_policy_update symbol : %s", dlerror()); + goto free_data; + } + + errCode = pSmackPolicyUpdateFuncPointer(); + + free_data: + + if(dlHandle){ + dlclose(dlHandle); + } + + return errCode; +} + +void vconf_smack_update_cb(keynode_t *key, void* data) +{ + SLOGD("Callback received"); + int errorCode; + + switch(vconf_keynode_get_type(key)) + { + case VCONF_TYPE_INT: + printf("key = %s, value = %d(int)\n", + vconf_keynode_get_name(key), vconf_keynode_get_int(key)); + break; + case VCONF_TYPE_STRING: + { + printf("key = %s, value = %s(string)\n", + vconf_keynode_get_name(key), vconf_keynode_get_str(key)); + if (vconf_keynode_get_str(key)) + { + errorCode = SsServerUpdateSmackPolicy(); + LOGD("set the updation status with value %d", errorCode); + // set the update result for fota team + int ret = vconf_set_int(VCONF_UPDATE_RESULT_KEY_NODE, errorCode); + if (ret != VCONF_OK) + { + LOGD("failed to set the updation status for fota"); + } + + // set the update result for the app control + ret = vconf_set_int(VCONF_UPDATE_RESULT_KEY_NODE_FOR_APP, errorCode); + if (ret != VCONF_OK) + { + LOGD("failed to set the updation status for app control"); + } + } + + else + { + LOGD("file path is invalid"); + } + } + break; + fprintf(stderr, "Unknown Type(%d)\n", vconf_keynode_get_type(key)); + break; + } + + printf("%s Notification OK", (char *)data); + return; +} + +int vconf_smack_update(void* pData) +{ + vconf_notify_key_changed(VCONF_SMACK_UPDATE_FILE_PATH_KEY_NODE, vconf_smack_update_cb, NULL); + + event_loop = g_main_loop_new(NULL, FALSE); + g_main_loop_run(event_loop); + return 0; +} + + +int main(void) +{ + SLOGI("Secure Storage Server Start..\n"); + + int exist_ret = -1; + int make_ret = -1; + DIR* dp = NULL; // make default directory(if not exist) + pthread_t main_thread; + + pthread_create(&main_thread, NULL, vconf_smack_update, NULL); + if((dp = opendir(SS_STORAGE_DEFAULT_PATH)) == NULL) + { + SLOGI("directory [%s] is not exist, making now.\n", SS_STORAGE_DEFAULT_PATH); + if(mkdir(SS_STORAGE_DEFAULT_PATH, 0700) < 0) + { + int err_tmp = errno; + SLOGE("Failed while making [%s] directory. Errno: %s\n", SS_STORAGE_DEFAULT_PATH, strerror(err_tmp)); + return 0; + } + } + else + closedir(dp); + + exist_ret = check_key_file(); // if 0, there is not key file. Or 1, exist. + + if(exist_ret == 0) + { + make_ret = make_key_file(); + + if(make_ret == 0) + { + SLOGE("Making key file fail. ss-server will be terminated..\n"); + return 0; + } + } + + SsServerComm(); + + return 0; +} diff --git a/server/non-tz/src/ss_server_main.c b/server/non-tz/src/ss_server_main.c new file mode 100755 index 0000000..6d74541 --- /dev/null +++ b/server/non-tz/src/ss_server_main.c @@ -0,0 +1,969 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Contact: Kidong Kim + * + * 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. + * + */ + +/* encrypted file format + * + * total file size = metadata (8 bytes) + realdata (...) + * ----------------------------------------------------------- + * | metadata | realdata | + * ----------------------------------------------------------- + * 0 16 EOF + * metadata -> ssm_file_info_t + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "secure_storage.h" +#include "ss_server_main.h" +#include "ss_server_ipc.h" +#include +#include "SecTzSvc.h" + +#define CONF_FILE_PATH "/usr/share/secure-storage/config" + +#define ENCRYPT_SIZE 1024 + +/* skey : need to help from hardware */ +char skey[KEY_SIZE+1] = "thisisasecretkey"; + +/*************************************************************************** + * Internal functions + **************************************************************************/ + +char* get_preserved_dir() +{ + FILE* fp_conf = NULL; + char buf[128]; + char* retbuf = NULL; + char seps[] = " :\n\r\t"; + char* token = NULL; + + retbuf = (char*)malloc(sizeof(char) * 128); + if(retbuf == NULL) + { + SLOGE("malloc return NULL\n"); + return NULL; + } + memset(buf, 0x00, 128); + memset(retbuf, 0x00, 128); + + if(!(fp_conf = fopen(CONF_FILE_PATH, "r"))) + { + SLOGE("Configuration file is not exist\n"); + free(retbuf); + return NULL; + } + + while(fgets(buf, 128, fp_conf)) + { + token = strtok(buf, seps); + if(token != NULL) + { + if(!strncmp(token, "PRESERVE_DIR", 12)) // preserve directory? + { + token = strtok(NULL, seps); // real path + break; + } + } + token = NULL; + } + fclose(fp_conf); + + if(token) + strncpy(retbuf, token, 127); + else { + free(retbuf); + return NULL; + } + + return retbuf; +} + +int IsSmackEnabled() +{ + FILE *file = NULL; + if(file = fopen("/smack/load2", "r")) + { + fclose(file); + return 1; + } + return 0; +} + +/* get key from hardware( ex. OMAP e-fuse random key ) */ +void GetKey(char* key, unsigned char* iv) +{ + FILE* fp_key = NULL; + char buf[33]; + char* key_path = NULL; + + memset(buf, 0x00, 33); + + key_path = get_key_file_path(); + if(key_path == NULL) + { + SLOGE("Configuration file is not exist\n"); + memcpy(buf, skey, KEY_SIZE); + } + else + { + if(!(fp_key = fopen(key_path, "r"))) + { + SLOGE("Secret key file opening error\n"); + memcpy(buf, skey, KEY_SIZE); + } + else + { + if(!fgets(buf, 33, fp_key)) + { + SLOGE("Secret key file reading error\n"); + memcpy(buf, skey, KEY_SIZE); // if fail to get key, set to default value. + } + } + } + + if(key) + strncpy(key, buf, KEY_SIZE); + if(iv) + strncpy(iv, buf+KEY_SIZE, KEY_SIZE); + + if(key_path) + free(key_path); + if(fp_key) + fclose(fp_key); +} + +unsigned short GetHashCode(const unsigned char* pString) +{ + unsigned short hash = 5381; + int len = SHA_DIGEST_LENGTH; + int i; + + for(i = 0; i < len; i++) + { + hash = ((hash << 5) + hash) + (unsigned short)pString[i]; // hash * 33 + ch + } + + return hash; +} + +int IsDirExist(char* dirpath) +{ + DIR* dp = NULL; + + if((dp = opendir(dirpath)) == NULL) // dir is not exist + { + SECURE_SLOGE("directory [%s] is not exist.\n", dirpath); + return 0; // return value '0' represents dir is not exist + } + else + { + closedir(dp); + return 1; + } + + return -1; +} + +int check_privilege_by_sockfd(int sockfd, const char* object, const char* access_rights) +{ + if(!IsSmackEnabled()) + return 0; + + int ret = security_server_check_privilege_by_sockfd(sockfd, object, access_rights); + SECURE_SLOGD("object : %s, access_rights : %s, ret : %d", object, access_rights, ret); + return ret; +} + +/* convert normal file path to secure storage file path */ +int ConvertFileName(int sender_pid, char* dest, const char* src, ssm_flag flag, const char* group_id) +{ + char s[33+1]; + const char* dir = group_id; + char* preserved_dir = NULL; + int is_dir_exist = -1; + + if(!dest || !src) + { + SLOGE("Parameter error in ConvertFileName()...\n"); + return SS_FILE_OPEN_ERROR; // file related error + } + + if(CreateStorageDir(SS_STORAGE_DEFAULT_PATH) < 0) + { + return SS_FILE_OPEN_ERROR; + } + // TBD + strncpy(dest, SS_STORAGE_DEFAULT_PATH, strlen(SS_STORAGE_DEFAULT_PATH)); + dest[strlen(SS_STORAGE_DEFAULT_PATH)] = 0; + + strncat(dest, dir, (strlen(dir))); // add top-dir + dir(label) + strncat(dest, "/", 1); + + if(CreateStorageDir(dest) < 0) + { + return SS_FILE_OPEN_ERROR; + } + + strncat(dest, "_", 1); // /top-dir/label/_ + + GetPathHash(src, s); + strncat(dest, s, strlen(s)); // /top-dir/label/_hash + strncat(dest, SS_FILE_POSTFIX, strlen(SS_FILE_POSTFIX)); // /top-dir/label/_hash.e + + SECURE_SLOGD("final dest : %s", dest); + + return 1; +} + +int GetProcessExecPath(int pid, char* buffer) +{ + char tmp_cmd[32] = {0,}; + FILE *fp_proc = NULL; + snprintf(tmp_cmd, 32, "/proc/%d/cmdline", pid); + + if(!(fp_proc = fopen(tmp_cmd, "r"))) + { + SLOGE("file open error: [%s]", tmp_cmd); + return SS_FILE_OPEN_ERROR; + } + + fgets((char*)buffer, 256, fp_proc); + fclose(fp_proc); + + return 0; +} + +int GetProcessSmackLabel(int sockfd, char* proc_smack_label) +{ + char* smack_label = security_server_get_smacklabel_sockfd(sockfd); + if(smack_label && strlen(smack_label) < MAX_GROUP_ID_SIZE) + { + strncpy(proc_smack_label, smack_label, MAX_GROUP_ID_SIZE); + free(smack_label); + } + else + { + SLOGE("failed to get smack label"); + if(smack_label) + free(smack_label); + return -1; // SS_SECURITY_SERVER_ERROR? + } + SECURE_SLOGD("defined smack label : %s", proc_smack_label); + return 0; +} + +int GetPathHash(const char *src, char *output) +{ + unsigned short h_code = 0; + unsigned char path_hash[SHA_DIGEST_LENGTH + 1]; + + SHA1((unsigned char*)src, (size_t)strlen(src), path_hash); + h_code = GetHashCode(path_hash); + memset(output, 0x00, 34); + snprintf(output, 34, "%u", h_code); + + SLOGD("hashing src : %s to output : %s", src, output); + + return 0; +} + + +int CreateStorageDir(const char* path) +{ + int is_dir_exist = IsDirExist(path); + + if (is_dir_exist == 0) // path directory is not exist + { + SLOGI("directory [%s] is making now.\n", path); + if(mkdir(path, 0700) < 0) // fail to make directory + { + SLOGE("[%s] cannot be made\n", SS_STORAGE_DEFAULT_PATH); + return SS_SECURE_STORAGE_ERROR; + } + } + + return 0; +} + +/* + * if group_id is given, use group_id + * + * if NULL group_id is given + * smack enable : use process smack label + * smack disable : use process exec path + * + */ +int GetProcessStorageDir(int sockfd, int sender_pid, const char* group_id, char* output) +{ + char *object = group_id; + char proc_smack_label[MAX_GROUP_ID_SIZE+1] = {0,}; + char hash_buf[10] = {0, }; + int is_shared = strncmp(group_id, "NOTUSED", 7) ? 1 : 0; + +#ifdef SMACK_GROUP_ID + if(IsSmackEnabled()) + { + if(!is_shared) // don't share, use process smack label + { + if(GetProcessSmackLabel(sockfd, proc_smack_label) != 0) + { + return -SS_SECURE_STORAGE_ERROR; + } + object = proc_smack_label; + } + } + else{ +#endif + char exe_path[256] = {0,}; + int h_code2 = 0; + + if(!is_shared) // don't share + { + if(GetProcessExecPath(sender_pid, exe_path) != 0) + { + return -SS_SECURE_STORAGE_ERROR; + } + h_code2 = GetHashCode(exe_path); + snprintf(hash_buf, 10, "%u", h_code2); + object = hash_buf; + } +#ifdef SMACK_GROUP_ID + } +#endif + strncpy(output, object, MAX_GROUP_ID_SIZE); + return 0; +} + +void SetMetaData(ssm_file_info_convert_t* sfic, unsigned int orig_size, unsigned int stored_size, int flag) +{ + sfic->fInfoStruct.originSize = (unsigned int)orig_size; + sfic->fInfoStruct.storedSize = (unsigned int)stored_size; + sfic->fInfoStruct.reserved[0] = flag & 0x000000ff; +} + +/* aes crypto function wrapper - p_text : plain text, c_text : cipher text, aes_key : from GetKey, mode : ENCRYPT/DECRYPT, size : data size */ +unsigned char* AES_Crypto(unsigned char* p_text, unsigned char* c_text, char* aes_key, unsigned char* iv, int mode, unsigned long size) +{ + AES_KEY e_key, d_key; + + AES_set_encrypt_key((unsigned char*)aes_key, 128, &e_key); + AES_set_decrypt_key((unsigned char*)aes_key, 128, &d_key); + + if(mode == 1) + { + AES_cbc_encrypt(p_text, c_text, size, &e_key, iv, AES_ENCRYPT); + return c_text; + } + else + { + AES_cbc_encrypt(c_text, p_text, size, &d_key, iv, AES_DECRYPT); + return p_text; + } +} + + +/*************************************************************************** + * Function Definition + **************************************************************************/ +#ifndef SMACK_GROUP_ID +int SsServerDataStoreFromFile(int sender_pid, const char* data_filepath, ssm_flag flag, const char* cookie, const char* group_id) +#else +int SsServerDataStoreFromFile(int sender_pid, const char* data_filepath, ssm_flag flag, int sockfd, const char* group_id) +#endif +{ + char key[KEY_SIZE] = {0, }; + unsigned char iv[KEY_SIZE] = {0, }; + const char* in_filepath = data_filepath; + char out_filepath[MAX_FILENAME_SIZE] = {0, }; + FILE* fd_in = NULL; + FILE* fd_out = NULL; + struct stat file_info; + ssm_file_info_convert_t sfic; + int res = -1; + + unsigned char p_text[ENCRYPT_SIZE]= {0, }; + unsigned char e_text[ENCRYPT_SIZE]= {0, }; + + size_t read = 0, rest = 0; + + //0. get directory name and privilege check to access + char dir[MAX_GROUP_ID_SIZE+1] = {0,}; + if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) + { + SLOGE("Failed to get storage dir\n"); + return SS_SECURE_STORAGE_ERROR; + } + +#ifdef SMACK_GROUP_ID + if(check_privilege_by_sockfd(sockfd, dir, "w") < 0) + { + SLOGE("Permission denied\n"); + return SS_PERMISSION_DENIED; + } +#endif + + // 1. create out file name + ConvertFileName(sender_pid, out_filepath, in_filepath, flag, dir); + + // 2. file open + if(!(fd_in = fopen(in_filepath, "rb"))) + { + SECURE_SLOGE("File open error:(in_filepath) %s\n", in_filepath); + return SS_FILE_OPEN_ERROR; // file related error + } + + if(!(fd_out = fopen(out_filepath, "wb"))) + { + SECURE_SLOGE("File open error:(out_filepath) %s\n", out_filepath); + fclose(fd_in); + return SS_FILE_OPEN_ERROR; // file related error + } + if(chmod(out_filepath, 0600) < 0) + { + int err_tmp = errno; + SLOGE("chmod error: %s\n", strerror(err_tmp)); + fclose(fd_in); + fclose(fd_out); + return SS_FILE_OPEN_ERROR; // file related error + } + + // 3. write metadata + if(!stat(in_filepath, &file_info)) + { + SetMetaData(&sfic, file_info.st_size, (file_info.st_size/AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE, flag); + } + else + { + SLOGE("the function stat() fail.\n"); + fclose(fd_in); + fclose(fd_out); + return SS_FILE_READ_ERROR; + } + + fwrite(sfic.fInfoArray, 1, sizeof(ssm_file_info_t), fd_out); + + // 4. encrypt real data + read = fread(p_text, 1, ENCRYPT_SIZE, fd_in); + GetKey(key, iv); + + while(read == ENCRYPT_SIZE) + { + AES_Crypto(p_text, e_text, key, iv, 1, ENCRYPT_SIZE); + + fwrite(e_text, 1, ENCRYPT_SIZE, fd_out); + + memset(e_text, 0x00, ENCRYPT_SIZE); + memset(p_text, 0x00, ENCRYPT_SIZE); + read = fread( p_text, 1, ENCRYPT_SIZE, fd_in ); + } + + rest = AES_BLOCK_SIZE - (read % AES_BLOCK_SIZE); + AES_Crypto(p_text, e_text, key, iv, 1, read+rest); + fwrite(e_text, 1, read + rest, fd_out); + + if((res = fflush(fd_out)) != 0) { + SLOGE("fail to execute fflush().\n"); + fclose(fd_in); + fclose(fd_out); + return SS_FILE_WRITE_ERROR; + } + else { + SLOGI("success to execute fflush().\n"); + if((res = fsync(fd_out->_fileno)) == -1) { + SLOGE("fail to execute fsync().\n"); + fclose(fd_in); + fclose(fd_out); + return SS_FILE_WRITE_ERROR; + } + else + SLOGI("success to execute fsync(). read=[%d], rest=[%d]\n", read, rest); + } + + fclose(fd_in); + fclose(fd_out); + + return 1; +} + +#ifndef SMACK_GROUP_ID +int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* cookie, const char* group_id) +#else +int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, int sockfd, const char* group_id) +#endif +{ + char key[KEY_SIZE] = {0, }; + unsigned char iv[KEY_SIZE] = {0, }; + char out_filepath[MAX_FILENAME_SIZE+1] = {0, }; + char *buffer = NULL; + unsigned int writeLen = 0, loop, rest, count; + FILE *fd_out = NULL; + ssm_file_info_convert_t sfic; + unsigned char p_text[ENCRYPT_SIZE]= {0, }; + unsigned char e_text[ENCRYPT_SIZE]= {0, }; + int res = -1; + + writeLen = (unsigned int)(bufLen / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE; + buffer = (char*)malloc(writeLen + 1); + if(!buffer) + { + SLOGE("Memory Allocation Fail in SsServerDataStoreFromBuffer()..\n"); + return SS_MEMORY_ERROR; + } + memset(buffer, 0x00, writeLen); + memcpy(buffer, writebuffer, bufLen); + + //0. get directory name and privilege check + char dir[MAX_GROUP_ID_SIZE+1] = {0,}; + if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) + { + SLOGE("Failed to get storage dir\n"); + free(buffer); + return SS_SECURE_STORAGE_ERROR; + } + +#ifdef SMACK_GROUP_ID + if(check_privilege_by_sockfd(sockfd, dir, "w") < 0) + { + SLOGE("Permission denied\n"); + free(buffer); + return SS_PERMISSION_DENIED; + } +#endif + + // create file path from filename + ConvertFileName(sender_pid, out_filepath, filename, flag, dir); + + // open a file with write mode + if(!(fd_out = fopen(out_filepath, "wb"))) + { + SECURE_SLOGE("File open error:(out_filepath) %s\n", out_filepath); + free(buffer); + return SS_FILE_OPEN_ERROR; // file related error + } + if(chmod(out_filepath, 0600) < 0) + { + int err_tmp = errno; + SLOGE("chmod error: %s\n", strerror(err_tmp)); + free(buffer); + fclose(fd_out); + return SS_FILE_OPEN_ERROR; // file related error + } + + // write metadata + SetMetaData(&sfic, bufLen, writeLen, flag); + + fwrite(sfic.fInfoArray, 1, sizeof(ssm_file_info_t), fd_out); + + // encrypt buffer + loop = writeLen / ENCRYPT_SIZE; + rest = writeLen % ENCRYPT_SIZE; + GetKey(key, iv); + + for(count = 0; count < loop; count++) + { + memcpy(p_text, buffer+count*ENCRYPT_SIZE, ENCRYPT_SIZE); + AES_Crypto( p_text, e_text, key, iv, 1, ENCRYPT_SIZE); + fwrite(e_text, 1, ENCRYPT_SIZE, fd_out); + memset(e_text, 0x00, ENCRYPT_SIZE); + memset(p_text, 0x00, ENCRYPT_SIZE); + } + + memcpy(p_text, buffer + loop*ENCRYPT_SIZE, rest); + AES_Crypto(p_text, e_text, key, iv, 1, rest); + fwrite(e_text, 1, rest, fd_out); + + if((res = fflush(fd_out)) != 0) { + SLOGE("fail to execute fflush().\n"); + fclose(fd_out); + free(buffer); + return SS_FILE_WRITE_ERROR; + } + else { + SLOGI("success to execute fflush().\n"); + if((res = fsync(fd_out->_fileno)) == -1) { + SLOGE("fail to execute fsync().\n"); + fclose(fd_out); + free(buffer); + return SS_FILE_WRITE_ERROR; + } + else + SLOGI("success to execute fsync(). loop=[%d], rest=[%d]\n", loop, rest); + } + + fclose(fd_out); + free(buffer); + + return 1; +} + +#ifndef SMACK_GROUP_ID +int SsServerDataRead(int sender_pid, const char* data_filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, const char* cookie, const char* group_id) +#else +int SsServerDataRead(int sender_pid, const char* data_filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, int sockfd, const char* group_id) +#endif +{ + unsigned int offset = count * MAX_RECV_DATA_SIZE; + char key[KEY_SIZE] = {0, }; + static unsigned char iv[KEY_SIZE] = {0, }; + unsigned char temp_iv[KEY_SIZE] = {0, }; + char in_filepath[MAX_FILENAME_SIZE] = {0, }; + FILE* fd_in = NULL; + char *out_data = pRetBuf; + unsigned char p_text[ENCRYPT_SIZE]= {0, }; + unsigned char e_text[ENCRYPT_SIZE]= {0, }; + size_t read = 0; + + *readLen = 0; + + //0. get directory name and privilege check + char dir[MAX_GROUP_ID_SIZE+1] = {0,}; + if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) + { + SLOGE("Failed to get storage dir\n"); + return SS_SECURE_STORAGE_ERROR; + } + +#ifdef SMACK_GROUP_ID + if(check_privilege_by_sockfd(sockfd, dir, "r") < 0) + { + SLOGE("Permission denied\n"); + return SS_PERMISSION_DENIED; + } +#endif + + // 1. create in file name : convert file name in order to access secure storage + if(flag == SSM_FLAG_WIDGET) + strncpy(in_filepath, data_filepath, MAX_FILENAME_SIZE - 1); + else + ConvertFileName(sender_pid, in_filepath, data_filepath, flag, dir); + + // 2. open file + if(!(fd_in = fopen(in_filepath, "rb"))) + { + SECURE_SLOGE("File open error:(in_filepath) %s\n", in_filepath); + return SS_FILE_OPEN_ERROR; // file related error + } + + // 3. skip to offset + if(fseek(fd_in, (long)offset + sizeof(ssm_file_info_t), SEEK_SET) < 0) + { + int err_tmp = errno; + SECURE_SLOGE("Fseek error: %s in %s\n", strerror(err_tmp), in_filepath); + fclose(fd_in); + return SS_FILE_OPEN_ERROR; // file related error + } + + // 4. decrypt data + GetKey(key, temp_iv); + if(count == 0) + memcpy(iv, temp_iv, KEY_SIZE); + + read = fread(e_text, 1, ENCRYPT_SIZE, fd_in); + + while((read == ENCRYPT_SIZE)) + { + AES_Crypto(p_text, e_text, key, iv, 0, ENCRYPT_SIZE) ; + + memcpy(out_data, p_text, ENCRYPT_SIZE); + out_data += ENCRYPT_SIZE; + *readLen += ENCRYPT_SIZE; + + if(*readLen == MAX_RECV_DATA_SIZE) + goto Last; + + memset(p_text, 0x00, ENCRYPT_SIZE); + memset(e_text, 0x00, ENCRYPT_SIZE); + + read = fread(e_text, 1, ENCRYPT_SIZE, fd_in); + } + + AES_Crypto(p_text, e_text, key, iv, 0, read) ; + + memcpy(out_data, p_text, read); + out_data += read; + *readLen += read; +Last: + *out_data = '\0'; + + fclose(fd_in); + + return 1; +} + +#ifndef SMACK_GROUP_ID +int SsServerDeleteFile(int sender_pid, const char* data_filepath, ssm_flag flag, const char* cookie, const char* group_id) +#else +int SsServerDeleteFile(int sender_pid, const char* data_filepath, ssm_flag flag, int sockfd, const char* group_id) +#endif +{ + const char* in_filepath = data_filepath; + char out_filepath[MAX_FILENAME_SIZE] = {0, }; + + //0. get directory name and privilege check + char dir[MAX_GROUP_ID_SIZE+1] = {0,}; + if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) + { + SLOGE("Failed to get storage dir\n"); + return SS_SECURE_STORAGE_ERROR; + } + +#ifdef SMACK_GROUP_ID + if(check_privilege_by_sockfd(sockfd, dir, "w") < 0) + { + SLOGE("Permission denied\n"); + return SS_PERMISSION_DENIED; + } +#endif + + // create file path from filename + ConvertFileName(sender_pid, out_filepath, in_filepath, flag, dir); + + // 2. delete designated file + if(unlink(out_filepath) != 0) // unlink fail? + { + SLOGE("error occured while deleting file\n"); + return SS_FILE_WRITE_ERROR; + } + + return 1; +} + +#ifndef SMACK_GROUP_ID +int SsServerGetInfo(int sender_pid, const char* data_filepath, char* file_info, ssm_flag flag, const char* cookie, const char* group_id) +#else +int SsServerGetInfo(int sender_pid, const char* data_filepath, char* file_info, ssm_flag flag, int sockfd, const char* group_id) +#endif +{ + size_t read = 0; + FILE *fd_in = NULL; + char in_filepath[MAX_FILENAME_SIZE] = {0, }; + + //0. get directory name and privilege check + char dir[MAX_GROUP_ID_SIZE+1] = {0,}; + if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) + { + SLOGE("Failed to get storage dir\n"); + return SS_SECURE_STORAGE_ERROR; + } + +#ifdef SMACK_GROUP_ID + if(check_privilege_by_sockfd(sockfd, dir, "r") < 0) + { + SLOGE("Permission denied\n"); + return SS_PERMISSION_DENIED; + } +#endif + + // 1. create in file name : convert file name in order to access secure storage + if(flag == SSM_FLAG_WIDGET) + strncpy(in_filepath, data_filepath, MAX_FILENAME_SIZE - 1); + else + ConvertFileName(sender_pid, in_filepath, data_filepath, flag, dir); + + // 1. open file + if(!(fd_in = fopen( in_filepath, "rb"))) + { + SECURE_SLOGE("File open error:(in_filepath) [%s], [%s]\n", data_filepath, in_filepath ); + return SS_FILE_OPEN_ERROR; // file related error + } + + // 2. read metadata field - first 8 bytes + read = fread(file_info, 1, sizeof(ssm_file_info_t), fd_in); + + if(read != sizeof(ssm_file_info_t)) + { + fclose(fd_in); + return SS_FILE_READ_ERROR; + } + + fclose(fd_in); + return 1; +} + +/* +__attribute__((visibility("hidden"))) +int GetWrapKey(char** ppWrapKey, int* wrapKeyLen) +{ + FILE* fp_read_key = NULL; + char* duk_path = "/csa/.ssduk"; + int keyLen = 0; + int test = 0; + + keyLen = SecGetCipherLen(32); + if(keyLen == 0) + { + SLOGE("failed to get key length"); + return SS_TZ_ERROR;; + } + + //check key exist + if(!(fp_read_key = fopen(duk_path, "r"))) + { + int result = 0; + char* pKey = NULL; + FILE* fp_write_key = NULL; + + pKey = (char*)calloc(keyLen, 1); + result = SecGenerateTzKey((unsigned char*)pKey, keyLen); + if(result != 0) + { + SLOGE("SecGetCipherLen = %d", keyLen); + SLOGE("failed to get duk"); + free(pKey); + return SS_TZ_ERROR;; + } + + if(!(fp_write_key = fopen(duk_path, "w"))) + { + SLOGE("failed to write duk"); + free(pKey); + return SS_TZ_ERROR;; + } + + if(chmod(duk_path, 0600) < 0) + { + int err_tmp = errno; + SLOGE("chmod error: %s\n", strerror(err_tmp)); + free(pKey); + fclose(fp_write_key); + return SS_FILE_OPEN_ERROR; // file related error + } + + fwrite(pKey, keyLen, 1, fp_write_key); + *ppWrapKey = pKey; + *wrapKeyLen = keyLen; + fclose(fp_write_key); + + return 1; + } + + + *ppWrapKey = (char*)calloc(keyLen, 1); + test = fread(*ppWrapKey, 1, keyLen, fp_read_key); + if(test != keyLen) + { + SLOGE("failed to read duk [%d] ", test); + fclose(fp_read_key); + free(*ppWrapKey); + return SS_FILE_READ_ERROR; + } + + *wrapKeyLen = keyLen; + fclose(fp_read_key); + + return 1; +} + +__attribute__((visibility("hidden"))) +int RequestUnwrapKey(char* pWrapKey, int wrapKeyLen, char** ppUnwrapKey, int* unwrapKeyLen) +{ + int result = 0; + int keyLen = 0; + char* pUnwrapKey = NULL; + + pUnwrapKey = (char*)calloc(256, 1); + + result = SecRetrieveTzKey((unsigned char*)pWrapKey, wrapKeyLen, (unsigned char*)pUnwrapKey, (unsigned int*)&keyLen); + if(result != 0) + { + SLOGE("failed to get unwrap duk"); + free(pUnwrapKey); + return SS_TZ_ERROR; + } + + *ppUnwrapKey = pUnwrapKey; + *unwrapKeyLen = keyLen; + + return 1; +} +*/ +int SsServerGetDuk(int client_sockfd, char* pBuffer, unsigned int* pBufferLen, char* pAppId, unsigned int flag) +{ + int result = 0; + int keyLen = 0; + int unwrapKeyLen = 0; + int hashLen = 0; + char* pTempDuk = NULL; + char* pSmackLabel = NULL; + char hashVal1[HASH_SIZE] = {0,}; + char hashVal2[HASH_SIZE] = {0,}; + +//temporary + pTempDuk = (char*)malloc(KEY_SIZE); + memcpy(pTempDuk, "0123456789abcdef", KEY_SIZE); + unwrapKeyLen = KEY_SIZE; +//end temporary + + if(!IsSmackEnabled()) + { + pSmackLabel = (char*)calloc(8, 1); + memcpy(pSmackLabel, "NOSMACK", 7); + } + + else + { + if(flag == 0) + { + pSmackLabel = security_server_get_smacklabel_sockfd(client_sockfd); + if(!pSmackLabel) + { + SLOGE("failed to get smack label"); + free(pTempDuk); + return -1; + } + } + + else + { + pSmackLabel = (char*)calloc(strlen(pAppId)+1,1); + memcpy(pSmackLabel, pAppId, strlen(pAppId)); + } + } + + SECURE_SLOGI("smack lebel = %s, smack label length = %d", pSmackLabel, strlen(pSmackLabel)); + + + //ToDo + HMAC(EVP_sha1(), pSmackLabel, strlen(pSmackLabel), (unsigned char*)pTempDuk, unwrapKeyLen, (unsigned char*)hashVal1, (unsigned int*)&hashLen); + HMAC(EVP_sha1(), hashVal1, hashLen, (unsigned char*)pTempDuk, unwrapKeyLen, (unsigned char*)hashVal2, (unsigned int*)&hashLen); + memcpy(pBuffer, hashVal1, KEY_SIZE); + memcpy(pBuffer+KEY_SIZE, hashVal2, KEY_SIZE); + *pBufferLen = KEY_SIZE*2; + free(pSmackLabel); + free(pTempDuk); + + return 1; +} diff --git a/server/src/ss_server_ipc.c b/server/src/ss_server_ipc.c deleted file mode 100755 index aa01f1c..0000000 --- a/server/src/ss_server_ipc.c +++ /dev/null @@ -1,459 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "secure_storage.h" -#include "ss_server_ipc.h" -#include "ss_server_main.h" - -#ifdef USE_KEY_FILE -#define CONF_FILE_PATH "/usr/share/secure-storage/config" -#endif // USE_KEY_FILE - -char* get_key_file_path() -{ - FILE* fp_conf = NULL; - char buf[128]; - char* retbuf = NULL; - char seps[] = " :\n\r\t"; - char* token = NULL; - - retbuf = (char*)malloc(sizeof(char) * 128); - if(!retbuf) - { - SLOGE("fail to allocate memory.\n"); - return NULL; - } - memset(buf, 0x00, 128); - memset(retbuf, 0x00, 128); - - if(!(fp_conf = fopen(CONF_FILE_PATH, "r"))) - { - SLOGE("Configuration file is not exist\n"); - free(retbuf); - return NULL; - } - - while(fgets(buf, 128, fp_conf)) - { - token = strtok(buf, seps); - if(token != NULL) - { - if(!strncmp(token, "MASTER_KEY_PATH", 15)) // master key path - { - token = strtok(NULL, seps); // real path - break; - } - } - token = NULL; - } - fclose(fp_conf); - - if(token) - strncpy(retbuf, token, 128); - else { - if(retbuf != NULL) - free(retbuf); - return NULL; - } - - return retbuf; -} - -int check_key_file() -{ - FILE* fp_key = NULL; - char* key_path = NULL; - - key_path = get_key_file_path(); - if(key_path == NULL) - { - SLOGE("Configuration file is not exist\n"); - return 0; - } - - if(!(fp_key = fopen(key_path, "r"))) - { - SECURE_SLOGE("Secret key file is not exist, [%s]\n", key_path); - free(key_path); - return 0; - } - - free(key_path); - fclose(fp_key); - return 1; -} - -int make_key_file() -{ - FILE* fp_key = NULL; - int random_dev = -1; - int i = 0; - char tmp_key[1]; - char key[33]; - char* key_path = NULL; - - memset(key, 0x00, 33); - - key_path = get_key_file_path(); - if(key_path == NULL) - { - SLOGE("Configuration file is not exist\n"); - return 0; - } - - if((random_dev = open("/dev/urandom", O_RDONLY)) < 0) - { - SLOGE("Random device Open error\n"); - free(key_path); - return 0; - } - - while(i < 32) - { - read(random_dev, tmp_key, 1); - - if((tmp_key[0] >= '!') && (tmp_key[0] <= '~')) { - key[i] = tmp_key[0]; - i++; - } - } - - if(!(fp_key = fopen(key_path, "w"))) - { - SECURE_SLOGE("Secret key file Open error, [%s]\n", key_path); - free(key_path); - close(random_dev); - return 0; - } - - fprintf(fp_key, "%s", key); - - if(chmod(key_path, 0600)!=0) - { - SLOGE("Secret key file chmod error, [%s]\n", strerror(errno)); - free(key_path); - close(random_dev); - fclose(fp_key); - return 0; - } - - free(key_path); - fclose(fp_key); - close(random_dev); - return 1; -} - -/* for executing coverage tool (2009-04-03) */ -void SigHandler(int signo) -{ - SLOGI("Got Signal %d\n", signo); - exit(1); -} -/* end */ - -void SsServerComm(void) -{ - int server_sockfd, client_sockfd; - int client_len; - struct sockaddr_un clientaddr, serveraddr; - - struct ucred cr; // for test client pid. 2009-03-24 - int cl = sizeof(cr); // - int temp_len_sock = 0; - int temp_len_in = 0; - - ReqData_t recv_data = {0, }; - RspData_t send_data = {0, }; - - client_len = sizeof(clientaddr); - - server_sockfd = client_sockfd = -1; - - int number_fds = sd_listen_fds(1); - if (number_fds > 1) - { - SLOGE("Too many file descriptors received..\n"); - send_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_exit; - } - if (number_fds == 1) - { - int r; - if ((r = sd_is_socket_unix(SD_LISTEN_FDS_START, SOCK_STREAM, 1, SS_SOCK_PATH, 0)) <= 0) - { - SLOGE("The file descriptor received from systemd is of a wrong type.\n"); - send_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_exit; - } - server_sockfd = SD_LISTEN_FDS_START + 0; - } - else - { - if((server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) - { - SLOGE("Error in function socket()..\n"); - send_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_exit; - } - - temp_len_sock = strlen(SS_SOCK_PATH); - - memset(&serveraddr, '0', sizeof(serveraddr)); - serveraddr.sun_family = AF_UNIX; - strncpy(serveraddr.sun_path, SS_SOCK_PATH, temp_len_sock); - serveraddr.sun_path[temp_len_sock] = '\0'; - - if((bind(server_sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr))) < 0) - { - unlink(SS_SOCK_PATH); - if((bind(server_sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr))) < 0) - { - SLOGE("Error in function bind()..\n"); - send_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_close_exit; - } - } - - if(chmod(SS_SOCK_PATH, S_IRWXU | S_IRWXG | S_IRWXO) != 0) - { - send_data.rsp_type = SS_SOCKET_ERROR; - goto Error_close_exit; - } - - if((listen(server_sockfd, 5)) < 0) - { - SLOGE("Error in function listen()..\n"); - send_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_close_exit; - } - } - - signal(SIGINT, (void*)SigHandler); - sd_notify(0, "READY=1"); - - while(1) - { - errno = 0; - - if((client_sockfd = accept(server_sockfd, (struct sockaddr*)&clientaddr, (socklen_t*)&client_len)) < 0) - { - SLOGE("Error in function accept()..[%d, %d]\n", client_sockfd, errno); - send_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_close_exit; - } - - // for test client pid. 2009-03-24 - if(getsockopt(client_sockfd, SOL_SOCKET, SO_PEERCRED, &cr, (socklen_t*)&cl) != 0) - { - SLOGE("getsockopt() fail\n"); - } - // end - - if(read(client_sockfd, (char*)&recv_data, sizeof(recv_data)) < 0) - { - SLOGE("Error in function read()..\n"); - send_data.rsp_type = SS_SOCKET_ERROR; // ipc error - goto Error_close_exit; - } - - temp_len_in = strlen(recv_data.data_infilepath); - - switch(recv_data.req_type) - { - case 1: -#ifndef SMACK_GROUP_ID - send_data.rsp_type = SsServerDataStoreFromFile(cr.pid, recv_data.data_infilepath, recv_data.flag, recv_data.cookie, recv_data.group_id); -#else - send_data.rsp_type = SsServerDataStoreFromFile(cr.pid, recv_data.data_infilepath, recv_data.flag, client_sockfd, recv_data.group_id); -#endif - - if(send_data.rsp_type == 1) - { - strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_LEN - 1); - send_data.data_filepath[temp_len_in] = '\0'; - } - else - { - strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_LEN - 1); - send_data.data_filepath[15] = '\0'; - } - - write(client_sockfd, (char*)&send_data, sizeof(send_data)); - break; - case 2: -#ifndef SMACK_GROUP_ID - send_data.rsp_type = SsServerDataStoreFromBuffer(cr.pid, recv_data.buffer, recv_data.count, recv_data.data_infilepath, recv_data.flag, recv_data.cookie, recv_data.group_id); -#else - send_data.rsp_type = SsServerDataStoreFromBuffer(cr.pid, recv_data.buffer, recv_data.count, recv_data.data_infilepath, recv_data.flag, client_sockfd, recv_data.group_id); -#endif - - if(send_data.rsp_type == 1) - { - strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_LEN - 1); - send_data.data_filepath[temp_len_in] = '\0'; - } - else - { - strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_LEN - 1); - send_data.data_filepath[15] = '\0'; - } - - write(client_sockfd, (char*)&send_data, sizeof(send_data)); - break; - case 3: -#ifndef SMACK_GROUP_ID - send_data.rsp_type = SsServerDataRead(cr.pid, recv_data.data_infilepath, send_data.buffer, recv_data.count, &(send_data.readLen), recv_data.flag, recv_data.cookie, recv_data.group_id); -#else - send_data.rsp_type = SsServerDataRead(cr.pid, recv_data.data_infilepath, send_data.buffer, recv_data.count, &(send_data.readLen), recv_data.flag, client_sockfd, recv_data.group_id); -#endif - if(send_data.rsp_type == 1) - { - strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_LEN - 1); - send_data.data_filepath[temp_len_in] = '\0'; - } - else - { - strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_LEN - 1); - send_data.data_filepath[15] = '\0'; - } - - write(client_sockfd, (char*)&send_data, sizeof(send_data)); - break; - case 4: -#ifndef SMACK_GROUP_ID - send_data.rsp_type = SsServerGetInfo(cr.pid, recv_data.data_infilepath, send_data.buffer, recv_data.flag, recv_data.cookie, recv_data.group_id); -#else - send_data.rsp_type = SsServerGetInfo(cr.pid, recv_data.data_infilepath, send_data.buffer, recv_data.flag, client_sockfd /*recv_data.cookie*/, recv_data.group_id); -#endif - - if(send_data.rsp_type == 1) - { - strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_LEN - 1); - send_data.data_filepath[temp_len_in] = '\0'; - } - else - { - strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_LEN - 1); - send_data.data_filepath[15] = '\0'; - } - - write(client_sockfd, (char*)&send_data, sizeof(send_data)); - break; - case 10: -#ifndef SMACK_GROUP_ID - send_data.rsp_type = SsServerDeleteFile(cr.pid, recv_data.data_infilepath, recv_data.flag, recv_data.cookie, recv_data.group_id); -#else - send_data.rsp_type = SsServerDeleteFile(cr.pid, recv_data.data_infilepath, recv_data.flag, client_sockfd, recv_data.group_id); -#endif - - if(send_data.rsp_type == 1) - { - strncpy(send_data.data_filepath, recv_data.data_infilepath, MAX_FILENAME_LEN - 1); - send_data.data_filepath[temp_len_in] = '\0'; - } - else - { - strncpy(send_data.data_filepath, "Error Occured..", MAX_FILENAME_LEN - 1); - send_data.data_filepath[15] = '\0'; - } - - write(client_sockfd, (char*)&send_data, sizeof(send_data)); - break; - - default: - SLOGE("Input error..Please check request type\n"); - break; - } - close(client_sockfd); - } - -Error_close_exit: - close(server_sockfd); - -Error_exit: - strncpy(send_data.data_filepath, "error", MAX_FILENAME_LEN - 1); - send_data.data_filepath[5] = '\0'; - - if(client_sockfd >= 0) - { - write(client_sockfd, (char*)&send_data, sizeof(send_data)); - close(client_sockfd); - } - else - SLOGE("cannot connect to client socket.\n"); -} - -int main(void) -{ - SLOGI("Secure Storage Server Start..\n"); - -#ifdef USE_KEY_FILE - int exist_ret = -1; - int make_ret = -1; -#endif // USE_KEY_FILE - DIR* dp = NULL; // make default directory(if not exist) - - if((dp = opendir(SS_STORAGE_DEFAULT_PATH)) == NULL) - { - SLOGI("directory [%s] is not exist, making now.\n", SS_STORAGE_DEFAULT_PATH); - if(mkdir(SS_STORAGE_DEFAULT_PATH, 0700) < 0) - { - int err_tmp = errno; - SLOGE("Failed while making [%s] directory. Errno: %s\n", SS_STORAGE_DEFAULT_PATH, strerror(err_tmp)); - return 0; - } - } - else - closedir(dp); - -#ifdef USE_KEY_FILE - exist_ret = check_key_file(); // if 0, there is not key file. Or 1, exist. - - if(exist_ret == 0) - { - make_ret = make_key_file(); - - if(make_ret == 0) - { - SLOGE("Making key file fail. ss-server will be terminated..\n"); - return 0; - } - } -#endif // USE_KEY_FILE - - SsServerComm(); - - return 0; -} diff --git a/server/src/ss_server_main.c b/server/src/ss_server_main.c deleted file mode 100755 index a4ca619..0000000 --- a/server/src/ss_server_main.c +++ /dev/null @@ -1,849 +0,0 @@ -/* - * secure storage - * - * Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved - * - * Contact: Kidong Kim - * - * 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. - * - */ - -/* encrypted file format - * - * total file size = metadata (8 bytes) + realdata (...) - * ----------------------------------------------------------- - * | metadata | realdata | - * ----------------------------------------------------------- - * 0 16 EOF - * metadata -> ssm_file_info_t - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "secure_storage.h" -#include "ss_server_main.h" -#include "ss_server_ipc.h" -#include - -#ifdef USE_KEY_FILE -#define CONF_FILE_PATH "/usr/share/secure-storage/config" -#endif // USE_KEY_FILE - -#define ENCRYPT_SIZE 1024 - -/* skey : need to help from hardware */ -char skey[16+1] = "thisisasecretkey"; - -/*************************************************************************** - * Internal functions - **************************************************************************/ - -char* get_preserved_dir() -{ - FILE* fp_conf = NULL; - char buf[128]; - char* retbuf = NULL; - char seps[] = " :\n\r\t"; - char* token = NULL; - - retbuf = (char*)malloc(sizeof(char) * 128); - if(retbuf == NULL) - { - SLOGE("malloc return NULL\n"); - return NULL; - } - memset(buf, 0x00, 128); - memset(retbuf, 0x00, 128); - - if(!(fp_conf = fopen(CONF_FILE_PATH, "r"))) - { - SLOGE("Configuration file is not exist\n"); - free(retbuf); - return NULL; - } - - while(fgets(buf, 128, fp_conf)) - { - token = strtok(buf, seps); - if(token != NULL) - { - if(!strncmp(token, "PRESERVE_DIR", 12)) // preserve directory? - { - token = strtok(NULL, seps); // real path - break; - } - } - token = NULL; - } - fclose(fp_conf); - - if(token) - strncpy(retbuf, token, 127); - else { - free(retbuf); - return NULL; - } - - return retbuf; -} - -int IsSmackEnabled() -{ - FILE *file = NULL; - if((file = fopen("/smack/load2", "r"))) - { - fclose(file); - return 1; - } - return 0; -} - -/* get key from hardware( ex. OMAP e-fuse random key ) */ -void GetKey(char* key, unsigned char* iv) -{ -#ifdef USE_KEY_FILE - FILE* fp_key = NULL; - char buf[33]; - char* key_path = NULL; - - memset(buf, 0x00, 33); - - key_path = get_key_file_path(); - if(key_path == NULL) - { - SLOGE("Configuration file is not exist\n"); - memcpy(buf, skey, 16); - } - else - { - if(!(fp_key = fopen(key_path, "r"))) - { - SLOGE("Secret key file opening error\n"); - memcpy(buf, skey, 16); - } - else - { - if(!fgets(buf, 33, fp_key)) - { - SLOGE("Secret key file reading error\n"); - memcpy(buf, skey, 16); // if fail to get key, set to default value. - } - } - } - - if(key) - strncpy(key, buf, 16); - if(iv) - strncpy(iv, buf+16, 16); - - if(key_path) - free(key_path); - if(fp_key) - fclose(fp_key); - -#else - if(key) - memcpy(key, skey, 16); - if(iv) - memcpy(iv, 0x00, 16); -#endif // USE_KEY_FILE -} - -unsigned short GetHashCode(const unsigned char* pString) -{ - unsigned short hash = 5381; - int len = SHA_DIGEST_LENGTH; - int i; - - for(i = 0; i < len; i++) - { - hash = ((hash << 5) + hash) + (unsigned short)pString[i]; // hash * 33 + ch - } - - return hash; -} - -int IsDirExist(const char* dirpath) -{ - DIR* dp = NULL; - - if((dp = opendir(dirpath)) == NULL) // dir is not exist - { - SECURE_SLOGE("directory [%s] is not exist.\n", dirpath); - return 0; // return value '0' represents dir is not exist - } - else - { - closedir(dp); - return 1; - } - - return -1; -} - -int check_privilege_by_sockfd(int sockfd, const char* object, const char* access_rights) -{ - if(!IsSmackEnabled()) - return 0; - - int ret = security_server_check_privilege_by_sockfd(sockfd, object, access_rights); - SECURE_SLOGD("object : %s, access_rights : %s, ret : %d", object, access_rights, ret); - return ret; -} - -/* convert normal file path to secure storage file path */ -int ConvertFileName(int sender_pid, char* dest, const char* src, ssm_flag flag, const char* group_id) -{ - char s[33+1]; - const char* dir = group_id; - char* preserved_dir = NULL; - int is_dir_exist = -1; - - if(!dest || !src) - { - SLOGE("Parameter error in ConvertFileName()...\n"); - return SS_FILE_OPEN_ERROR; // file related error - } - - // get top-dir path - if(flag == SSM_FLAG_SECRET_PRESERVE) - { - preserved_dir = get_preserved_dir(); - if(preserved_dir == NULL) // fail to get preserved directory - { - SLOGE("fail to get preserved dir\n"); - return SS_FILE_OPEN_ERROR; - } - - strncpy(dest, preserved_dir, strlen(preserved_dir)); //dest <= /csa - free(preserved_dir); - } - else // SSM_FLAG_SECRET_DATA || SSM_FLAG_SECRET_OPERATION || SSM_FLAG_PRELOADED_WEB_APP - { - if(CreateStorageDir(SS_STORAGE_DEFAULT_PATH) < 0) - { - return SS_FILE_OPEN_ERROR; - } - // TBD - strncpy(dest, SS_STORAGE_DEFAULT_PATH, strlen(SS_STORAGE_DEFAULT_PATH) + 1); - } - - strncat(dest, dir, (strlen(dir))); // add top-dir + dir(label) - strncat(dest, "/", 1); - - if(CreateStorageDir(dest) < 0) - { - return SS_FILE_OPEN_ERROR; - } - - strncat(dest, "_", 1); // /top-dir/label/_ - - GetPathHash(src, s); - strncat(dest, s, strlen(s)); // /top-dir/label/_hash - strncat(dest, SS_FILE_POSTFIX, strlen(SS_FILE_POSTFIX)); // /top-dir/label/_hash.e - - SECURE_SLOGD("final dest : %s", dest); - - return 1; -} - -int GetProcessExecPath(int pid, char* buffer) -{ - char tmp_cmd[32] = {0,}; - FILE *fp_proc = NULL; - snprintf(tmp_cmd, 32, "/proc/%d/cmdline", pid); - - if(!(fp_proc = fopen(tmp_cmd, "r"))) - { - SECURE_SLOGE("file open error: [%s]", tmp_cmd); - return SS_FILE_OPEN_ERROR; - } - - fgets((char*)buffer, 256, fp_proc); - fclose(fp_proc); - - return 0; -} - -int GetProcessSmackLabel(int sockfd, char* proc_smack_label) -{ - char* smack_label = security_server_get_smacklabel_sockfd(sockfd); - if(smack_label) - { - strncpy(proc_smack_label, smack_label, strlen(smack_label)); - free(smack_label); - } - else - { - SLOGE("failed to get smack label"); - return -1; // SS_SECURITY_SERVER_ERROR? - } - SECURE_SLOGD("defined smack label : %s", proc_smack_label); - return 0; -} - -int GetPathHash(const char *src, char *output) -{ - unsigned short h_code = 0; - unsigned char path_hash[SHA_DIGEST_LENGTH + 1]; - - SHA1((unsigned char*)src, (size_t)strlen(src), path_hash); - h_code = GetHashCode(path_hash); - memset(output, 0x00, 34); - snprintf(output, 34, "%u", h_code); - - SECURE_SLOGD("hashing src : %s to output : %s", src, output); - - return 0; -} - - -int CreateStorageDir(const char* path) -{ - int is_dir_exist = IsDirExist(path); - - if (is_dir_exist == 0) // path directory is not exist - { - SECURE_SLOGI("directory [%s] is making now.\n", path); - if(mkdir(path, 0700) < 0) // fail to make directory - { - SLOGE("[%s] cannot be made\n", SS_STORAGE_DEFAULT_PATH); - return -SS_FILE_OPEN_ERROR; - } - } - - return 0; -} - -/* - * if group_id is given, use group_id - * - * if NULL group_id is given - * smack enable : use process smack label - * smack disable : use process exec path - * - */ -int GetProcessStorageDir(int sockfd, int sender_pid, const char* group_id, char* output) -{ - char *object = group_id; - char proc_smack_label[MAX_GROUP_ID_LEN+1] = {0,}; - char hash_buf[10] = {0, }; - int is_shared = strncmp(group_id, "NOTUSED", 7) ? 1 : 0; - -#ifdef SMACK_GROUP_ID - if(IsSmackEnabled()) - { - if(!is_shared) // don't share, use process smack label - { - if(GetProcessSmackLabel(sockfd, proc_smack_label) != 0) - { - return -SS_SECURE_STORAGE_ERROR; - } - object = proc_smack_label; - } - } - else{ -#endif - char exe_path[256] = {0,}; - int h_code2 = 0; - - if(!is_shared) // don't share - { - if(GetProcessExecPath(sender_pid, exe_path) != 0) - { - return -SS_SECURE_STORAGE_ERROR; - } - h_code2 = GetHashCode(exe_path); - snprintf(hash_buf, 10, "%u", h_code2); - object = hash_buf; - } -#ifdef SMACK_GROUP_ID - } -#endif - strncpy(output, object, strlen(object)); - return 0; -} - -void SetMetaData(ssm_file_info_convert_t* sfic, unsigned int orig_size, unsigned int stored_size, int flag) -{ - sfic->fInfoStruct.originSize = (unsigned int)orig_size; - sfic->fInfoStruct.storedSize = (unsigned int)stored_size; - sfic->fInfoStruct.reserved[0] = flag & 0x000000ff; -} - -/* aes crypto function wrapper - p_text : plain text, c_text : cipher text, aes_key : from GetKey, mode : ENCRYPT/DECRYPT, size : data size */ -unsigned char* AES_Crypto(unsigned char* p_text, unsigned char* c_text, char* aes_key, unsigned char* iv, int mode, unsigned long size) -{ - AES_KEY e_key, d_key; - - AES_set_encrypt_key((unsigned char*)aes_key, 128, &e_key); - AES_set_decrypt_key((unsigned char*)aes_key, 128, &d_key); - - if(mode == 1) - { - AES_cbc_encrypt(p_text, c_text, size, &e_key, iv, AES_ENCRYPT); - return c_text; - } - else - { - AES_cbc_encrypt(c_text, p_text, size, &d_key, iv, AES_DECRYPT); - return p_text; - } -} - - -/*************************************************************************** - * Function Definition - **************************************************************************/ -#ifndef SMACK_GROUP_ID -int SsServerDataStoreFromFile(int sender_pid, const char* data_filepath, ssm_flag flag, const char* cookie, const char* group_id) -#else -int SsServerDataStoreFromFile(int sender_pid, const char* data_filepath, ssm_flag flag, int sockfd, const char* group_id) -#endif -{ - char key[16] = {0, }; - unsigned char iv[16] = {0, }; - const char* in_filepath = data_filepath; - char out_filepath[MAX_FILENAME_LEN] = {0, }; - FILE* fd_in = NULL; - FILE* fd_out = NULL; - struct stat file_info; - ssm_file_info_convert_t sfic; - - unsigned char p_text[ENCRYPT_SIZE]= {0, }; - unsigned char e_text[ENCRYPT_SIZE]= {0, }; - - size_t read = 0, rest = 0; - int res = -1; - - //0. privilege check and get directory name - char dir[MAX_GROUP_ID_LEN] = {0,}; - if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) - { - SLOGE("Failed to get storage dir\n"); - return SS_SECURE_STORAGE_ERROR; - } - -#ifdef SMACK_GROUP_ID - if(flag != SSM_FLAG_PRELOADED_WEB_APP) - { - if(check_privilege_by_sockfd(sockfd, dir, "w") < 0) - { - SLOGE("Permission denied\n"); - return SS_PERMISSION_DENIED; - } - } -#endif - - // 1. create out file name - ConvertFileName(sender_pid, out_filepath, in_filepath, flag, dir); - - // 2. file open - if(!(fd_in = fopen(in_filepath, "rb"))) - { - SLOGE("File open error:(in_filepath) %s\n", in_filepath); - return SS_FILE_OPEN_ERROR; // file related error - } - - if(!(fd_out = fopen(out_filepath, "wb"))) - { - SLOGE("File open error:(out_filepath) %s\n", out_filepath); - fclose(fd_in); - return SS_FILE_OPEN_ERROR; // file related error - } - if(chmod(out_filepath, 0600) < 0) - { - int err_tmp = errno; - SLOGE("chmod error: %s\n", strerror(err_tmp)); - fclose(fd_in); - fclose(fd_out); - return SS_FILE_OPEN_ERROR; // file related error - } - - // 3. write metadata - if(!stat(in_filepath, &file_info)) - { - SetMetaData(&sfic, file_info.st_size, (file_info.st_size/AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE, flag); - } - else - { - SLOGE("the function stat() fail.\n"); - fclose(fd_in); - fclose(fd_out); - return SS_FILE_READ_ERROR; - } - - fwrite(sfic.fInfoArray, 1, sizeof(ssm_file_info_t), fd_out); - - // 4. encrypt real data - read = fread(p_text, 1, ENCRYPT_SIZE, fd_in); - GetKey(key, iv); - - while(read == ENCRYPT_SIZE) - { - AES_Crypto(p_text, e_text, key, iv, 1, ENCRYPT_SIZE); - - fwrite(e_text, 1, ENCRYPT_SIZE, fd_out); - - memset(e_text, 0x00, ENCRYPT_SIZE); - memset(p_text, 0x00, ENCRYPT_SIZE); - read = fread( p_text, 1, ENCRYPT_SIZE, fd_in ); - } - - rest = AES_BLOCK_SIZE - (read % AES_BLOCK_SIZE); - AES_Crypto(p_text, e_text, key, iv, 1, read+rest); - fwrite(e_text, 1, read + rest, fd_out); - - if((res = fflush(fd_out)) != 0) { - SLOGE("fail to execute fflush().\n"); - fclose(fd_in); - fclose(fd_out); - return SS_FILE_WRITE_ERROR; - } - else { - SLOGI("success to execute fflush().\n"); - if((res = fsync(fd_out->_fileno)) == -1) { - SLOGE("fail to execute fsync().\n"); - fclose(fd_in); - fclose(fd_out); - return SS_FILE_WRITE_ERROR; - } - else - SLOGI("success to execute fsync(). read=[%d], rest=[%d]\n", read, rest); - } - - fclose(fd_in); - fclose(fd_out); - - return 1; -} - -#ifndef SMACK_GROUP_ID -int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, const char* cookie, const char* group_id) -#else -int SsServerDataStoreFromBuffer(int sender_pid, char* writebuffer, size_t bufLen, const char* filename, ssm_flag flag, int sockfd, const char* group_id) -#endif -{ - char key[16] = {0, }; - unsigned char iv[16] = {0, }; - char out_filepath[MAX_FILENAME_LEN+1] = {0,}; - char *buffer = NULL; - unsigned int writeLen = 0, loop, rest, count; - FILE *fd_out = NULL; - ssm_file_info_convert_t sfic; - unsigned char p_text[ENCRYPT_SIZE] = {0, }; - unsigned char e_text[ENCRYPT_SIZE] = {0, }; - int res = -1; - - //0. get directory name and privilege check - char dir[MAX_GROUP_ID_LEN] = {0,}; - if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) - { - SLOGE("Failed to get storage dir\n"); - return SS_SECURE_STORAGE_ERROR; - } - -#ifdef SMACK_GROUP_ID - if(flag != SSM_FLAG_PRELOADED_WEB_APP) - { - if(check_privilege_by_sockfd(sockfd, dir, "w") < 0) - { - SLOGE("Permission denied\n"); - return SS_PERMISSION_DENIED; - } - } -#endif - - // create file path from filename - ConvertFileName(sender_pid, out_filepath, filename, flag, dir); - - writeLen = (unsigned int)(bufLen / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE; - buffer = (char*)malloc(writeLen + 1); - if(!buffer) - { - SLOGE("Memory Allocation Fail in SsServerDataStoreFromBuffer()..\n"); - return SS_MEMORY_ERROR; - } - memset(buffer, 0x00, writeLen); - memcpy(buffer, writebuffer, bufLen); - - // open a file with write mode - if(!(fd_out = fopen(out_filepath, "wb"))) - { - SECURE_SLOGE("File open error:(out_filepath) %s\n", out_filepath); - free(buffer); - return SS_FILE_OPEN_ERROR; // file related error - } - if(chmod(out_filepath, 0600) < 0) - { - int err_tmp = errno; - SLOGE("chmod error: %s\n", strerror(err_tmp)); - free(buffer); - fclose(fd_out); - return SS_FILE_OPEN_ERROR; // file related error - } - - // write metadata - SetMetaData(&sfic, bufLen, writeLen, flag); - - fwrite(sfic.fInfoArray, 1, sizeof(ssm_file_info_t), fd_out); - - // encrypt buffer - loop = writeLen / ENCRYPT_SIZE; - rest = writeLen % ENCRYPT_SIZE; - GetKey(key, iv); - - for(count = 0; count < loop; count++) - { - memcpy(p_text, buffer+count*ENCRYPT_SIZE, ENCRYPT_SIZE); - AES_Crypto( p_text, e_text, key, iv, 1, ENCRYPT_SIZE); - fwrite(e_text, 1, ENCRYPT_SIZE, fd_out); - memset(e_text, 0x00, ENCRYPT_SIZE); - memset(p_text, 0x00, ENCRYPT_SIZE); - } - - memcpy(p_text, buffer + loop*ENCRYPT_SIZE, rest); - AES_Crypto(p_text, e_text, key, iv, 1, rest); - fwrite(e_text, 1, rest, fd_out); - - if((res = fflush(fd_out)) != 0) { - SLOGE("fail to execute fflush().\n"); - fclose(fd_out); - free(buffer); - return SS_FILE_WRITE_ERROR; - } - else { - SLOGI("success to execute fflush().\n"); - if((res = fsync(fd_out->_fileno)) == -1) { - SLOGE("fail to execute fsync().\n"); - fclose(fd_out); - free(buffer); - return SS_FILE_WRITE_ERROR; - } - else - SLOGI("success to execute fsync(). loop=[%d], rest=[%d]\n", loop, rest); - } - - fclose(fd_out); - free(buffer); - - return 1; -} - -#ifndef SMACK_GROUP_ID -int SsServerDataRead(int sender_pid, const char* data_filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, const char* cookie, const char* group_id) -#else -int SsServerDataRead(int sender_pid, const char* data_filepath, char* pRetBuf, unsigned int count, unsigned int* readLen, ssm_flag flag, int sockfd, const char* group_id) -#endif -{ - unsigned int offset = count * MAX_RECV_DATA_LEN; - char key[16] = {0, }; - static unsigned char iv[16] = {0, }; - unsigned char temp_iv[16] = {0, }; - char in_filepath[MAX_FILENAME_LEN] = {0, }; - FILE* fd_in = NULL; - char *out_data = pRetBuf; - unsigned char p_text[ENCRYPT_SIZE]= {0, }; - unsigned char e_text[ENCRYPT_SIZE]= {0, }; - size_t read = 0; - - *readLen = 0; - - //0. get directory name and privilege check - char dir[MAX_GROUP_ID_LEN] = {0,}; - if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) - { - SLOGE("Failed to get storage dir\n"); - return SS_SECURE_STORAGE_ERROR; - } - -#ifdef SMACK_GROUP_ID - if(flag != SSM_FLAG_PRELOADED_WEB_APP) - { - if(check_privilege_by_sockfd(sockfd, dir, "r") < 0) - { - SLOGE("Permission denied\n"); - return SS_PERMISSION_DENIED; - } - } -#endif - - // 1. create in file name : convert file name in order to access secure storage - if(flag == SSM_FLAG_WIDGET) - strncpy(in_filepath, data_filepath, MAX_FILENAME_LEN - 1); - else - ConvertFileName(sender_pid, in_filepath, data_filepath, flag, dir); - - // 2. open file - if(!(fd_in = fopen(in_filepath, "rb"))) - { - SECURE_SLOGE("File open error:(in_filepath) %s\n", in_filepath); - return SS_FILE_OPEN_ERROR; // file related error - } - - // 3. skip to offset - if(fseek(fd_in, (long)offset + sizeof(ssm_file_info_t), SEEK_SET) < 0) - { - int err_tmp = errno; - SECURE_SLOGE("Fseek error: %s in %s\n", strerror(err_tmp), in_filepath); - fclose(fd_in); - return SS_FILE_OPEN_ERROR; // file related error - } - - // 4. decrypt data - GetKey(key, temp_iv); - if(count == 0) - memcpy(iv, temp_iv, 16); - - read = fread(e_text, 1, ENCRYPT_SIZE, fd_in); - - while((read == ENCRYPT_SIZE)) - { - AES_Crypto(p_text, e_text, key, iv, 0, ENCRYPT_SIZE) ; - - memcpy(out_data, p_text, ENCRYPT_SIZE); - out_data += ENCRYPT_SIZE; - *readLen += ENCRYPT_SIZE; - - if(*readLen == MAX_RECV_DATA_LEN) - goto Last; - - memset(p_text, 0x00, ENCRYPT_SIZE); - memset(e_text, 0x00, ENCRYPT_SIZE); - - read = fread(e_text, 1, ENCRYPT_SIZE, fd_in); - } - - AES_Crypto(p_text, e_text, key, iv, 0, read) ; - - memcpy(out_data, p_text, read); - out_data += read; - *readLen += read; -Last: - *out_data = '\0'; - - fclose(fd_in); - - return 1; -} - -#ifndef SMACK_GROUP_ID -int SsServerDeleteFile(int sender_pid, const char* data_filepath, ssm_flag flag, const char* cookie, const char* group_id) -#else -int SsServerDeleteFile(int sender_pid, const char* data_filepath, ssm_flag flag, int sockfd, const char* group_id) -#endif -{ - const char* in_filepath = data_filepath; - char out_filepath[MAX_FILENAME_LEN] = {0, }; - - //0. get directory name and privilege check - char dir[MAX_GROUP_ID_LEN] = {0,}; - if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) - { - SLOGE("Failed to get storage dir\n"); - return SS_SECURE_STORAGE_ERROR; - } - -#ifdef SMACK_GROUP_ID - if(flag != SSM_FLAG_PRELOADED_WEB_APP) - { - if(check_privilege_by_sockfd(sockfd, dir, "w") < 0) - { - SLOGE("Permission denied\n"); - return SS_PERMISSION_DENIED; - } - } -#endif - - // create file path from filename - ConvertFileName(sender_pid, out_filepath, in_filepath, flag, dir); - - // 2. delete designated file - if(unlink(out_filepath) != 0) // unlink fail? - { - SLOGE("error occured while deleting file\n"); - return SS_FILE_WRITE_ERROR; - } - - return 1; -} - -#ifndef SMACK_GROUP_ID -int SsServerGetInfo(int sender_pid, const char* data_filepath, char* file_info, ssm_flag flag, const char* cookie, const char* group_id) -#else -int SsServerGetInfo(int sender_pid, const char* data_filepath, char* file_info, ssm_flag flag, int sockfd, const char* group_id) -#endif -{ - size_t read = 0; - FILE *fd_in = NULL; - char in_filepath[MAX_FILENAME_LEN] = {0, }; - - //0. get directory name and privilege check - char dir[MAX_GROUP_ID_LEN] = {0,}; - if(GetProcessStorageDir(sockfd, sender_pid, group_id, dir) < 0) - { - SLOGE("Failed to get storage dir\n"); - return SS_SECURE_STORAGE_ERROR; - } - -#ifdef SMACK_GROUP_ID - if(flag != SSM_FLAG_PRELOADED_WEB_APP) - { - if(check_privilege_by_sockfd(sockfd, dir, "r") < 0) - { - SLOGE("Permission denied\n"); - return SS_PERMISSION_DENIED; - } - } -#endif - - // 1. create in file name : convert file name in order to access secure storage - if(flag == SSM_FLAG_WIDGET) - strncpy(in_filepath, data_filepath, MAX_FILENAME_LEN - 1); - else - ConvertFileName(sender_pid, in_filepath, data_filepath, flag, dir); - - // 1. open file - if(!(fd_in = fopen( in_filepath, "rb"))) - { - SECURE_SLOGE("File open error:(in_filepath) [%s], [%s]\n", data_filepath, in_filepath ); - return SS_FILE_OPEN_ERROR; // file related error - } - - // 2. read metadata field - first 8 bytes - read = fread(file_info, 1, sizeof(ssm_file_info_t), fd_in); - - if(read != sizeof(ssm_file_info_t)) - { - fclose(fd_in); - return SS_FILE_READ_ERROR; - } - - fclose(fd_in); - return 1; -} diff --git a/ss-server.manifest b/ss-server.manifest old mode 100755 new mode 100644 index 5612058..4c304bc --- a/ss-server.manifest +++ b/ss-server.manifest @@ -1,20 +1,28 @@ - + + + + - - diff --git a/systemd/secure-storage.service b/systemd/secure-storage.service deleted file mode 100644 index 553539e..0000000 --- a/systemd/secure-storage.service +++ /dev/null @@ -1,11 +0,0 @@ - -[Unit] -Description=Start the Secure Storage server - -[Service] -Type=notify -ExecStartPre=-/bin/mkdir -p /csa -ExecStart=/usr/bin/ss-server - -[Install] -WantedBy=multi-user.target diff --git a/systemd/secure-storage.socket b/systemd/secure-storage.socket deleted file mode 100644 index 631c09a..0000000 --- a/systemd/secure-storage.socket +++ /dev/null @@ -1,6 +0,0 @@ -[Socket] -ListenStream=/tmp/SsSocket -SocketMode=0777 - -[Install] -WantedBy=sockets.target diff --git a/testcases/ss_test.c b/testcases/ss_test.c new file mode 100644 index 0000000..46b118d --- /dev/null +++ b/testcases/ss_test.c @@ -0,0 +1,243 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd. + * + * Contact: Kidong Kim + * + */ + +#include +#include +#include +#include + +#include "ss_manager.h" + +#define MAX_FILENAME_SIZE 256 + +void usage(void) +{ + printf("\n == Secure Storage Test Usage ==\n\n"); + printf(" ./ss_test\n"); +} + +void prepare_test(void) +{ + // 1. make some directories + // 2. make test file + printf("Make directory - /opt/secure-storage/test\n"); + mkdir("/opt/secure-storage", 0777); + mkdir("/opt/secure-storage/test", 0777); + + printf("Make test file\n"); + system("touch /opt/secure-storage/test/input.txt"); + system("echo \"abcdefghijklnmopqrstuvwxyz\" > /opt/secure-storage/test/input.txt"); +} + +int test_ssm_write_file() +{ + /* + * input : const char* pFilePath + * ssm_flag flag + * return : if 0, success + * if < 0, fail + */ + printf("the file '/opt/secure-storage/test/input.txt' will be stored in secure-storage\n"); + + int ret = -1; + char *infilepath = "/opt/secure-storage/test/input.txt"; + ssm_flag flag = SSM_FLAG_DATA; + + ret = ssm_write_file(infilepath, flag, NULL); + printf("test function end\n"); + + return ret; +} + +int test_ssm_write_buffer() +{ + /* + * input : char* pWriteBuffer + * size_t bufLen + * const char* pFileName + * ssm_flag flag + * return : if 0, success + * if < 0, fail + */ + printf("the buffer will be stored in secure-storage\n"); + + int ret = -1; + char buf[27] = "abcdefghijklmnopqrstuvwxyz\0"; + int buflen = strlen(buf); + char *filename = "res_write_buf.txt"; + ssm_flag flag = SSM_FLAG_SECRET_OPERATION; + + printf(" ** buffer content : [%s]\n", buf); + printf(" ** buffer length : [%d]\n", buflen); + + ret = ssm_write_buffer(buf, buflen, filename, flag, NULL); + printf("test function end\n"); + + return ret; +} + +int test_ssm_getinfo() +{ + /* + * input : const char* pFilePath + * ssm_flag flag + * ssm_file_info_t* sfi + * return : if 0, success + * if < 0, fail + */ + printf("get information of encrypted file. your input in plaintext\n"); + + int ret = -1; + char *filepath = "/opt/secure-storage/test/input.txt"; + ssm_flag flag = SSM_FLAG_DATA; + ssm_file_info_t sfi; + + ret = ssm_getinfo(filepath, &sfi, flag, NULL); + printf(" ** original size: [%d]\n", sfi.originSize); + printf(" ** stored size: [%d]\n", sfi.storedSize); + printf(" ** reserved: [%s]\n", sfi.reserved); + printf("test function end\n"); + + return ret; +} + +int test_ssm_read() +{ + /* + * input : const char* pFilePath + * size_t bufLen + * ssm_flag flag + * output : char* pRetBuf + * size_t readLen + * return : if 0, success + * if < 0, fail + */ + printf("decrypt content from encrypted file\n"); + + int ret = -1; + char *filepath = "/opt/secure-storage/test/input.txt"; +// char *filepath = "res_write_buf.txt"; + int buflen = 128; + ssm_flag flag = SSM_FLAG_DATA; +// ssm_flag flag = SSM_FLAG_SECRET_OPERATION; + char* retbuf = NULL; + int readlen = 0; + ssm_file_info_t sfi; + +// ssm_getinfo(filepath, &sfi, SSM_FLAG_DATA); + ssm_getinfo(filepath, &sfi, flag, NULL); + retbuf = (char*)malloc(sizeof(char) * (sfi.originSize + 1)); + memset(retbuf, 0x00, (sfi.originSize + 1)); + +// ret = ssm_read(filepath, retbuf, sfi.originSize, &readlen, SSM_FLAG_DATA); + ret = ssm_read(filepath, retbuf, sfi.originSize, &readlen, flag, NULL); + + printf(" ** decrypted data: [%s][%d]\n", retbuf, strlen(retbuf)); + free(retbuf); + printf("test function end\n"); + + return ret; +} + +int test_ssm_delete_file() +{ + /* + * input : const char* pFilePath + * ssm_flag flag + * return : if 0, success + * if < 0, fail + */ + printf("the file '/opt/secure-storage/test/input.txt' will be stored in secure-storage\n"); + printf(" and encrypted one of this file will be deleted\n"); + + int ret = -1; + char *infilepath = "/opt/secure-storage/test/input.txt"; + ssm_flag flag = SSM_FLAG_DATA; +// char *infilepath = "res_write_buf.txt"; +// ssm_flag flag = SSM_FLAG_SECRET_OPERATION; + + ret = ssm_delete_file(infilepath, flag, NULL); + printf("test function end\n"); + + return ret; +} + +int main(int argc, char* argv[]) +{ + int ret = -1; + int choice; + + char in_filepath[MAX_FILENAME_SIZE] = {0, }; + char out_filepath[MAX_FILENAME_SIZE] = {0, }; + + if(argc != 1) + { + printf("Error...input argument error\n"); + usage(); + } + + printf("\n= This is Secure Storage test program. =\n"); + printf(" 0. Prepare Secure Storage test\n"); + printf(" 1. Data Store\n"); + printf(" 11. ssm_write_file()\n"); + printf(" 12. ssm_write_buffer()\n"); + printf(" 2. Data Information\n"); + printf(" 21. ssm_getinfo()\n"); + printf(" 3. Data Read\n"); + printf(" 31. ssm_read()\n"); + printf(" 4. Delete encrypted file\n"); + printf(" 41. ssm_delete_file()\n"); + printf(" 5. Exit\n"); + + printf("\nselect num: "); + scanf("%d", &choice); + + switch( choice ) + { + case 0: + printf("\nYou select \"Prepare test\"\n"); + prepare_test(); + break; + case 11: + printf("\nYou select \"ssm_write_file()\"\n"); + ret = test_ssm_write_file(); + printf( "return: %d\n", ret ); + break; + case 12: + printf("\nYou select \"ssm_write_buffer()\"\n"); + ret = test_ssm_write_buffer(); + printf( "return: %d\n", ret ); + break; + case 21: + printf("\nYou select \"ssm_getinfo()\"\n"); + ret = test_ssm_getinfo(); + printf( "return: %d\n", ret ); + break; + case 31: + printf("\nYou select \"ssm_read()\"\n"); + ret = test_ssm_read(); + printf( "return: %d\n", ret ); + break; + case 41: + printf("\nYou select \"ssm_delete_file()\"\n"); + ret = test_ssm_delete_file(); + printf("return: %d\n", ret); + break; + case 5: + printf("\nYou select \"Exit\"\n"); + printf( "Bye~\n"); + break; + default: + printf( "\nError...select wrong number\n" ); + usage(); + break; + } + + return 0; +} diff --git a/testcases/test_manager.c b/testcases/test_manager.c new file mode 100644 index 0000000..0fea648 --- /dev/null +++ b/testcases/test_manager.c @@ -0,0 +1,138 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd. + * + * Contact: Kidong Kim + * + */ + +#include +#include +#include + +#include "ss_manager.h" + + +void format_mount_csa(void) +{ + system("mkdir /tmp/csa"); +// system("insmod /lib/modules/yaffs2.ko yaffs_format=1"); + system("ffdisk -a /dev/bml2"); + system("fformat -s 1 -S 512 16 /dev/stl2"); + system("mount -t rfs /dev/bml2 /tmp/csa"); + + printf("format_mount_csa...\n"); +} + +void mount_csa(void) +{ + system("mkdir /tmp/csa"); +// system("insmod /lib/modules/yaffs2.ko"); + system("mount -t rfs /dev/bml2 /tmp/csa"); + + printf("mount_csa...\n"); +} + +void umount_csa(void) +{ + system("umount /tmp/csa"); +// system("rmmod /lib/modules/yaffs2.ko"); + printf("umount_csa...\n"); +} + + +int main( int argc, char* argv[] ) +{ + int ret; + int choice; + + FILE *fp; + + char in_filepath[50]; + char writebuffer[31] = "abcdefghijklmnopqrstuvwxyz1234"; + char *retBuf = NULL; + + size_t readSize = 0; + + ssm_file_info_t sfi; + + system("mkdir -p /opt/share/secure-storage/"); + + do { + printf( "= This is Secure Storage test program. =\n" ); + printf( " 1. Secure Storage WriteFile() API\n" ); + printf( " 2. Secure Storage WriteBuffer() API \n" ); + printf( " 3. Secure Storage Read() API\n"); + printf( " 4. view rfs partition\n" ); + printf( " 5. Exit\n" ); + printf( "\nselect num: " ); + scanf( "%d", &choice ); + + switch( choice ) + { + case 1: + printf("Call SSM_Store with /tmp/csa/cert.cp...\n"); + mount_csa(); + system("cp /opt/var/drm/cert.cp /tmp/csa/"); + + ret = SSM_WriteFile("/tmp/csa/cert.cp", SSM_FLAG_SECRET_PRESERVE); + umount_csa(); + printf( "You select 'WriteFile'\n" ); + printf( "\nreturn: %d\n", ret ); + break; + case 2: + ret = SSM_WriteBuffer(writebuffer, 30, "writebuf.txt", SSM_FLAG_SECRET_OPERATION); + printf( "You select 'WriteBuffer'\n" ); + printf( "return: %d\n", ret ); + break; + case 3: + printf("Call SSM_Read for OMA_DRM_CERT in secure storage...\n"); + //retBuf = (char*) malloc (50); + printf("- read cert.cp\n"); + mount_csa(); + SSM_GetInfo("/tmp/csa/cert.cp", &sfi, SSM_FLAG_SECRET_PRESERVE); + retBuf = (char*)malloc(sfi.originSize + 1); + ret = SSM_Read("/tmp/csa/cert.cp", retBuf, sfi.originSize, &readSize, SSM_FLAG_SECRET_PRESERVE); + //free(retBuf); + umount(); + printf( "You select 'read1' : read Size = %u \n", readSize); + + fp = fopen("/opt/var/ss_test_result","wb"); + fwrite(retBuf, 1, readSize, fp); + fclose(fp); + + printf( "address of retBuf : %x\n", retBuf); + printf( "\nreturn: %d\n", ret ); + + free(retBuf); + + printf("- read writebuf.txt"); + SSM_GetInfo("writebuf.txt", &sfi, SSM_FLAG_SECRET_OPERATION); + retBuf = (char*)malloc(sfi.originSize); + ret = SSM_Read("writebuf.txt", retBuf, sfi.originSize, &readSize, SSM_FLAG_SECRET_OPERATION); + + printf("You select 'read2' : read size %u \n", readSize); + printf("return : %d, original data : %s\n", ret, retBuf); + + free(retBuf); + + break; + + case 4: + mount_csa(); + system("df -h"); + system("ls -alF /tmp/csa"); + break; + case 5: + printf( "You select 'Exit'\n" ); + exit(1); + default: + printf( "Error...select wrong number\n" ); + break; + } + } + while(choice > 0 && choice < 5); + + return 0; +} diff --git a/testcases/unit_test.c b/testcases/unit_test.c new file mode 100644 index 0000000..9c43175 --- /dev/null +++ b/testcases/unit_test.c @@ -0,0 +1,487 @@ +/* + * secure storage + * + * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd. + * + * Contact: Kidong Kim + * + */ + +/* unit test for secure storage manager */ + +#include +#include +#include + +#include "ss_manager.h" + + +#define LOG_FILE "/opt/var/drm/unit_test_log.txt" +#define TEST_PATH "/tmp/csa/" +#define OMA_DRM_CERT "/tmp/csa/cert.cp" +#define TEST_FILE_NORMAL "/opt/var/drm/normal" + +#define TEST_SUCCESS "test success!" +#define TEST_FAIL "test fail!" + +const char* testcases[] = { + "unit_test_write_file", + "unit_test_write_buffer", + "unit_test_read", + "unit_test_all", + "unit_test_pid", + NULL +}; + +void mount_csa(void) +{ + system("mkdir /tmp/csa"); +// system("insmod /lib/modules/yaffs2.ko"); + system("mount -t rfs /dev/bml2 /tmp/csa"); + + printf("mount_csa\n"); +} + +void umount_csa(void) +{ + system("umount /tmp/csa"); +// system("rmmod /lib/modules/yaffs2.ko"); + printf("umount_csa\n"); +} + +int write_log(FILE *fp, char *data, unsigned int len) +{ + size_t writelen; + + if(!fp) + { + printf("Error... log file open fail...\n"); + exit(0); + } + + writelen = fwrite(data, 1, (size_t)len, fp); + + fputc('\n', fp); + + if(writelen == len) + { + printf("log write %u bytes...\n", writelen); + return 0; + } + else + { + printf("Error... log write fail...\n"); + return -1; + } +} + +void unit_test_write_file(FILE *fp) +{ + char* store_cases[] = { + "1. invalid filepath = NULL", + "2. invalid flag = -1", + "3. invalid flag = 10", + "4. filepath = cert.cp", + "5. filepath = otherfile", + NULL + }; + char text[1024]; + int ret; + + sprintf(text, "----- %s Start -----", testcases[0]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); + + // # store case 1. invalid filepath = NULL + // expected result ==> SSM_FALSE + write_log(fp, store_cases[0], strlen(store_cases[0])); + ret = SSM_WriteFile(NULL, SSM_FLAG_DATA); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 2. invalid flag = -1 + // expected result ==> SSM_FALSE + write_log(fp, store_cases[1], strlen(store_cases[1])); + ret = SSM_WriteFile(TEST_FILE_NORMAL, -1); + if(ret != SSM_FALSE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 3. invalid flag = 10 + // expected result ==> SSM_FALSE + write_log(fp, store_cases[2], strlen(store_cases[2])); + ret = SSM_WriteFile(TEST_FILE_NORMAL, 10); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 4. filepath = cert.cp + // expected result ==> SSM_TRUE + write_log(fp, store_cases[3], strlen(store_cases[3])); + ret = SSM_WriteFile(OMA_DRM_CERT, SSM_FLAG_SECRET_PRESERVE); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 5. filepath = otherfile + // expected result ==> SSM_TRUE + write_log(fp, store_cases[4], strlen(store_cases[4])); + ret = SSM_WriteFile(TEST_FILE_NORMAL, SSM_FLAG_DATA); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + sprintf(text, "----- %s End -----", testcases[0]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); +} + +void unit_test_write_buffer(FILE *fp) +{ + char* store_cases[] = { + "1. invalid pWriteBuffer = NULL", + "2. invalid bufLen = 0", + "3. invalid pFileName = NULL", + "4. invalid pFileName = /xxxxxxx", + "5. invalud flag = -1", + "6. invalid flag = 10", + "7. a buffer input", + NULL + }; + char text[1024] = "This is a test buffer. WoW. that's wonderful."; + int ret; + + sprintf(text, "----- %s Start -----", testcases[1]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); + + // # store case 1. invalid pWriteBuffer = NULL + // expected result ==> SSM_FALSE + write_log(fp, store_cases[0], strlen(store_cases[0])); + ret = SSM_WriteBuffer(NULL, strlen(text), "text.txt", SSM_FLAG_SECRET_OPERATION); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 2. invalid bufLen = 0 + // expected result ==> SSM_FALSE + write_log(fp, store_cases[1], strlen(store_cases[1])); + ret = SSM_WriteBuffer(text, 0, "text.txt", SSM_FLAG_SECRET_OPERATION); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 3. invalid pFileName = NULL + // expected result ==> SSM_FALSE + write_log(fp, store_cases[2], strlen(store_cases[2])); + ret = SSM_WriteBuffer(text, strlen(text), NULL, SSM_FLAG_SECRET_OPERATION); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 4. invalid pFileName = /xxxxxx + // expected result ==> SSM_FALSE + write_log(fp, store_cases[3], strlen(store_cases[3])); + ret = SSM_WriteBuffer(text, strlen(text), "/opt/var/text.txt", SSM_FLAG_SECRET_OPERATION); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 5. invalid flag = -1 + // expected result ==> SSM_FALSE + write_log(fp, store_cases[4], strlen(store_cases[4])); + ret = SSM_WriteBuffer(text, strlen(text), "text.txt", -1); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 6. invalid flag = 10 + // expected result ==> SSM_FALSE + write_log(fp, store_cases[5], strlen(store_cases[5])); + ret = SSM_WriteBuffer(text, strlen(text), "text.txt", 10); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + // # store case 7. a buffer input + // expected result ==> SSM_TRUE + write_log(fp, store_cases[6], strlen(store_cases[6])); + ret = SSM_WriteBuffer(text, strlen(text), "text.txt", SSM_FLAG_SECRET_OPERATION); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + + sprintf(text, "----- %s End -----", testcases[1]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); +} + +void unit_test_read(FILE *fp) +{ + char* read_cases[] = { + "1. invalid filepath = NULL", + "2. invalid readLen = NULL", + "3. invalid flag = -1", + "4. invalid flag = 10", + "5. proper parameters = cert.cp", + "6. proper parameters = otherfile", + "7. proper parameters = text.txt", + NULL + }; + char text[1024]; + char *retBuf = NULL; + int ret; + size_t readLen = 0, bufLen = 1024; + ssm_file_info_t sfi; + + sprintf(text, "----- %s Start -----", testcases[2]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); + + // # read case 1. invalid filepath = NULL + // expected result ==> SSM_FALSE + write_log(fp, read_cases[0], strlen(read_cases[0])); + ret = SSM_Read(NULL, retBuf, bufLen, &readLen, SSM_FLAG_DATA); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + //if(retBuf) + // free(retBuf); + } + + // # read case 2. invalid readLen = NULL + // expected result ==> SSM_FALSE + write_log(fp, read_cases[1], strlen(read_cases[1])); + ret = SSM_Read(TEST_FILE_NORMAL, retBuf, bufLen, NULL, SSM_FLAG_DATA); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + //if(retBuf) + // free(retBuf); + } + + // # read case 3. invalid flag = -1 + // expected result ==> SSM_FALSE + write_log(fp, read_cases[2], strlen(read_cases[2])); + ret = SSM_Read(TEST_FILE_NORMAL, retBuf, bufLen, &readLen, -1); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + //if(retBuf) + // free(retBuf); + } + + // # read case 4. invalid flag = 10 + // expected result ==> SSM_FALSE + write_log(fp, read_cases[3], strlen(read_cases[3])); + ret = SSM_Read(TEST_FILE_NORMAL, retBuf, bufLen, &readLen, 10); + if(ret != SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + //if(retBuf) + // free(retBuf); + } + + // # read case 5. proper parameters = cert.cp + // expected result ==> SSM_TRUE + write_log(fp, read_cases[4], strlen(read_cases[4])); + SSM_GetInfo(OMA_DRM_CERT, &sfi, SSM_FLAG_SECRET_PRESERVE); + retBuf = (char*)malloc(sfi.originSize+1); + ret = SSM_Read(OMA_DRM_CERT, retBuf, sfi.originSize, &readLen, SSM_FLAG_SECRET_PRESERVE); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + if(retBuf) + free(retBuf); + + // # read case 6. proper parameters = otherfile + // expected result ==> SSM_TRUE + write_log(fp, read_cases[5], strlen(read_cases[5])); + SSM_GetInfo(TEST_FILE_NORMAL, &sfi, SSM_FLAG_DATA); + retBuf = (char*)malloc(sfi.originSize+1); + ret = SSM_Read(TEST_FILE_NORMAL, retBuf, sfi.originSize, &readLen, SSM_FLAG_DATA); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + if(retBuf) + free(retBuf); + + // # read case 7. proper parameters = text.txt + // expected result ==> SSM_TRUE + write_log(fp, read_cases[6], strlen(read_cases[6])); + SSM_GetInfo("text.txt", &sfi, SSM_FLAG_SECRET_OPERATION); + retBuf = (char*)malloc(sfi.originSize+1); + ret = SSM_Read("text.txt", retBuf, sfi.originSize, &readLen, SSM_FLAG_SECRET_OPERATION); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + } + if(retBuf) + free(retBuf); + + + sprintf(text, "----- %s End -----", testcases[2]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); +} + + +void unit_test_pid(FILE *fp) +{ +#define ENCRYPT_PID 1 +#define DECRYPT_PID 0 + + int ret = 0; + int i; + char* pid_cases[] = { + "1. encrypt pid", + "2. decrypt pid", + NULL + }; + char text[256]; + int encSize = 0; + unsigned long pid = 1111, newPid; + unsigned char testPid[16] = {0,}; + + write_log(fp, pid_cases[0], strlen(pid_cases[0])); + ret = SSM_EncryptPid(&pid, testPid, &encSize, ENCRYPT_PID); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + + printf("%s result : pid - %u, size - %u\nencrypted pid -", pid_cases[0], pid, encSize); + for(i = 0; i < 16; i++) + printf("%.2x ", testPid[i]); + printf("\n"); + } + + write_log(fp, pid_cases[1], strlen(pid_cases[1])); + ret = SSM_EncryptPid(&newPid, testPid, &encSize, DECRYPT_PID); + if(ret == SSM_TRUE) + { + sprintf(text, " result = %s", TEST_SUCCESS); + write_log(fp, text, strlen(text)); + + printf("%s result : pid - %u, size - %u\n", pid_cases[1], newPid, encSize); + + } + +} + +void unit_test_all(FILE *fp) +{ + char text[1024]; + + sprintf(text, "----- %s Start -----", testcases[3]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); + + unit_test_write_file(fp); + unit_test_write_buffer(fp); + unit_test_read(fp); + + sprintf(text, "----- %s End -----", testcases[3]); + write_log(fp, text, strlen(text)); + printf("%s\n", text); +} + +int main( int argc, char* argv[] ) +{ + int ret; + int choice; + + char in_filepath[50]; + + FILE *log = NULL; + +system("mkdir -p /opt/share/secure-storage/"); + + printf( " 1. " ); printf(testcases[0]); printf( " \n" ); + printf( " 2. " ); printf(testcases[1]); printf( " \n" ); + printf( " 3. " ); printf(testcases[2]); printf( " \n" ); + printf( " 4. " ); printf(testcases[3]); printf( " \n" ); + printf( " 5. " ); printf(testcases[4]); printf( " \n" ); + printf( " 6. Exit\n" ); + + printf( "\nselect num: " ); + scanf( "%d", &choice ); + +mount_csa(); +system("cp /opt/var/drm/cert.cp /tmp/csa/"); // cert.cp +system("cp /opt/var/drm/cert.cp /opt/var/drm/normal"); // normal + + log = fopen(LOG_FILE, "wb"); + + if(!log) + { + printf("Error... log file open fail...\n"); + exit(0); + } + + switch( choice ) + { + case 1: + unit_test_write_file(log); + break; + case 2: + unit_test_write_buffer(log); + break; + case 3: + unit_test_read(log); + break; + case 4: + unit_test_all(log); + break; + case 5: + unit_test_pid(log); + break; + case 6: + printf( "You select 'Exit'\n" ); + break; + default: + printf( "Error...select wrong number\n" ); + break; + } + +umount_csa(); + + if(log) + fclose(log); + + return 0; +} -- cgit v1.2.3