summaryrefslogtreecommitdiff
path: root/src/common/mount-namespace.cpp
blob: 8294a581ec3e61a8835c040eacacde654d62c939 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 * Copyright (c) 2017-2022 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * This file is licensed under the terms of MIT License or the Apache License
 * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
 * See the LICENSE file or the notice below for Apache License Version 2.0
 * details.
 *
 * 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        mount-namespace.cpp
 * @author      Dariusz Michaluk <d.michaluk@samsung.com>
 * @version     1.0
 * @brief       Mount namespace utility.
 *
 */

#include <pwd.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <string>

#include <mount-namespace.h>
#include <config.h>
#include <config-file.h>
#include <filesystem.h>
#include <tzplatform-config.h>
#include <dpl/log/log.h>
#include <dpl/errno_string.h>
#include <security-manager.h>

namespace SecurityManager {
namespace MountNS {

const std::string EMPTY_MOUNT_DIR      = "-";
const std::string MAIN_MOUNT_NAMESPACE = "/proc/1/ns/mnt";
const std::string SELF_MOUNT_NAMESPACE = "/proc/self/ns/mnt";

PrivilegePathsMap getPrivilegePathMap(uid_t uid)
{
    PrivilegePathsMap map;
    TizenPlatformConfig tpcUser(uid);

    auto conf = ConfigFile(PRIVILEGE_MOUNT_LIST_FILE).read();
    for (auto &confEntry : conf) {
        if (confEntry.size() != 4)
            continue;

        for (int i = 1; i <= 3; ++i)
            if (confEntry[i] == EMPTY_MOUNT_DIR)
                confEntry[i].clear();
            else if (!strncmp(confEntry[i].c_str(), "TZ_SYS_", 7))
                confEntry[i] = TizenPlatformConfig::getEnv(TizenPlatformConfig::getId(confEntry[i]));
            else if (!strncmp(confEntry[i].c_str(), "TZ_USER_", 8))
                confEntry[i] = tpcUser.ctxGetEnv(TizenPlatformConfig::getId(confEntry[i]));

        std::string &privilege    = confEntry[0];
        std::string &dstPath      = confEntry[1];
        std::string &allowSrcPath = confEntry[2];
        std::string &denySrcPath  = confEntry[3];

        map[std::move(privilege)].emplace_back(
                PrivilegePath{std::move(dstPath), std::move(allowSrcPath), std::move(denySrcPath)});
    }

    return map;
}

int applyPrivilegePath(bool allow, const PrivilegePath &privilegePath)
{
    const std::string &srcPath = allow ? privilegePath.allowSrcPath : privilegePath.denySrcPath;
    const std::string &otherSrcPath = allow ? privilegePath.denySrcPath : privilegePath.allowSrcPath;

    LogDebug("Applying privilege mount enforcement:" <<
        " allow = " << allow << " dstPath = " << privilegePath.dstPath <<
        " allowSrcPath = " << privilegePath.allowSrcPath <<
        " denySrcPath = " << privilegePath.denySrcPath);

    if (srcPath.empty()) {
        if (!otherSrcPath.empty() && isPathBound(otherSrcPath, privilegePath.dstPath)) {
            LogDebug("Unmounting " << otherSrcPath << " from " << privilegePath.dstPath);
            return uMount(privilegePath.dstPath);
        }
        return 0;
    }

    if (isPathBound(srcPath, privilegePath.dstPath))
        return 0;

    LogDebug("Bind mounting " << srcPath << " to " << privilegePath.dstPath);
    return bindMountRW(srcPath, privilegePath.dstPath);
}

std::string getUsersAppsMountPointsPath(void)
{
    return TizenPlatformConfig::makePath(TZ_SYS_RUN, "user");
}

std::string getUserAppsMountPointsPath(uid_t uid)
{
    return TizenPlatformConfig::makePath(TZ_SYS_RUN, "user", std::to_string(uid), "apps");
}

std::string getUserAppMountPointPath(uid_t uid, const std::string &smackLabel)
{
    return getUserAppsMountPointsPath(uid) + "/" + smackLabel;
}

std::string getUserAppServiceMountPointPath(uid_t uid, const std::string &smackLabel, pid_t pid)
{
    return getUserAppMountPointPath(uid, smackLabel) + "/" + std::to_string(pid);
}

bool isPrivacyPrivilegeMountNamespaceEnabled(void)
{
    auto getStatus = []() -> bool {
        try {
            if (access(SELF_MOUNT_NAMESPACE.c_str(), F_OK) < 0)
                return false;

            struct stat st;
            if (stat(PRIVILEGE_MOUNT_LIST_FILE, &st) < 0)
                return false;
            if (st.st_size == 0)
                return false;

            // File exists and is not empty.
            // Let's check if it contains any relevant configuration entries.
            if (getPrivilegePathMap(getuid()).empty())
                return false;
        } catch (...) {
            return false;
        }

        return true;
    };

    static bool enabled = getStatus();

    return enabled;
}

int createMountNamespace(void)
{
    int ret = unshare(CLONE_NEWNS);
    if (ret != 0) {
        LogError("Failed to unshare mount namespace: " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int enterMountNamespace(const Path &mntPath)
{
    int fd = open(mntPath.c_str(), O_RDONLY);
    if (fd < 0) {
        LogError("Failed to open " << mntPath << ": " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_FILE_OPEN_FAILED;
    }

    // 0 == allow any type of namespace
    int ret = setns(fd, 0);
    close(fd);
    if (ret != 0) {
        LogError("Failed to setns " << mntPath << ": " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int makeMountSlave(const Path &mountPoint)
{
    int ret = mount("none", mountPoint.c_str(), NULL, MS_REC|MS_SLAVE, NULL);
    if (ret != 0) {
        LogError("Failed to make mount point " << mountPoint << " slave: " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int makeMountPrivate(const Path &mountPoint)
{
    int ret = mount("none", mountPoint.c_str(), NULL, MS_PRIVATE, NULL);
    if (ret != 0) {
        LogError("Failed to make mount point " << mountPoint << " private: " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int bindMountRW(const Path &source, const Path &target)
{
    int ret = mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL);
    if (ret != 0) {
        LogError("Failed to RW bind directory " << source << " to " << target << " " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int bindMountRO(const Path &source, const Path &target)
{
    int ret = mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL);
    if (ret != 0) {
        LogError("Failed to bind directory " << source << " to " << target << " " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }

    ret = mount(NULL, target.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL);
    if (ret != 0) {
        LogError("Failed to RO bind directory " << source << " to " << target << " " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int bindMountROIfExists(const Path &source, const Path &target)
{
    int ret = mount(source.c_str(), target.c_str(), NULL, MS_BIND, NULL);
    if (ret != 0) {
        if (errno == ENOENT) {
            LogDebug("ENOENT when binding " << source << " to " << target << ", skipping");
            return SECURITY_MANAGER_SUCCESS;
        }
        LogError("Failed to bind directory " << source << " to " << target << " " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }

    ret = mount(NULL, target.c_str(), NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL);
    if (ret != 0) {
        LogError("Failed to RO bind directory " << source << " to " << target << " " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int uMount(const Path &target)
{
    int ret = umount(target.c_str());
    if (ret != 0) {
        LogWarning("Failed to umount: "  << target << " " << GetErrnoString(errno));
        return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    }
    return SECURITY_MANAGER_SUCCESS;
}

bool isPathBound(const Path &what, const Path &where)
{
    struct stat st1, st2;
    int ret;

    ret = lstat(what.c_str(), &st1);
    if (ret < 0) {
        LogError("Unable to stat " << what << " " << GetErrnoString(errno));
        return false;
    }

    ret = lstat(where.c_str(), &st2);
    if (ret < 0) {
        LogError("Unable to stat " << where << " " << GetErrnoString(errno));
        return false;
    }

    // Check whether both paths have the same device ID and inode number
    // If yes, they point to the same file or directory, which is proof of either
    // bind mount or a hard link
    return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
}

std::vector<AppContext> getMountNSApps()
{
    const static std::string rootDir = getUsersAppsMountPointsPath();
    const static std::string regexp =
        rootDir + "/(\\d*)/apps/(User::Pkg::[^/]*)|(User::Pkg::User::App::[^/]*)";


    boost::system::error_code ec;
    boost::filesystem::path root(rootDir);
    boost::regex mountNSAppFilter(regexp);

    std::vector<AppContext> apps;
    for (boost::filesystem::recursive_directory_iterator it(root, ec), eit;
         it != eit;
         it.increment(ec))
    {
        if (ec) // Old Boost versions compatibility.
            break;

        boost::smatch matches;
        std::string path = it->path().string();
        if (boost::regex_match(path, matches, mountNSAppFilter)) {
            if (matches.size() < 4) {
                LogError("Failed to properly process regexp " << regexp);
                return {};
            }
            apps.push_back({matches[2], matches[1]});
        }
    }

    if (ec)
        ThrowMsg(FS::Exception::FileError,
            "Error scanning app mount points at " << rootDir << ", " << ec.message());
    return apps;
}

} // namespace MountNS
} // namespace SecurityManager