blob: 1d91458b5a6885e5073bfe70c3f5d078ad010163 [file] [log] [blame]
Paul Crowley1a965262017-10-13 13:49:50 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Tool to create a directory with the right SELinux context applied, or
19 * apply the context if it's absent. Also fixes mode, uid, gid.
20 */
21
22#include <string>
23#include <vector>
24
25#include <stdio.h>
26#include <stdlib.h>
27#include <sys/stat.h>
28
29#include <android-base/logging.h>
30
31#include <cutils/fs.h>
32#include <selinux/android.h>
33
34void usage(const char* progname) {
35 fprintf(stderr, "Usage: %s --mode MODE --uid UID --gid GID -- <path>\n", progname);
36}
37
38bool small_int(const std::string& s) {
39 return !s.empty() && s.size() < 7 && s.find_first_not_of("0123456789") == std::string::npos;
40}
41
42int main(int argc, const char* const argv[]) {
43 setenv("ANDROID_LOG_TAGS", "*:v", 1);
44 android::base::InitLogging(const_cast<char**>(argv));
45 std::vector<std::string> args(argv + 1, argv + argc);
46 // Enforce exact format of arguments. You can always loosen but you can never tighten :)
47 if (args.size() != 8 || args[0] != "--mode" || !small_int(args[1]) || args[2] != "--uid" ||
48 !small_int(args[3]) || args[4] != "--gid" || !small_int(args[5]) || args[6] != "--") {
49 usage(argv[0]);
50 return -1;
51 }
52 mode_t mode = (mode_t)stoi(args[1], nullptr, 8);
53 uid_t uid = (uid_t)stoi(args[3]);
54 gid_t gid = (gid_t)stoi(args[5]);
55 const char* path = args[7].c_str();
56
57 struct selabel_handle* sehandle = selinux_android_file_context_handle();
58 char* secontext = nullptr;
59 if (sehandle) {
60 if (selabel_lookup(sehandle, &secontext, path, S_IFDIR) == 0) {
61 setfscreatecon(secontext);
62 }
63 }
64
65 if (fs_prepare_dir(path, mode, uid, gid) != 0) {
66 return -1;
67 }
68 if (secontext) {
69 char* oldsecontext = nullptr;
70 if (lgetfilecon(path, &oldsecontext) < 0) {
71 PLOG(ERROR) << "Unable to read secontext for: " << path;
72 return -1;
73 }
74 if (strcmp(secontext, oldsecontext) != 0) {
75 LOG(INFO) << "Relabelling from " << oldsecontext << " to " << secontext << ": " << path;
76 if (lsetfilecon(path, secontext) != 0) {
77 PLOG(ERROR) << "Relabelling failed for: " << path;
78 }
79 }
80 }
81 return 0;
82}