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