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