1 /*
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 <iostream>
23 #include <string>
24 #include <vector>
25 
26 #include <dirent.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 
32 #include <android-base/logging.h>
33 #include <android-base/scopeguard.h>
34 
35 #include <cutils/fs.h>
36 #include <selinux/android.h>
37 
38 #include "Utils.h"
39 #include "android/os/IVold.h"
40 
41 #include <private/android_filesystem_config.h>
42 
usage(const char * progname)43 static void usage(const char* progname) {
44     std::cerr << "Usage: " << progname << " [ prepare | destroy ] <volume_uuid> <user_id> <flags>"
45               << std::endl;
46     exit(-1);
47 }
48 
small_int(const std::string & s)49 static bool small_int(const std::string& s) {
50     return !s.empty() && s.size() < 7 && s.find_first_not_of("0123456789") == std::string::npos;
51 }
52 
valid_uuid(const std::string & s)53 static bool valid_uuid(const std::string& s) {
54     return s.size() < 40 && s.find_first_not_of("0123456789abcdefABCDEF-_") == std::string::npos;
55 }
56 
prepare_dir_for_user(struct selabel_handle * sehandle,mode_t mode,uid_t uid,gid_t gid,const std::string & path,uid_t user_id)57 static bool prepare_dir_for_user(struct selabel_handle* sehandle, mode_t mode, uid_t uid, gid_t gid,
58                                  const std::string& path, uid_t user_id) {
59     auto clearfscreatecon = android::base::make_scope_guard([] { setfscreatecon(nullptr); });
60     auto secontext = std::unique_ptr<char, void (*)(char*)>(nullptr, freecon);
61     char* tmp_secontext;
62 
63     if (selabel_lookup(sehandle, &tmp_secontext, path.c_str(), S_IFDIR) == 0) {
64         secontext.reset(tmp_secontext);
65         if (user_id != (uid_t)-1) {
66             if (selinux_android_context_with_level(secontext.get(), &tmp_secontext, user_id,
67                                                    (uid_t)-1) != 0) {
68                 PLOG(ERROR) << "Unable to create context with level for: " << path;
69                 return false;
70             }
71             secontext.reset(tmp_secontext);
72         }
73         if (setfscreatecon(secontext.get()) != 0) {
74             LOG(ERROR) << "Failed to setfscreatecon for directory " << path;
75             return false;
76         }
77     } else if (errno == ENOENT) {
78         LOG(DEBUG) << "No selabel defined for directory " << path;
79     } else {
80         PLOG(ERROR) << "Failed to look up selabel for directory " << path;
81         return false;
82     }
83 
84     LOG(DEBUG) << "Setting up mode " << std::oct << mode << std::dec << " uid " << uid << " gid "
85                << gid << " context " << (secontext ? secontext.get() : "null")
86                << " on path: " << path;
87     if (fs_prepare_dir(path.c_str(), mode, uid, gid) != 0) {
88         return false;
89     }
90     if (secontext) {
91         char* tmp_oldsecontext = nullptr;
92         if (lgetfilecon(path.c_str(), &tmp_oldsecontext) < 0) {
93             PLOG(ERROR) << "Unable to read secontext for: " << path;
94             return false;
95         }
96         auto oldsecontext = std::unique_ptr<char, void (*)(char*)>(tmp_oldsecontext, freecon);
97         if (strcmp(secontext.get(), oldsecontext.get()) != 0) {
98             LOG(INFO) << "Relabelling from " << ((char*)oldsecontext.get()) << " to "
99                       << ((char*)secontext.get()) << ": " << path;
100             if (lsetfilecon(path.c_str(), secontext.get()) != 0) {
101                 PLOG(ERROR) << "Relabelling failed for: " << path;
102                 return false;
103             }
104         }
105     }
106     return true;
107 }
108 
prepare_dir(struct selabel_handle * sehandle,mode_t mode,uid_t uid,gid_t gid,const std::string & path)109 static bool prepare_dir(struct selabel_handle* sehandle, mode_t mode, uid_t uid, gid_t gid,
110                         const std::string& path) {
111     return prepare_dir_for_user(sehandle, mode, uid, gid, path, (uid_t)-1);
112 }
113 
rmrf_contents(const std::string & path)114 static bool rmrf_contents(const std::string& path) {
115     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(path.c_str()), closedir);
116     if (!dirp) {
117         if (errno == ENOENT) {
118             return true;
119         }
120         PLOG(ERROR) << "Unable to open directory: " << path;
121         return false;
122     }
123     bool res = true;
124     for (;;) {
125         errno = 0;
126         auto const entry = readdir(dirp.get());
127         if (!entry) {
128             if (errno) {
129                 PLOG(ERROR) << "readdir failed on: " << path;
130                 return false;
131             }
132             return res;
133         }
134         if (entry->d_name[0] == '.') continue;
135         auto subdir = path + "/" + entry->d_name;
136         if (0 !=
137             android::vold::ForkExecvp(std::vector<std::string>{"/system/bin/rm", "-rf", subdir})) {
138             LOG(ERROR) << "rm -rf failed on " << subdir;
139             res = false;
140         }
141     }
142 }
143 
prepare_apex_subdirs(struct selabel_handle * sehandle,const std::string & path)144 static bool prepare_apex_subdirs(struct selabel_handle* sehandle, const std::string& path) {
145     if (!prepare_dir(sehandle, 0711, 0, 0, path + "/apexdata")) return false;
146 
147     // Since vold/vold_prepare_subdirs run in the bootstrap mount namespace
148     // we can't get the full list of APEXes by scanning /apex directory.
149     // Instead, we can look up /data/misc/apexdata for the list of APEXes,
150     // which is populated during `perform_apex_config` in init.
151     // Note: `init_user0` should be invoked after `perform_apex_config`.
152     auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir("/data/misc/apexdata"), closedir);
153     if (!dirp) {
154         PLOG(ERROR) << "Unable to open apex directory";
155         return false;
156     }
157     struct dirent* entry;
158     while ((entry = readdir(dirp.get())) != nullptr) {
159         if (entry->d_type != DT_DIR) continue;
160 
161         const char* name = entry->d_name;
162         // skip any starting with "."
163         if (name[0] == '.') continue;
164 
165         if (!prepare_dir(sehandle, 0771, AID_ROOT, AID_SYSTEM, path + "/apexdata/" + name)) {
166             return false;
167         }
168     }
169     return true;
170 }
171 
prepare_subdirs(const std::string & volume_uuid,int user_id,int flags)172 static bool prepare_subdirs(const std::string& volume_uuid, int user_id, int flags) {
173     struct selabel_handle* sehandle = selinux_android_file_context_handle();
174     if (!sehandle) {
175         LOG(ERROR) << "Failed to get SELinux file contexts handle";
176         return false;
177     }
178 
179     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
180         auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
181         if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, user_de_path, user_id)) {
182             return false;
183         }
184 
185         auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id);
186         if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM,
187                                   misc_de_path + "/sdksandbox", user_id)) {
188             return false;
189         }
190 
191         if (volume_uuid.empty()) {
192             if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/vold")) return false;
193             if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/storaged")) return false;
194             if (!prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/rollback")) return false;
195             // TODO: Return false if this returns false once sure this should succeed.
196             prepare_dir(sehandle, 0700, 0, 0, misc_de_path + "/apexrollback");
197             prepare_apex_subdirs(sehandle, misc_de_path);
198 
199             auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
200             if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, profiles_de_path,
201                                       user_id)) {
202                 return false;
203             }
204 
205             auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
206             if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, vendor_de_path + "/fpdata")) {
207                 return false;
208             }
209             auto facedata_path = vendor_de_path + "/facedata";
210             if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, facedata_path)) {
211                 return false;
212             }
213         }
214     }
215     if (flags & android::os::IVold::STORAGE_FLAG_CE) {
216         auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
217         if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM, user_ce_path, user_id)) {
218             return false;
219         }
220 
221         auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id);
222         if (!prepare_dir_for_user(sehandle, 0771, AID_SYSTEM, AID_SYSTEM,
223                                   misc_ce_path + "/sdksandbox", user_id)) {
224             return false;
225         }
226 
227         if (volume_uuid.empty()) {
228             if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/vold")) return false;
229             if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/storaged")) return false;
230             if (!prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/rollback")) return false;
231             // TODO: Return false if this returns false once sure this should succeed.
232             prepare_dir(sehandle, 0700, 0, 0, misc_ce_path + "/apexrollback");
233             prepare_apex_subdirs(sehandle, misc_ce_path);
234             // Give gmscore (who runs in cache group) access to the checkin directory. Also provide
235             // the user id to set the correct selinux mls_level.
236             if (!prepare_dir_for_user(sehandle, 0770, AID_SYSTEM, AID_CACHE,
237                                       misc_ce_path + "/checkin", user_id)) {
238                 // TODO(b/203742483) the checkin directory was created with the wrong permission &
239                 // context. Delete the directory to get these devices out of the bad state. Revert
240                 // the change once the droidfood population is on newer build.
241                 LOG(INFO) << "Failed to prepare the checkin directory, deleting for recreation";
242                 android::vold::DeleteDirContentsAndDir(misc_ce_path + "/checkin");
243                 if (!prepare_dir_for_user(sehandle, 0770, AID_SYSTEM, AID_CACHE,
244                                           misc_ce_path + "/checkin", user_id)) {
245                     return false;
246                 }
247             }
248 
249             auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
250             if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, system_ce_path + "/backup")) {
251                 return false;
252             }
253             if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM,
254                              system_ce_path + "/backup_stage")) {
255                 return false;
256             }
257             auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
258             auto facedata_path = vendor_ce_path + "/facedata";
259             if (!prepare_dir(sehandle, 0700, AID_SYSTEM, AID_SYSTEM, facedata_path)) {
260                 return false;
261             }
262         }
263     }
264     return true;
265 }
266 
destroy_subdirs(const std::string & volume_uuid,int user_id,int flags)267 static bool destroy_subdirs(const std::string& volume_uuid, int user_id, int flags) {
268     bool res = true;
269     if (flags & android::os::IVold::STORAGE_FLAG_CE) {
270         auto misc_ce_path = android::vold::BuildDataMiscCePath(volume_uuid, user_id);
271         res &= rmrf_contents(misc_ce_path);
272 
273         if (volume_uuid.empty()) {
274             auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
275             res &= rmrf_contents(vendor_ce_path);
276         }
277     }
278     if (flags & android::os::IVold::STORAGE_FLAG_DE) {
279         auto misc_de_path = android::vold::BuildDataMiscDePath(volume_uuid, user_id);
280         res &= rmrf_contents(misc_de_path);
281 
282         if (volume_uuid.empty()) {
283             auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
284             res &= rmrf_contents(vendor_de_path);
285         }
286     }
287     return res;
288 }
289 
main(int argc,const char * const argv[])290 int main(int argc, const char* const argv[]) {
291     android::base::InitLogging(const_cast<char**>(argv));
292     std::vector<std::string> args(argv + 1, argv + argc);
293 
294     if (args.size() != 4 || !valid_uuid(args[1]) || !small_int(args[2]) || !small_int(args[3])) {
295         usage(argv[0]);
296         return -1;
297     }
298 
299     auto volume_uuid = args[1];
300     int user_id = stoi(args[2]);
301     int flags = stoi(args[3]);
302     if (args[0] == "prepare") {
303         if (!prepare_subdirs(volume_uuid, user_id, flags)) return -1;
304     } else if (args[0] == "destroy") {
305         if (!destroy_subdirs(volume_uuid, user_id, flags)) return -1;
306     } else {
307         usage(argv[0]);
308         return -1;
309     }
310     return 0;
311 }
312