1 /*
2  * Copyright (C) 2007 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 #include "devices.h"
18 
19 #include <errno.h>
20 #include <fnmatch.h>
21 #include <sys/sysmacros.h>
22 #include <unistd.h>
23 
24 #include <chrono>
25 #include <filesystem>
26 #include <memory>
27 #include <string>
28 #include <thread>
29 
30 #include <android-base/chrono_utils.h>
31 #include <android-base/file.h>
32 #include <android-base/logging.h>
33 #include <android-base/stringprintf.h>
34 #include <android-base/strings.h>
35 #include <private/android_filesystem_config.h>
36 #include <selinux/android.h>
37 #include <selinux/selinux.h>
38 
39 #include "selabel.h"
40 #include "util.h"
41 
42 using namespace std::chrono_literals;
43 
44 using android::base::Basename;
45 using android::base::Dirname;
46 using android::base::ReadFileToString;
47 using android::base::Readlink;
48 using android::base::Realpath;
49 using android::base::StartsWith;
50 using android::base::StringPrintf;
51 using android::base::Trim;
52 
53 namespace android {
54 namespace init {
55 
56 /* Given a path that may start with a PCI device, populate the supplied buffer
57  * with the PCI domain/bus number and the peripheral ID and return 0.
58  * If it doesn't start with a PCI device, or there is some error, return -1 */
FindPciDevicePrefix(const std::string & path,std::string * result)59 static bool FindPciDevicePrefix(const std::string& path, std::string* result) {
60     result->clear();
61 
62     if (!StartsWith(path, "/devices/pci")) return false;
63 
64     /* Beginning of the prefix is the initial "pci" after "/devices/" */
65     std::string::size_type start = 9;
66 
67     /* End of the prefix is two path '/' later, capturing the domain/bus number
68      * and the peripheral ID. Example: pci0000:00/0000:00:1f.2 */
69     auto end = path.find('/', start);
70     if (end == std::string::npos) return false;
71 
72     end = path.find('/', end + 1);
73     if (end == std::string::npos) return false;
74 
75     auto length = end - start;
76     if (length <= 4) {
77         // The minimum string that will get to this check is 'pci/', which is malformed,
78         // so return false
79         return false;
80     }
81 
82     *result = path.substr(start, length);
83     return true;
84 }
85 
86 /* Given a path that may start with a virtual block device, populate
87  * the supplied buffer with the virtual block device ID and return 0.
88  * If it doesn't start with a virtual block device, or there is some
89  * error, return -1 */
FindVbdDevicePrefix(const std::string & path,std::string * result)90 static bool FindVbdDevicePrefix(const std::string& path, std::string* result) {
91     result->clear();
92 
93     if (!StartsWith(path, "/devices/vbd-")) return false;
94 
95     /* Beginning of the prefix is the initial "vbd-" after "/devices/" */
96     std::string::size_type start = 13;
97 
98     /* End of the prefix is one path '/' later, capturing the
99        virtual block device ID. Example: 768 */
100     auto end = path.find('/', start);
101     if (end == std::string::npos) return false;
102 
103     auto length = end - start;
104     if (length == 0) return false;
105 
106     *result = path.substr(start, length);
107     return true;
108 }
109 
110 // Given a path that may start with a virtual dm block device, populate
111 // the supplied buffer with the dm module's instantiated name.
112 // If it doesn't start with a virtual block device, or there is some
113 // error, return false.
FindDmDevice(const std::string & path,std::string * name,std::string * uuid)114 static bool FindDmDevice(const std::string& path, std::string* name, std::string* uuid) {
115     if (!StartsWith(path, "/devices/virtual/block/dm-")) return false;
116 
117     if (!ReadFileToString("/sys" + path + "/dm/name", name)) {
118         return false;
119     }
120     ReadFileToString("/sys" + path + "/dm/uuid", uuid);
121 
122     *name = android::base::Trim(*name);
123     *uuid = android::base::Trim(*uuid);
124     return true;
125 }
126 
Permissions(const std::string & name,mode_t perm,uid_t uid,gid_t gid,bool no_fnm_pathname)127 Permissions::Permissions(const std::string& name, mode_t perm, uid_t uid, gid_t gid,
128                          bool no_fnm_pathname)
129     : name_(name),
130       perm_(perm),
131       uid_(uid),
132       gid_(gid),
133       prefix_(false),
134       wildcard_(false),
135       no_fnm_pathname_(no_fnm_pathname) {
136     // Set 'prefix_' or 'wildcard_' based on the below cases:
137     //
138     // 1) No '*' in 'name' -> Neither are set and Match() checks a given path for strict
139     //    equality with 'name'
140     //
141     // 2) '*' only appears as the last character in 'name' -> 'prefix'_ is set to true and
142     //    Match() checks if 'name' is a prefix of a given path.
143     //
144     // 3) '*' appears elsewhere -> 'wildcard_' is set to true and Match() uses fnmatch()
145     //    with FNM_PATHNAME to compare 'name' to a given path.
146     auto wildcard_position = name_.find('*');
147     if (wildcard_position != std::string::npos) {
148         if (wildcard_position == name_.length() - 1) {
149             prefix_ = true;
150             name_.pop_back();
151         } else {
152             wildcard_ = true;
153         }
154     }
155 }
156 
Match(const std::string & path) const157 bool Permissions::Match(const std::string& path) const {
158     if (prefix_) return StartsWith(path, name_);
159     if (wildcard_)
160         return fnmatch(name_.c_str(), path.c_str(), no_fnm_pathname_ ? 0 : FNM_PATHNAME) == 0;
161     return path == name_;
162 }
163 
MatchWithSubsystem(const std::string & path,const std::string & subsystem) const164 bool SysfsPermissions::MatchWithSubsystem(const std::string& path,
165                                           const std::string& subsystem) const {
166     std::string path_basename = Basename(path);
167     if (name().find(subsystem) != std::string::npos) {
168         if (Match("/sys/class/" + subsystem + "/" + path_basename)) return true;
169         if (Match("/sys/bus/" + subsystem + "/devices/" + path_basename)) return true;
170     }
171     return Match(path);
172 }
173 
SetPermissions(const std::string & path) const174 void SysfsPermissions::SetPermissions(const std::string& path) const {
175     std::string attribute_file = path + "/" + attribute_;
176     LOG(VERBOSE) << "fixup " << attribute_file << " " << uid() << " " << gid() << " " << std::oct
177                  << perm();
178 
179     if (access(attribute_file.c_str(), F_OK) == 0) {
180         if (chown(attribute_file.c_str(), uid(), gid()) != 0) {
181             PLOG(ERROR) << "chown(" << attribute_file << ", " << uid() << ", " << gid()
182                         << ") failed";
183         }
184         if (chmod(attribute_file.c_str(), perm()) != 0) {
185             PLOG(ERROR) << "chmod(" << attribute_file << ", " << perm() << ") failed";
186         }
187     }
188 }
189 
190 // Given a path that may start with a platform device, find the parent platform device by finding a
191 // parent directory with a 'subsystem' symlink that points to the platform bus.
192 // If it doesn't start with a platform device, return false
FindPlatformDevice(std::string path,std::string * platform_device_path) const193 bool DeviceHandler::FindPlatformDevice(std::string path, std::string* platform_device_path) const {
194     platform_device_path->clear();
195 
196     // Uevents don't contain the mount point, so we need to add it here.
197     path.insert(0, sysfs_mount_point_);
198 
199     std::string directory = Dirname(path);
200 
201     while (directory != "/" && directory != ".") {
202         std::string subsystem_link_path;
203         if (Realpath(directory + "/subsystem", &subsystem_link_path) &&
204             (subsystem_link_path == sysfs_mount_point_ + "/bus/platform" ||
205              subsystem_link_path == sysfs_mount_point_ + "/bus/amba")) {
206             // We need to remove the mount point that we added above before returning.
207             directory.erase(0, sysfs_mount_point_.size());
208             *platform_device_path = directory;
209             return true;
210         }
211 
212         auto last_slash = path.rfind('/');
213         if (last_slash == std::string::npos) return false;
214 
215         path.erase(last_slash);
216         directory = Dirname(path);
217     }
218 
219     return false;
220 }
221 
FixupSysPermissions(const std::string & upath,const std::string & subsystem) const222 void DeviceHandler::FixupSysPermissions(const std::string& upath,
223                                         const std::string& subsystem) const {
224     // upaths omit the "/sys" that paths in this list
225     // contain, so we prepend it...
226     std::string path = "/sys" + upath;
227 
228     for (const auto& s : sysfs_permissions_) {
229         if (s.MatchWithSubsystem(path, subsystem)) s.SetPermissions(path);
230     }
231 
232     if (!skip_restorecon_ && access(path.c_str(), F_OK) == 0) {
233         LOG(VERBOSE) << "restorecon_recursive: " << path;
234         if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
235             PLOG(ERROR) << "selinux_android_restorecon(" << path << ") failed";
236         }
237     }
238 }
239 
GetDevicePermissions(const std::string & path,const std::vector<std::string> & links) const240 std::tuple<mode_t, uid_t, gid_t> DeviceHandler::GetDevicePermissions(
241     const std::string& path, const std::vector<std::string>& links) const {
242     // Search the perms list in reverse so that ueventd.$hardware can override ueventd.rc.
243     for (auto it = dev_permissions_.crbegin(); it != dev_permissions_.crend(); ++it) {
244         if (it->Match(path) || std::any_of(links.cbegin(), links.cend(),
245                                            [it](const auto& link) { return it->Match(link); })) {
246             return {it->perm(), it->uid(), it->gid()};
247         }
248     }
249     /* Default if nothing found. */
250     return {0600, 0, 0};
251 }
252 
MakeDevice(const std::string & path,bool block,int major,int minor,const std::vector<std::string> & links) const253 void DeviceHandler::MakeDevice(const std::string& path, bool block, int major, int minor,
254                                const std::vector<std::string>& links) const {
255     auto[mode, uid, gid] = GetDevicePermissions(path, links);
256     mode |= (block ? S_IFBLK : S_IFCHR);
257 
258     std::string secontext;
259     if (!SelabelLookupFileContextBestMatch(path, links, mode, &secontext)) {
260         PLOG(ERROR) << "Device '" << path << "' not created; cannot find SELinux label";
261         return;
262     }
263     if (!secontext.empty()) {
264         setfscreatecon(secontext.c_str());
265     }
266 
267     dev_t dev = makedev(major, minor);
268     /* Temporarily change egid to avoid race condition setting the gid of the
269      * device node. Unforunately changing the euid would prevent creation of
270      * some device nodes, so the uid has to be set with chown() and is still
271      * racy. Fixing the gid race at least fixed the issue with system_server
272      * opening dynamic input devices under the AID_INPUT gid. */
273     if (setegid(gid)) {
274         PLOG(ERROR) << "setegid(" << gid << ") for " << path << " device failed";
275         goto out;
276     }
277     /* If the node already exists update its SELinux label to handle cases when
278      * it was created with the wrong context during coldboot procedure. */
279     if (mknod(path.c_str(), mode, dev) && (errno == EEXIST) && !secontext.empty()) {
280         char* fcon = nullptr;
281         int rc = lgetfilecon(path.c_str(), &fcon);
282         if (rc < 0) {
283             PLOG(ERROR) << "Cannot get SELinux label on '" << path << "' device";
284             goto out;
285         }
286 
287         bool different = fcon != secontext;
288         freecon(fcon);
289 
290         if (different && lsetfilecon(path.c_str(), secontext.c_str())) {
291             PLOG(ERROR) << "Cannot set '" << secontext << "' SELinux label on '" << path
292                         << "' device";
293         }
294     }
295 
296 out:
297     chown(path.c_str(), uid, -1);
298     if (setegid(AID_ROOT)) {
299         PLOG(FATAL) << "setegid(AID_ROOT) failed";
300     }
301 
302     if (!secontext.empty()) {
303         setfscreatecon(nullptr);
304     }
305 }
306 
307 // replaces any unacceptable characters with '_', the
308 // length of the resulting string is equal to the input string
SanitizePartitionName(std::string * string)309 void SanitizePartitionName(std::string* string) {
310     const char* accept =
311         "abcdefghijklmnopqrstuvwxyz"
312         "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
313         "0123456789"
314         "_-.";
315 
316     if (!string) return;
317 
318     std::string::size_type pos = 0;
319     while ((pos = string->find_first_not_of(accept, pos)) != std::string::npos) {
320         (*string)[pos] = '_';
321     }
322 }
323 
GetBlockDeviceSymlinks(const Uevent & uevent) const324 std::vector<std::string> DeviceHandler::GetBlockDeviceSymlinks(const Uevent& uevent) const {
325     std::string device;
326     std::string type;
327     std::string partition;
328     std::string uuid;
329 
330     if (FindPlatformDevice(uevent.path, &device)) {
331         // Skip /devices/platform or /devices/ if present
332         static const std::string devices_platform_prefix = "/devices/platform/";
333         static const std::string devices_prefix = "/devices/";
334 
335         if (StartsWith(device, devices_platform_prefix)) {
336             device = device.substr(devices_platform_prefix.length());
337         } else if (StartsWith(device, devices_prefix)) {
338             device = device.substr(devices_prefix.length());
339         }
340 
341         type = "platform";
342     } else if (FindPciDevicePrefix(uevent.path, &device)) {
343         type = "pci";
344     } else if (FindVbdDevicePrefix(uevent.path, &device)) {
345         type = "vbd";
346     } else if (FindDmDevice(uevent.path, &partition, &uuid)) {
347         std::vector<std::string> symlinks = {"/dev/block/mapper/" + partition};
348         if (!uuid.empty()) {
349             symlinks.emplace_back("/dev/block/mapper/by-uuid/" + uuid);
350         }
351         return symlinks;
352     } else {
353         return {};
354     }
355 
356     std::vector<std::string> links;
357 
358     LOG(VERBOSE) << "found " << type << " device " << device;
359 
360     auto link_path = "/dev/block/" + type + "/" + device;
361 
362     bool is_boot_device = boot_devices_.find(device) != boot_devices_.end();
363     if (!uevent.partition_name.empty()) {
364         std::string partition_name_sanitized(uevent.partition_name);
365         SanitizePartitionName(&partition_name_sanitized);
366         if (partition_name_sanitized != uevent.partition_name) {
367             LOG(VERBOSE) << "Linking partition '" << uevent.partition_name << "' as '"
368                          << partition_name_sanitized << "'";
369         }
370         links.emplace_back(link_path + "/by-name/" + partition_name_sanitized);
371         // Adds symlink: /dev/block/by-name/<partition_name>.
372         if (is_boot_device) {
373             links.emplace_back("/dev/block/by-name/" + partition_name_sanitized);
374         }
375     } else if (is_boot_device) {
376         // If we don't have a partition name but we are a partition on a boot device, create a
377         // symlink of /dev/block/by-name/<device_name> for symmetry.
378         links.emplace_back("/dev/block/by-name/" + uevent.device_name);
379     }
380 
381     auto last_slash = uevent.path.rfind('/');
382     links.emplace_back(link_path + "/" + uevent.path.substr(last_slash + 1));
383 
384     return links;
385 }
386 
RemoveDeviceMapperLinks(const std::string & devpath)387 static void RemoveDeviceMapperLinks(const std::string& devpath) {
388     std::vector<std::string> dirs = {
389             "/dev/block/mapper",
390             "/dev/block/mapper/by-uuid",
391     };
392     for (const auto& dir : dirs) {
393         if (access(dir.c_str(), F_OK) != 0) continue;
394 
395         std::unique_ptr<DIR, decltype(&closedir)> dh(opendir(dir.c_str()), closedir);
396         if (!dh) {
397             PLOG(ERROR) << "Failed to open directory " << dir;
398             continue;
399         }
400 
401         struct dirent* dp;
402         std::string link_path;
403         while ((dp = readdir(dh.get())) != nullptr) {
404             if (dp->d_type != DT_LNK) continue;
405 
406             auto path = dir + "/" + dp->d_name;
407             if (Readlink(path, &link_path) && link_path == devpath) {
408                 unlink(path.c_str());
409             }
410         }
411     }
412 }
413 
HandleDevice(const std::string & action,const std::string & devpath,bool block,int major,int minor,const std::vector<std::string> & links) const414 void DeviceHandler::HandleDevice(const std::string& action, const std::string& devpath, bool block,
415                                  int major, int minor, const std::vector<std::string>& links) const {
416     if (action == "add") {
417         MakeDevice(devpath, block, major, minor, links);
418     }
419 
420     // We don't have full device-mapper information until a change event is fired.
421     if (action == "add" || (action == "change" && StartsWith(devpath, "/dev/block/dm-"))) {
422         for (const auto& link : links) {
423             if (!mkdir_recursive(Dirname(link), 0755)) {
424                 PLOG(ERROR) << "Failed to create directory " << Dirname(link);
425             }
426 
427             if (symlink(devpath.c_str(), link.c_str())) {
428                 if (errno != EEXIST) {
429                     PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link;
430                 } else if (std::string link_path;
431                            Readlink(link, &link_path) && link_path != devpath) {
432                     PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link
433                                 << ", which already links to: " << link_path;
434                 }
435             }
436         }
437     }
438 
439     if (action == "remove") {
440         if (StartsWith(devpath, "/dev/block/dm-")) {
441             RemoveDeviceMapperLinks(devpath);
442         }
443         for (const auto& link : links) {
444             std::string link_path;
445             if (Readlink(link, &link_path) && link_path == devpath) {
446                 unlink(link.c_str());
447             }
448         }
449         unlink(devpath.c_str());
450     }
451 }
452 
HandleAshmemUevent(const Uevent & uevent)453 void DeviceHandler::HandleAshmemUevent(const Uevent& uevent) {
454     if (uevent.device_name == "ashmem") {
455         static const std::string boot_id_path = "/proc/sys/kernel/random/boot_id";
456         std::string boot_id;
457         if (!ReadFileToString(boot_id_path, &boot_id)) {
458             PLOG(ERROR) << "Cannot duplicate ashmem device node. Failed to read " << boot_id_path;
459             return;
460         };
461         boot_id = Trim(boot_id);
462 
463         Uevent dup_ashmem_uevent = uevent;
464         dup_ashmem_uevent.device_name += boot_id;
465         dup_ashmem_uevent.path += boot_id;
466         HandleUevent(dup_ashmem_uevent);
467     }
468 }
469 
HandleUevent(const Uevent & uevent)470 void DeviceHandler::HandleUevent(const Uevent& uevent) {
471   if (uevent.action == "add" || uevent.action == "change" ||
472       uevent.action == "bind" || uevent.action == "online") {
473     FixupSysPermissions(uevent.path, uevent.subsystem);
474   }
475 
476     // if it's not a /dev device, nothing to do
477     if (uevent.major < 0 || uevent.minor < 0) return;
478 
479     std::string devpath;
480     std::vector<std::string> links;
481     bool block = false;
482 
483     if (uevent.subsystem == "block") {
484         block = true;
485         devpath = "/dev/block/" + Basename(uevent.path);
486 
487         if (StartsWith(uevent.path, "/devices")) {
488             links = GetBlockDeviceSymlinks(uevent);
489         }
490     } else if (const auto subsystem =
491                    std::find(subsystems_.cbegin(), subsystems_.cend(), uevent.subsystem);
492                subsystem != subsystems_.cend()) {
493         devpath = subsystem->ParseDevPath(uevent);
494     } else if (uevent.subsystem == "usb") {
495         if (!uevent.device_name.empty()) {
496             devpath = "/dev/" + uevent.device_name;
497         } else {
498             // This imitates the file system that would be created
499             // if we were using devfs instead.
500             // Minors are broken up into groups of 128, starting at "001"
501             int bus_id = uevent.minor / 128 + 1;
502             int device_id = uevent.minor % 128 + 1;
503             devpath = StringPrintf("/dev/bus/usb/%03d/%03d", bus_id, device_id);
504         }
505     } else if (StartsWith(uevent.subsystem, "usb")) {
506         // ignore other USB events
507         return;
508     } else if (uevent.subsystem == "misc" && StartsWith(uevent.device_name, "dm-user/")) {
509         devpath = "/dev/dm-user/" + uevent.device_name.substr(8);
510     } else {
511         devpath = "/dev/" + Basename(uevent.path);
512     }
513 
514     mkdir_recursive(Dirname(devpath), 0755);
515 
516     HandleDevice(uevent.action, devpath, block, uevent.major, uevent.minor, links);
517 
518     // Duplicate /dev/ashmem device and name it /dev/ashmem<boot_id>.
519     // TODO(b/111903542): remove once all users of /dev/ashmem are migrated to libcutils API.
520     HandleAshmemUevent(uevent);
521 }
522 
ColdbootDone()523 void DeviceHandler::ColdbootDone() {
524     skip_restorecon_ = false;
525 }
526 
DeviceHandler(std::vector<Permissions> dev_permissions,std::vector<SysfsPermissions> sysfs_permissions,std::vector<Subsystem> subsystems,std::set<std::string> boot_devices,bool skip_restorecon)527 DeviceHandler::DeviceHandler(std::vector<Permissions> dev_permissions,
528                              std::vector<SysfsPermissions> sysfs_permissions,
529                              std::vector<Subsystem> subsystems, std::set<std::string> boot_devices,
530                              bool skip_restorecon)
531     : dev_permissions_(std::move(dev_permissions)),
532       sysfs_permissions_(std::move(sysfs_permissions)),
533       subsystems_(std::move(subsystems)),
534       boot_devices_(std::move(boot_devices)),
535       skip_restorecon_(skip_restorecon),
536       sysfs_mount_point_("/sys") {}
537 
DeviceHandler()538 DeviceHandler::DeviceHandler()
539     : DeviceHandler(std::vector<Permissions>{}, std::vector<SysfsPermissions>{},
540                     std::vector<Subsystem>{}, std::set<std::string>{}, false) {}
541 
542 }  // namespace init
543 }  // namespace android
544