51b0ad0faf934bc0cb24daab0efe4bb4ac85484a
[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 #include <smack-labels.h>
43 #include <message-buffer.h>
44 #include <client-common.h>
45 #include <protocols.h>
46 #include <service_impl.h>
47 #include <file-lock.h>
48
49 #include <security-manager.h>
50
51 /**
52  * Mapping of lib_retcode error codes to theirs strings equivalents
53  */
54 static std::map<enum lib_retcode, std::string> lib_retcode_string_map = {
55     {SECURITY_MANAGER_SUCCESS, "Success"},
56     {SECURITY_MANAGER_ERROR_UNKNOWN, "Unknown error"},
57     {SECURITY_MANAGER_ERROR_INPUT_PARAM, "Invalid function parameter was given"},
58     {SECURITY_MANAGER_ERROR_MEMORY, "Memory allocation error"},
59     {SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE, "Incomplete data in application request"},
60     {SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED, "User does not have sufficient "
61                                                    "rigths to perform an operation"}
62 };
63
64 SECURITY_MANAGER_API
65 const char *security_manager_strerror(enum lib_retcode rc)
66 {
67     try {
68         return lib_retcode_string_map.at(rc).c_str();
69     } catch (const std::out_of_range &e) {
70         return "Unknown error code";
71     }
72 }
73
74 SECURITY_MANAGER_API
75 int security_manager_app_inst_req_new(app_inst_req **pp_req)
76 {
77     if (!pp_req)
78         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
79
80     try {
81         *pp_req = new app_inst_req;
82     } catch (std::bad_alloc& ex) {
83         return SECURITY_MANAGER_ERROR_MEMORY;
84     }
85     (*pp_req)->uid = geteuid();
86
87     return SECURITY_MANAGER_SUCCESS;
88 }
89
90 SECURITY_MANAGER_API
91 void security_manager_app_inst_req_free(app_inst_req *p_req)
92 {
93     delete p_req;
94 }
95
96 SECURITY_MANAGER_API
97 int security_manager_app_inst_req_set_uid(app_inst_req *p_req,
98                                           const uid_t uid)
99 {
100     if (!p_req)
101         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
102
103     p_req->uid = uid;
104
105     return SECURITY_MANAGER_SUCCESS;
106 }
107
108 SECURITY_MANAGER_API
109 int security_manager_app_inst_req_set_app_id(app_inst_req *p_req, const char *app_id)
110 {
111     if (!p_req || !app_id)
112         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
113
114     p_req->appId = app_id;
115
116     return SECURITY_MANAGER_SUCCESS;
117 }
118
119 SECURITY_MANAGER_API
120 int security_manager_app_inst_req_set_pkg_id(app_inst_req *p_req, const char *pkg_id)
121 {
122     if (!p_req || !pkg_id)
123         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
124
125     p_req->pkgId = pkg_id;
126
127     return SECURITY_MANAGER_SUCCESS;
128 }
129
130 SECURITY_MANAGER_API
131 int security_manager_app_inst_req_add_privilege(app_inst_req *p_req, const char *privilege)
132 {
133     if (!p_req || !privilege)
134         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
135
136     p_req->privileges.push_back(privilege);
137
138     return SECURITY_MANAGER_SUCCESS;
139 }
140
141 SECURITY_MANAGER_API
142 int security_manager_app_inst_req_add_path(app_inst_req *p_req, const char *path, const int path_type)
143 {
144     if (!p_req || !path || (path_type < 0) || (path_type >= SECURITY_MANAGER_ENUM_END))
145         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
146
147     p_req->appPaths.push_back(std::make_pair(path, path_type));
148
149     return SECURITY_MANAGER_SUCCESS;
150 }
151
152 SECURITY_MANAGER_API
153 int security_manager_app_install(const app_inst_req *p_req)
154 {
155     using namespace SecurityManager;
156
157     return try_catch([&] {
158         //checking parameters
159         if (!p_req)
160             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
161         if (p_req->appId.empty() || p_req->pkgId.empty())
162             return SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE;
163
164         bool offlineMode;
165         int retval;
166
167         try {
168             SecurityManager::FileLocker serviceLock(SecurityManager::SERVICE_LOCK_FILE);
169             if ((offlineMode = serviceLock.Locked())) {
170                 LogInfo("Working in offline mode.");
171                 retval = SecurityManager::ServiceImpl::appInstall(*p_req, geteuid());
172             }
173         } catch (const SecurityManager::FileLocker::Exception::Base &e) {
174             offlineMode = false;
175         }
176         if (!offlineMode) {
177             MessageBuffer send, recv;
178
179             //put data into buffer
180             Serialization::Serialize(send, (int)SecurityModuleCall::APP_INSTALL);
181             Serialization::Serialize(send, p_req->appId);
182             Serialization::Serialize(send, p_req->pkgId);
183             Serialization::Serialize(send, p_req->privileges);
184             Serialization::Serialize(send, p_req->appPaths);
185             Serialization::Serialize(send, p_req->uid);
186
187             //send buffer to server
188             retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
189             if (retval != SECURITY_MANAGER_API_SUCCESS) {
190                 LogError("Error in sendToServer. Error code: " << retval);
191                 return SECURITY_MANAGER_ERROR_UNKNOWN;
192             }
193
194             //receive response from server
195             Deserialization::Deserialize(recv, retval);
196         }
197         switch(retval) {
198             case SECURITY_MANAGER_API_SUCCESS:
199                 return SECURITY_MANAGER_SUCCESS;
200             case SECURITY_MANAGER_API_ERROR_AUTHENTICATION_FAILED:
201                 return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
202             case SECURITY_MANAGER_API_ERROR_INPUT_PARAM:
203                 return SECURITY_MANAGER_ERROR_INPUT_PARAM;
204             default:
205                 return SECURITY_MANAGER_ERROR_UNKNOWN;
206         }
207
208     });
209 }
210
211 SECURITY_MANAGER_API
212 int security_manager_app_uninstall(const app_inst_req *p_req)
213 {
214     using namespace SecurityManager;
215     MessageBuffer send, recv;
216
217     return try_catch([&] {
218         //checking parameters
219         if (!p_req)
220             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
221         if (p_req->appId.empty())
222             return SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE;
223
224         //put data into buffer
225         Serialization::Serialize(send, (int)SecurityModuleCall::APP_UNINSTALL);
226         Serialization::Serialize(send, p_req->appId);
227
228         //send buffer to server
229         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
230         if (retval != SECURITY_MANAGER_API_SUCCESS) {
231             LogError("Error in sendToServer. Error code: " << retval);
232             return SECURITY_MANAGER_ERROR_UNKNOWN;
233         }
234
235         //receive response from server
236         Deserialization::Deserialize(recv, retval);
237         if (retval != SECURITY_MANAGER_API_SUCCESS)
238             return SECURITY_MANAGER_ERROR_UNKNOWN;
239
240         return SECURITY_MANAGER_SUCCESS;;
241     });
242 }
243
244 SECURITY_MANAGER_API
245 int security_manager_get_app_pkgid(char **pkg_id, const char *app_id)
246 {
247     using namespace SecurityManager;
248     MessageBuffer send, recv;
249
250     LogDebug("security_manager_get_app_pkgid() called");
251
252     return try_catch([&] {
253         //checking parameters
254
255         if (app_id == NULL) {
256             LogError("security_manager_app_get_pkgid: app_id is NULL");
257             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
258         }
259
260         if (pkg_id == NULL) {
261             LogError("security_manager_app_get_pkgid: pkg_id is NULL");
262             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
263         }
264
265         //put data into buffer
266         Serialization::Serialize(send, static_cast<int>(SecurityModuleCall::APP_GET_PKGID));
267         Serialization::Serialize(send, std::string(app_id));
268
269         //send buffer to server
270         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
271         if (retval != SECURITY_MANAGER_API_SUCCESS) {
272             LogDebug("Error in sendToServer. Error code: " << retval);
273             return SECURITY_MANAGER_ERROR_UNKNOWN;
274         }
275
276         //receive response from server
277         Deserialization::Deserialize(recv, retval);
278         if (retval != SECURITY_MANAGER_API_SUCCESS)
279             return SECURITY_MANAGER_ERROR_UNKNOWN;
280
281         std::string pkgIdString;
282         Deserialization::Deserialize(recv, pkgIdString);
283         if (pkgIdString.empty()) {
284             LogError("Unexpected empty pkgId");
285             return SECURITY_MANAGER_ERROR_UNKNOWN;
286         }
287
288         *pkg_id = strdup(pkgIdString.c_str());
289         if (*pkg_id == NULL) {
290             LogError("Failed to allocate memory for pkgId");
291             return SECURITY_MANAGER_ERROR_MEMORY;
292         }
293
294         return SECURITY_MANAGER_SUCCESS;
295     });
296 }
297
298 static bool setup_smack(const char *label)
299 {
300     int labelSize = strlen(label);
301
302     // Set Smack label for open socket file descriptors
303
304     std::unique_ptr<DIR, std::function<int(DIR*)>> dir(
305         opendir("/proc/self/fd"), closedir);
306     if (!dir.get()) {
307         LogError("Unable to read list of open file descriptors: " <<
308             strerror(errno));
309         return SECURITY_MANAGER_ERROR_UNKNOWN;
310     }
311
312     do {
313         errno = 0;
314         struct dirent *dirEntry = readdir(dir.get());
315         if (dirEntry == nullptr) {
316             if (errno == 0) // NULL return value also signals end of directory
317                 break;
318
319             LogError("Unable to read list of open file descriptors: " <<
320                 strerror(errno));
321             return SECURITY_MANAGER_ERROR_UNKNOWN;
322         }
323
324         // Entries with numerical names specify file descriptors, ignore the rest
325         if (!isdigit(dirEntry->d_name[0]))
326             continue;
327
328         struct stat statBuf;
329         int fd = atoi(dirEntry->d_name);
330         int ret = fstat(fd, &statBuf);
331         if (ret != 0) {
332             LogWarning("fstat failed on file descriptor " << fd << ": " <<
333                 strerror(errno));
334             continue;
335         }
336         if (S_ISSOCK(statBuf.st_mode)) {
337             ret = fsetxattr(fd, XATTR_NAME_SMACKIPIN, label, labelSize, 0);
338             if (ret != 0) {
339                 LogError("Setting Smack label failed on file descriptor " <<
340                     fd << ": " << strerror(errno));
341                 return SECURITY_MANAGER_ERROR_UNKNOWN;
342             }
343
344             ret = fsetxattr(fd, XATTR_NAME_SMACKIPOUT, label, labelSize, 0);
345             if (ret != 0) {
346                 LogError("Setting Smack label failed on file descriptor " <<
347                     fd << ": " << strerror(errno));
348                 return SECURITY_MANAGER_ERROR_UNKNOWN;
349             }
350         }
351     } while (true);
352
353     // Set Smack label of current process
354     smack_set_label_for_self(label);
355
356     return SECURITY_MANAGER_SUCCESS;
357 }
358
359 SECURITY_MANAGER_API
360 int security_manager_set_process_label_from_appid(const char *app_id)
361 {
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     if (SecurityManager::generateAppLabel(std::string(app_id), appLabel) == false) {
371         LogError("Failed to generate smack label for appId: " << app_id);
372         return SECURITY_MANAGER_API_ERROR_NO_SUCH_OBJECT;
373     }
374
375     if ((ret = setup_smack(appLabel.c_str())) != SECURITY_MANAGER_SUCCESS) {
376         LogError("Failed to set smack label " << appLabel << " for current process");
377         return ret;
378     }
379
380     return SECURITY_MANAGER_SUCCESS;
381 }
382
383 SECURITY_MANAGER_API
384 int security_manager_set_process_groups_from_appid(const char *app_id)
385 {
386     using namespace SecurityManager;
387     MessageBuffer send, recv;
388     int ret;
389
390     LogDebug("security_manager_set_process_groups_from_appid() called");
391
392     return try_catch([&] {
393         //checking parameters
394
395         if (app_id == nullptr) {
396             LogError("app_id is NULL");
397             return SECURITY_MANAGER_ERROR_INPUT_PARAM;
398         }
399
400         //put data into buffer
401         Serialization::Serialize(send, static_cast<int>(SecurityModuleCall::APP_GET_GROUPS));
402         Serialization::Serialize(send, std::string(app_id));
403
404         //send buffer to server
405         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
406         if (retval != SECURITY_MANAGER_API_SUCCESS) {
407             LogDebug("Error in sendToServer. Error code: " << retval);
408             return SECURITY_MANAGER_ERROR_UNKNOWN;
409         }
410
411         //receive response from server
412         Deserialization::Deserialize(recv, retval);
413         if (retval != SECURITY_MANAGER_API_SUCCESS)
414             return SECURITY_MANAGER_ERROR_UNKNOWN;
415
416         //How many new groups?
417         int newGroupsCnt;
418         Deserialization::Deserialize(recv, newGroupsCnt);
419
420         //And how many groups do we belong to already?
421         int oldGroupsCnt;
422         ret = getgroups(0, nullptr);
423         if (ret == -1) {
424             LogError("Unable to get list of current supplementary groups: " <<
425                 strerror(errno));
426             return SECURITY_MANAGER_ERROR_UNKNOWN;
427         }
428         oldGroupsCnt = ret;
429
430         //Allocate an array for both old and new groups gids
431         std::unique_ptr<gid_t[]> groups(new gid_t[oldGroupsCnt + newGroupsCnt]);
432         if (!groups.get()) {
433             LogError("Memory allocation failed.");
434             return SECURITY_MANAGER_ERROR_MEMORY;
435         }
436
437         //Get the old groups from process
438         ret = getgroups(oldGroupsCnt, groups.get());
439         if (ret == -1) {
440             LogError("Unable to get list of current supplementary groups: " <<
441                 strerror(errno));
442             return SECURITY_MANAGER_ERROR_UNKNOWN;
443         }
444
445         //Get the new groups from server response
446         for (int i = 0; i < newGroupsCnt; ++i) {
447             gid_t gid;
448             Deserialization::Deserialize(recv, gid);
449             groups.get()[oldGroupsCnt + i] = gid;
450             LogDebug("Adding process to group " << gid);
451         }
452
453         //Apply the modified groups list
454         ret = setgroups(oldGroupsCnt + newGroupsCnt, groups.get());
455         if (ret == -1) {
456             LogError("Unable to get list of current supplementary groups: " <<
457                 strerror(errno));
458             return SECURITY_MANAGER_ERROR_UNKNOWN;
459         }
460
461         return SECURITY_MANAGER_SUCCESS;
462     });
463 }
464
465 SECURITY_MANAGER_API
466 int security_manager_drop_process_privileges(void)
467 {
468     LogDebug("security_manager_drop_process_privileges() called");
469
470     int ret;
471     cap_t cap = cap_init();
472     if (!cap) {
473         LogError("Unable to allocate capability object");
474         return SECURITY_MANAGER_ERROR_MEMORY;
475     }
476
477     ret = cap_clear(cap);
478     if (ret) {
479         LogError("Unable to initialize capability object");
480         cap_free(cap);
481         return SECURITY_MANAGER_ERROR_UNKNOWN;
482     }
483
484     ret = cap_set_proc(cap);
485     if (ret) {
486         LogError("Unable to drop process capabilities");
487         cap_free(cap);
488         return SECURITY_MANAGER_ERROR_UNKNOWN;
489     }
490
491     cap_free(cap);
492     return SECURITY_MANAGER_SUCCESS;
493 }
494
495 SECURITY_MANAGER_API
496 int security_manager_prepare_app(const char *app_id)
497 {
498     LogDebug("security_manager_prepare_app() called");
499     int ret;
500
501     ret = security_manager_set_process_label_from_appid(app_id);
502     if (ret != SECURITY_MANAGER_SUCCESS)
503         return ret;
504
505     ret = security_manager_set_process_groups_from_appid(app_id);
506     if (ret != SECURITY_MANAGER_SUCCESS)
507         return ret;
508
509     ret = security_manager_drop_process_privileges();
510     return ret;
511 }
512
513 SECURITY_MANAGER_API
514 int security_manager_user_req_new(user_req **pp_req)
515 {
516     if (!pp_req)
517         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
518     try {
519         *pp_req = new user_req;
520     } catch (std::bad_alloc& ex) {
521         return SECURITY_MANAGER_ERROR_MEMORY;
522     }
523     return SECURITY_MANAGER_SUCCESS;
524 }
525
526 SECURITY_MANAGER_API
527 void security_manager_user_req_free(user_req *p_req)
528 {
529     delete p_req;
530 }
531
532 SECURITY_MANAGER_API
533 int security_manager_user_req_set_uid(user_req *p_req, uid_t uid)
534 {
535     if (!p_req)
536         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
537
538     p_req->uid = uid;
539
540     return SECURITY_MANAGER_SUCCESS;
541 }
542
543 SECURITY_MANAGER_API
544 int security_manager_user_req_set_user_type(user_req *p_req, security_manager_user_type utype)
545 {
546     if (!p_req)
547         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
548
549     p_req->utype = static_cast<int>(utype);
550
551     return SECURITY_MANAGER_SUCCESS;
552 }
553
554 SECURITY_MANAGER_API
555 int security_manager_user_add(const user_req *p_req)
556 {
557     using namespace SecurityManager;
558     MessageBuffer send, recv;
559     if (!p_req)
560         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
561     return try_catch([&] {
562
563         //put data into buffer
564         Serialization::Serialize(send, static_cast<int>(SecurityModuleCall::USER_ADD));
565
566         Serialization::Serialize(send, p_req->uid);
567         Serialization::Serialize(send, p_req->utype);
568
569         //send buffer to server
570         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
571         if (retval != SECURITY_MANAGER_API_SUCCESS) {
572             LogError("Error in sendToServer. Error code: " << retval);
573             return SECURITY_MANAGER_ERROR_UNKNOWN;
574         }
575
576         //receive response from server
577         Deserialization::Deserialize(recv, retval);
578         switch(retval) {
579         case SECURITY_MANAGER_API_SUCCESS:
580             return SECURITY_MANAGER_SUCCESS;
581         case SECURITY_MANAGER_API_ERROR_AUTHENTICATION_FAILED:
582             return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
583         default:
584             return SECURITY_MANAGER_ERROR_UNKNOWN;
585         }
586     });
587 }
588
589 SECURITY_MANAGER_API
590 int security_manager_user_delete(const user_req *p_req)
591 {
592     using namespace SecurityManager;
593     MessageBuffer send, recv;
594     if (!p_req)
595         return SECURITY_MANAGER_ERROR_INPUT_PARAM;
596     return try_catch([&] {
597
598         //put data into buffer
599         Serialization::Serialize(send, static_cast<int>(SecurityModuleCall::USER_DELETE));
600
601         Serialization::Serialize(send, p_req->uid);
602
603
604         //send buffer to server
605         int retval = sendToServer(SERVICE_SOCKET, send.Pop(), recv);
606         if (retval != SECURITY_MANAGER_API_SUCCESS) {
607             LogError("Error in sendToServer. Error code: " << retval);
608             return SECURITY_MANAGER_ERROR_UNKNOWN;
609         }
610
611         //receive response from server
612         Deserialization::Deserialize(recv, retval);
613         switch(retval) {
614         case SECURITY_MANAGER_API_SUCCESS:
615             return SECURITY_MANAGER_SUCCESS;
616         case SECURITY_MANAGER_API_ERROR_AUTHENTICATION_FAILED:
617             return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
618         default:
619             return SECURITY_MANAGER_ERROR_UNKNOWN;
620         }
621     });
622 }