Refactor AccessProvider and ScopedAccessProvider
[platform/core/test/security-tests.git] / src / common / app_context.cpp
1 /*
2  * Copyright (c) 2013 - 2020 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        app_context.cpp
18  * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
19  * @version     1.0
20  * @brief       Common functions and macros used in security-tests package.
21  */
22
23 #include <app_context.h>
24 #include <scoped_process_label.h>
25 #include <tests_common.h>
26
27 #include <map>
28
29 #include <sys/smack.h>
30 #include <unistd.h>
31
32 AppContext::AppContext(const std::string& label)
33     : m_label(label)
34 {
35 }
36
37 void AppContext::allowAccessFrom(const std::string& subject, const std::string& rule)
38 {
39     m_smackAccess.add(subject, m_label, rule);
40 }
41
42 void AppContext::allowAccessTo(const std::string& object, const std::string& rule)
43 {
44     m_smackAccess.add(m_label, object, rule);
45 }
46
47 void AppContext::apply(uid_t user, gid_t group)
48 {
49     revokeAccessToAll();
50     applyRules();
51     applyLabel();
52     applyUserSwitch(user, group);
53 }
54
55 void AppContext::applyLabel()
56 {
57     ScopedProcessLabel spl(m_label, false);
58 }
59
60 ScopedProcessLabel AppContext::applyLabelScoped()
61 {
62     return ScopedProcessLabel(m_label, true);
63 }
64
65 void AppContext::applyRules()
66 {
67     m_smackAccess.apply();
68 }
69
70 void AppContext::applyUserSwitch(uid_t user, gid_t group)
71 {
72     RUNNER_ASSERT_MSG(0 == setgid(group), "Error in setgid.");
73     RUNNER_ASSERT_MSG(0 == setuid(user), "Error in setuid.");
74 }
75
76 void AppContext::applyUserSwitchEffective(uid_t user, gid_t group)
77 {
78     RUNNER_ASSERT_MSG(0 == setegid(group), "Error in setegid.");
79     RUNNER_ASSERT_MSG(0 == seteuid(user), "Error in seteuid.");
80 }
81
82 void AppContext::revokeAccessToAll()
83 {
84     RUNNER_ASSERT_MSG(0 == smack_revoke_subject(m_label.c_str()),
85         "Error in smack_revoke_subject(" << m_label << ")");
86 }
87
88 void AppContext::revokeRules()
89 {
90     m_smackAccess.clear();
91 }