Merge branch 'tizen' into security-manager
[platform/core/test/security-tests.git] / src / common / tests_common.cpp
1 /*
2  * Copyright (c) 2013-2015 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 /*
18  * @file        tests_common.cpp
19  * @author      Lukasz Kostyra (l.kostyra@partner.samsung.com)
20  * @version     1.0
21  * @brief       Common functions and macros used in security-tests package.
22  */
23
24 #include "tests_common.h"
25 #include <fcntl.h>
26 #include <sys/mman.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30 #include <grp.h>
31 #include <errno.h>
32 #include <vector>
33 #include <algorithm>
34
35 int DB::Transaction::db_result = PC_OPERATION_SUCCESS;
36
37 const char *WGT_APP_ID = "QwCqJ0ttyS";
38
39 bool smack_check(void)
40 {
41 #ifndef WRT_SMACK_ENABLED
42     return false;
43 #else
44     static int smack_present = -1;
45     if (-1 == smack_present)
46         smack_present = smack_smackfs_path() == nullptr ? 0 : 1;
47     return smack_present == 1;
48 #endif
49 }
50
51 /**
52  * Dropping root privileges
53  * returns 0 on success, 1 on error
54  */
55 int drop_root_privileges(uid_t appUid, gid_t appGid)
56 {
57     if (getuid() == 0) {
58         /* process is running as root, drop privileges */
59         if (setgid(appGid) != 0)
60             return 1;
61         if (setuid(appUid) != 0)
62             return 1;
63     }
64     uid_t uid = getuid();
65     if (uid == appUid)
66         return 0;
67
68     return 1;
69 }
70
71 void setLabelForSelf(const int line, const char *label)
72 {
73     int ret = smack_set_label_for_self(label);
74     RUNNER_ASSERT_MSG(ret == 0, "Error in smack_set_label_for_self(): " << ret << ", line: " << line);
75 }
76
77 /*
78  * Add a new group to the current process groups.
79  */
80 void add_process_group(const char* group_name)
81 {
82     // get group ID by group name
83     group *gr = getgrnam(group_name);
84     RUNNER_ASSERT_ERRNO_MSG(gr != nullptr, "getgrnam failed on '" << group_name << "' group");
85     const gid_t new_group_id = gr->gr_gid;
86
87     // get number of groups that the current process belongs to
88     int ngroups = getgroups(0, nullptr);
89
90     //allocate groups table + space for new group entry
91     std::vector<gid_t> groups(ngroups + 1);
92     getgroups(ngroups, groups.data());
93
94     // check if the process already belongs to the group
95     if (std::find(groups.begin(), groups.end(), new_group_id) != groups.end()) return;
96
97     // add new group & apply change
98     groups[ngroups] = new_group_id;
99     int ret = setgroups(groups.size(), groups.data());
100     RUNNER_ASSERT_ERRNO_MSG(ret == 0, "setgroups() failed");
101 }
102
103 /*
104  * Remove specific group from the current process groups.
105  */
106 void remove_process_group(const char* group_name)
107 {
108     // get group ID by group name
109     group *gr = getgrnam(group_name);
110     RUNNER_ASSERT_ERRNO_MSG(gr != nullptr, "getgrnam failed on '" << group_name << "' group");
111     const gid_t new_group_id = gr->gr_gid;
112
113     int ngroups = getgroups(0, nullptr);
114     std::vector<gid_t> groups(ngroups);
115     getgroups(ngroups, groups.data());
116
117     // remove group from the list
118     groups.erase(std::remove(groups.begin(), groups.end(), new_group_id), groups.end());
119
120     if (groups.size() != (size_t)ngroups) {
121         // apply change
122         int ret = setgroups(groups.size(), groups.data());
123         RUNNER_ASSERT_ERRNO_MSG(ret == 0, "setgroups() failed");
124     }
125 }
126
127 std::string formatCstr(const char *cstr)
128 {
129     if (!cstr)
130         return std::string("nullptr");
131     return std::string("\"") + cstr + "\"";
132 }
133
134 int files_compare(int fd1, int fd2)
135 {
136     //for getting files sizes
137     struct stat fs1, fs2;
138
139     //handlers for mmap()
140     void *h1 = MAP_FAILED;
141     void *h2 = MAP_FAILED;
142
143     //getting files information
144     RUNNER_ASSERT_ERRNO_MSG(fstat(fd1, &fs1) == 0, "fstat failed");
145     RUNNER_ASSERT_ERRNO_MSG(fstat(fd2, &fs2) == 0, "fstat failed");
146
147     if (fs1.st_size < fs2.st_size) {
148         return -1;
149     }
150
151     if (fs1.st_size > fs2.st_size) {
152         return 1;
153     }
154
155     //since Linux 2.6.12, mmap returns EINVAL if length is 0
156     //if both lengths are 0, files are actually the same
157     if (0 == fs1.st_size && 0 == fs2.st_size) {
158         return 0;
159     }
160
161     //mapping files to process memory
162     RUNNER_ASSERT_ERRNO_MSG((h1 = mmap(0, fs1.st_size, PROT_READ, MAP_SHARED, fd1, 0 )) != MAP_FAILED,
163                                "mmap failed for fd=" << fd1);
164
165     if ((h2 = mmap(0, fs2.st_size, PROT_READ, MAP_SHARED, fd2, 0 )) == MAP_FAILED) {
166         munmap(h1, fs1.st_size);
167         RUNNER_ASSERT_MSG(h2 != MAP_FAILED, "mmap failed for fd=" << fd2
168                                             << ". " << strerror(errno));
169     }
170
171     int result = memcmp(h1, h2, fs1.st_size);
172     munmap(h1, fs1.st_size);
173     munmap(h2, fs2.st_size);
174
175     return result;
176 }
177
178 void mkdirSafe(const std::string &path, mode_t mode)
179 {
180     RUNNER_ASSERT_ERRNO_MSG(0 == mkdir(path.c_str(), mode) || errno == EEXIST,
181                             "mkdir for <" << path << "> with mode <" << mode << "> failed");
182 }
183
184 void mktreeSafe(const std::string &path, mode_t mode)
185 {
186     // Create subsequent parent directories
187     // Assume that path is absolute - i.e. starts with '/'
188     for (size_t pos = 0; (pos = path.find("/", pos + 1)) != std::string::npos; )
189         mkdirSafe(path.substr(0, pos).c_str(), mode);
190
191     mkdirSafe(path, mode);
192 }
193
194 void creatSafe(const std::string &path, mode_t mode)
195 {
196     RUNNER_ASSERT_ERRNO_MSG(-1 != creat(path.c_str(), mode),
197                             "creat for <" << path << "> with mode <" << mode << "> failed");
198 }
199
200 void symlinkSafe(const std::string &targetPath, const std::string &linkPath)
201 {
202     RUNNER_ASSERT_ERRNO_MSG(0 == symlink(targetPath.c_str(), linkPath.c_str()),
203                             "symlink for <" << linkPath << "> to <" << targetPath << "> failed");
204 }
205
206 void removeDir(const std::string &path)
207 {
208     DIR *d = opendir(path.c_str());
209
210     if (nullptr == d) {
211         RUNNER_ASSERT_ERRNO_MSG(errno == ENOENT, "opendir of <" << path << "> failed");
212         return;
213     }
214
215     struct dirent *dirEntry;
216     while (nullptr != (dirEntry = readdir(d))) {
217         std::string entryName(dirEntry->d_name);
218         if (entryName == "." || entryName == "..")
219             continue;
220
221         std::string entryPath(path + "/" + entryName);
222         struct stat st;
223
224         RUNNER_ASSERT_ERRNO_MSG(0 == lstat(entryPath.c_str(), &st),
225                                 "stat for <" << entryPath << "> failed");
226         if (S_ISDIR(st.st_mode))
227             removeDir(entryPath);
228         else
229             RUNNER_ASSERT_ERRNO_MSG(0 == unlink(entryPath.c_str()),
230                                     "unlink for <" << entryPath << "> failed");
231     }
232
233     closedir(d);
234
235     RUNNER_ASSERT_ERRNO_MSG(0 == rmdir(path.c_str()), "rmdir for <" << path << "> failed");
236 }