1e03d3677fcfce8908527043d490a1e0da0f0c82
[platform/core/security/security-manager.git] / src / client / client-security-manager.cpp
1 /*
2  *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Contact: Rafal Krypa <r.krypa@samsung.com>
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License
17  *
18  *      Security Manager library header
19  */
20 /*
21  * @file        client-security-manager.cpp
22  * @author      Pawel Polawski <p.polawski@samsung.com>
23  * @author      Rafal Krypa <r.krypa@samsung.com>
24  * @version     1.0
25  * @brief       This file contain client side implementation of security-manager API
26  */
27
28 #include <cstdio>
29 #include <utility>
30
31 #include <unistd.h>
32 #include <grp.h>
33 #include <dirent.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/xattr.h>
37 #include <sys/smack.h>
38 #include <sys/capability.h>
39
40 #include <dpl/log/log.h>
41 #include <dpl/exception.h>
42
43 #include <message-buffer.h>
44 #include <client-common.h>
45 #include <protocols.h>
46 #include <smack-common.h>
47 #include <service_impl.h>
48 #include <file-lock.h>
49
50 #include <security-manager.h>
51
52 /**
53  * Mapping of lib_retcode error codes to theirs strings equivalents
54  */
55 static std::map<enum lib_retcode, std::string> lib_retcode_string_map = {
56     {SECURITY_MANAGER_SUCCESS, "Success"},
57     {SECURITY_MANAGER_ERROR_UNKNOWN, "Unknown error"},
58     {SECURITY_MANAGER_ERROR_INPUT_PARAM, "Invalid function parameter was given"},
59     {SECURITY_MANAGER_ERROR_MEMORY, "Memory allocation error"},
60     {SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE, "Incomplete data in application request"},
61     {SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED, "User does not have sufficient "
62                                                    "rigths to perform an operation"}
63 };
64
65 SECURITY_MANAGER_API
66 const char *security_manager_strerror(enum lib_retcode rc)
67 {
68     try {
69         return lib_retcode_string_map.at(rc).c_str();
70     } catch (const std::out_of_range &e) {
71         return "Unknown error code";
72     }
73 }
74
75 SECURITY_MANAGER_API
76 int security_manager_app_inst_req_new(app_inst_req **pp_req)
77 {
78     if (!pp_req)
79         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
80
81     try {
82         *pp_req = new app_inst_req;
83     } catch (std::bad_alloc& ex) {
84         return SECURITY_MANAGER_ERROR_MEMORY;
85     }
86     (*pp_req)->uid = geteuid();
87
88     return SECURITY_MANAGER_SUCCESS;
89 }
90
91 SECURITY_MANAGER_API
92 void security_manager_app_inst_req_free(app_inst_req *p_req)
93 {
94     delete p_req;
95 }
96
97 SECURITY_MANAGER_API
98 int security_manager_app_inst_req_set_uid(app_inst_req *p_req,
99                                           const uid_t uid)
100 {
101     if (!p_req)
102         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
103
104     p_req->uid = uid;
105
106     return SECURITY_MANAGER_SUCCESS;
107 }
108
109 SECURITY_MANAGER_API
110 int security_manager_app_inst_req_set_app_id(app_inst_req *p_req, const char *app_id)
111 {
112     if (!p_req || !app_id)
113         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
114
115     p_req->appId = app_id;
116
117     return SECURITY_MANAGER_SUCCESS;
118 }
119
120 SECURITY_MANAGER_API
121 int security_manager_app_inst_req_set_pkg_id(app_inst_req *p_req, const char *pkg_id)
122 {
123     if (!p_req || !pkg_id)
124         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
125
126     p_req->pkgId = pkg_id;
127
128     return SECURITY_MANAGER_SUCCESS;
129 }
130
131 SECURITY_MANAGER_API
132 int security_manager_app_inst_req_add_privilege(app_inst_req *p_req, const char *privilege)
133 {
134     if (!p_req || !privilege)
135         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
136
137     p_req->privileges.push_back(privilege);
138
139     return SECURITY_MANAGER_SUCCESS;
140 }
141
142 SECURITY_MANAGER_API
143 int security_manager_app_inst_req_add_path(app_inst_req *p_req, const char *path, const int path_type)
144 {
145     if (!p_req || !path || (path_type < 0) || (path_type >= SECURITY_MANAGER_ENUM_END))
146         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
147
148     p_req->appPaths.push_back(std::make_pair(path, path_type));
149
150     return SECURITY_MANAGER_SUCCESS;
151 }
152
153 SECURITY_MANAGER_API
154 int security_manager_app_install(const app_inst_req *p_req)
155 {
156     using namespace SecurityManager;
157
158     return try_catch([&] {
159         //checking parameters
160         if (!p_req)
161             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
162         if (p_req->appId.empty() || p_req->pkgId.empty())
163             return SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE;
164
165         bool offlineMode;
166         int retval;
167
168         try {
169             SecurityManager::FileLocker serviceLock(SecurityManager::SERVICE_LOCK_FILE);
170             if ((offlineMode = serviceLock.Locked())) {
171                 LogInfo("Working in offline mode.");
172                 retval = SecurityManager::ServiceImpl::appInstall(*p_req, geteuid());
173             }
174         } catch (const SecurityManager::FileLocker::Exception::Base &e) {
175             offlineMode = false;
176         }
177         if (!offlineMode) {
178             MessageBuffer send, recv;
179
180             //put data into buffer
181             Serialization::Serialize(send, (int)SecurityModuleCall::APP_INSTALL);
182             Serialization::Serialize(send, p_req->appId);
183             Serialization::Serialize(send, p_req->pkgId);
184             Serialization::Serialize(send, p_req->privileges);
185             Serialization::Serialize(send, p_req->appPaths);
186             Serialization::Serialize(send, p_req->uid);
187
188             //send buffer to server
189             retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
190             if (retval != SECURITY_MANAGER_API_SUCCESS) {
191                 LogError("Error in sendToServer. Error code: " << retval);
192                 return SECURITY_MANAGER_ERROR_UNKNOWN;
193             }
194
195             //receive response from server
196             Deserialization::Deserialize(recv, retval);
197         }
198         switch(retval) {
199             case SECURITY_MANAGER_API_SUCCESS:
200                 return SECURITY_MANAGER_SUCCESS;
201             case SECURITY_MANAGER_API_ERROR_AUTHENTICATION_FAILED:
202                 return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
203             default:
204                 return SECURITY_MANAGER_ERROR_UNKNOWN;
205         }
206
207     });
208 }
209
210 SECURITY_MANAGER_API
211 int security_manager_app_uninstall(const app_inst_req *p_req)
212 {
213     using namespace SecurityManager;
214     MessageBuffer send, recv;
215
216     return try_catch([&] {
217         //checking parameters
218         if (!p_req)
219             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
220         if (p_req->appId.empty())
221             return SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE;
222
223         //put data into buffer
224         Serialization::Serialize(send, (int)SecurityModuleCall::APP_UNINSTALL);
225         Serialization::Serialize(send, p_req->appId);
226
227         //send buffer to server
228         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
229         if (retval != SECURITY_MANAGER_API_SUCCESS) {
230             LogError("Error in sendToServer. Error code: " << retval);
231             return SECURITY_MANAGER_ERROR_UNKNOWN;
232         }
233
234         //receive response from server
235         Deserialization::Deserialize(recv, retval);
236         if (retval != SECURITY_MANAGER_API_SUCCESS)
237             return SECURITY_MANAGER_ERROR_UNKNOWN;
238
239         return SECURITY_MANAGER_SUCCESS;;
240     });
241 }
242
243 SECURITY_MANAGER_API
244 int security_manager_get_app_pkgid(char **pkg_id, const char *app_id)
245 {
246     using namespace SecurityManager;
247     MessageBuffer send, recv;
248
249     LogDebug("security_manager_get_app_pkgid() called");
250
251     return try_catch([&] {
252         //checking parameters
253
254         if (app_id == NULL) {
255             LogError("security_manager_app_get_pkgid: app_id is NULL");
256             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
257         }
258
259         if (pkg_id == NULL) {
260             LogError("security_manager_app_get_pkgid: pkg_id is NULL");
261             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
262         }
263
264         //put data into buffer
265         Serialization::Serialize(send, static_cast<int>(SecurityModuleCall::APP_GET_PKGID));
266         Serialization::Serialize(send, std::string(app_id));
267
268         //send buffer to server
269         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
270         if (retval != SECURITY_MANAGER_API_SUCCESS) {
271             LogDebug("Error in sendToServer. Error code: " << retval);
272             return SECURITY_MANAGER_ERROR_UNKNOWN;
273         }
274
275         //receive response from server
276         Deserialization::Deserialize(recv, retval);
277         if (retval != SECURITY_MANAGER_API_SUCCESS)
278             return SECURITY_MANAGER_ERROR_UNKNOWN;
279
280         std::string pkgIdString;
281         Deserialization::Deserialize(recv, pkgIdString);
282         if (pkgIdString.empty()) {
283             LogError("Unexpected empty pkgId");
284             return SECURITY_MANAGER_ERROR_UNKNOWN;
285         }
286
287         *pkg_id = strdup(pkgIdString.c_str());
288         if (*pkg_id == NULL) {
289             LogError("Failed to allocate memory for pkgId");
290             return SECURITY_MANAGER_ERROR_MEMORY;
291         }
292
293         return SECURITY_MANAGER_SUCCESS;
294     });
295 }
296
297 static bool setup_smack(const char *label)
298 {
299     int labelSize = strlen(label);
300
301     // Set Smack label for open socket file descriptors
302
303     std::unique_ptr<DIR, std::function<int(DIR*)>> dir(
304         opendir("/proc/self/fd"), closedir);
305     if (!dir.get()) {
306         LogError("Unable to read list of open file descriptors: " <<
307             strerror(errno));
308         return SECURITY_MANAGER_ERROR_UNKNOWN;
309     }
310
311     do {
312         errno = 0;
313         struct dirent *dirEntry = readdir(dir.get());
314         if (dirEntry == nullptr) {
315             if (errno == 0) // NULL return value also signals end of directory
316                 break;
317
318             LogError("Unable to read list of open file descriptors: " <<
319                 strerror(errno));
320             return SECURITY_MANAGER_ERROR_UNKNOWN;
321         }
322
323         // Entries with numerical names specify file descriptors, ignore the rest
324         if (!isdigit(dirEntry->d_name[0]))
325             continue;
326
327         struct stat statBuf;
328         int fd = atoi(dirEntry->d_name);
329         int ret = fstat(fd, &statBuf);
330         if (ret != 0) {
331             LogWarning("fstat failed on file descriptor " << fd << ": " <<
332                 strerror(errno));
333             continue;
334         }
335         if (S_ISSOCK(statBuf.st_mode)) {
336             ret = fsetxattr(fd, XATTR_NAME_SMACKIPIN, label, labelSize, 0);
337             if (ret != 0) {
338                 LogError("Setting Smack label failed on file descriptor " <<
339                     fd << ": " << strerror(errno));
340                 return SECURITY_MANAGER_ERROR_UNKNOWN;
341             }
342
343             ret = fsetxattr(fd, XATTR_NAME_SMACKIPOUT, label, labelSize, 0);
344             if (ret != 0) {
345                 LogError("Setting Smack label failed on file descriptor " <<
346                     fd << ": " << strerror(errno));
347                 return SECURITY_MANAGER_ERROR_UNKNOWN;
348             }
349         }
350     } while (true);
351
352     // Set Smack label of current process
353     smack_set_label_for_self(label);
354
355     return SECURITY_MANAGER_SUCCESS;
356 }
357
358 SECURITY_MANAGER_API
359 int security_manager_set_process_label_from_appid(const char *app_id)
360 {
361     char *pkg_id;
362     int ret;
363     std::string appLabel;
364
365     LogDebug("security_manager_set_process_label_from_appid() called");
366
367     if (smack_smackfs_path() == NULL)
368         return SECURITY_MANAGER_SUCCESS;
369
370     ret = security_manager_get_app_pkgid(&pkg_id, app_id);
371     if (ret != SECURITY_MANAGER_SUCCESS) {
372         return ret;
373     }
374
375     if (SecurityManager::generateAppLabel(std::string(pkg_id), appLabel)) {
376         ret = setup_smack(appLabel.c_str());
377         if (ret != SECURITY_MANAGER_SUCCESS) {
378             LogError("Failed to set smack label " << appLabel << " for current process");
379         }
380     }
381     else {
382         ret = SECURITY_MANAGER_ERROR_UNKNOWN;
383     }
384
385     free(pkg_id);
386     return ret;
387 }
388
389 SECURITY_MANAGER_API
390 int security_manager_set_process_groups_from_appid(const char *app_id)
391 {
392     using namespace SecurityManager;
393     MessageBuffer send, recv;
394     int ret;
395
396     LogDebug("security_manager_set_process_groups_from_appid() called");
397
398     return try_catch([&] {
399         //checking parameters
400
401         if (app_id == nullptr) {
402             LogError("app_id is NULL");
403             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
404         }
405
406         //put data into buffer
407         Serialization::Serialize(send, static_cast<int>(SecurityModuleCall::APP_GET_GROUPS));
408         Serialization::Serialize(send, std::string(app_id));
409
410         //send buffer to server
411         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
412         if (retval != SECURITY_MANAGER_API_SUCCESS) {
413             LogDebug("Error in sendToServer. Error code: " << retval);
414             return SECURITY_MANAGER_ERROR_UNKNOWN;
415         }
416
417         //receive response from server
418         Deserialization::Deserialize(recv, retval);
419         if (retval != SECURITY_MANAGER_API_SUCCESS)
420             return SECURITY_MANAGER_ERROR_UNKNOWN;
421
422         //How many new groups?
423         int newGroupsCnt;
424         Deserialization::Deserialize(recv, newGroupsCnt);
425
426         //And how many groups do we belong to already?
427         int oldGroupsCnt;
428         ret = getgroups(0, nullptr);
429         if (ret == -1) {
430             LogError("Unable to get list of current supplementary groups: " <<
431                 strerror(errno));
432             return SECURITY_MANAGER_ERROR_UNKNOWN;
433         }
434         oldGroupsCnt = ret;
435
436         //Allocate an array for both old and new groups gids
437         std::unique_ptr<gid_t[]> groups(new gid_t[oldGroupsCnt + newGroupsCnt]);
438         if (!groups.get()) {
439             LogError("Memory allocation failed.");
440             return SECURITY_MANAGER_ERROR_MEMORY;
441         }
442
443         //Get the old groups from process
444         ret = getgroups(oldGroupsCnt, groups.get());
445         if (ret == -1) {
446             LogError("Unable to get list of current supplementary groups: " <<
447                 strerror(errno));
448             return SECURITY_MANAGER_ERROR_UNKNOWN;
449         }
450
451         //Get the new groups from server response
452         for (int i = 0; i < newGroupsCnt; ++i) {
453             gid_t gid;
454             Deserialization::Deserialize(recv, gid);
455             groups.get()[oldGroupsCnt + i] = gid;
456             LogDebug("Adding process to group " << gid);
457         }
458
459         //Apply the modified groups list
460         ret = setgroups(oldGroupsCnt + newGroupsCnt, groups.get());
461         if (ret == -1) {
462             LogError("Unable to get list of current supplementary groups: " <<
463                 strerror(errno));
464             return SECURITY_MANAGER_ERROR_UNKNOWN;
465         }
466
467         return SECURITY_MANAGER_SUCCESS;
468     });
469 }
470
471 SECURITY_MANAGER_API
472 int security_manager_drop_process_privileges(void)
473 {
474     LogDebug("security_manager_drop_process_privileges() called");
475
476     int ret;
477     cap_t cap = cap_init();
478     if (!cap) {
479         LogError("Unable to allocate capability object");
480         return SECURITY_MANAGER_ERROR_MEMORY;
481     }
482
483     ret = cap_clear(cap);
484     if (ret) {
485         LogError("Unable to initialize capability object");
486         cap_free(cap);
487         return SECURITY_MANAGER_ERROR_UNKNOWN;
488     }
489
490     ret = cap_set_proc(cap);
491     if (ret) {
492         LogError("Unable to drop process capabilities");
493         cap_free(cap);
494         return SECURITY_MANAGER_ERROR_UNKNOWN;
495     }
496
497     cap_free(cap);
498     return SECURITY_MANAGER_SUCCESS;
499 }
500
501 SECURITY_MANAGER_API
502 int security_manager_prepare_app(const char *app_id)
503 {
504     LogDebug("security_manager_prepare_app() called");
505     int ret;
506
507     ret = security_manager_set_process_label_from_appid(app_id);
508     if (ret != SECURITY_MANAGER_SUCCESS)
509         return ret;
510
511     ret = security_manager_set_process_groups_from_appid(app_id);
512     if (ret != SECURITY_MANAGER_SUCCESS)
513         return ret;
514
515     ret = security_manager_drop_process_privileges();
516     return ret;
517 }