Common ckm functions moved to separate file
[platform/core/test/security-tests.git] / tests / ckm / ckm-common.cpp
1 /*
2  *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License
15  */
16 /*
17  * @file       ckm-common.cpp
18  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
19  * @version    1.0
20  */
21
22 #include <sys/smack.h>
23 #include <ckm-common.h>
24 #include <tests_common.h>
25 #include <access_provider.h>
26 #include <ckm/ckm-manager.h>
27
28 void switch_to_app(const char* label)
29 {
30     SecurityServer::AccessProvider ap(label);
31     ap.allowAPI("key-manager::api-storage", "rw");
32     ap.applyAndSwithToUser(APP_UID, APP_GID);
33 }
34
35 DBCleanup::~DBCleanup()
36 {
37     // Let it throw. If db can't be cleared further tests are unreliable
38     CKM::ManagerShPtr mgr = CKM::Manager::create();
39     for(const auto& it:m_keys)
40         mgr->removeKey(it);
41     m_keys.clear();
42     for(const auto& it:m_certs)
43         mgr->removeCertificate(it);
44     m_certs.clear();
45     for(const auto& it:m_data)
46         mgr->removeData(it);
47     m_data.clear();
48 }
49
50 // returns process label
51 CharPtr get_label()
52 {
53     int ret;
54     char* my_label = NULL;
55     RUNNER_ASSERT_MSG(0 == (ret = smack_new_label_from_self(&my_label)),
56                          "Failed to get smack label for self. Error: " << ret);
57
58     return CharPtr(my_label, free);
59 }
60
61 // changes process label
62 void change_label(const char* label)
63 {
64     int ret = smack_set_label_for_self(label);
65     RUNNER_ASSERT_MSG(0 == ret, "Error in smack_set_label_for_self. Error: " << ret);
66 }
67
68 ScopedLabel::ScopedLabel(const char* label) : m_original_label(get_label())
69 {
70     change_label(label);
71 }
72
73 ScopedLabel::~ScopedLabel()
74 {
75     /*
76      * Let it throw. If we can't restore label then remaining tests results will be
77      * unreliable anyway.
78      */
79     change_label(m_original_label.get());
80 }