summaryrefslogtreecommitdiff
path: root/src/common/smack-labels.cpp
blob: 07c34200d775cd92a35ad414a518ed8e4d66aecd (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
329
330
/*
 * Copyright (c) 2014-2020 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        smack-labels.cpp
 * @author      Jan Cybulski <j.cybulski@samsung.com>
 * @author      Rafal Krypa <r.krypa@samsung.com>
 * @version     1.0
 * @brief       Implementation of functions managing smack labels
 *
 */

#include <crypt.h>
#include <sys/stat.h>
#include <sys/smack.h>
#include <sys/xattr.h>
#include <linux/xattr.h>
#include <memory>
#include <fts.h>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>

#include <dpl/log/log.h>
#include <dpl/errno_string.h>

#include "security-manager.h"
#include "smack-labels.h"
#include "utils.h"


namespace SecurityManager {
namespace SmackLabels {

//! Smack label used for SECURITY_MANAGER_PATH_PUBLIC_RO paths (RO for all apps)
const char *const LABEL_FOR_APP_PUBLIC_RO_PATH = "User::Home";

typedef std::function<bool(const FTSENT*)> LabelDecisionFn;

static bool labelAll(const FTSENT *ftsent __attribute__((unused)))
{
    return true;
}

static bool labelDirs(const FTSENT *ftsent)
{
    // label only directories
    return (S_ISDIR(ftsent->fts_statp->st_mode));
}

static bool labelExecs(const FTSENT *ftsent)
{
    // LogDebug("Mode = " << ftsent->fts_statp->st_mode); // this could be helpfull in debugging
    // label only regular executable files
    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,
        const char *xattr_name)
{
    if (smack_set_label_for_path(path, xattr_name, 0, label.c_str())) {
        LogError("smack_set_label_for_path failed. Path: " << path << " Label:" << label);
        ThrowMsg(SmackException::FileError,
            "smack_set_label_for_path failed failed. Path: " << path << " Label: " << label);
    }
}

static void dirSetSmack(const std::string &path, const std::string &label,
        const char *xattr_name, LabelDecisionFn fn)
{
    char *const path_argv[] = {const_cast<char *>(path.c_str()), NULL};
    FTSENT *ftsent;

    auto fts = makeUnique(fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL), fts_close);
    if (!fts) {
        LogError("fts_open failed.");
        ThrowMsg(SmackException::FileError, "fts_open failed.");
    }

    while ((ftsent = fts_read(fts.get())) != NULL) {
        /* Check for error (FTS_ERR) or failed stat(2) (FTS_NS) */
        if (ftsent->fts_info == FTS_ERR || ftsent->fts_info == FTS_NS) {
            LogError("FTS_ERR error or failed stat(2) (FTS_NS)");
            ThrowMsg(SmackException::FileError, "FTS_ERR error or failed stat(2) (FTS_NS)");
        }

        /* avoid to tag directories two times */
        if (ftsent->fts_info == FTS_D)
            continue;

        if (fn(ftsent))
            pathSetSmack(ftsent->fts_path, label, xattr_name);
    }

    /* If last call to fts_read() set errno, we need to return error. */
    if ((errno != 0) && (ftsent == NULL)) {
        LogError("Last errno from fts_read: " << GetErrnoString(errno));
        ThrowMsg(SmackException::FileError, "Last errno from fts_read: " << GetErrnoString(errno));
    }
}

static void labelDir(const std::string &path, const std::string &label,
        bool set_transmutable, bool set_executables)
{
    // setting access label on everything in given directory and below
    dirSetSmack(path, label, XATTR_NAME_SMACK, labelAll);

    // setting transmute on dirs
    if (set_transmutable)
        dirSetSmack(path, "TRUE", XATTR_NAME_SMACKTRANSMUTE, labelDirs);

    // setting SMACK64EXEC labels
    if (set_executables)
        dirSetSmack(path, label, XATTR_NAME_SMACKEXEC, &labelExecs);
}

void setupPath(
        const std::string &pkgName,
        const std::string &path,
        app_install_path_type pathType,
        const int authorId)
{
    std::string label;
    bool label_executables, label_transmute;

    switch (pathType) {
    case SECURITY_MANAGER_PATH_RW:
        label = generatePathRWLabel(pkgName);
        label_executables = false;
        label_transmute = true;
        break;
    case SECURITY_MANAGER_PATH_RO:
        label = generatePathROLabel(pkgName);
        label_executables = false;
        label_transmute = false;
        break;
    case SECURITY_MANAGER_PATH_PUBLIC_RO:
        label.assign(LABEL_FOR_APP_PUBLIC_RO_PATH);
        label_executables = false;
        label_transmute = true;
        break;
    case SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO:
        label = generatePathSharedROLabel(pkgName);
        label_executables = false;
        label_transmute = true;
        break;
    case SECURITY_MANAGER_PATH_TRUSTED_RW:
        if (authorId < 0)
            ThrowMsg(SmackException::InvalidParam, "You must define author to use PATH_TRUSED_RW");
        label = generatePathTrustedLabel(authorId);
        label_executables = false;
        label_transmute = true;
        break;
    default:
        LogError("Path type not known.");
        Throw(SmackException::InvalidPathType);
    }
    return labelDir(path, label, label_transmute, label_executables);
}

void setupPkgBasePath(const std::string &basePath)
{
    pathSetSmack(basePath.c_str(), LABEL_FOR_APP_PUBLIC_RO_PATH, XATTR_NAME_SMACK);
}

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)
{
    static const char pkgPrefix[] = "User::Pkg::";
    static const char appPrefix[] = "::App::";

    if (label.compare(0, sizeof(pkgPrefix) - 1, pkgPrefix))
        ThrowMsg(SmackException::InvalidLabel, "Invalid application process label " << label);

    size_t pkgStartPos = sizeof(pkgPrefix) - 1;
    size_t pkgEndPos = label.find(appPrefix, pkgStartPos);
    if (pkgEndPos != std::string::npos) {
        LogDebug("Hybrid application process label");
        size_t appStartPos = pkgEndPos + sizeof(appPrefix) - 1;
        appName = label.substr(appStartPos, std::string::npos);
        pkgName = label.substr(pkgStartPos, pkgEndPos - pkgStartPos);
    } else {
        appName = std::string();
        pkgName = label.substr(pkgStartPos, std::string::npos);
    }

    if (pkgName.empty())
        ThrowMsg(SmackException::InvalidLabel, "No pkgName in Smack label " << label);
}

std::string generateProcessLabel(const std::string &appName, const std::string &pkgName,
                                 bool isHybrid)
{
    std::string label = "User::Pkg::" + pkgName;
    if (isHybrid)
        label += "::App::" + appName;

    if (smack_label_length(label.c_str()) <= 0)
        ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from appName " << appName);

    return label;
}

std::string generatePathSharedROLabel(const std::string &pkgName)
{
    std::string label = "User::Pkg::" + pkgName + "::SharedRO";

    if (smack_label_length(label.c_str()) <= 0)
        ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName);

    return label;
}

std::string generatePathRWLabel(const std::string &pkgName)
{
    std::string label = "User::Pkg::" + pkgName;

    if (smack_label_length(label.c_str()) <= 0)
        ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName);

    return label;
}

std::string generatePathROLabel(const std::string &pkgName)
{
    std::string label = "User::Pkg::" + pkgName + "::RO";

    if (smack_label_length(label.c_str()) <= 0)
        ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from pkgName " << pkgName);

    return label;
}

std::string generateSharedPrivateLabel(const std::string &pkgName, const std::string &path)
{
    // Prefix $1$ causes crypt() to use MD5 function
    std::string label = "User::Pkg::";
    std::string salt = "$1$" + pkgName;

    const char * cryptLabel = crypt(path.c_str(), salt.c_str());
    if (!cryptLabel) {
        ThrowMsg(SmackException::Base, "crypt error");
    }
    label += cryptLabel;
    std::replace(label.begin(), label.end(), '/', '%');
    if (smack_label_length(label.c_str()) <= 0)
        ThrowMsg(SmackException::InvalidLabel, "Invalid Smack label generated from path " << path);
    return label;
}

template<typename FuncType, typename... ArgsType>
static std::string 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);
}

std::string getSmackLabelFromSocket(int socketFd)
{
    return getSmackLabel(&smack_new_label_from_socket, socketFd);
}

std::string getSmackLabelFromPath(const std::string &path)
{
    return getSmackLabel(&smack_new_label_from_path, path.c_str(), XATTR_NAME_SMACK, true);
}

std::string getSmackLabelFromFd(int fd)
{
    return getSmackLabel(&smack_new_label_from_file, fd, XATTR_NAME_SMACK);
}

std::string getSmackLabelFromSelf(void)
{
    return getSmackLabel(&smack_new_label_from_self);
}

std::string getSmackLabelFromPid(pid_t pid)
{
    return getSmackLabel(&smack_new_label_from_process, pid);
}

std::string generatePathTrustedLabel(const int authorId)
{
    if (authorId < 0) {
        LogError("Author was not set. It's not possible to generate label for unknown author.");
        ThrowMsg(SmackException::InvalidLabel, "Could not generate valid label without authorId");
    }

    return "User::Author::" + std::to_string(authorId);
}

void setSmackLabelForFd(int fd, const std::string &label)
{
    if (smack_set_label_for_file(fd, XATTR_NAME_SMACK, label.c_str())) {
        LogError("smack_set_label_for_file failed.");
        ThrowMsg(SmackException::FileError, "smack_set_label_for_file failed.");
    }
}

} // namespace SmackLabels
} // namespace SecurityManager