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