Split smack API wrapper and rules management 12/228212/12
authorZofia Grzelewska <z.abramowska@samsung.com>
Tue, 3 Mar 2020 15:10:19 +0000 (16:10 +0100)
committerZofia Abramowska <z.abramowska@samsung.com>
Fri, 17 Apr 2020 10:27:26 +0000 (12:27 +0200)
Split smack API wrapper (SmackAccesses) and rules generation and management
(SmackRules) into separate classes. Make SmackRules a class,
not a namespace, in a preparation for pre-loading of rules template files.

Change-Id: I695a7cbaef404462909b80271d0775a2c725d4f3

13 files changed:
src/common/CMakeLists.txt
src/common/include/service_impl.h
src/common/include/smack-accesses.h [new file with mode: 0644]
src/common/include/smack-common.h [new file with mode: 0644]
src/common/include/smack-labels.h
src/common/include/smack-rules.h
src/common/service_impl.cpp
src/common/smack-accesses.cpp [new file with mode: 0644]
src/common/smack-common.cpp [new file with mode: 0644]
src/common/smack-labels.cpp
src/common/smack-rules.cpp
test/CMakeLists.txt
test/test_smack-rules.cpp

index 8c2f9865a05f9249d907cd6b15ac3d9884f6352b..4c76ac91a56038695352ac4f4119920f12547c14 100644 (file)
@@ -61,6 +61,8 @@ SET(COMMON_SOURCES
     ${COMMON_PATH}/nsmount-logic.cpp
     ${COMMON_PATH}/privilege_db.cpp
     ${COMMON_PATH}/smack-labels.cpp
+    ${COMMON_PATH}/smack-accesses.cpp
+    ${COMMON_PATH}/smack-common.cpp
     ${COMMON_PATH}/smack-rules.cpp
     ${COMMON_PATH}/smack-check.cpp
     ${COMMON_PATH}/service_impl.cpp
index fd8e7a1da3d471d4349ebd96fda31c1066de136e..33a3d1d4b280ee9989643ee0ab4cc7b664217100 100644 (file)
@@ -33,6 +33,7 @@
 #include "cynara.h"
 #include "nsmount-logic.h"
 #include "security-manager.h"
+#include "smack-common.h"
 #include "smack-rules.h"
 #include "protocols.h"
 #include "privilege_db.h"
@@ -54,7 +55,7 @@ struct UninstallHelper {
     bool removePkg;
     bool removeAuthor;
     int authorId;
-    SmackRules::Labels pkgLabels;
+    Smack::Labels pkgLabels;
     std::vector<bool> removeApps;
     AppDefinedPrivilegesVector oldAppDefinedPrivileges;
 
@@ -183,7 +184,7 @@ public:
      *
      * @return API return code, as defined in protocols.h
      */
-    int getAppAllowedPrivileges(const std::string &appProcessLabel, uid_t uid,
+    int getAppAllowedPrivileges(const Smack::Label &appProcessLabel, uid_t uid,
                                 std::vector<std::string> &allowedPrivileges);
 
     /**
@@ -200,7 +201,7 @@ public:
     *
     * @return API return code, as defined in protocols.h
     */
-    int getForbiddenAndAllowedGroups(const std::string &appProcessLabel,
+    int getForbiddenAndAllowedGroups(const Smack::Label &appProcessLabel,
         const std::vector<std::string> &allowedPrivileges,
         std::vector<gid_t> &forbiddenGroups, std::vector<gid_t> &allowedGroups);
 
@@ -362,7 +363,7 @@ public:
      *
      * @return generated label
      */
-    std::string getProcessLabel(const std::string &appName);
+    Smack::Label getProcessLabel(const std::string &appName);
 
     /**
      * Get app info (process label, package name, shared_ro flag)
@@ -380,7 +381,7 @@ public:
      * @return API return code, as defined in protocols.h
      */
     int prepareApp(const Credentials &creds, const std::string &appName, const std::vector<std::string> &privPathsVector,
-            std::string &label, std::string &pkgName, bool &enabledSharedRO,
+            Smack::Label &label, std::string &pkgName, bool &enabledSharedRO,
             std::vector<gid_t> &forbiddenGroups, std::vector<gid_t> &allowedGroups, std::vector<bool> &privPathsStatusVector);
 
 private:
@@ -397,7 +398,7 @@ private:
 
     int appInstallSmackRules(app_inst_req &req, InstallHelper &ih);
 
-    int appSetupNamespace(const Credentials &creds, const std::string &appProcessLabel,
+    int appSetupNamespace(const Credentials &creds, const Smack::Label &appProcessLabel,
             const std::vector<std::string> &privPathsVector, std::vector<bool> &privPathsStatusVector);
 
     int appUninstallInitialChecks(const Credentials &creds,
@@ -426,7 +427,7 @@ private:
                    const uid_t &uid,
                    bool isSharedRO);
 
-    void getPkgLabels(const std::string &pkgName, SmackRules::Labels &pkgsLabels);
+    void getPkgLabels(const std::string &pkgName, Smack::Labels &pkgsLabels);
 
     int squashDropPrivateSharing(const std::string &ownerAppName,
                                  const std::string &targetAppName,
@@ -434,16 +435,16 @@ private:
 
     int dropOnePrivateSharing(const std::string &ownerAppName,
                               const std::string &ownerPkgName,
-                              const SmackRules::Labels &ownerPkgLabels,
+                              const Smack::Labels &ownerPkgLabels,
                               const std::string &targetAppName,
-                              const std::string &targetAppLabel,
+                              const Smack::Label &targetAppLabel,
                               const std::string &path);
 
     void updatePermissibleSet(uid_t uid, int type);
 
-    std::string getAppProcessLabel(const std::string &appName, const std::string &pkgName);
+    Smack::Label getAppProcessLabel(const std::string &appName, const std::string &pkgName);
 
-    std::string getAppProcessLabel(const std::string &appName);
+    Smack::Label getAppProcessLabel(const std::string &appName);
 
     bool sharingExists(const std::string &targetAppName, const std::string &path);
 
@@ -452,6 +453,7 @@ private:
     int getAppDefinedPrivilegeDescription(uid_t uid, const std::string &privilege, std::string &appName, std::string &pkgName, std::string &license);
 
     Cynara m_cynara;
+    SmackRules m_smackRules;
     PrivilegeDb m_privilegeDb;
     CynaraAdmin m_cynaraAdmin;
     PrivilegeGids m_privilegeGids;
diff --git a/src/common/include/smack-accesses.h b/src/common/include/smack-accesses.h
new file mode 100644 (file)
index 0000000..74ed2d7
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ *  Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ *  Contact: Rafal Krypa <r.krypa@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/**
+ * @file        smack-accesses.h
+ * @author      Jacek Bukarewicz <j.bukarewicz@samsung.com>
+ * @author      Zofia Abramowska <z.abramowska@samsung.com>
+ * @version     1.0
+ * @brief       Header file of a class managing smack rules
+ *
+ */
+#pragma once
+
+#include "smack-common.h"
+
+struct smack_accesses;
+
+namespace SecurityManager {
+
+class SmackAccesses
+{
+public:
+    SmackAccesses();
+    virtual ~SmackAccesses();
+
+    SmackAccesses(SmackAccesses &other) = delete;
+    SmackAccesses& operator=(const SmackAccesses &other) = delete;
+
+    void add(const Smack::Label &subject, const Smack::Label &object,
+             const Smack::Permission &permissions);
+    void add(const Smack::Rule &rule);
+    void addModify(const Smack::Label &subject, const Smack::Label &object,
+                   const Smack::Permission &allowPermissions, const Smack::Permission &denyPermissions);
+
+    void apply() const;
+    void clear() const;
+private:
+    smack_accesses *m_handle;
+};
+
+} // namespace SecurityManager
diff --git a/src/common/include/smack-common.h b/src/common/include/smack-common.h
new file mode 100644 (file)
index 0000000..254e863
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ *  Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ *  Contact: Rafal Krypa <r.krypa@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/**
+ * @file        smack-common.h
+ * @author      Zofia Abramowska <z.abramowska@samsung.com>
+ * @version     1.0
+ * @brief       Header file of a smack utility types and functions
+ *
+ */
+
+#pragma once
+
+#include <vector>
+#include <string>
+
+namespace SecurityManager {
+
+namespace Smack {
+typedef std::string Label;
+typedef std::string Permission;
+
+struct Rule {
+    Label subject;
+    Label object;
+    Permission permissions;
+};
+
+typedef std::vector<Rule> Rules;
+typedef std::vector<Rule> TemplateRules;
+typedef std::vector<Label> Labels;
+
+Rule fromRaw(const std::vector<std::string> &rawRule);
+Rules fromConfig(const std::string &path);
+
+} // namespace Smack
+
+} // namespace SecurityManager
index ac4a043944f50e4429bdfeb509b858444697b363..b18e5dd343bda620a5d064d43ac1024c2f0f0c65 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (c) 2014-2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *  Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved
  *
  *  Contact: Rafal Krypa <r.krypa@samsung.com>
  *
@@ -27,6 +27,7 @@
 
 #include <string>
 #include <utility>
+#include <smack-common.h>
 #include <smack-exceptions.h>
 #include <security-manager.h>
 
@@ -70,7 +71,7 @@ void setupSharedPrivatePath(const std::string &pkgName, const std::string &path)
  * @param[out] pkgName package identifier (cannot be empty)
  * @return application name on success, empty string on error.
 */
-void generateAppPkgNameFromLabel(const std::string &label, std::string &appName, std::string &pkgName);
+void generateAppPkgNameFromLabel(const Smack::Label &label, std::string &appName, std::string &pkgName);
 
 /**
  * Generates label for an application identifier
@@ -80,9 +81,9 @@ void generateAppPkgNameFromLabel(const std::string &label, std::string &appName,
  * @param[in] isHybrid package is hybrid flag
  * @return resulting Smack label
 */
-std::string generateProcessLabel(const std::string &appName,
-                                 const std::string &pkgName,
-                                 bool isHybrid);
+Smack::Label generateProcessLabel(const std::string &appName,
+                                  const std::string &pkgName,
+                                  bool isHybrid);
 
 /**
  * Generates label for an application, specific for folders that can be modified
@@ -90,7 +91,7 @@ std::string generateProcessLabel(const std::string &appName,
  *
  * @return resulting Smack label
 */
-std::string generatePathSharedROLabel();
+Smack::Label generatePathSharedROLabel();
 
 /**
  * Generates label for a package identifier
@@ -98,7 +99,7 @@ std::string generatePathSharedROLabel();
  * @param[in] pkgName package identifier
  * @return resulting Smack label
  */
-std::string generatePathRWLabel(const std::string &pkgName);
+Smack::Label generatePathRWLabel(const std::string &pkgName);
 
 /**
  * Generates label for private application RO files with package identifier @ref pkgName
@@ -106,7 +107,7 @@ std::string generatePathRWLabel(const std::string &pkgName);
  * @param[in] pkgName package identifier
  * @return resulting Smack label
  */
-std::string generatePathROLabel(const std::string &pkgName);
+Smack::Label generatePathROLabel(const std::string &pkgName);
 
 /**
  * Generates unique label per path for private path sharing.
@@ -115,7 +116,7 @@ std::string generatePathROLabel(const std::string &pkgName);
  * @param[in] path
  * @return resulting Smack label
  */
-std::string generateSharedPrivateLabel(const std::string &pkgName, const std::string &path);
+Smack::Label generateSharedPrivateLabel(const std::string &pkgName, const std::string &path);
 
 /*
  * Generates label for trusted paths. Trusted paths are paths where all application
@@ -124,7 +125,7 @@ std::string generateSharedPrivateLabel(const std::string &pkgName, const std::st
  * @param[in] authorId
  * @return resulting Smack label
  */
-std::string generatePathTrustedLabel(const int authorId);
+Smack::Label generatePathTrustedLabel(const int authorId);
 
 /**
  * Returns smack label for given socket
@@ -132,7 +133,7 @@ std::string generatePathTrustedLabel(const int authorId);
  * @param[in] socket descriptor
  * @return resulting Smack label
  */
-std::string getSmackLabelFromSocket(int socketFd);
+Smack::Label getSmackLabelFromSocket(int socketFd);
 
 /**
  * Returns smack label for given process
@@ -140,7 +141,7 @@ std::string getSmackLabelFromSocket(int socketFd);
  * @param[in] process identifier
  * @return resulting Smack label
  */
-std::string getSmackLabelFromPid(pid_t pid);
+Smack::Label getSmackLabelFromPid(pid_t pid);
 
 /**
  * Returns smack label for given path
@@ -148,7 +149,7 @@ std::string getSmackLabelFromPid(pid_t pid);
  * @param[in] process identifier
  * @return resulting Smack label
  */
-std::string getSmackLabelFromPath(const std::string &path);
+Smack::Label getSmackLabelFromPath(const std::string &path);
 
 /**
  * Returns smack label for given file descriptor
@@ -156,7 +157,7 @@ std::string getSmackLabelFromPath(const std::string &path);
  * @param[in] fd file descriptor
  * @return resulting Smack label
  */
-std::string getSmackLabelFromFd(int fd);
+Smack::Label getSmackLabelFromFd(int fd);
 
 /**
  * Returns smack label for current process
@@ -164,7 +165,7 @@ std::string getSmackLabelFromFd(int fd);
  * @param[in] sock socket file descriptor
  * @return resulting Smack label
  */
-std::string getSmackLabelFromSelf(void);
+Smack::Label getSmackLabelFromSelf(void);
 
 /**
  * Set up smack label for given file descriptor
@@ -172,7 +173,15 @@ std::string getSmackLabelFromSelf(void);
  * @param[in] fd file descriptor
  * @param[in] label new smack label for file
  */
-void setSmackLabelForFd(int fd, const std::string &label);
+void setSmackLabelForFd(int fd, const Smack::Label &label);
+
+
+/**
+ * Revoke rules for which given \ref label is a subject.
+ *
+ * @param[in] label process label
+ */
+void revokeSubject(const Smack::Label &label);
 
 } // namespace SmackLabels
 } // namespace SecurityManager
index b69c17067fd054ce0671eee1e135176d83690cd8..0019a3e61fcd7f54fdb8e1db570280576eddbf6d 100644 (file)
@@ -18,6 +18,7 @@
 /**
  * @file        smack-rules.h
  * @author      Jacek Bukarewicz <j.bukarewicz@samsung.com>
+ * @author      Zofia Abramowska <z.abramowska@samsung.com>
  * @version     1.0
  * @brief       Header file of a class managing smack rules
  *
 
 #include <vector>
 #include <string>
-#include <smack-exceptions.h>
+#include <utility>
 
-struct smack_accesses;
+#include <smack-accesses.h>
+#include <smack-common.h>
 
 namespace SecurityManager {
 
-class SmackRules
-{
+class SmackRules {
 public:
-    typedef std::vector<std::string> Rule;
-    typedef std::vector<Rule> RuleVector;
-    typedef std::vector<std::string> Pkgs;
-    typedef std::vector<std::string> Labels;
-    typedef std::vector<std::pair<std::string, std::vector<std::string>>> PkgsApps;
-
-    SmackRules();
-    virtual ~SmackRules();
-
-    void add(const std::string &subject, const std::string &object,
-            const std::string &permissions);
-    void addModify(const std::string &subject, const std::string &object,
-            const std::string &allowPermissions, const std::string &denyPermissions);
-
-    void addFromTemplate(
-            const RuleVector &templateRules,
-            const std::string &appProcessLabel,
-            const std::string &pkgName,
-            const int authorId);
-
-    void addFromTemplateFile(
-            const std::string &templatePath,
-            const std::string &appProcessLabel,
-            const std::string &pkgName,
-            const int authorId);
-
-    void addFromPrivTemplate(
-            const RuleVector &templateRules,
-            const std::string &appProcessLabel,
-            const std::string &privilegeLabel,
-            const std::string &pkgName,
-            int authorId);
-
-    void addFromPrivTemplateFile(
-            const std::string &templatePath,
-            const std::string &appProcessLabel,
-            const std::string &privilegeLabel,
-            const std::string &pkgName,
-            int authorId);
-
-    void apply() const;
-    void clear() const;
-
-    /**
-     * Create cross dependencies for all applications in a package
-     *
-     * This is needed for all applications within a package to have
-     * correct permissions to shared data.
-     *
-     * @param[in] pkgLabels - a list of process labels of all applications inside this package
-     */
-    void generatePackageCrossDeps(const Labels &pkgLabels);
-
     /**
      * Install package-specific smack rules plus add rules for specified external apps.
      *
@@ -99,11 +47,11 @@ public:
      * @param[in] authorId - author id of application
      * @param[in] pkgLabels - a list of process labels of all applications inside this package
      */
-    static void installApplicationRules(
-            const std::string &appProcessLabel,
-            const std::string &pkgName,
-            const int authorId,
-            const Labels &pkgLabels);
+    void installApplicationRules(
+        const std::string &appProcessLabel,
+        const std::string &pkgName,
+        const int authorId,
+        const Smack::Labels &pkgLabels);
 
     /**
      * Enable privilege-specific smack rules for given application
@@ -116,8 +64,8 @@ public:
      * @param[in] authorId - author id of given application (if not applicable, set to -1)
      * @param[in] privileges - a list of privileges allowed for given application
      */
-    static void enablePrivilegeRules(
-        const std::string &appProcessLabel,
+    void enablePrivilegeRules(
+        const Smack::Label &appProcessLabel,
         const std::string &pkgName,
         int authorId,
         const std::vector<std::string> &privileges);
@@ -130,7 +78,7 @@ public:
      * @param[in] pkgName - package identifier
      * @param[in] pkgLabels - a list of process labels of all applications inside this package
      */
-    static void uninstallPackageRules(const std::string &pkgName, const Labels &pkgLabels);
+    void uninstallPackageRules(const std::string &pkgName, const Smack::Labels &pkgLabels);
 
     /**
     * Uninstall application-specific smack rules.
@@ -141,7 +89,9 @@ public:
     * @param[in] pkgName - package identifier that the application is in
     * @param[in] authorId - identification (datbase key) of the author
     */
-    static void uninstallApplicationRules(const std::string &appProcessLabel, const std::string &pkgName, const int authorId);
+    void uninstallApplicationRules(const Smack::Label &appProcessLabel,
+        const std::string &pkgName,
+        const int authorId);
 
     /**
      * Update package specific rules
@@ -153,16 +103,16 @@ public:
      * @param[in] pkgName - package identifier that the application is in
      * @param[in] pkgContents - list of all applications in the package
      */
-    static void updatePackageRules(
-            const std::string &pkgName,
-            const std::vector<std::string> &pkgContents);
+    void updatePackageRules(
+        const std::string &pkgName,
+        const std::vector<std::string> &pkgContents);
 
     /**
      * Uninstall author-specific smack rules.
      *
      * param[in] authorId - identification (datbase key) of the author
      */
-    static void uninstallAuthorRules(const int authorId);
+    void uninstallAuthorRules(const int authorId);
 
     /**
      * Add rules related to private path sharing rules
@@ -180,12 +130,14 @@ public:
      * @param[in] isTargetSharingAlready - flag indicated, if target is already sharing anything
      *                                     with owner
      */
-    static void applyPrivateSharingRules(const std::string &ownerPkgName,
-                                         const SmackRules::Labels &ownerPkgLabels,
-                                         const std::string &targetAppLabel,
-                                         const std::string &pathLabel,
-                                         bool isPathSharedAlready,
-                                         bool isTargetSharingAlready);
+    void applyPrivateSharingRules(
+        const std::string &ownerPkgName,
+        const Smack::Labels &ownerPkgLabels,
+        const Smack::Label &targetAppLabel,
+        const Smack::Label &pathLabel,
+        bool isPathSharedAlready,
+        bool isTargetSharingAlready);
+
     /**
      * Remove rules related to private path sharing rules
      *
@@ -203,39 +155,61 @@ public:
      * @param[in] isTargetSharingNoMore - flag indicated, if target is not sharing anything
      *                                    with owner
      */
-    static void dropPrivateSharingRules(const std::string &ownerPkgName,
-                                        const Labels &ownerPkgLabels,
-                                        const std::string &targetAppLabel,
-                                        const std::string &pathLabel,
-                                        bool isPathSharedNoMore,
-                                        bool isTargetSharingNoMore);
+    void dropPrivateSharingRules(
+        const std::string &ownerPkgName,
+        const Smack::Labels &ownerPkgLabels,
+        const Smack::Label &targetAppLabel,
+        const Smack::Label &pathLabel,
+        bool isPathSharedNoMore,
+        bool isTargetSharingNoMore);
 
-    /**
-     * Revoke rules for which label of given \ref appName is a subject.
-     *
-     * @param[in] appProcessLabel = application process label
-     */
-    static void revokeAppSubject(const std::string &appProcessLabel);
+    void addFromTemplate(
+        SmackAccesses &rules,
+        const Smack::TemplateRules &templateRules,
+        const Smack::Label &appProcessLabel,
+        const std::string &pkgName,
+        const int authorId);
 
-private:
-    static void useTemplate(
-            const std::string &templatePath,
-            const std::string &appProcessLabel,
-            const std::string &pkgName,
-            const int authorId = -1);
+    void addFromTemplateFile(
+        SmackAccesses &rules,
+        const std::string &templatePath,
+        const Smack::Label &appProcessLabel,
+        const std::string &pkgName,
+        const int authorId);
+
+    void addFromPrivTemplate(
+        SmackAccesses &rules,
+        const Smack::TemplateRules &templateRules,
+        const Smack::Label &appProcessLabel,
+        const Smack::Label &privilegeLable,
+        const std::string &pkgName,
+        const int authorId);
+
+    void addFromPrivTemplateFile(
+        SmackAccesses &rules,
+        const std::string &templatePath,
+        const Smack::Label &appProcessLabel,
+        const Smack::Label &privilegeLabel,
+        const std::string &pkgName,
+        int AuthorId);
+
+    void useTemplate(
+        const std::string &templatePath,
+        const Smack::Label &appProcessLabel,
+        const std::string &pkgName,
+        const int authorId = -1);
 
+private:
     /**
-     * Helper method: replace all occurrences of \ref needle in \ref haystack
-     * with \ref replace.
+     * Create cross dependencies for all applications in a package
+     *
+     * This is needed for all applications within a package to have
+     * correct permissions to shared data.
      *
-     * @param[in,out] haystack string to modify
-     * @param needle string to find in \ref haystack
-     * @param replace string to replace \ref needle with
+     * @param[in] pkgLabels - a list of process labels of all applications inside this package
      */
-    static void strReplace(std::string &haystack, const std::string &needle,
-            const std::string &replace);
+    void generatePackageCrossDeps(SmackAccesses &rules, const Smack::Labels &pkgLabels);
 
-    smack_accesses *m_handle;
 };
 
 } // namespace SecurityManager
index 2dd7bf8f7200bd5bdd96010ae3b3ced153ab2a18..dad228729296c51568b30d343715e051ae628ff5 100644 (file)
@@ -258,13 +258,13 @@ int ServiceImpl::validatePolicy(const Credentials &creds, policy_entry &policyEn
     return SECURITY_MANAGER_SUCCESS;
 }
 
-std::string ServiceImpl::getAppProcessLabel(const std::string &appName, const std::string &pkgName)
+Smack::Label ServiceImpl::getAppProcessLabel(const std::string &appName, const std::string &pkgName)
 {
     bool isPkgHybrid = m_privilegeDb.IsPackageHybrid(pkgName);
     return SmackLabels::generateProcessLabel(appName, pkgName, isPkgHybrid);
 }
 
-std::string ServiceImpl::getAppProcessLabel(const std::string &appName)
+Smack::Label ServiceImpl::getAppProcessLabel(const std::string &appName)
 {
     std::string pkgName;
     m_privilegeDb.GetAppPkgName(appName, pkgName);
@@ -404,7 +404,7 @@ int ServiceImpl::labelPaths(const pkg_paths &paths,
     }
 }
 
-void ServiceImpl::getPkgLabels(const std::string &pkgName, SmackRules::Labels &pkgsLabels)
+void ServiceImpl::getPkgLabels(const std::string &pkgName, Smack::Labels &pkgsLabels)
 {
     bool isPkgHybrid = m_privilegeDb.IsPackageHybrid(pkgName);
     if (isPkgHybrid) {
@@ -424,9 +424,9 @@ void ServiceImpl::updatePermissibleSet(uid_t uid, int type)
 {
     std::vector<std::string> userPkgs;
     m_privilegeDb.GetUserPkgs(uid, userPkgs);
-    std::vector<std::string> labelsForUser;
+    Smack::Labels labelsForUser;
     for (const auto &pkg : userPkgs) {
-        std::vector<std::string> pkgLabels;
+        Smack::Labels pkgLabels;
         getPkgLabels(pkg, pkgLabels);
         labelsForUser.insert(labelsForUser.end(), pkgLabels.begin(), pkgLabels.end());
     }
@@ -477,8 +477,8 @@ void ServiceImpl::appInstallCynaraPolicies(app_inst_req::app& app, app_inst_req&
         InstallHelper &ih)
 {
     // Generate and verify Smack labels
-    std::string pkgLabel = SmackLabels::generatePathRWLabel(req.pkgName);
-    std::string appLabel = SmackLabels::generateProcessLabel(
+    Smack::Label pkgLabel = SmackLabels::generatePathRWLabel(req.pkgName);
+    Smack::Label appLabel = SmackLabels::generateProcessLabel(
         app.appName, req.pkgName, req.isHybrid);
     LogDebug("Generated install parameters: app label: " << appLabel <<
              ", pkg label: " << pkgLabel);
@@ -497,7 +497,7 @@ void ServiceImpl::appInstallCynaraPolicies(app_inst_req::app& app, app_inst_req&
     for (auto &priv : app.privileges)
         privileges.push_back(priv.first);
 
-    std::string oldAppLabel = SmackLabels::generateProcessLabel(
+    Smack::Label oldAppLabel = SmackLabels::generateProcessLabel(
             app.appName, req.pkgName, ih.isOldPkgHybrid);
 
     m_cynaraAdmin.updateAppPolicy(oldAppLabel, appLabel, global, req.uid, privileges);
@@ -508,7 +508,7 @@ void ServiceImpl::appInstallCynaraPolicies(app_inst_req::app& app, app_inst_req&
 int ServiceImpl::appInstallSmackRules(app_inst_req &req, InstallHelper &ih)
 {
     int authorId = -1;
-    SmackRules::Labels pkgLabels;
+    Smack::Labels pkgLabels;
 
     try {
         m_privilegeDb.GetPkgAuthorId(req.pkgName, authorId);
@@ -516,9 +516,9 @@ int ServiceImpl::appInstallSmackRules(app_inst_req &req, InstallHelper &ih)
         // Check if hybridity is changed if the package is installed
         if (ih.isUserPkgInstalled && ih.isOldPkgHybrid != req.isHybrid) {
             for (auto &app : req.apps) {
-                std::string oldAppLabel = SmackLabels::generateProcessLabel(
+                Smack::Label oldAppLabel = SmackLabels::generateProcessLabel(
                     app.appName, req.pkgName, ih.isOldPkgHybrid);
-                SmackRules::uninstallApplicationRules(oldAppLabel, req.pkgName, authorId);
+                m_smackRules.uninstallApplicationRules(oldAppLabel, req.pkgName, authorId);
                 if (req.isHybrid) // was not hybrid - all labels were the same
                     break;
             }
@@ -529,10 +529,10 @@ int ServiceImpl::appInstallSmackRules(app_inst_req &req, InstallHelper &ih)
         for (auto &app : req.apps) {
             LogDebug("Adding Smack rules for new appName: " << app.appName << " with pkgName: "
                     << req.pkgName << ".");
-            std::string appLabel = SmackLabels::generateProcessLabel(
+            Smack::Label appLabel = SmackLabels::generateProcessLabel(
                 app.appName, req.pkgName, req.isHybrid);
 
-            SmackRules::installApplicationRules(appLabel, req.pkgName, authorId, pkgLabels);
+            m_smackRules.installApplicationRules(appLabel, req.pkgName, authorId, pkgLabels);
             if (!req.isHybrid) // is not hybrid - all labels are the same
                 break;
         }
@@ -812,13 +812,13 @@ void ServiceImpl::appUninstallPrivileges(app_inst_req::app &app, app_inst_req &r
     std::map<std::string, std::vector<std::string>> asTargetSharing;
     m_privilegeDb.GetPrivateSharingForTarget(app.appName, asTargetSharing);
 
-    std::string processLabel = getAppProcessLabel(app.appName, req.pkgName);
+    Smack::Label processLabel = getAppProcessLabel(app.appName, req.pkgName);
     for (const auto &ownerPathsInfo : asTargetSharing) {
         const auto &ownerAppName = ownerPathsInfo.first;
         const auto &paths = ownerPathsInfo.second;
         // Squash sharing - change counter to 1, so dropPrivatePathSharing will completely clean it
         std::string ownerPkgName;
-        SmackRules::Labels ownerPkgLabels;
+        Smack::Labels ownerPkgLabels;
         m_privilegeDb.GetAppPkgName(ownerAppName, ownerPkgName);
         getPkgLabels(ownerPkgName, ownerPkgLabels);
         for (const auto &path : paths) {
@@ -862,19 +862,19 @@ int ServiceImpl::appUninstallSmackRules(app_inst_req &req, UninstallHelper &uh)
 {
     try {
         LogDebug("Removing Smack rules for pkgName " << req.pkgName);
-        SmackRules::uninstallPackageRules(req.pkgName, uh.pkgLabels);
+        m_smackRules.uninstallPackageRules(req.pkgName, uh.pkgLabels);
 
         for (unsigned appIdx = 0; appIdx < req.apps.size(); ++appIdx) {
             if (uh.removeApps[appIdx]) {
                 const std::string &appName = req.apps[appIdx].appName;
-                std::string processLabel = SmackLabels::generateProcessLabel(appName, req.pkgName, uh.isPkgHybrid);
+                Smack::Label processLabel = SmackLabels::generateProcessLabel(appName, req.pkgName, uh.isPkgHybrid);
                 LogDebug("Removing Smack rules for appName " << appName);
                 if (uh.removePkg || uh.isPkgHybrid || req.isHybrid) {
                     /*
                      * Nonhybrid apps have the same label, so revoking it is unnecessary
                      * unless whole package is being removed.
                      */
-                    SmackRules::uninstallApplicationRules(processLabel, req.pkgName, uh.authorId);
+                    m_smackRules.uninstallApplicationRules(processLabel, req.pkgName, uh.authorId);
                 }
                 if (!uh.removePkg) {
                     uh.pkgLabels.erase(std::remove(uh.pkgLabels.begin(), uh.pkgLabels.end(), processLabel),
@@ -885,12 +885,12 @@ int ServiceImpl::appUninstallSmackRules(app_inst_req &req, UninstallHelper &uh)
 
         if (!uh.removePkg) {
             LogDebug("Recreating Smack rules for pkgName " << req.pkgName);
-            SmackRules::updatePackageRules(req.pkgName, uh.pkgLabels);
+            m_smackRules.updatePackageRules(req.pkgName, uh.pkgLabels);
         }
 
         if (uh.authorId != -1 && uh.removeAuthor) {
             LogDebug("Removing Smack rules for authorId " << uh.authorId);
-            SmackRules::uninstallAuthorRules(uh.authorId);
+            m_smackRules.uninstallAuthorRules(uh.authorId);
         }
     } catch (const SmackException::Base &e) {
         LogError("Error while removing Smack rules for application: " << e.DumpToString());
@@ -1135,8 +1135,8 @@ int ServiceImpl::getConfiguredPolicy(const Credentials &creds, bool forAdmin,
         std::vector<CynaraAdminPolicy> listOfPolicies;
 
         //convert appName to smack label
-        std::string appProcessLabel = filter.appName.compare(SECURITY_MANAGER_ANY) ?
-                                getAppProcessLabel(filter.appName) : CYNARA_ADMIN_ANY;
+        Smack::Label appProcessLabel = filter.appName.compare(SECURITY_MANAGER_ANY) ?
+            getAppProcessLabel(filter.appName) : CYNARA_ADMIN_ANY;
         std::string user = filter.user.compare(SECURITY_MANAGER_ANY) ? filter.user : CYNARA_ADMIN_ANY;
         std::string privilege = filter.privilege.compare(SECURITY_MANAGER_ANY) ? filter.privilege : CYNARA_ADMIN_ANY;
 
@@ -1400,7 +1400,7 @@ int ServiceImpl::policyGetDesc(std::vector<std::string> &levels)
     return ret;
 }
 
-int ServiceImpl::getAppAllowedPrivileges(const std::string &appProcessLabel,
+int ServiceImpl::getAppAllowedPrivileges(const Smack::Label &appProcessLabel,
     uid_t uid, std::vector<std::string> &allowedPrivileges)
 {
     try {
@@ -1434,7 +1434,7 @@ int ServiceImpl::getAppAllowedPrivileges(const std::string &appProcessLabel,
 }
 
 int ServiceImpl::getForbiddenAndAllowedGroups(
-    const std::string &appProcessLabel, const std::vector<std::string> &allowedPrivileges,
+    const Smack::Label &appProcessLabel, const std::vector<std::string> &allowedPrivileges,
     std::vector<gid_t> &forbiddenGroups, std::vector<gid_t> &allowedGroups)
 {
 
@@ -1530,7 +1530,7 @@ int ServiceImpl::appHasPrivilege(
         bool &result)
 {
     try {
-        std::string appProcessLabel = getAppProcessLabel(appName);
+        Smack::Label appProcessLabel = getAppProcessLabel(appName);
         if ((appProcessLabel != creds.label || creds.uid != uid)
             && !authenticate(creds, PRIVILEGE_POLICY_USER)
             && !authenticate(creds, PRIVILEGE_PERMISSION_CHECK)) {
@@ -1559,9 +1559,9 @@ int ServiceImpl::appHasPrivilege(
 int ServiceImpl::dropOnePrivateSharing(
         const std::string &ownerAppName,
         const std::string &ownerPkgName,
-        const SmackRules::Labels &ownerPkgLabels,
+        const Smack::Labels &ownerPkgLabels,
         const std::string &targetAppName,
-        const std::string &targetAppLabel,
+        const Smack::Label &targetAppLabel,
         const std::string &path)
 {
     int errorRet;
@@ -1578,9 +1578,9 @@ int ServiceImpl::dropOnePrivateSharing(
         if (pathCount < 1 && FS::fileExists(path)) {
             SmackLabels::setupPath(ownerPkgName, path, SECURITY_MANAGER_PATH_RW);
         }
-        std::string pathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
-        SmackRules::dropPrivateSharingRules(ownerPkgName, ownerPkgLabels, targetAppLabel,
-                                            pathLabel, pathCount < 1, ownerTargetCount < 1);
+        Smack::Label pathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
+        m_smackRules.dropPrivateSharingRules(ownerPkgName, ownerPkgLabels, targetAppLabel,
+                                           pathLabel, pathCount < 1, ownerTargetCount < 1);
         return SECURITY_MANAGER_SUCCESS;
     } catch (const PrivilegeDb::Exception::Base &e) {
         LogError("Error while dropping private sharing in database: " << e.DumpToString());
@@ -1611,8 +1611,8 @@ int ServiceImpl::applyPrivatePathSharing(
     int sharingAdded = 0;
     std::string ownerPkgName;
     std::string targetPkgName;
-    std::string targetAppLabel;
-    SmackRules::Labels pkgsLabels;
+    Smack::Label targetAppLabel;
+    Smack::Labels pkgsLabels;
 
     try {
         if (!authenticate(creds, PRIVILEGE_APPSHARING_ADMIN)) {
@@ -1635,7 +1635,7 @@ int ServiceImpl::applyPrivatePathSharing(
         for (const auto &path : paths) {
             std::string pathLabel = SmackLabels::getSmackLabelFromPath(path);
             if (pathLabel != SmackLabels::generatePathRWLabel(ownerPkgName)) {
-                std::string generatedPathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
+                Smack::Label generatedPathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
                 if (generatedPathLabel != pathLabel) {
                     LogError("Path " << path << " has label " << pathLabel << " and dosen't belong"
                              " to application " << ownerAppName);
@@ -1661,7 +1661,7 @@ int ServiceImpl::applyPrivatePathSharing(
             m_privilegeDb.GetTargetPathSharingCount(targetAppName, path, targetPathCount);
             m_privilegeDb.GetPathSharingCount(path, pathCount);
             m_privilegeDb.GetOwnerTargetSharingCount(ownerAppName, targetAppName, ownerTargetCount);
-            std::string pathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
+            Smack::Label pathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
             m_privilegeDb.ApplyPrivateSharing(ownerAppName, targetAppName, path, pathLabel);
             sharingAdded++;
             if (targetPathCount > 0) {
@@ -1671,8 +1671,10 @@ int ServiceImpl::applyPrivatePathSharing(
             if (pathCount <= 0) {
                 SmackLabels::setupSharedPrivatePath(ownerPkgName, path);
             }
-            SmackRules::applyPrivateSharingRules(ownerPkgName, pkgsLabels,
-                    targetAppLabel, pathLabel, (pathCount > 0), (ownerTargetCount > 0));
+            m_smackRules.applyPrivateSharingRules(ownerPkgName, pkgsLabels,
+                                                targetAppLabel, pathLabel,
+                                                (pathCount > 0),
+                                                (ownerTargetCount > 0));
         }
         trans.commit();
         return SECURITY_MANAGER_SUCCESS;
@@ -1735,9 +1737,9 @@ int ServiceImpl::dropPrivatePathSharing(
                          << ", target=" << targetAppName << ", path=" << path);
                 return SECURITY_MANAGER_ERROR_INPUT_PARAM;
             }
-            std::string pathLabel = SmackLabels::getSmackLabelFromPath(path);
+            Smack::Label pathLabel = SmackLabels::getSmackLabelFromPath(path);
             if (pathLabel != SmackLabels::generatePathRWLabel(ownerPkgName)) {
-                std::string generatedPathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
+                Smack::Label generatedPathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
                 if (generatedPathLabel != pathLabel) {
                     LogError("Path " << path << " has label " << pathLabel << " and dosen't belong"
                              " to application " << ownerAppName);
@@ -1756,7 +1758,7 @@ int ServiceImpl::dropPrivatePathSharing(
             return SECURITY_MANAGER_SUCCESS;
         }
 
-        SmackRules::Labels pkgLabels;
+        Smack::Labels pkgLabels;
         getPkgLabels(ownerPkgName, pkgLabels);
         auto targetAppLabel = getAppProcessLabel(targetAppName, targetPkgName);
 
@@ -1857,7 +1859,7 @@ int ServiceImpl::shmAppName(const Credentials &creds, const std::string &shmName
             return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
         }
 
-        std::string label = getAppProcessLabel(appName);
+        Smack::Label label = getAppProcessLabel(appName);
 
         int fd = shm_open(shmName.c_str(), O_RDWR, 0);
         if (fd < 0) {
@@ -2135,14 +2137,14 @@ int ServiceImpl::appCleanNamespace(const Credentials &creds, const std::string &
     return ret;
 }
 
-std::string ServiceImpl::getProcessLabel(const std::string &appName)
+Smack::Label ServiceImpl::getProcessLabel(const std::string &appName)
 {
     LogDebug("Requested fetching label of process for application " << appName);
     return getAppProcessLabel(appName);
 }
 
 int ServiceImpl::prepareApp(const Credentials &creds, const std::string &appName, const std::vector<std::string> &privPathsVector,
-        std::string &label, std::string &pkgName, bool &enabledSharedRO,
+        Smack::Label &label, std::string &pkgName, bool &enabledSharedRO,
         std::vector<gid_t> &forbiddenGroups, std::vector<gid_t> &allowedGroups, std::vector<bool> &privPathsStatusVector)
 {
     LogDebug("Requested prepareApp for application " << appName);
@@ -2164,9 +2166,9 @@ int ServiceImpl::prepareApp(const Credentials &creds, const std::string &appName
     std::vector<std::string> pkgLabels;
     getPkgLabels(pkgName, pkgLabels);
 
-    SmackRules::revokeAppSubject(label);
-    SmackRules::installApplicationRules(label, pkgName, authorId, pkgLabels);
-    SmackRules::enablePrivilegeRules(label, pkgName, authorId, allowedPrivileges);
+    SmackLabels::revokeSubject(label);
+    m_smackRules.installApplicationRules(label, pkgName, authorId, pkgLabels);
+    m_smackRules.enablePrivilegeRules(label, pkgName, authorId, allowedPrivileges);
 
     ret = getForbiddenAndAllowedGroups(label, allowedPrivileges, forbiddenGroups,
                                        allowedGroups);
diff --git a/src/common/smack-accesses.cpp b/src/common/smack-accesses.cpp
new file mode 100644 (file)
index 0000000..d8ce186
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ *  Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ *  Contact: Rafal Krypa <r.krypa@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/**
+ * @file        smack-accesses.cpp
+ * @author      Jacek Bukarewicz <j.bukarewicz@samsung.com>
+ * @version     1.0
+ * @brief       Implementation of a class managing smack rules
+ *
+ */
+
+#include <sys/smack.h>
+
+#include <dpl/log/log.h>
+#include <smack-exceptions.h>
+
+#include "smack-accesses.h"
+
+namespace SecurityManager {
+
+SmackAccesses::SmackAccesses()
+{
+    if (smack_accesses_new(&m_handle) < 0) {
+        LogError("Failed to create smack_accesses handle");
+        throw std::bad_alloc();
+    }
+}
+
+SmackAccesses::~SmackAccesses() {
+    smack_accesses_free(m_handle);
+}
+
+void SmackAccesses::add(const Smack::Label &subject, const Smack::Label &object,
+        const Smack::Permission &permissions)
+{
+    if (smack_accesses_add(m_handle, subject.c_str(), object.c_str(), permissions.c_str()))
+        ThrowMsg(SmackException::LibsmackError, "smack_accesses_add");
+}
+
+void SmackAccesses::add(const Smack::Rule &rule)
+{
+    add(rule.subject, rule.object, rule.permissions);
+}
+
+void SmackAccesses::addModify(const Smack::Label &subject, const Smack::Label &object,
+        const Smack::Permission &allowPermissions, const Smack::Permission &denyPermissions)
+{
+    if (smack_accesses_add_modify(m_handle, subject.c_str(), object.c_str(), allowPermissions.c_str(), denyPermissions.c_str()))
+        ThrowMsg(SmackException::LibsmackError, "smack_accesses_add_modify");
+}
+
+void SmackAccesses::clear() const
+{
+    if (smack_accesses_clear(m_handle))
+        ThrowMsg(SmackException::LibsmackError, "smack_accesses_clear");
+}
+
+void SmackAccesses::apply() const
+{
+    if (smack_accesses_apply(m_handle))
+        ThrowMsg(SmackException::LibsmackError, "smack_accesses_apply");
+
+}
+
+} // namespace SecurityManager
diff --git a/src/common/smack-common.cpp b/src/common/smack-common.cpp
new file mode 100644 (file)
index 0000000..ebcf7c5
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ *  Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ *  Contact: Rafal Krypa <r.krypa@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+/**
+ * @file        smack-common.cpp
+ * @author      Zofia Abramowska <z.abramowska@samsung.com>
+ * @version     1.0
+ * @brief       Source file of a smack utility types and functions
+ *
+ */
+#include <cassert>
+#include <config-file.h>
+#include <smack-exceptions.h>
+#include <dpl/log/log.h>
+
+#include <sys/smack.h>
+
+#include "smack-common.h"
+
+namespace SecurityManager {
+
+namespace Smack {
+
+Rule fromRaw(const std::vector<std::string> &rawRule)
+{
+    assert(rawRule.size() == 3);
+    return {rawRule[0], rawRule[1], rawRule[2]};
+}
+
+Rules fromConfig(const std::string &path)
+{
+    ConfigFile file(path);
+    std::vector<std::vector<std::string>> rawRules = file.read();
+    Rules rules;
+
+    for (auto &rawRule : rawRules) {
+        if (rawRule.size() != 3) {
+            std::string errorMsg = "Invalid rule template: " + std::to_string(rawRule.size())
+                + " tokens in file " + path + ". Expected 3.";
+            LogError(errorMsg);
+            ThrowMsg(SmackException::FileError, errorMsg);
+        }
+        rules.push_back(fromRaw(rawRule));
+    }
+
+    return rules;
+}
+
+} // namespace Smack
+
+} // namespace SecurityManager
index a9a7a19fbfef476f741703ef9b361dd7c21552df..c8fd6a0f9f1ecfbf240c234dc7159e68acd7dd82 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (c) 2014-2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *  Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved
  *
  *  Contact: Rafal Krypa <r.krypa@samsung.com>
  *
@@ -73,7 +73,7 @@ static bool labelExecs(const FTSENT *ftsent)
     return (S_ISREG(ftsent->fts_statp->st_mode) && (ftsent->fts_statp->st_mode & S_IXUSR));
 }
 
-static inline void pathSetSmack(const char *path, const std::string &label,
+static inline void pathSetSmack(const char *path, const Smack::Label &label,
         const char *xattr_name)
 {
     if (smack_set_label_for_path(path, xattr_name, 0, label.c_str())) {
@@ -83,7 +83,7 @@ static inline void pathSetSmack(const char *path, const std::string &label,
     }
 }
 
-static void dirSetSmack(const std::string &path, const std::string &label,
+static void dirSetSmack(const std::string &path, const Smack::Label &label,
         const char *xattr_name, LabelDecisionFn fn)
 {
     char *const path_argv[] = {const_cast<char *>(path.c_str()), NULL};
@@ -117,7 +117,7 @@ static void dirSetSmack(const std::string &path, const std::string &label,
     }
 }
 
-static void labelDir(const std::string &path, const std::string &label,
+static void labelDir(const std::string &path, const Smack::Label &label,
         bool set_transmutable, bool set_executables)
 {
     // setting access label on everything in given directory and below
@@ -189,7 +189,7 @@ void setupSharedPrivatePath(const std::string &pkgName, const std::string &path)
     pathSetSmack(path.c_str(), generateSharedPrivateLabel(pkgName, path), XATTR_NAME_SMACK);
 }
 
-void generateAppPkgNameFromLabel(const std::string &label, std::string &appName, std::string &pkgName)
+void generateAppPkgNameFromLabel(const Smack::Label &label, std::string &appName, std::string &pkgName)
 {
     static const char pkgPrefix[] = "User::Pkg::";
     static const char appPrefix[] = "::App::";
@@ -213,10 +213,10 @@ void generateAppPkgNameFromLabel(const std::string &label, std::string &appName,
         ThrowMsg(SmackException::InvalidLabel, "No pkgName in Smack label " << label);
 }
 
-std::string generateProcessLabel(const std::string &appName, const std::string &pkgName,
+Smack::Label generateProcessLabel(const std::string &appName, const std::string &pkgName,
                                  bool isHybrid)
 {
-    std::string label = "User::Pkg::" + pkgName;
+    Smack::Label label = "User::Pkg::" + pkgName;
     if (isHybrid)
         label += "::App::" + appName;
 
@@ -226,14 +226,14 @@ std::string generateProcessLabel(const std::string &appName, const std::string &
     return label;
 }
 
-std::string generatePathSharedROLabel()
+Smack::Label generatePathSharedROLabel()
 {
     return "User::App::Shared";
 }
 
-std::string generatePathRWLabel(const std::string &pkgName)
+Smack::Label generatePathRWLabel(const std::string &pkgName)
 {
-    std::string label = "User::Pkg::" + pkgName;
+    Smack::Label label = "User::Pkg::" + pkgName;
 
     if (smack_label_length(label.c_str()) <= 0)
         ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName);
@@ -241,9 +241,9 @@ std::string generatePathRWLabel(const std::string &pkgName)
     return label;
 }
 
-std::string generatePathROLabel(const std::string &pkgName)
+Smack::Label generatePathROLabel(const std::string &pkgName)
 {
-    std::string label = "User::Pkg::" + pkgName + "::RO";
+    Smack::Label label = "User::Pkg::" + pkgName + "::RO";
 
     if (smack_label_length(label.c_str()) <= 0)
         ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName);
@@ -251,10 +251,10 @@ std::string generatePathROLabel(const std::string &pkgName)
     return label;
 }
 
-std::string generateSharedPrivateLabel(const std::string &pkgName, const std::string &path)
+Smack::Label generateSharedPrivateLabel(const std::string &pkgName, const std::string &path)
 {
     // Prefix $1$ causes crypt() to use MD5 function
-    std::string label = "User::Pkg::";
+    Smack::Label label = "User::Pkg::";
     std::string salt = "$1$" + pkgName;
 
     const char * cryptLabel = crypt(path.c_str(), salt.c_str());
@@ -269,42 +269,42 @@ std::string generateSharedPrivateLabel(const std::string &pkgName, const std::st
 }
 
 template<typename FuncType, typename... ArgsType>
-static std::string getSmackLabel(FuncType func, ArgsType... args)
+static Smack::Label getSmackLabel(FuncType func, ArgsType... args)
 {
     char *label;
     ssize_t labelLen = func(args..., &label);
     if (labelLen <= 0)
         ThrowMsg(SmackException::Base, "Error while getting Smack label");
     auto labelPtr = makeUnique(label, free);
-    return std::string(labelPtr.get(), labelLen);
+    return Smack::Label(labelPtr.get(), labelLen);
 }
 
-std::string getSmackLabelFromSocket(int socketFd)
+Smack::Label getSmackLabelFromSocket(int socketFd)
 {
     return getSmackLabel(&smack_new_label_from_socket, socketFd);
 }
 
-std::string getSmackLabelFromPath(const std::string &path)
+Smack::Label getSmackLabelFromPath(const std::string &path)
 {
     return getSmackLabel(&smack_new_label_from_path, path.c_str(), XATTR_NAME_SMACK, true);
 }
 
-std::string getSmackLabelFromFd(int fd)
+Smack::Label getSmackLabelFromFd(int fd)
 {
     return getSmackLabel(&smack_new_label_from_file, fd, XATTR_NAME_SMACK);
 }
 
-std::string getSmackLabelFromSelf(void)
+Smack::Label getSmackLabelFromSelf(void)
 {
     return getSmackLabel(&smack_new_label_from_self);
 }
 
-std::string getSmackLabelFromPid(pid_t pid)
+Smack::Label getSmackLabelFromPid(pid_t pid)
 {
     return getSmackLabel(&smack_new_label_from_process, pid);
 }
 
-std::string generatePathTrustedLabel(const int authorId)
+Smack::Label generatePathTrustedLabel(const int authorId)
 {
     if (authorId < 0) {
         LogError("Author was not set. It's not possible to generate label for unknown author.");
@@ -314,7 +314,7 @@ std::string generatePathTrustedLabel(const int authorId)
     return "User::Author::" + std::to_string(authorId);
 }
 
-void setSmackLabelForFd(int fd, const std::string &label)
+void setSmackLabelForFd(int fd, const Smack::Label &label)
 {
     if (smack_set_label_for_file(fd, XATTR_NAME_SMACK, label.c_str())) {
         LogError("smack_set_label_for_file failed.");
@@ -322,5 +322,11 @@ void setSmackLabelForFd(int fd, const std::string &label)
     }
 }
 
+void revokeSubject(const Smack::Label &label)
+{
+    if (smack_revoke_subject(label.c_str()))
+        ThrowMsg(SmackException::LibsmackError, "smack_revoke_subject failed for " + label);
+}
+
 } // namespace SmackLabels
 } // namespace SecurityManager
index 469f69e341e5598804e9e68990f0c26c13250938..e8781a0b84850fa567274e92048db2440e0b65e6 100644 (file)
  *
  */
 
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/smack.h>
-#include <cstring>
 #include <string>
 #include <map>
-#include <memory>
-#include <algorithm>
-
-#include "config.h"
-#include "config-file.h"
-#include "dpl/log/log.h"
-#include "dpl/errno_string.h"
-#include "filesystem.h"
-#include "smack-labels.h"
-#include "tzplatform-config.h"
-
-#include "smack-check.h"
+
+#include <config.h>
+#include <config-file.h>
+#include <dpl/log/log.h>
+#include <dpl/errno_string.h>
+#include <filesystem.h>
+#include <smack-check.h>
+#include <smack-exceptions.h>
+#include <smack-labels.h>
+#include <tzplatform-config.h>
+
 #include "smack-rules.h"
 
 namespace SecurityManager {
 
+namespace {
+/**
+ * Helper method: replace all occurrences of \ref needle in \ref haystack
+ * with \ref replace.
+ *
+ * @param[in,out] haystack string to modify
+ * @param needle string to find in \ref haystack
+ * @param replace string to replace \ref needle with
+ */
+void strReplace(std::string &haystack, const std::string &needle,
+                const std::string &replace)
+{
+    size_t pos;
+    while ((pos = haystack.find(needle)) != std::string::npos)
+        haystack.replace(pos, needle.size(), replace);
+}
+
 const std::string SMACK_PROCESS_LABEL_TEMPLATE     = "~PROCESS~";
 const std::string SMACK_PATH_RW_LABEL_TEMPLATE     = "~PATH_RW~";
 const std::string SMACK_PATH_RO_LABEL_TEMPLATE     = "~PATH_RO~";
@@ -89,53 +101,17 @@ const std::string SMACK_APP_PATH_USER_PERMS = "rwxat";
 
 const std::string PRIV_TEMPLATE_DEFAULT = "default";
 
-SmackRules::SmackRules()
-{
-    if (smack_accesses_new(&m_handle) < 0) {
-        LogError("Failed to create smack_accesses handle");
-        throw std::bad_alloc();
-    }
-}
-
-SmackRules::~SmackRules() {
-    smack_accesses_free(m_handle);
-}
-
-void SmackRules::add(const std::string &subject, const std::string &object,
-        const std::string &permissions)
-{
-    if (smack_accesses_add(m_handle, subject.c_str(), object.c_str(), permissions.c_str()))
-        ThrowMsg(SmackException::LibsmackError, "smack_accesses_add");
-}
-
-void SmackRules::addModify(const std::string &subject, const std::string &object,
-        const std::string &allowPermissions, const std::string &denyPermissions)
-{
-    if (smack_accesses_add_modify(m_handle, subject.c_str(), object.c_str(), allowPermissions.c_str(), denyPermissions.c_str()))
-        ThrowMsg(SmackException::LibsmackError, "smack_accesses_add_modify");
-}
-
-void SmackRules::clear() const
-{
-    if (smack_accesses_clear(m_handle))
-        ThrowMsg(SmackException::LibsmackError, "smack_accesses_clear");
-}
-
-void SmackRules::apply() const
-{
-    if (smack_accesses_apply(m_handle))
-        ThrowMsg(SmackException::LibsmackError, "smack_accesses_apply");
-
-}
+} // namespace anonymous
 
 void SmackRules::addFromTemplateFile(
-        const std::string &templatePath,
-        const std::string &appProcessLabel,
-        const std::string &pkgName,
-        const int authorId)
+    SmackAccesses &rules,
+    const std::string &templatePath,
+    const Smack::Label &appProcessLabel,
+    const std::string &pkgName,
+    const int authorId)
 {
     try {
-        addFromTemplate(ConfigFile(templatePath).read(), appProcessLabel, pkgName, authorId);
+        addFromTemplate(rules, Smack::fromConfig(templatePath), appProcessLabel, pkgName, authorId);
     } catch (FS::Exception::Base &) {
         LogError("Error reading template file: " << templatePath);
         ThrowMsg(SmackException::FileError, "Error reading template file: " << templatePath);
@@ -143,13 +119,14 @@ void SmackRules::addFromTemplateFile(
 }
 
 void SmackRules::addFromTemplate(
-        const RuleVector &templateRules,
-        const std::string &appProcessLabel,
-        const std::string &pkgName,
-        const int authorId)
+    SmackAccesses &rules,
+    const Smack::Rules &templateRules,
+    const Smack::Label &appProcessLabel,
+    const std::string &pkgName,
+    const int authorId)
 {
-    std::string pathRWLabel, pathROLabel;
-    std::string pathTrustedLabel;
+    Smack::Label pathRWLabel, pathROLabel;
+    Smack::Label pathTrustedLabel;
 
     if (!pkgName.empty()) {
         pathRWLabel = SmackLabels::generatePathRWLabel(pkgName);
@@ -159,34 +136,26 @@ void SmackRules::addFromTemplate(
     if (authorId >= 0)
         pathTrustedLabel = SmackLabels::generatePathTrustedLabel(authorId);
 
-    for (auto &rule : templateRules) {
-        if (rule.size() != 3) {
-            LogError("Invalid rule template: " << rule.size() << " tokens");
-            ThrowMsg(SmackException::FileError, "Invalid rule template: " << rule.size() << " tokens");
-        }
-
-        std::string subject = rule[0];
-        std::string object = rule[1];
-        std::string permissions = rule[2];
+    for (auto rule : templateRules) {
+        strReplace(rule.subject, SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
+        strReplace(rule.object,  SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
+        strReplace(rule.object,  SMACK_PATH_RW_LABEL_TEMPLATE, pathRWLabel);
+        strReplace(rule.object,  SMACK_PATH_RO_LABEL_TEMPLATE, pathROLabel);
+        strReplace(rule.object,  SMACK_PATH_TRUSTED_LABEL_TEMPLATE, pathTrustedLabel);
 
-        strReplace(subject, SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
-        strReplace(object,  SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
-        strReplace(object,  SMACK_PATH_RW_LABEL_TEMPLATE, pathRWLabel);
-        strReplace(object,  SMACK_PATH_RO_LABEL_TEMPLATE, pathROLabel);
-        strReplace(object,  SMACK_PATH_TRUSTED_LABEL_TEMPLATE, pathTrustedLabel);
-
-        if (subject.empty() || object.empty())
+        if (rule.subject.empty() || rule.object.empty())
             continue;
-        add(subject, object, permissions);
+        rules.add(rule);
     }
 }
 
 void SmackRules::addFromPrivTemplate(
-        const RuleVector &templateRules,
-        const std::string &appProcessLabel,
-        const std::string &privilegeLabel,
-        const std::string &pkgName,
-        int authorId)
+    SmackAccesses &rules,
+    const Smack::TemplateRules &templateRules,
+    const Smack::Label &appProcessLabel,
+    const Smack::Label &privilegeLabel,
+    const std::string &pkgName,
+    int authorId)
 {
     std::string pathRWLabel, pathROLabel;
     std::string pathTrustedLabel;
@@ -199,45 +168,37 @@ void SmackRules::addFromPrivTemplate(
     if (authorId >= 0)
         pathTrustedLabel = SmackLabels::generatePathTrustedLabel(authorId);
 
-    for (auto &rule : templateRules) {
-        if (rule.size() != 3) {
-            LogError("Invalid rule template: " << rule.size() << " tokens");
-            ThrowMsg(SmackException::FileError, "Invalid rule template: " << rule.size() << " tokens");
-        }
-
-        std::string subject = rule[0];
-        std::string object = rule[1];
-        std::string permissions = rule[2];
-
-        if (subject[0] != '~' || object[0] != '~') {
+    for (auto rule : templateRules) {
+        if (rule.subject[0] != '~' || rule.object[0] != '~') {
             LogWarning("Unsupported rule <"
-                     << subject << " " << object << " " << permissions
-                     << "> detected. Ignoring");
+                       << rule.subject << " " << rule.object << " " << rule.permissions
+                       << "> detected. Ignoring");
         }
 
-        strReplace(subject, SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
-        strReplace(subject, SMACK_PRIVILEGE_LABEL_TEMPLATE, privilegeLabel);
-        strReplace(object,  SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
-        strReplace(object,  SMACK_PRIVILEGE_LABEL_TEMPLATE, privilegeLabel);
-        strReplace(object,  SMACK_PATH_RW_LABEL_TEMPLATE, pathRWLabel);
-        strReplace(object,  SMACK_PATH_RO_LABEL_TEMPLATE, pathROLabel);
-        strReplace(object,  SMACK_PATH_TRUSTED_LABEL_TEMPLATE, pathTrustedLabel);
+        strReplace(rule.subject, SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
+        strReplace(rule.subject, SMACK_PRIVILEGE_LABEL_TEMPLATE, privilegeLabel);
+        strReplace(rule.object,  SMACK_PROCESS_LABEL_TEMPLATE, appProcessLabel);
+        strReplace(rule.object,  SMACK_PRIVILEGE_LABEL_TEMPLATE, privilegeLabel);
+        strReplace(rule.object,  SMACK_PATH_RW_LABEL_TEMPLATE, pathRWLabel);
+        strReplace(rule.object,  SMACK_PATH_RO_LABEL_TEMPLATE, pathROLabel);
+        strReplace(rule.object,  SMACK_PATH_TRUSTED_LABEL_TEMPLATE, pathTrustedLabel);
 
-        if (subject.empty() || object.empty())
+        if (rule.subject.empty() || rule.object.empty())
             continue;
-        add(subject, object, permissions);
+        rules.add(rule);
     }
 }
 
 void SmackRules::addFromPrivTemplateFile(
-        const std::string &templatePath,
-        const std::string &appProcessLabel,
-        const std::string &privilegeLabel,
-        const std::string &pkgName,
-        int authorId)
+    SmackAccesses &rules,
+    const std::string &templatePath,
+    const Smack::Label &appProcessLabel,
+    const Smack::Label &privilegeLabel,
+    const std::string &pkgName,
+    int authorId)
 {
     try {
-        addFromPrivTemplate(ConfigFile(templatePath).read(), appProcessLabel, privilegeLabel,
+        addFromPrivTemplate(rules, Smack::fromConfig(templatePath), appProcessLabel, privilegeLabel,
                             pkgName, authorId);
     } catch (FS::Exception::Base &) {
         LogError("Error reading template file: " << templatePath);
@@ -245,7 +206,7 @@ void SmackRules::addFromPrivTemplateFile(
     }
 }
 
-void SmackRules::generatePackageCrossDeps(const Labels &pkgLabels)
+void SmackRules::generatePackageCrossDeps(SmackAccesses &rules, const Smack::Labels &pkgLabels)
 {
     LogDebug("Generating cross-package rules");
 
@@ -258,41 +219,40 @@ void SmackRules::generatePackageCrossDeps(const Labels &pkgLabels)
 
             LogDebug("Trying to add rule subject: " << subject
                       << " object: " << object << " perms: " << appsInPackagePerms);
-            add(subject, object, appsInPackagePerms);
+            rules.add(subject, object, appsInPackagePerms);
         }
     }
 }
 
 void SmackRules::useTemplate(
         const std::string &templatePath,
-        const std::string &appProcessLabel,
+        const Smack::Label &appProcessLabel,
         const std::string &pkgName,
         const int authorId)
 {
-    SmackRules smackRules;
-    smackRules.addFromTemplateFile(templatePath, appProcessLabel, pkgName, authorId);
+    SmackAccesses smackRules;
+    addFromTemplateFile(smackRules, templatePath, appProcessLabel, pkgName, authorId);
 
     if (smack_check())
         smackRules.apply();
 }
 
 void SmackRules::installApplicationRules(
-        const std::string &appProcessLabel,
+        const Smack::Label &appProcessLabel,
         const std::string &pkgName,
         const int authorId,
-        const Labels &pkgLabels)
+        const Smack::Labels &pkgLabels)
 {
     useTemplate(getPolicyFile(POLICY_FILE::APP_RULES_TEMPLATE), appProcessLabel, pkgName, authorId);
 
     if (authorId >= 0)
-        useTemplate(getPolicyFile(POLICY_FILE::AUTHOR_RULES_TEMPLATE),
-                    appProcessLabel, pkgName, authorId);
+        useTemplate(getPolicyFile(POLICY_FILE::AUTHOR_RULES_TEMPLATE), appProcessLabel, pkgName, authorId);
 
     updatePackageRules(pkgName, pkgLabels);
 }
 
 void SmackRules::enablePrivilegeRules(
-        const std::string &appProcessLabel,
+        const Smack::Label &appProcessLabel,
         const std::string &pkgName,
         int authorId,
         const std::vector<std::string> &privileges)
@@ -302,7 +262,7 @@ void SmackRules::enablePrivilegeRules(
         return;
     }
 
-    SmackRules smackRules;
+    SmackAccesses smackRules;
 
     auto privMapping = ConfigFile(PRIVILEGE_SMACK_LIST_FILE).read();
 
@@ -322,8 +282,8 @@ void SmackRules::enablePrivilegeRules(
 
         for (auto &privilege : privileges) {
             if (privilege == privName) {
-                smackRules.addFromPrivTemplateFile(privTemplate, appProcessLabel, privLabel,
-                                                   pkgName, authorId);
+                addFromPrivTemplateFile(smackRules, privTemplate, appProcessLabel, privLabel,
+                                        pkgName, authorId);
                 break;
             }
         }
@@ -335,69 +295,57 @@ void SmackRules::enablePrivilegeRules(
 
 void SmackRules::updatePackageRules(
         const std::string &pkgName,
-        const Labels &pkgLabels)
+        const Smack::Labels &pkgLabels)
 {
-    SmackRules smackRules;
-    smackRules.addFromTemplateFile(
-        getPolicyFile(POLICY_FILE::PKG_RULES_TEMPLATE),
+    SmackAccesses smackRules;
+    addFromTemplateFile(smackRules,
+            getPolicyFile(POLICY_FILE::PKG_RULES_TEMPLATE),
             std::string(),
             pkgName,
             -1);
 
-    smackRules.generatePackageCrossDeps(pkgLabels);
+    generatePackageCrossDeps(smackRules, pkgLabels);
 
     if (smack_check())
         smackRules.apply();
 }
 
-
-void SmackRules::revokeAppSubject(const std::string &appLabel)
+void SmackRules::uninstallPackageRules(const std::string &pkgName,
+                                       const Smack::Labels &pkgLabels)
 {
-    if (smack_revoke_subject(appLabel.c_str()))
-        ThrowMsg(SmackException::LibsmackError, "smack_revoke_subject");
-}
-
-void SmackRules::uninstallPackageRules(const std::string &pkgName, const Labels &pkgLabels)
-{
-    SmackRules smackRules;
-    smackRules.addFromTemplateFile(getPolicyFile(POLICY_FILE::PKG_RULES_TEMPLATE), {}, pkgName, -1);
-    smackRules.generatePackageCrossDeps(pkgLabels);
+    SmackAccesses smackRules;
+    addFromTemplateFile(smackRules, getPolicyFile(POLICY_FILE::PKG_RULES_TEMPLATE), {}, pkgName, -1);
+    generatePackageCrossDeps(smackRules, pkgLabels);
     smackRules.clear();
 }
 
-void SmackRules::uninstallApplicationRules(const std::string &appLabel, const std::string &pkgName, const int authorId)
+void SmackRules::uninstallApplicationRules(
+        const Smack::Label &appLabel,
+        const std::string &pkgName,
+        const int authorId)
 {
-    SmackRules smackRules;
-    smackRules.addFromTemplateFile(getPolicyFile(POLICY_FILE::APP_RULES_TEMPLATE),
-                                   appLabel, pkgName, authorId);
+    SmackAccesses smackRules;
+    addFromTemplateFile(smackRules, getPolicyFile(POLICY_FILE::APP_RULES_TEMPLATE), appLabel, pkgName, authorId);
     smackRules.clear();
-    revokeAppSubject(appLabel);
-}
-
-void SmackRules::strReplace(std::string &haystack, const std::string &needle,
-            const std::string &replace)
-{
-    size_t pos;
-    while ((pos = haystack.find(needle)) != std::string::npos)
-        haystack.replace(pos, needle.size(), replace);
+    SmackLabels::revokeSubject(appLabel);
 }
 
 void SmackRules::uninstallAuthorRules(const int authorId)
 {
-    SmackRules smackRules;
-    smackRules.addFromTemplateFile(getPolicyFile(POLICY_FILE::AUTHOR_RULES_TEMPLATE), {}, {}, authorId);
+    SmackAccesses smackRules;
+    addFromTemplateFile(smackRules, getPolicyFile(POLICY_FILE::AUTHOR_RULES_TEMPLATE), {}, {}, authorId);
     smackRules.clear();
 }
 
 void SmackRules::applyPrivateSharingRules(
         const std::string &ownerPkgName,
-        const SmackRules::Labels &ownerPkgLabels,
-        const std::string &targetLabel,
-        const std::string &pathLabel,
+        const Smack::Labels &ownerPkgLabels,
+        const Smack::Label &targetLabel,
+        const Smack::Label &pathLabel,
         bool isPathSharedAlready,
         bool isTargetSharingAlready)
 {
-    SmackRules rules;
+    SmackAccesses rules;
     if (!isTargetSharingAlready) {
 
         rules.add(targetLabel,
@@ -418,13 +366,13 @@ void SmackRules::applyPrivateSharingRules(
 
 void SmackRules::dropPrivateSharingRules(
         const std::string &ownerPkgName,
-        const Labels &ownerPkgLabels,
-        const std::string &targetLabel,
-        const std::string &pathLabel,
+        const Smack::Labels &ownerPkgLabels,
+        const Smack::Label &targetLabel,
+        const Smack::Label &pathLabel,
         bool isPathSharedNoMore,
         bool isTargetSharingNoMore)
 {
-    SmackRules rules;
+    SmackAccesses rules;
     if (isTargetSharingNoMore) {
         rules.addModify(targetLabel,
                   SmackLabels::generatePathRWLabel(ownerPkgName),
index 7fc1cf334964b11e9755f5e38bf308ea4b585141..84e4417b1867b6a2cd8236febf78dc0292b355f7 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2016 - 2018 Samsung Electronics Co., Ltd All Rights Reserved
+# Copyright (c) 2016-2020 Samsung Electronics Co., Ltd. All rights reserved
 #
 #    Licensed under the Apache License, Version 2.0 (the "License");
 #    you may not use this file except in compliance with the License.
@@ -79,6 +79,8 @@ SET(SM_TESTS_SOURCES
     ${PROJECT_SOURCE_DIR}/src/common/file-lock.cpp
     ${PROJECT_SOURCE_DIR}/src/common/privilege_db.cpp
     ${PROJECT_SOURCE_DIR}/src/common/service_impl_utils.cpp
+    ${PROJECT_SOURCE_DIR}/src/common/smack-accesses.cpp
+    ${PROJECT_SOURCE_DIR}/src/common/smack-common.cpp
     ${PROJECT_SOURCE_DIR}/src/common/smack-check.cpp
     ${PROJECT_SOURCE_DIR}/src/common/smack-labels.cpp
     ${PROJECT_SOURCE_DIR}/src/common/smack-rules.cpp
index 06b23f25e86b8d07157e5a294f441848b9de4411..a54433dc7bfa8106d3fccddb043d43ea6bb290ae 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (c) 2016 - 2017 Samsung Electronics Co., Ltd All Rights Reserved
+ *  Copyright (c) 2016-2020 Samsung Electronics Co., Ltd. All rights reserved
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@
 #include <boost/test/unit_test.hpp>
 #include <fstream>
 
+#include <smack-accesses.h>
 #include <smack-rules.h>
 #include <smack-labels.h>
 
@@ -54,7 +55,7 @@ BOOST_AUTO_TEST_SUITE(SMACK_RULES_TEST)
 
 BOOST_AUTO_TEST_CASE(T1120_smack_rules_exception)
 {
-    SmackRules smackRules;
+    SmackAccesses smackRules;
 
     BOOST_REQUIRE_THROW(smackRules.add("subject", "object", "invalidPermission"),
                         SmackException::LibsmackError);
@@ -75,18 +76,17 @@ BOOST_AUTO_TEST_CASE(T1120_smack_rules_exception)
 
 BOOST_FIXTURE_TEST_CASE(T1130_smack_rules_templates, RulesFixture)
 {
-    SmackRules::RuleVector templateRules = {{"System", "~PROCESS~", "rwxat"},
-                                            {"~PROCESS~", "System", "wx"},
-                                            {"~PROCESS~", "~PATH_RW~", "rwxat"},
-                                            {"~PROCESS~", "~PATH_RO~", "rxl"},
-                                            {"~PROCESS~", "~PATH_TRUSTED~", "rwxat"}};
+    Smack::TemplateRules templateRules = {{"System", "~PROCESS~", "rwxat"},
+                                          {"~PROCESS~", "System", "wx"},
+                                          {"~PROCESS~", "~PATH_RW~", "rwxat"},
+                                          {"~PROCESS~", "~PATH_RO~", "rxl"},
+                                          {"~PROCESS~", "~PATH_TRUSTED~", "rwxat"}};
 
     std::ofstream templateRulesFile;
     templateRulesFile.open(templateRulesFilePath);
     for (auto &templateRule : templateRules) {
-        for (auto &templateRuleToken : templateRule)
-            templateRulesFile << templateRuleToken << ' ';
-        templateRulesFile << std::endl;
+        templateRulesFile << templateRule.subject << ' ' << templateRule.object << ' '
+                          << templateRule.permissions << std::endl;
     }
     templateRulesFile.close();
 
@@ -94,24 +94,31 @@ BOOST_FIXTURE_TEST_CASE(T1130_smack_rules_templates, RulesFixture)
     const std::string pkgName = "pkgNameT1130";
     const std::string appProcessLabel = generateProcessLabel(appName, pkgName, false);
     const int authorId = 5000;
-    SmackRules smackRulesFromTemplate, smackRulesFromFileTemplate;
+    SmackAccesses smackAccessesFromTemplate, smackAccessesFromFileTemplate;
+    SmackRules smackRules;
 
-    BOOST_REQUIRE_NO_THROW(smackRulesFromTemplate.addFromTemplate(templateRules,
-                                                                  appProcessLabel,
-                                                                  pkgName,
-                                                                  authorId));
+    BOOST_REQUIRE_NO_THROW(smackRules.addFromTemplate(
+                               smackAccessesFromTemplate,
+                               templateRules,
+                               appProcessLabel,
+                               pkgName,
+                               authorId));
 
     const std::string noExistingFilePath = "/tmp/SecurityManagerUTNoExistingFile";
-    BOOST_REQUIRE_THROW(smackRulesFromFileTemplate.addFromTemplateFile(noExistingFilePath,
-                                                                       appProcessLabel,
-                                                                       pkgName,
-                                                                       authorId),
-                                                                       SmackException::FileError);
-
-    BOOST_REQUIRE_NO_THROW(smackRulesFromFileTemplate.addFromTemplateFile(templateRulesFilePath,
-                                                                          appProcessLabel,
-                                                                          pkgName,
-                                                                          authorId));
+    BOOST_REQUIRE_THROW(smackRules.addFromTemplateFile(
+                            smackAccessesFromFileTemplate,
+                            noExistingFilePath,
+                            appProcessLabel,
+                            pkgName,
+                            authorId),
+                        SmackException::FileError);
+
+    BOOST_REQUIRE_NO_THROW(smackRules.addFromTemplateFile(
+                               smackAccessesFromFileTemplate,
+                               templateRulesFilePath,
+                               appProcessLabel,
+                               pkgName,
+                               authorId));
 }
 
 BOOST_AUTO_TEST_SUITE_END()