Merge branch 'ckm' into tizen
[platform/core/test/security-tests.git] / src / common / pkg_privacy_privileges.h
1 /*
2  * Copyright (c) 2018 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 #pragma once
18
19 #include <string>
20 #include <sys/types.h>
21 #include <vector>
22
23 #include <app_def_privilege.h>
24 #include <app_install_helper.h>
25 #include <privilege_manager.h>
26 #include <memory.h>
27 #include <dpl/test/safe_cleanup.h>
28
29 class PkgPrivacyPrivileges {
30 public:
31     PkgPrivacyPrivileges(const AppInstallHelper &app)
32         : m_pkgId(app.getPkgId()),
33           m_uid(app.getUID()),
34           m_creatorPid(getpid()),
35           m_shouldUnsetPrivacy(false)
36     {
37         std::vector<std::string> privacyPrivileges;
38         for (const Privilege &privilege : app.getPrivileges())
39             if (privilege.isPrivacy())
40                 privacyPrivileges.push_back(privilege.getName());
41
42         if (!privacyPrivileges.empty()) {
43             PrivilegeManager::setPrivacyPrivileges(
44                 app.getUID(), app.getPkgId(), app.getVersion(), privacyPrivileges);
45             m_shouldUnsetPrivacy = true;
46         }
47     }
48
49     PkgPrivacyPrivileges(const PkgPrivacyPrivileges &) = delete;
50     PkgPrivacyPrivileges(PkgPrivacyPrivileges &&other)
51         : m_pkgId(std::move(other.m_pkgId)),
52           m_uid(other.m_uid),
53           m_shouldUnsetPrivacy(other.m_shouldUnsetPrivacy)
54     {
55         other.m_uid = 0;
56         other.m_shouldUnsetPrivacy = false;
57         other.m_creatorPid = -1;
58     }
59
60     PkgPrivacyPrivileges& operator=(const PkgPrivacyPrivileges &) = delete;
61
62     virtual ~PkgPrivacyPrivileges() {
63         if (m_creatorPid == getpid())
64         {
65             SafeCleanup::run([this]{ unsetPrivacy(); });
66         }
67     }
68
69     void unsetPrivacy() {
70         if (!m_shouldUnsetPrivacy)
71             return;
72         PrivilegeManager::unsetPrivacyPrivileges(m_uid, m_pkgId);
73         m_shouldUnsetPrivacy = false;
74     }
75
76 protected:
77     std::string m_pkgId;
78     uid_t m_uid;
79     pid_t m_creatorPid;
80     bool m_shouldUnsetPrivacy;
81 };