E2EE: Require e2ee-tests to be ran by default user
[platform/core/test/security-tests.git] / src / ckm / ckm-common.cpp
index 47ac15d..01c265c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
+ *  Copyright (c) 2000-2020 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.
  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
  * @version    1.0
  */
+
+#include <unistd.h>
+#include <sys/types.h>
+#include <cstdlib>
 #include <string>
 #include <fstream>
 #include <sys/smack.h>
+#include <ckm/ckm-type.h>
 #include <ckmc/ckmc-type.h>
 #include <ckm-common.h>
 #include <tests_common.h>
-#include <access_provider2.h>
 #include <ckm/ckm-control.h>
 #include <ckm/ckm-manager.h>
 #include <ckmc/ckmc-control.h>
 #include <ckmc/ckmc-manager.h>
-#include <service_manager.h>
 #include <fcntl.h>
 #include <unistd.h>
+#include <unordered_map>
+#include <tzplatform_config.h>
 
-const std::string SMACK_USER_APP_PREFIX = "User::App::";
+const std::string SMACK_USER_APP_PREFIX = "User::Pkg::";
+const char *SYSTEM_LABEL = ckmc_owner_id_system;
+const char *TEST_LABEL = "test_label";
+const char *TEST_LABEL_2 = "test_label_2";
+const char *TEST_LABEL_3 = "test_label_3";
+const char *TEST_LABEL_4 = "test_label_4";
+const char *TEST_LABEL_5 = "test_label_5";
 
 void generate_random(size_t random_bytes, char *output)
 {
@@ -49,22 +60,6 @@ void generate_random(size_t random_bytes, char *output)
     }
 }
 
-const char* SERVICE[] = {
-        "central-key-manager-listener.service",
-        "central-key-manager.service" };
-
-void start_service(ServiceIdx idx)
-{
-    ServiceManager sm(SERVICE[idx]);
-    sm.startService();
-}
-
-void stop_service(ServiceIdx idx)
-{
-    ServiceManager sm(SERVICE[idx]);
-    sm.stopService();
-}
-
 std::string getLabel() {
     int ret;
     char* myLabel = NULL;
@@ -95,29 +90,16 @@ std::string aliasWithLabel(const char *label, const char *alias)
     return std::string(alias);
 }
 
-// changes process label
-void change_label(const char* label)
-{
-    int ret = smack_set_label_for_self(label);
-    RUNNER_ASSERT_MSG(0 == ret, "Error in smack_set_label_for_self("<<label<<"). Error: " << ret);
-}
-
-ScopedLabel::ScopedLabel(const char* label) : m_original_label(getLabel())
+std::string aliasWithLabelFromSelf(const char *alias)
 {
-    change_label(label);
-}
+    std::ostringstream oss;
+    oss << getOwnerIdFromSelf() << ckmc_label_name_separator << alias;
 
-ScopedLabel::~ScopedLabel()
-{
-    /*
-     * Let it throw. If we can't restore label then remaining tests results will be
-     * unreliable anyway.
-     */
-    change_label(m_original_label.c_str());
+    return oss.str();
 }
 
-const char * CKMCErrorToString(int error) {
 #define ERRORDESCRIBE(name) case name: return #name
+const char * CKMCErrorToString(int error) {
     switch(error) {
         ERRORDESCRIBE(CKMC_ERROR_NONE);
         ERRORDESCRIBE(CKMC_ERROR_INVALID_PARAMETER);
@@ -144,8 +126,8 @@ const char * CKMCErrorToString(int error) {
         ERRORDESCRIBE(CKMC_ERROR_UNKNOWN);
         default: return "Error not defined";
     }
-#undef ERRORDESCRIBE
 }
+#undef ERRORDESCRIBE
 
 std::string CKMCReadableError(int error) {
     std::string output("Error: ");
@@ -155,12 +137,8 @@ std::string CKMCReadableError(int error) {
     return output;
 }
 
-void save_data(const char* alias, const char *data, int expected_err)
-{
-    save_data(alias, data, strlen(data), expected_err);
-}
-
-void save_data(const char* alias, const char *data, size_t len, int expected_err = CKMC_ERROR_NONE)
+void save_data(const char* alias, const char *data, size_t len, const char* password,
+               int expected_err, bool exportable)
 {
     RUNNER_ASSERT(alias);
     RUNNER_ASSERT(data);
@@ -169,14 +147,22 @@ void save_data(const char* alias, const char *data, size_t len, int expected_err
     buffer.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
     buffer.size = len;
     ckmc_policy_s policy;
-    policy.password = NULL;
-    policy.extractable = true;
-
+    policy.password = const_cast<char*>(password);
+    policy.extractable = exportable;
     int ret = ckmc_save_data(alias, buffer, policy);
     RUNNER_ASSERT_MSG(expected_err == ret, "Saving data failed. "
-                        << CKMCErrorToString(ret) << " while expected: "
-                        << CKMCErrorToString(expected_err));
+                      << CKMCErrorToString(ret) << " while expected: "
+                      << CKMCErrorToString(expected_err));
+}
+
+void save_data(const char* alias, const char *data, int expected_err, bool exportable)
+{
+    save_data(alias, data, strlen(data), nullptr, expected_err, exportable);
+}
 
+void save_data(const char* alias, const char *data, size_t len, int expected_err, bool exportable)
+{
+    save_data(alias, data, len, nullptr, expected_err, exportable);
 }
 
 ScopedSaveData::ScopedSaveData(const char* alias, const char *data, int expected_err) : m_alias(alias)
@@ -359,7 +345,7 @@ void unlock_user_data(uid_t user_id, const char *passwd)
     int ret;
     auto control = CKM::Control::create();
     RUNNER_ASSERT_MSG(CKM_API_SUCCESS == (ret = control->unlockUserKey(user_id, passwd)),
-                      "Error=" << CKM::ErrorToString(ret));
+                      "Error=" << CKM::APICodeToString(ret));
 }
 
 void remove_user_data(uid_t user_id)
@@ -401,6 +387,74 @@ void check_alias_list(const CKM::AliasVector& expected)
     RUNNER_ASSERT_MSG(expected == actual, "Actual list of aliases differ from expected list.");
 }
 
+void check_alias_info_list_helper(const CKM::AliasPwdVector& expected, const CKM::AliasPwdVector& actual,
+        const std::string &userSmackLabel)
+{
+    std::string errorLogMsg;
+    std::unordered_map<std::string, bool> aliasPwdMap;
+
+    RUNNER_ASSERT_MSG(expected.size() == actual.size(), "Aliases item count differs, expected: " <<
+        expected.size() << " actual: " << actual.size());
+
+    for (const auto &it : actual)
+    {
+        aliasPwdMap[std::get<0>(it)] = std::get<1>(it);
+    }
+
+
+    for (const auto &it : expected)
+    {
+        auto aliasPwd = aliasPwdMap.find(userSmackLabel + std::get<0>(it));
+        if (aliasPwd != aliasPwdMap.end()) {
+            if (aliasPwd->second != std::get<1>(it)) {
+                errorLogMsg += "Alias: " + std::get<0>(it) + " has wrong encryption status: "
+                                + std::to_string(std::get<1>(it)) + "\n";
+            }
+        }
+        else {
+            errorLogMsg += "Expected alias: " + std::get<0>(it) + " not found.\n";
+        }
+    }
+
+    if (!errorLogMsg.empty()) {
+        for (const auto &it : actual)
+        {
+            errorLogMsg += "Actual alias: " + std::get<0>(it) + " status: "
+                + std::to_string(std::get<1>(it)) + "\n";
+        }
+        RUNNER_FAIL_MSG("Actual list of aliases differ from expected list.\n" + errorLogMsg);
+    }
+}
+
+void check_alias_info_list(const CKM::AliasPwdVector& expected)
+{
+    ckmc_alias_info_list_s *aliasInfoList = NULL;
+    int ret = ckmc_get_data_alias_info_list(&aliasInfoList);
+    RUNNER_ASSERT_MSG(ret == CKMC_ERROR_NONE, "Failed to get the list of data aliases. " << ret << " / "
+                      << CKMCErrorToString(ret));
+
+    CKM::AliasPwdVector actual;
+    ckmc_alias_info_list_s *plist = aliasInfoList;
+    char* alias;
+    bool isPasswordProtected;
+    unsigned int it = 0;
+    while (plist)
+    {
+        ret = ckmc_alias_info_get_alias(plist->info, &alias);
+        RUNNER_ASSERT_MSG(ret == CKMC_ERROR_NONE, "Failed to get alias. " << ret << " / "
+                          << CKMCErrorToString(ret));
+        ret = ckmc_alias_info_is_password_protected(plist->info, &isPasswordProtected);
+        RUNNER_ASSERT_MSG(ret == CKMC_ERROR_NONE, "Failed to get password protection status" << ret << " / "
+                          << CKMCErrorToString(ret));
+        RUNNER_ASSERT_MSG(alias != nullptr, "Got null alias. Iterator: " << it);
+        actual.push_back(std::make_pair(alias, isPasswordProtected));
+        plist = plist->next;
+        it++;
+    }
+    ckmc_alias_info_list_all_free(aliasInfoList);
+    check_alias_info_list_helper(expected, actual);
+}
+
 size_t count_aliases(alias_type_ type, size_t minimum_initial_element_count)
 {
     ckmc_alias_list_s *aliasList = NULL;
@@ -515,13 +569,28 @@ ParamListPtr createParamListPtr()
     return ParamListPtr(list, ckmc_param_list_free);
 }
 
-void assert_buffers_equal(const ckmc_raw_buffer_s b1, const ckmc_raw_buffer_s b2, bool equal)
+void setParam(ParamListPtr& params, ckmc_param_name_e name, ckmc_raw_buffer_s* buffer)
+{
+    int ret = ckmc_param_list_set_buffer(params.get(), name, buffer);
+    RUNNER_ASSERT_MSG(ret == CKMC_ERROR_NONE,
+                      "Failed to set param " << name << " error: " << CKMCErrorToString(ret));
+}
+
+void setParam(ParamListPtr& params, ckmc_param_name_e name, uint64_t integer)
+{
+    int ret = ckmc_param_list_set_integer(params.get(), name, integer);
+    RUNNER_ASSERT_MSG(ret == CKMC_ERROR_NONE,
+                      "Failed to set param " << name << " error: " << CKMCErrorToString(ret));
+}
+
+void assert_buffers_equal(const ckmc_raw_buffer_s* b1, const ckmc_raw_buffer_s* b2, bool equal)
 {
     if(equal) {
-        RUNNER_ASSERT_MSG(b1.size == b2.size, "Buffer size differs: " << b1.size << "!=" << b2.size);
-        RUNNER_ASSERT_MSG(0 == memcmp(b1.data, b2.data, b1.size), "Buffer contents differ");
+        RUNNER_ASSERT_MSG(b1->size == b2->size,
+                          "Buffer size differs: " << b1->size << "!=" << b2->size);
+        RUNNER_ASSERT_MSG(0 == memcmp(b1->data, b2->data, b1->size), "Buffer contents differ");
     } else {
-        RUNNER_ASSERT_MSG(b1.size != b2.size || 0 != memcmp(b1.data, b2.data, b1.size),
+        RUNNER_ASSERT_MSG(b1->size != b2->size || 0 != memcmp(b1->data, b2->data, b1->size),
                           "Buffers should be different");
     }
 }
@@ -530,3 +599,24 @@ RawBufferPtr create_raw_buffer(ckmc_raw_buffer_s* buffer)
 {
     return RawBufferPtr(buffer, ckmc_buffer_free);
 }
+
+CKM::Policy generate_ckm_policy(int iterator_nr) {
+    if (iterator_nr % 2) { // policy with password and with / without extractable flag
+        return CKM::Policy(CKM::Password("test_pwd"), iterator_nr % 4);
+    }
+    return CKM::Policy();
+}
+
+void require_default_user(char *argv[])
+{
+    uid_t expected_uid = tzplatform_getuid(TZ_SYS_DEFAULT_USER);
+    if (expected_uid != geteuid()) {
+        std::string userStr("owner");
+        const char* user = tzplatform_getenv(TZ_SYS_DEFAULT_USER);
+        if (user)
+            userStr = user;
+
+        std::cerr << argv[0] << " should be executed as " << userStr << ". Aborting" << std::endl;
+        exit(-1);
+    }
+}