]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/home/homed-manager.c
homed: make it easier to run multiple instances of homed
[thirdparty/systemd.git] / src / home / homed-manager.c
CommitLineData
70a5db58
LP
1/* SPDX-License-Identifier: LGPL-2.1+ */
2
3#include <grp.h>
4#include <linux/fs.h>
5#include <linux/magic.h>
6#include <openssl/pem.h>
7#include <pwd.h>
8#include <sys/ioctl.h>
9#include <sys/quota.h>
10#include <sys/stat.h>
11
12#include "btrfs-util.h"
13#include "bus-common-errors.h"
14#include "bus-error.h"
ac9f55ed 15#include "bus-log-control-api.h"
70a5db58
LP
16#include "bus-polkit.h"
17#include "clean-ipc.h"
18#include "conf-files.h"
19#include "device-util.h"
20#include "dirent-util.h"
21#include "fd-util.h"
22#include "fileio.h"
23#include "format-util.h"
24#include "fs-util.h"
25#include "gpt.h"
26#include "home-util.h"
c76dd733 27#include "homed-conf.h"
70a5db58
LP
28#include "homed-home-bus.h"
29#include "homed-home.h"
30#include "homed-manager-bus.h"
31#include "homed-manager.h"
32#include "homed-varlink.h"
33#include "io-util.h"
34#include "mkdir.h"
35#include "process-util.h"
36#include "quota-util.h"
37#include "random-util.h"
38#include "socket-util.h"
39#include "stat-util.h"
40#include "strv.h"
41#include "tmpfile-util.h"
42#include "udev-util.h"
43#include "user-record-sign.h"
44#include "user-record-util.h"
45#include "user-record.h"
46#include "user-util.h"
47
48/* Where to look for private/public keys that are used to sign the user records. We are not using
49 * CONF_PATHS_NULSTR() here since we want to insert /var/lib/systemd/home/ in the middle. And we insert that
50 * since we want to auto-generate a persistent private/public key pair if we need to. */
51#define KEY_PATHS_NULSTR \
52 "/etc/systemd/home/\0" \
53 "/run/systemd/home/\0" \
54 "/var/lib/systemd/home/\0" \
55 "/usr/local/lib/systemd/home/\0" \
56 "/usr/lib/systemd/home/\0"
57
58static bool uid_is_home(uid_t uid) {
59 return uid >= HOME_UID_MIN && uid <= HOME_UID_MAX;
60}
61/* Takes a value generated randomly or by hashing and turns it into a UID in the right range */
62
63#define UID_CLAMP_INTO_HOME_RANGE(rnd) (((uid_t) (rnd) % (HOME_UID_MAX - HOME_UID_MIN + 1)) + HOME_UID_MIN)
64
65DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(homes_by_uid_hash_ops, void, trivial_hash_func, trivial_compare_func, Home, home_free);
66DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(homes_by_name_hash_ops, char, string_hash_func, string_compare_func, Home, home_free);
67DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(homes_by_worker_pid_hash_ops, void, trivial_hash_func, trivial_compare_func, Home, home_free);
68DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(homes_by_sysfs_hash_ops, char, path_hash_func, path_compare, Home, home_free);
69
70static int on_home_inotify(sd_event_source *s, const struct inotify_event *event, void *userdata);
71static int manager_gc_images(Manager *m);
72static int manager_enumerate_images(Manager *m);
73static int manager_assess_image(Manager *m, int dir_fd, const char *dir_path, const char *dentry_name);
74static void manager_revalidate_image(Manager *m, Home *h);
75
76static void manager_watch_home(Manager *m) {
77 struct statfs sfs;
78 int r;
79
80 assert(m);
81
82 m->inotify_event_source = sd_event_source_unref(m->inotify_event_source);
83 m->scan_slash_home = false;
84
85 if (statfs("/home/", &sfs) < 0) {
86 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
87 "Failed to statfs() /home/ directory, disabling automatic scanning.");
88 return;
89 }
90
91 if (is_network_fs(&sfs)) {
92 log_info("/home/ is a network file system, disabling automatic scanning.");
93 return;
94 }
95
96 if (is_fs_type(&sfs, AUTOFS_SUPER_MAGIC)) {
97 log_info("/home/ is on autofs, disabling automatic scanning.");
98 return;
99 }
100
101 m->scan_slash_home = true;
102
103 r = sd_event_add_inotify(m->event, &m->inotify_event_source, "/home/", IN_CREATE|IN_CLOSE_WRITE|IN_DELETE_SELF|IN_MOVE_SELF|IN_ONLYDIR|IN_MOVED_TO|IN_MOVED_FROM|IN_DELETE, on_home_inotify, m);
104 if (r < 0)
105 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
106 "Failed to create inotify watch on /home/, ignoring.");
107
108 (void) sd_event_source_set_description(m->inotify_event_source, "home-inotify");
109}
110
111static int on_home_inotify(sd_event_source *s, const struct inotify_event *event, void *userdata) {
112 Manager *m = userdata;
113 const char *e, *n;
114
115 assert(m);
116 assert(event);
117
118 if ((event->mask & (IN_Q_OVERFLOW|IN_MOVE_SELF|IN_DELETE_SELF|IN_IGNORED|IN_UNMOUNT)) != 0) {
119
120 if (FLAGS_SET(event->mask, IN_Q_OVERFLOW))
121 log_debug("/home/ inotify queue overflow, rescanning.");
122 else if (FLAGS_SET(event->mask, IN_MOVE_SELF))
123 log_info("/home/ moved or renamed, recreating watch and rescanning.");
124 else if (FLAGS_SET(event->mask, IN_DELETE_SELF))
125 log_info("/home/ deleted, recreating watch and rescanning.");
126 else if (FLAGS_SET(event->mask, IN_UNMOUNT))
127 log_info("/home/ unmounted, recreating watch and rescanning.");
128 else if (FLAGS_SET(event->mask, IN_IGNORED))
129 log_info("/home/ watch invalidated, recreating watch and rescanning.");
130
131 manager_watch_home(m);
132 (void) manager_gc_images(m);
133 (void) manager_enumerate_images(m);
134 (void) bus_manager_emit_auto_login_changed(m);
135 return 0;
136 }
137
138 /* For the other inotify events, let's ignore all events for file names that don't match our
139 * expectations */
140 if (isempty(event->name))
141 return 0;
142 e = endswith(event->name, FLAGS_SET(event->mask, IN_ISDIR) ? ".homedir" : ".home");
143 if (!e)
144 return 0;
145
146 n = strndupa(event->name, e - event->name);
147 if (!suitable_user_name(n))
148 return 0;
149
150 if ((event->mask & (IN_CREATE|IN_CLOSE_WRITE|IN_MOVED_TO)) != 0) {
151 if (FLAGS_SET(event->mask, IN_CREATE))
152 log_debug("/home/%s has been created, having a look.", event->name);
153 else if (FLAGS_SET(event->mask, IN_CLOSE_WRITE))
154 log_debug("/home/%s has been modified, having a look.", event->name);
155 else if (FLAGS_SET(event->mask, IN_MOVED_TO))
156 log_debug("/home/%s has been moved in, having a look.", event->name);
157
158 (void) manager_assess_image(m, -1, "/home/", event->name);
159 (void) bus_manager_emit_auto_login_changed(m);
160 }
161
162 if ((event->mask & (IN_DELETE|IN_MOVED_FROM|IN_DELETE)) != 0) {
163 Home *h;
164
165 if (FLAGS_SET(event->mask, IN_DELETE))
166 log_debug("/home/%s has been deleted, revalidating.", event->name);
167 else if (FLAGS_SET(event->mask, IN_CLOSE_WRITE))
168 log_debug("/home/%s has been closed after writing, revalidating.", event->name);
169 else if (FLAGS_SET(event->mask, IN_MOVED_FROM))
170 log_debug("/home/%s has been moved away, revalidating.", event->name);
171
172 h = hashmap_get(m->homes_by_name, n);
173 if (h) {
174 manager_revalidate_image(m, h);
175 (void) bus_manager_emit_auto_login_changed(m);
176 }
177 }
178
179 return 0;
180}
181
182int manager_new(Manager **ret) {
183 _cleanup_(manager_freep) Manager *m = NULL;
184 int r;
185
186 assert(ret);
187
c76dd733 188 m = new(Manager, 1);
70a5db58
LP
189 if (!m)
190 return -ENOMEM;
191
c76dd733
LP
192 *m = (Manager) {
193 .default_storage = _USER_STORAGE_INVALID,
194 };
195
196 r = manager_parse_config_file(m);
197 if (r < 0)
198 return r;
199
70a5db58
LP
200 r = sd_event_default(&m->event);
201 if (r < 0)
202 return r;
203
204 r = sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
205 if (r < 0)
206 return r;
207
208 r = sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
209 if (r < 0)
210 return r;
211
212 (void) sd_event_set_watchdog(m->event, true);
213
214 m->homes_by_uid = hashmap_new(&homes_by_uid_hash_ops);
215 if (!m->homes_by_uid)
216 return -ENOMEM;
217
218 m->homes_by_name = hashmap_new(&homes_by_name_hash_ops);
219 if (!m->homes_by_name)
220 return -ENOMEM;
221
222 m->homes_by_worker_pid = hashmap_new(&homes_by_worker_pid_hash_ops);
223 if (!m->homes_by_worker_pid)
224 return -ENOMEM;
225
226 m->homes_by_sysfs = hashmap_new(&homes_by_sysfs_hash_ops);
227 if (!m->homes_by_sysfs)
228 return -ENOMEM;
229
230 *ret = TAKE_PTR(m);
231 return 0;
232}
233
234Manager* manager_free(Manager *m) {
235 assert(m);
236
237 hashmap_free(m->homes_by_uid);
238 hashmap_free(m->homes_by_name);
239 hashmap_free(m->homes_by_worker_pid);
240 hashmap_free(m->homes_by_sysfs);
241
242 m->inotify_event_source = sd_event_source_unref(m->inotify_event_source);
243
244 bus_verify_polkit_async_registry_free(m->polkit_registry);
245
246 sd_bus_flush_close_unref(m->bus);
247 sd_event_unref(m->event);
248
249 m->notify_socket_event_source = sd_event_source_unref(m->notify_socket_event_source);
250 m->device_monitor = sd_device_monitor_unref(m->device_monitor);
251
252 m->deferred_rescan_event_source = sd_event_source_unref(m->deferred_rescan_event_source);
253 m->deferred_gc_event_source = sd_event_source_unref(m->deferred_gc_event_source);
254 m->deferred_auto_login_event_source = sd_event_source_unref(m->deferred_auto_login_event_source);
255
256 if (m->private_key)
257 EVP_PKEY_free(m->private_key);
258
259 hashmap_free(m->public_keys);
260
261 varlink_server_unref(m->varlink_server);
cc9886bc 262 free(m->userdb_service);
70a5db58 263
c76dd733
LP
264 free(m->default_file_system_type);
265
70a5db58
LP
266 return mfree(m);
267}
268
269int manager_verify_user_record(Manager *m, UserRecord *hr) {
270 EVP_PKEY *pkey;
70a5db58
LP
271 int r;
272
273 assert(m);
274 assert(hr);
275
276 if (!m->private_key && hashmap_isempty(m->public_keys)) {
277 r = user_record_has_signature(hr);
278 if (r < 0)
279 return r;
280
281 return r ? -ENOKEY : USER_RECORD_UNSIGNED;
282 }
283
284 /* Is it our own? */
285 if (m->private_key) {
286 r = user_record_verify(hr, m->private_key);
287 switch (r) {
288
289 case USER_RECORD_FOREIGN:
290 /* This record is not signed by this key, but let's see below */
291 break;
292
293 case USER_RECORD_SIGNED: /* Signed by us, but also by others, let's propagate that */
294 case USER_RECORD_SIGNED_EXCLUSIVE: /* Signed by us, and nothing else, ditto */
295 case USER_RECORD_UNSIGNED: /* Not signed at all, ditto */
296 default:
297 return r;
298 }
299 }
300
90e74a66 301 HASHMAP_FOREACH(pkey, m->public_keys) {
70a5db58
LP
302 r = user_record_verify(hr, pkey);
303 switch (r) {
304
305 case USER_RECORD_FOREIGN:
306 /* This record is not signed by this key, but let's see our other keys */
307 break;
308
309 case USER_RECORD_SIGNED: /* It's signed by this key we are happy with, but which is not our own. */
310 case USER_RECORD_SIGNED_EXCLUSIVE:
311 return USER_RECORD_FOREIGN;
312
313 case USER_RECORD_UNSIGNED: /* It's not signed at all */
314 default:
315 return r;
316 }
317 }
318
319 return -ENOKEY;
320}
321
322static int manager_add_home_by_record(
323 Manager *m,
324 const char *name,
325 int dir_fd,
326 const char *fname) {
327
328 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
852640f8 329 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
70a5db58
LP
330 unsigned line, column;
331 int r, is_signed;
20f4a308 332 struct stat st;
70a5db58
LP
333 Home *h;
334
335 assert(m);
336 assert(name);
337 assert(fname);
338
20f4a308
LP
339 if (fstatat(dir_fd, fname, &st, 0) < 0)
340 return log_error_errno(errno, "Failed to stat identity record %s: %m", fname);
341
342 if (!S_ISREG(st.st_mode)) {
343 log_debug("Identity record file %s is not a regular file, ignoring.", fname);
344 return 0;
345 }
346
347 if (st.st_size == 0)
348 goto unlink_this_file;
349
70a5db58
LP
350 r = json_parse_file_at(NULL, dir_fd, fname, JSON_PARSE_SENSITIVE, &v, &line, &column);
351 if (r < 0)
352 return log_error_errno(r, "Failed to parse identity record at %s:%u%u: %m", fname, line, column);
353
20f4a308
LP
354 if (json_variant_is_blank_object(v))
355 goto unlink_this_file;
356
70a5db58
LP
357 hr = user_record_new();
358 if (!hr)
359 return log_oom();
360
b8471926 361 r = user_record_load(hr, v, USER_RECORD_LOAD_REFUSE_SECRET|USER_RECORD_LOG);
70a5db58
LP
362 if (r < 0)
363 return r;
364
365 if (!streq_ptr(hr->user_name, name))
366 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Identity's user name %s does not match file name %s, refusing.", hr->user_name, name);
367
368 is_signed = manager_verify_user_record(m, hr);
369 switch (is_signed) {
370
371 case -ENOKEY:
372 return log_warning_errno(is_signed, "User record %s is not signed by any accepted key, ignoring.", fname);
373 case USER_RECORD_UNSIGNED:
374 return log_warning_errno(SYNTHETIC_ERRNO(EPERM), "User record %s is not signed at all, ignoring.", fname);
375 case USER_RECORD_SIGNED:
376 log_info("User record %s is signed by us (and others), accepting.", fname);
377 break;
378 case USER_RECORD_SIGNED_EXCLUSIVE:
379 log_info("User record %s is signed only by us, accepting.", fname);
380 break;
381 case USER_RECORD_FOREIGN:
382 log_info("User record %s is signed by registered key from others, accepting.", fname);
383 break;
384 default:
385 assert(is_signed < 0);
386 return log_error_errno(is_signed, "Failed to verify signature of user record in %s: %m", fname);
387 }
388
389 h = hashmap_get(m->homes_by_name, name);
390 if (h) {
391 r = home_set_record(h, hr);
392 if (r < 0)
393 return log_error_errno(r, "Failed to update home record for %s: %m", name);
394
395 /* If we acquired a record now for a previously unallocated entry, then reset the state. This
396 * makes sure home_get_state() will check for the availability of the image file dynamically
162392b7 397 * in order to detect to distinguish HOME_INACTIVE and HOME_ABSENT. */
70a5db58
LP
398 if (h->state == HOME_UNFIXATED)
399 h->state = _HOME_STATE_INVALID;
400 } else {
401 r = home_new(m, hr, NULL, &h);
402 if (r < 0)
403 return log_error_errno(r, "Failed to allocate new home object: %m");
404
405 log_info("Added registered home for user %s.", hr->user_name);
406 }
407
408 /* Only entries we exclusively signed are writable to us, hence remember the result */
409 h->signed_locally = is_signed == USER_RECORD_SIGNED_EXCLUSIVE;
410
411 return 1;
20f4a308
LP
412
413unlink_this_file:
414 /* If this is an empty file, then let's just remove it. An empty file is not useful in any case, and
415 * apparently xfs likes to leave empty files around when not unmounted cleanly (see
416 * https://github.com/systemd/systemd/issues/15178 for example). Note that we don't delete non-empty
417 * files even if they are invalid, because that's just too risky, we might delete data the user still
418 * needs. But empty files are never useful, hence let's just remove them. */
419
420 if (unlinkat(dir_fd, fname, 0) < 0)
421 return log_error_errno(errno, "Failed to remove empty user record file %s: %m", fname);
422
423 log_notice("Discovered empty user record file /var/lib/systemd/home/%s, removed automatically.", fname);
424 return 0;
70a5db58
LP
425}
426
427static int manager_enumerate_records(Manager *m) {
428 _cleanup_closedir_ DIR *d = NULL;
429 struct dirent *de;
430
431 assert(m);
432
433 d = opendir("/var/lib/systemd/home/");
434 if (!d)
435 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
436 "Failed to open /var/lib/systemd/home/: %m");
437
438 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read record directory: %m")) {
439 _cleanup_free_ char *n = NULL;
440 const char *e;
441
442 if (!dirent_is_file(de))
443 continue;
444
445 e = endswith(de->d_name, ".identity");
446 if (!e)
447 continue;
448
449 n = strndup(de->d_name, e - de->d_name);
450 if (!n)
451 return log_oom();
452
453 if (!suitable_user_name(n))
454 continue;
455
456 (void) manager_add_home_by_record(m, n, dirfd(d), de->d_name);
457 }
458
459 return 0;
460}
461
462static int search_quota(uid_t uid, const char *exclude_quota_path) {
463 struct stat exclude_st = {};
464 dev_t previous_devno = 0;
465 const char *where;
466 int r;
467
468 /* Checks whether the specified UID owns any files on the files system, but ignore any file system
469 * backing the specified file. The file is used when operating on home directories, where it's OK if
470 * the UID of them already owns files. */
471
472 if (exclude_quota_path && stat(exclude_quota_path, &exclude_st) < 0) {
473 if (errno != ENOENT)
474 return log_warning_errno(errno, "Failed to stat %s, ignoring: %m", exclude_quota_path);
475 }
476
477 /* Check a few usual suspects where regular users might own files. Note that this is by no means
478 * comprehensive, but should cover most cases. Note that in an ideal world every user would be
479 * registered in NSS and avoid our own UID range, but for all other cases, it's a good idea to be
480 * paranoid and check quota if we can. */
481 FOREACH_STRING(where, "/home/", "/tmp/", "/var/", "/var/mail/", "/var/tmp/", "/var/spool/") {
482 struct dqblk req;
483 struct stat st;
484
485 if (stat(where, &st) < 0) {
486 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
487 "Failed to stat %s, ignoring: %m", where);
488 continue;
489 }
490
491 if (major(st.st_dev) == 0) {
492 log_debug("Directory %s is not on a real block device, not checking quota for UID use.", where);
493 continue;
494 }
495
496 if (st.st_dev == exclude_st.st_dev) { /* If an exclude path is specified, then ignore quota
497 * reported on the same block device as that path. */
498 log_debug("Directory %s is where the home directory is located, not checking quota for UID use.", where);
499 continue;
500 }
501
502 if (st.st_dev == previous_devno) { /* Does this directory have the same devno as the previous
503 * one we tested? If so, there's no point in testing this
504 * again. */
505 log_debug("Directory %s is on same device as previous tested directory, not checking quota for UID use a second time.", where);
506 continue;
507 }
508
509 previous_devno = st.st_dev;
510
511 r = quotactl_devno(QCMD_FIXED(Q_GETQUOTA, USRQUOTA), st.st_dev, uid, &req);
512 if (r < 0) {
513 if (ERRNO_IS_NOT_SUPPORTED(r))
514 log_debug_errno(r, "No UID quota support on %s, ignoring.", where);
5e5e11b8
LP
515 else if (ERRNO_IS_PRIVILEGE(r))
516 log_debug_errno(r, "UID quota support for %s prohibited, ignoring.", where);
70a5db58 517 else
1a53adb3 518 log_warning_errno(r, "Failed to query quota on %s, ignoring: %m", where);
70a5db58
LP
519
520 continue;
521 }
522
523 if ((FLAGS_SET(req.dqb_valid, QIF_SPACE) && req.dqb_curspace > 0) ||
524 (FLAGS_SET(req.dqb_valid, QIF_INODES) && req.dqb_curinodes > 0)) {
525 log_debug_errno(errno, "Quota reports UID " UID_FMT " occupies disk space on %s.", uid, where);
526 return 1;
527 }
528 }
529
530 return 0;
531}
532
533static int manager_acquire_uid(
534 Manager *m,
535 uid_t start_uid,
536 const char *user_name,
537 const char *exclude_quota_path,
538 uid_t *ret) {
539
540 static const uint8_t hash_key[] = {
541 0xa3, 0xb8, 0x82, 0x69, 0x9a, 0x71, 0xf7, 0xa9,
542 0xe0, 0x7c, 0xf6, 0xf1, 0x21, 0x69, 0xd2, 0x1e
543 };
544
545 enum {
546 PHASE_SUGGESTED,
547 PHASE_HASHED,
548 PHASE_RANDOM
549 } phase = PHASE_SUGGESTED;
550
551 unsigned n_tries = 100;
552 int r;
553
554 assert(m);
555 assert(ret);
556
557 for (;;) {
558 struct passwd *pw;
559 struct group *gr;
560 uid_t candidate;
561 Home *other;
562
563 if (--n_tries <= 0)
564 return -EBUSY;
565
566 switch (phase) {
567
568 case PHASE_SUGGESTED:
569 phase = PHASE_HASHED;
570
571 if (!uid_is_home(start_uid))
572 continue;
573
574 candidate = start_uid;
575 break;
576
577 case PHASE_HASHED:
578 phase = PHASE_RANDOM;
579
580 if (!user_name)
581 continue;
582
583 candidate = UID_CLAMP_INTO_HOME_RANGE(siphash24(user_name, strlen(user_name), hash_key));
584 break;
585
586 case PHASE_RANDOM:
587 random_bytes(&candidate, sizeof(candidate));
588 candidate = UID_CLAMP_INTO_HOME_RANGE(candidate);
589 break;
590
591 default:
592 assert_not_reached("unknown phase");
593 }
594
595 other = hashmap_get(m->homes_by_uid, UID_TO_PTR(candidate));
596 if (other) {
597 log_debug("Candidate UID " UID_FMT " already used by another home directory (%s), let's try another.", candidate, other->user_name);
598 continue;
599 }
600
601 pw = getpwuid(candidate);
602 if (pw) {
603 log_debug("Candidate UID " UID_FMT " already registered by another user in NSS (%s), let's try another.", candidate, pw->pw_name);
604 continue;
605 }
606
607 gr = getgrgid((gid_t) candidate);
608 if (gr) {
609 log_debug("Candidate UID " UID_FMT " already registered by another group in NSS (%s), let's try another.", candidate, gr->gr_name);
610 continue;
611 }
612
613 r = search_ipc(candidate, (gid_t) candidate);
614 if (r < 0)
615 continue;
616 if (r > 0) {
617 log_debug_errno(r, "Candidate UID " UID_FMT " already owns IPC objects, let's try another: %m", candidate);
618 continue;
619 }
620
621 r = search_quota(candidate, exclude_quota_path);
622 if (r != 0)
623 continue;
624
625 *ret = candidate;
626 return 0;
627 }
628}
629
630static int manager_add_home_by_image(
631 Manager *m,
632 const char *user_name,
633 const char *realm,
634 const char *image_path,
635 const char *sysfs,
636 UserStorage storage,
637 uid_t start_uid) {
638
639 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
640 uid_t uid;
641 Home *h;
642 int r;
643
644 assert(m);
645
646 assert(m);
647 assert(user_name);
648 assert(image_path);
649 assert(storage >= 0);
650 assert(storage < _USER_STORAGE_MAX);
651
652 h = hashmap_get(m->homes_by_name, user_name);
653 if (h) {
654 bool same;
655
656 if (h->state != HOME_UNFIXATED) {
657 log_debug("Found an image for user %s which already has a record, skipping.", user_name);
658 return 0; /* ignore images that synthesize a user we already have a record for */
659 }
660
661 same = user_record_storage(h->record) == storage;
662 if (same) {
663 if (h->sysfs && sysfs)
664 same = path_equal(h->sysfs, sysfs);
665 else if (!!h->sysfs != !!sysfs)
666 same = false;
667 else {
668 const char *p;
669
670 p = user_record_image_path(h->record);
671 same = p && path_equal(p, image_path);
672 }
673 }
674
675 if (!same) {
80ace4f2 676 log_debug("Found multiple images for user '%s', ignoring image '%s'.", user_name, image_path);
70a5db58
LP
677 return 0;
678 }
679 } else {
680 /* Check NSS, in case there's another user or group by this name */
681 if (getpwnam(user_name) || getgrnam(user_name)) {
682 log_debug("Found an existing user or group by name '%s', ignoring image '%s'.", user_name, image_path);
683 return 0;
684 }
685 }
686
687 if (h && uid_is_valid(h->uid))
688 uid = h->uid;
689 else {
690 r = manager_acquire_uid(m, start_uid, user_name, IN_SET(storage, USER_SUBVOLUME, USER_DIRECTORY, USER_FSCRYPT) ? image_path : NULL, &uid);
691 if (r < 0)
692 return log_warning_errno(r, "Failed to acquire unused UID for %s: %m", user_name);
693 }
694
695 hr = user_record_new();
696 if (!hr)
697 return log_oom();
698
699 r = user_record_synthesize(hr, user_name, realm, image_path, storage, uid, (gid_t) uid);
700 if (r < 0)
701 return log_error_errno(r, "Failed to synthesize home record for %s (image %s): %m", user_name, image_path);
702
703 if (h) {
704 r = home_set_record(h, hr);
705 if (r < 0)
706 return log_error_errno(r, "Failed to update home record for %s: %m", user_name);
707 } else {
708 r = home_new(m, hr, sysfs, &h);
709 if (r < 0)
710 return log_error_errno(r, "Failed to allocate new home object: %m");
711
712 h->state = HOME_UNFIXATED;
713
714 log_info("Discovered new home for user %s through image %s.", user_name, image_path);
715 }
716
717 return 1;
718}
719
720int manager_augment_record_with_uid(
721 Manager *m,
722 UserRecord *hr) {
723
724 const char *exclude_quota_path = NULL;
725 uid_t start_uid = UID_INVALID, uid;
726 int r;
727
728 assert(m);
729 assert(hr);
730
731 if (uid_is_valid(hr->uid))
732 return 0;
733
734 if (IN_SET(hr->storage, USER_CLASSIC, USER_SUBVOLUME, USER_DIRECTORY, USER_FSCRYPT)) {
735 const char * ip;
736
737 ip = user_record_image_path(hr);
738 if (ip) {
739 struct stat st;
740
741 if (stat(ip, &st) < 0) {
742 if (errno != ENOENT)
743 log_warning_errno(errno, "Failed to stat(%s): %m", ip);
744 } else if (uid_is_home(st.st_uid)) {
745 start_uid = st.st_uid;
746 exclude_quota_path = ip;
747 }
748 }
749 }
750
751 r = manager_acquire_uid(m, start_uid, hr->user_name, exclude_quota_path, &uid);
752 if (r < 0)
753 return r;
754
755 log_debug("Acquired new UID " UID_FMT " for %s.", uid, hr->user_name);
756
757 r = user_record_add_binding(
758 hr,
759 _USER_STORAGE_INVALID,
760 NULL,
761 SD_ID128_NULL,
762 SD_ID128_NULL,
763 SD_ID128_NULL,
764 NULL,
765 NULL,
766 UINT64_MAX,
767 NULL,
768 NULL,
769 uid,
770 (gid_t) uid);
771 if (r < 0)
772 return r;
773
774 return 1;
775}
776
777static int manager_assess_image(
778 Manager *m,
779 int dir_fd,
780 const char *dir_path,
781 const char *dentry_name) {
782
783 char *luks_suffix, *directory_suffix;
784 _cleanup_free_ char *path = NULL;
785 struct stat st;
786 int r;
787
788 assert(m);
789 assert(dir_path);
790 assert(dentry_name);
791
792 luks_suffix = endswith(dentry_name, ".home");
793 if (luks_suffix)
794 directory_suffix = NULL;
795 else
796 directory_suffix = endswith(dentry_name, ".homedir");
797
798 /* Early filter out: by name */
799 if (!luks_suffix && !directory_suffix)
800 return 0;
801
802 path = path_join(dir_path, dentry_name);
803 if (!path)
804 return log_oom();
805
806 /* Follow symlinks here, to allow people to link in stuff to make them available locally. */
807 if (dir_fd >= 0)
808 r = fstatat(dir_fd, dentry_name, &st, 0);
809 else
810 r = stat(path, &st);
811 if (r < 0)
812 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
80ace4f2 813 "Failed to stat() directory entry '%s', ignoring: %m", dentry_name);
70a5db58
LP
814
815 if (S_ISREG(st.st_mode)) {
816 _cleanup_free_ char *n = NULL, *user_name = NULL, *realm = NULL;
817
818 if (!luks_suffix)
819 return 0;
820
821 n = strndup(dentry_name, luks_suffix - dentry_name);
822 if (!n)
823 return log_oom();
824
825 r = split_user_name_realm(n, &user_name, &realm);
826 if (r == -EINVAL) /* Not the right format: ignore */
827 return 0;
828 if (r < 0)
829 return log_error_errno(r, "Failed to split image name into user name/realm: %m");
830
831 return manager_add_home_by_image(m, user_name, realm, path, NULL, USER_LUKS, UID_INVALID);
832 }
833
834 if (S_ISDIR(st.st_mode)) {
835 _cleanup_free_ char *n = NULL, *user_name = NULL, *realm = NULL;
836 _cleanup_close_ int fd = -1;
837 UserStorage storage;
838
839 if (!directory_suffix)
840 return 0;
841
842 n = strndup(dentry_name, directory_suffix - dentry_name);
843 if (!n)
844 return log_oom();
845
846 r = split_user_name_realm(n, &user_name, &realm);
847 if (r == -EINVAL) /* Not the right format: ignore */
848 return 0;
849 if (r < 0)
850 return log_error_errno(r, "Failed to split image name into user name/realm: %m");
851
852 if (dir_fd >= 0)
853 fd = openat(dir_fd, dentry_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
854 else
855 fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC);
856 if (fd < 0)
857 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
858 "Failed to open directory '%s', ignoring: %m", path);
859
860 if (fstat(fd, &st) < 0)
861 return log_warning_errno(errno, "Failed to fstat() %s, ignoring: %m", path);
862
863 assert(S_ISDIR(st.st_mode)); /* Must hold, we used O_DIRECTORY above */
864
865 r = btrfs_is_subvol_fd(fd);
866 if (r < 0)
867 return log_warning_errno(errno, "Failed to determine whether %s is a btrfs subvolume: %m", path);
868 if (r > 0)
869 storage = USER_SUBVOLUME;
870 else {
871 struct fscrypt_policy policy;
872
873 if (ioctl(fd, FS_IOC_GET_ENCRYPTION_POLICY, &policy) < 0) {
874
875 if (errno == ENODATA)
876 log_debug_errno(errno, "Determined %s is not fscrypt encrypted.", path);
877 else if (ERRNO_IS_NOT_SUPPORTED(errno))
80ace4f2 878 log_debug_errno(errno, "Determined %s is not fscrypt encrypted because kernel or file system doesn't support it.", path);
70a5db58
LP
879 else
880 log_debug_errno(errno, "FS_IOC_GET_ENCRYPTION_POLICY failed with unexpected error code on %s, ignoring: %m", path);
881
882 storage = USER_DIRECTORY;
883 } else
884 storage = USER_FSCRYPT;
885 }
886
887 return manager_add_home_by_image(m, user_name, realm, path, NULL, storage, st.st_uid);
888 }
889
890 return 0;
891}
892
893int manager_enumerate_images(Manager *m) {
894 _cleanup_closedir_ DIR *d = NULL;
895 struct dirent *de;
896
897 assert(m);
898
899 if (!m->scan_slash_home)
900 return 0;
901
902 d = opendir("/home/");
903 if (!d)
904 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
905 "Failed to open /home/: %m");
906
907 FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read /home/ directory: %m"))
908 (void) manager_assess_image(m, dirfd(d), "/home", de->d_name);
909
910 return 0;
911}
912
913static int manager_connect_bus(Manager *m) {
cc9886bc 914 const char *suffix, *busname;
70a5db58
LP
915 int r;
916
917 assert(m);
918 assert(!m->bus);
919
920 r = sd_bus_default_system(&m->bus);
921 if (r < 0)
922 return log_error_errno(r, "Failed to connect to system bus: %m");
923
cfd508a9 924 r = bus_add_implementation(m->bus, &manager_object, m);
ac9f55ed
LP
925 if (r < 0)
926 return r;
927
cc9886bc
LP
928 suffix = getenv("SYSTEMD_HOME_DEBUG_SUFFIX");
929 if (suffix)
930 busname = strjoina("org.freedesktop.home1.", suffix);
931 else
932 busname = "org.freedesktop.home1";
933
934 r = sd_bus_request_name_async(m->bus, NULL, busname, 0, NULL, NULL);
70a5db58
LP
935 if (r < 0)
936 return log_error_errno(r, "Failed to request name: %m");
937
938 r = sd_bus_attach_event(m->bus, m->event, 0);
939 if (r < 0)
940 return log_error_errno(r, "Failed to attach bus to event loop: %m");
941
942 (void) sd_bus_set_exit_on_disconnect(m->bus, true);
943
944 return 0;
945}
946
947static int manager_bind_varlink(Manager *m) {
cc9886bc 948 const char *suffix, *socket_path;
70a5db58
LP
949 int r;
950
951 assert(m);
952 assert(!m->varlink_server);
953
954 r = varlink_server_new(&m->varlink_server, VARLINK_SERVER_ACCOUNT_UID);
955 if (r < 0)
956 return log_error_errno(r, "Failed to allocate varlink server object: %m");
957
958 varlink_server_set_userdata(m->varlink_server, m);
959
960 r = varlink_server_bind_method_many(
961 m->varlink_server,
962 "io.systemd.UserDatabase.GetUserRecord", vl_method_get_user_record,
963 "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record,
964 "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships);
965 if (r < 0)
966 return log_error_errno(r, "Failed to register varlink methods: %m");
967
968 (void) mkdir_p("/run/systemd/userdb", 0755);
969
cc9886bc
LP
970 /* To make things easier to debug, when working from a homed managed home directory, let's optionally
971 * use a different varlink socket name */
972 suffix = getenv("SYSTEMD_HOME_DEBUG_SUFFIX");
973 if (suffix)
974 socket_path = strjoina("/run/systemd/userdb/io.systemd.Home.", suffix);
975 else
976 socket_path = "/run/systemd/userdb/io.systemd.Home";
977
978 r = varlink_server_listen_address(m->varlink_server, socket_path, 0666);
70a5db58
LP
979 if (r < 0)
980 return log_error_errno(r, "Failed to bind to varlink socket: %m");
981
982 r = varlink_server_attach_event(m->varlink_server, m->event, SD_EVENT_PRIORITY_NORMAL);
983 if (r < 0)
984 return log_error_errno(r, "Failed to attach varlink connection to event loop: %m");
985
cc9886bc
LP
986 assert(!m->userdb_service);
987 m->userdb_service = strdup(basename(socket_path));
988 if (!m->userdb_service)
989 return log_oom();
990
991 /* Avoid recursion */
992 if (setenv("SYSTEMD_BYPASS_USERDB", m->userdb_service, 1) < 0)
993 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to set $SYSTEMD_BYPASS_USERDB: %m");
994
70a5db58
LP
995 return 0;
996}
997
998static ssize_t read_datagram(int fd, struct ucred *ret_sender, void **ret) {
999 _cleanup_free_ void *buffer = NULL;
1000 ssize_t n, m;
1001
1002 assert(fd >= 0);
1003 assert(ret_sender);
1004 assert(ret);
1005
1006 n = next_datagram_size_fd(fd);
1007 if (n < 0)
1008 return n;
1009
1010 buffer = malloc(n + 2);
1011 if (!buffer)
1012 return -ENOMEM;
1013
1014 if (ret_sender) {
fb29cdbe 1015 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control;
70a5db58
LP
1016 bool found_ucred = false;
1017 struct cmsghdr *cmsg;
1018 struct msghdr mh;
1019 struct iovec iov;
1020
1021 /* Pass one extra byte, as a size check */
1022 iov = IOVEC_MAKE(buffer, n + 1);
1023
1024 mh = (struct msghdr) {
1025 .msg_iov = &iov,
1026 .msg_iovlen = 1,
1027 .msg_control = &control,
1028 .msg_controllen = sizeof(control),
1029 };
1030
3691bcf3 1031 m = recvmsg_safe(fd, &mh, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
70a5db58 1032 if (m < 0)
3691bcf3 1033 return m;
70a5db58
LP
1034
1035 cmsg_close_all(&mh);
1036
1037 /* Ensure the size matches what we determined before */
1038 if (m != n)
1039 return -EMSGSIZE;
1040
1041 CMSG_FOREACH(cmsg, &mh)
1042 if (cmsg->cmsg_level == SOL_SOCKET &&
1043 cmsg->cmsg_type == SCM_CREDENTIALS &&
1044 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
1045
1046 memcpy(ret_sender, CMSG_DATA(cmsg), sizeof(struct ucred));
1047 found_ucred = true;
1048 }
1049
1050 if (!found_ucred)
1051 *ret_sender = (struct ucred) {
1052 .pid = 0,
1053 .uid = UID_INVALID,
1054 .gid = GID_INVALID,
1055 };
1056 } else {
1057 m = recv(fd, buffer, n + 1, MSG_DONTWAIT);
1058 if (m < 0)
1059 return -errno;
1060
1061 /* Ensure the size matches what we determined before */
1062 if (m != n)
1063 return -EMSGSIZE;
1064 }
1065
1066 /* For safety reasons: let's always NUL terminate. */
1067 ((char*) buffer)[n] = 0;
1068 *ret = TAKE_PTR(buffer);
1069
1070 return 0;
1071}
1072
1073static int on_notify_socket(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1074 _cleanup_strv_free_ char **l = NULL;
1075 _cleanup_free_ void *datagram = NULL;
1076 struct ucred sender;
1077 Manager *m = userdata;
1078 ssize_t n;
1079 Home *h;
1080
1081 assert(s);
1082 assert(m);
1083
1084 n = read_datagram(fd, &sender, &datagram);
1085 if (IN_SET(n, -EAGAIN, -EINTR))
1086 return 0;
1087 if (n < 0)
1088 return log_error_errno(n, "Failed to read notify datagram: %m");
1089
1090 if (sender.pid <= 0) {
1091 log_warning("Received notify datagram without valid sender PID, ignoring.");
1092 return 0;
1093 }
1094
1095 h = hashmap_get(m->homes_by_worker_pid, PID_TO_PTR(sender.pid));
1096 if (!h) {
162392b7 1097 log_warning("Received notify datagram of unknown process, ignoring.");
70a5db58
LP
1098 return 0;
1099 }
1100
1101 l = strv_split(datagram, "\n");
1102 if (!l)
1103 return log_oom();
1104
1105 home_process_notify(h, l);
1106 return 0;
1107}
1108
1109static int manager_listen_notify(Manager *m) {
1110 _cleanup_close_ int fd = -1;
425d925f
ZJS
1111 union sockaddr_union sa = {
1112 .un.sun_family = AF_UNIX,
1113 .un.sun_path = "/run/systemd/home/notify",
1114 };
cc9886bc 1115 const char *suffix;
70a5db58
LP
1116 int r;
1117
1118 assert(m);
1119 assert(!m->notify_socket_event_source);
1120
cc9886bc
LP
1121 suffix = getenv("SYSTEMD_HOME_DEBUG_SUFFIX");
1122 if (suffix) {
1123 const char *unix_path;
1124
1125 unix_path = strjoina("/run/systemd/home/notify.", suffix);
1126 r = sockaddr_un_set_path(&sa.un, unix_path);
1127 if (r < 0)
1128 return log_error_errno(r, "Socket path %s does not fit in sockaddr_un: %m", unix_path);
1129 }
1130
70a5db58
LP
1131 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
1132 if (fd < 0)
1133 return log_error_errno(errno, "Failed to create listening socket: %m");
1134
70a5db58
LP
1135 (void) mkdir_parents(sa.un.sun_path, 0755);
1136 (void) sockaddr_un_unlink(&sa.un);
1137
1138 if (bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0)
1139 return log_error_errno(errno, "Failed to bind to socket: %m");
1140
1141 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
1142 if (r < 0)
1143 return r;
1144
1145 r = sd_event_add_io(m->event, &m->notify_socket_event_source, fd, EPOLLIN, on_notify_socket, m);
1146 if (r < 0)
1147 return log_error_errno(r, "Failed to allocate event source for notify socket: %m");
1148
1149 (void) sd_event_source_set_description(m->notify_socket_event_source, "notify-socket");
1150
1151 /* Make sure we process sd_notify() before SIGCHLD for any worker, so that we always know the error
1152 * number of a client before it exits. */
1153 r = sd_event_source_set_priority(m->notify_socket_event_source, SD_EVENT_PRIORITY_NORMAL - 5);
1154 if (r < 0)
1155 return log_error_errno(r, "Failed to alter priority of NOTIFY_SOCKET event source: %m");
1156
1157 r = sd_event_source_set_io_fd_own(m->notify_socket_event_source, true);
1158 if (r < 0)
1159 return log_error_errno(r, "Failed to pass ownership of notify socket: %m");
1160
1161 return TAKE_FD(fd);
1162}
1163
1164static int manager_add_device(Manager *m, sd_device *d) {
1165 _cleanup_free_ char *user_name = NULL, *realm = NULL, *node = NULL;
1166 const char *tabletype, *parttype, *partname, *partuuid, *sysfs;
1167 sd_id128_t id;
1168 int r;
1169
1170 assert(m);
1171 assert(d);
1172
1173 r = sd_device_get_syspath(d, &sysfs);
1174 if (r < 0)
1175 return log_error_errno(r, "Failed to acquire sysfs path of device: %m");
1176
1177 r = sd_device_get_property_value(d, "ID_PART_TABLE_TYPE", &tabletype);
1178 if (r == -ENOENT)
1179 return 0;
1180 if (r < 0)
1181 return log_error_errno(r, "Failed to acquire ID_PART_TABLE_TYPE device property, ignoring: %m");
1182
1183 if (!streq(tabletype, "gpt")) {
1184 log_debug("Found partition (%s) on non-GPT table, ignoring.", sysfs);
1185 return 0;
1186 }
1187
1188 r = sd_device_get_property_value(d, "ID_PART_ENTRY_TYPE", &parttype);
1189 if (r == -ENOENT)
1190 return 0;
1191 if (r < 0)
1192 return log_error_errno(r, "Failed to acquire ID_PART_ENTRY_TYPE device property, ignoring: %m");
1193 r = sd_id128_from_string(parttype, &id);
1194 if (r < 0)
1195 return log_debug_errno(r, "Failed to parse ID_PART_ENTRY_TYPE field '%s', ignoring: %m", parttype);
1196 if (!sd_id128_equal(id, GPT_USER_HOME)) {
1197 log_debug("Found partition (%s) we don't care about, ignoring.", sysfs);
1198 return 0;
1199 }
1200
1201 r = sd_device_get_property_value(d, "ID_PART_ENTRY_NAME", &partname);
1202 if (r < 0)
1203 return log_warning_errno(r, "Failed to acquire ID_PART_ENTRY_NAME device property, ignoring: %m");
1204
1205 r = split_user_name_realm(partname, &user_name, &realm);
1206 if (r == -EINVAL)
1207 return log_warning_errno(r, "Found partition with correct partition type but a non-parsable partition name '%s', ignoring.", partname);
1208 if (r < 0)
1209 return log_error_errno(r, "Failed to validate partition name '%s': %m", partname);
1210
1211 r = sd_device_get_property_value(d, "ID_FS_UUID", &partuuid);
1212 if (r < 0)
1213 return log_warning_errno(r, "Failed to acquire ID_FS_UUID device property, ignoring: %m");
1214
1215 r = sd_id128_from_string(partuuid, &id);
1216 if (r < 0)
1217 return log_warning_errno(r, "Failed to parse ID_FS_UUID field '%s', ignoring: %m", partuuid);
1218
1219 if (asprintf(&node, "/dev/disk/by-uuid/" SD_ID128_UUID_FORMAT_STR, SD_ID128_FORMAT_VAL(id)) < 0)
1220 return log_oom();
1221
1222 return manager_add_home_by_image(m, user_name, realm, node, sysfs, USER_LUKS, UID_INVALID);
1223}
1224
1225static int manager_on_device(sd_device_monitor *monitor, sd_device *d, void *userdata) {
1226 Manager *m = userdata;
1227 int r;
1228
1229 assert(m);
1230 assert(d);
1231
1232 if (device_for_action(d, DEVICE_ACTION_REMOVE)) {
1233 const char *sysfs;
1234 Home *h;
1235
1236 r = sd_device_get_syspath(d, &sysfs);
1237 if (r < 0) {
1238 log_warning_errno(r, "Failed to acquire sysfs path from device: %m");
1239 return 0;
1240 }
1241
1242 log_info("block device %s has been removed.", sysfs);
1243
1244 /* Let's see if we previously synthesized a home record from this device, if so, let's just
1245 * revalidate that. Otherwise let's revalidate them all, but asynchronously. */
1246 h = hashmap_get(m->homes_by_sysfs, sysfs);
1247 if (h)
1248 manager_revalidate_image(m, h);
1249 else
1250 manager_enqueue_gc(m, NULL);
1251 } else
1252 (void) manager_add_device(m, d);
1253
1254 (void) bus_manager_emit_auto_login_changed(m);
1255 return 0;
1256}
1257
1258static int manager_watch_devices(Manager *m) {
1259 int r;
1260
1261 assert(m);
1262 assert(!m->device_monitor);
1263
1264 r = sd_device_monitor_new(&m->device_monitor);
1265 if (r < 0)
1266 return log_error_errno(r, "Failed to allocate device monitor: %m");
1267
1268 r = sd_device_monitor_filter_add_match_subsystem_devtype(m->device_monitor, "block", NULL);
1269 if (r < 0)
1270 return log_error_errno(r, "Failed to configure device monitor match: %m");
1271
1272 r = sd_device_monitor_attach_event(m->device_monitor, m->event);
1273 if (r < 0)
1274 return log_error_errno(r, "Failed to attach device monitor to event loop: %m");
1275
1276 r = sd_device_monitor_start(m->device_monitor, manager_on_device, m);
1277 if (r < 0)
1278 return log_error_errno(r, "Failed to start device monitor: %m");
1279
1280 return 0;
1281}
1282
1283static int manager_enumerate_devices(Manager *m) {
1284 _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
1285 sd_device *d;
1286 int r;
1287
1288 assert(m);
1289
1290 r = sd_device_enumerator_new(&e);
1291 if (r < 0)
1292 return r;
1293
1294 r = sd_device_enumerator_add_match_subsystem(e, "block", true);
1295 if (r < 0)
1296 return r;
1297
1298 FOREACH_DEVICE(e, d)
1299 (void) manager_add_device(m, d);
1300
1301 return 0;
1302}
1303
1304static int manager_load_key_pair(Manager *m) {
1305 _cleanup_(fclosep) FILE *f = NULL;
1306 struct stat st;
1307 int r;
1308
1309 assert(m);
1310
1311 if (m->private_key) {
1312 EVP_PKEY_free(m->private_key);
1313 m->private_key = NULL;
1314 }
1315
1316 r = search_and_fopen_nulstr("local.private", "re", NULL, KEY_PATHS_NULSTR, &f);
1317 if (r == -ENOENT)
1318 return 0;
1319 if (r < 0)
1320 return log_error_errno(r, "Failed to read private key file: %m");
1321
1322 if (fstat(fileno(f), &st) < 0)
1323 return log_error_errno(errno, "Failed to stat private key file: %m");
1324
1325 r = stat_verify_regular(&st);
1326 if (r < 0)
1327 return log_error_errno(r, "Private key file is not regular: %m");
1328
1329 if (st.st_uid != 0 || (st.st_mode & 0077) != 0)
1330 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Private key file is readable by more than the root user");
1331
1332 m->private_key = PEM_read_PrivateKey(f, NULL, NULL, NULL);
1333 if (!m->private_key)
1334 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to load private key pair");
1335
1336 log_info("Successfully loaded private key pair.");
1337
1338 return 1;
1339}
1340
1341DEFINE_TRIVIAL_CLEANUP_FUNC(EVP_PKEY_CTX*, EVP_PKEY_CTX_free);
1342
1343static int manager_generate_key_pair(Manager *m) {
1344 _cleanup_(EVP_PKEY_CTX_freep) EVP_PKEY_CTX *ctx = NULL;
1345 _cleanup_(unlink_and_freep) char *temp_public = NULL, *temp_private = NULL;
1346 _cleanup_fclose_ FILE *fpublic = NULL, *fprivate = NULL;
1347 int r;
1348
1349 if (m->private_key) {
1350 EVP_PKEY_free(m->private_key);
1351 m->private_key = NULL;
1352 }
1353
1354 ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_ED25519, NULL);
1355 if (!ctx)
1356 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to allocate Ed25519 key generation context.");
1357
1358 if (EVP_PKEY_keygen_init(ctx) <= 0)
1359 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize Ed25519 key generation context.");
1360
1361 log_info("Generating key pair for signing local user identity records.");
1362
1363 if (EVP_PKEY_keygen(ctx, &m->private_key) <= 0)
1364 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to generate Ed25519 key pair");
1365
1366 log_info("Successfully created Ed25519 key pair.");
1367
1368 (void) mkdir_p("/var/lib/systemd/home", 0755);
1369
1370 /* Write out public key (note that we only do that as a help to the user, we don't make use of this ever */
1371 r = fopen_temporary("/var/lib/systemd/home/local.public", &fpublic, &temp_public);
1372 if (r < 0)
80ace4f2 1373 return log_error_errno(errno, "Failed to open key file for writing: %m");
70a5db58
LP
1374
1375 if (PEM_write_PUBKEY(fpublic, m->private_key) <= 0)
1376 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write public key.");
1377
fa3709c5 1378 r = fflush_sync_and_check(fpublic);
70a5db58
LP
1379 if (r < 0)
1380 return log_error_errno(r, "Failed to write private key: %m");
1381
1382 fpublic = safe_fclose(fpublic);
1383
1384 /* Write out the private key (this actually writes out both private and public, OpenSSL is confusing) */
1385 r = fopen_temporary("/var/lib/systemd/home/local.private", &fprivate, &temp_private);
1386 if (r < 0)
80ace4f2 1387 return log_error_errno(errno, "Failed to open key file for writing: %m");
70a5db58
LP
1388
1389 if (PEM_write_PrivateKey(fprivate, m->private_key, NULL, NULL, 0, NULL, 0) <= 0)
1390 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write private key pair.");
1391
fa3709c5 1392 r = fflush_sync_and_check(fprivate);
70a5db58
LP
1393 if (r < 0)
1394 return log_error_errno(r, "Failed to write private key: %m");
1395
1396 fprivate = safe_fclose(fprivate);
1397
1398 /* Both are written now, move them into place */
1399
1400 if (rename(temp_public, "/var/lib/systemd/home/local.public") < 0)
1401 return log_error_errno(errno, "Failed to move public key file into place: %m");
1402 temp_public = mfree(temp_public);
1403
1404 if (rename(temp_private, "/var/lib/systemd/home/local.private") < 0) {
1405 (void) unlink_noerrno("/var/lib/systemd/home/local.public"); /* try to remove the file we already created */
e8dd54ab 1406 return log_error_errno(errno, "Failed to move private key file into place: %m");
70a5db58
LP
1407 }
1408 temp_private = mfree(temp_private);
1409
fa3709c5
LP
1410 r = fsync_path_at(AT_FDCWD, "/var/lib/systemd/home/");
1411 if (r < 0)
1412 log_warning_errno(r, "Failed to sync /var/lib/systemd/home/, ignoring: %m");
1413
70a5db58
LP
1414 return 1;
1415}
1416
1417int manager_acquire_key_pair(Manager *m) {
1418 int r;
1419
1420 assert(m);
1421
1422 /* Already there? */
1423 if (m->private_key)
1424 return 1;
1425
1426 /* First try to load key off disk */
1427 r = manager_load_key_pair(m);
1428 if (r != 0)
1429 return r;
1430
1431 /* Didn't work, generate a new one */
1432 return manager_generate_key_pair(m);
1433}
1434
1435int manager_sign_user_record(Manager *m, UserRecord *u, UserRecord **ret, sd_bus_error *error) {
1436 int r;
1437
1438 assert(m);
1439 assert(u);
1440 assert(ret);
1441
1442 r = manager_acquire_key_pair(m);
1443 if (r < 0)
1444 return r;
1445 if (r == 0)
1446 return sd_bus_error_setf(error, BUS_ERROR_NO_PRIVATE_KEY, "Can't sign without local key.");
1447
1448 return user_record_sign(u, m->private_key, ret);
1449}
1450
1451DEFINE_PRIVATE_HASH_OPS_FULL(public_key_hash_ops, char, string_hash_func, string_compare_func, free, EVP_PKEY, EVP_PKEY_free);
1452DEFINE_TRIVIAL_CLEANUP_FUNC(EVP_PKEY*, EVP_PKEY_free);
1453
1454static int manager_load_public_key_one(Manager *m, const char *path) {
1455 _cleanup_(EVP_PKEY_freep) EVP_PKEY *pkey = NULL;
1456 _cleanup_fclose_ FILE *f = NULL;
1457 _cleanup_free_ char *fn = NULL;
1458 struct stat st;
1459 int r;
1460
1461 assert(m);
1462
1463 if (streq(basename(path), "local.public")) /* we already loaded the private key, which includes the public one */
1464 return 0;
1465
1466 f = fopen(path, "re");
1467 if (!f) {
1468 if (errno == ENOENT)
1469 return 0;
1470
1471 return log_error_errno(errno, "Failed to open public key %s: %m", path);
1472 }
1473
1474 if (fstat(fileno(f), &st) < 0)
1475 return log_error_errno(errno, "Failed to stat public key %s: %m", path);
1476
1477 r = stat_verify_regular(&st);
1478 if (r < 0)
1479 return log_error_errno(r, "Public key file %s is not a regular file: %m", path);
1480
1481 if (st.st_uid != 0 || (st.st_mode & 0022) != 0)
1482 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Public key file %s is writable by more than the root user, refusing.", path);
1483
1484 r = hashmap_ensure_allocated(&m->public_keys, &public_key_hash_ops);
1485 if (r < 0)
1486 return log_oom();
1487
1488 pkey = PEM_read_PUBKEY(f, &pkey, NULL, NULL);
1489 if (!pkey)
1490 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to parse public key file %s.", path);
1491
1492 fn = strdup(basename(path));
1493 if (!fn)
1494 return log_oom();
1495
1496 r = hashmap_put(m->public_keys, fn, pkey);
1497 if (r < 0)
1498 return log_error_errno(r, "Failed to add public key to set: %m");
1499
1500 TAKE_PTR(fn);
1501 TAKE_PTR(pkey);
1502
1503 return 0;
1504}
1505
1506static int manager_load_public_keys(Manager *m) {
1507 _cleanup_strv_free_ char **files = NULL;
1508 char **i;
1509 int r;
1510
1511 assert(m);
1512
1513 m->public_keys = hashmap_free(m->public_keys);
1514
1515 r = conf_files_list_nulstr(
1516 &files,
1517 ".public",
1518 NULL,
1519 CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED,
1520 KEY_PATHS_NULSTR);
1521 if (r < 0)
1522 return log_error_errno(r, "Failed to assemble list of public key directories: %m");
1523
1524 STRV_FOREACH(i, files)
1525 (void) manager_load_public_key_one(m, *i);
1526
1527 return 0;
1528}
1529
1530int manager_startup(Manager *m) {
1531 int r;
1532
1533 assert(m);
1534
1535 r = manager_listen_notify(m);
1536 if (r < 0)
1537 return r;
1538
1539 r = manager_connect_bus(m);
1540 if (r < 0)
1541 return r;
1542
1543 r = manager_bind_varlink(m);
1544 if (r < 0)
1545 return r;
1546
1547 r = manager_load_key_pair(m); /* only try to load it, don't generate any */
1548 if (r < 0)
1549 return r;
1550
1551 r = manager_load_public_keys(m);
1552 if (r < 0)
1553 return r;
1554
1555 manager_watch_home(m);
1556 (void) manager_watch_devices(m);
1557
1558 (void) manager_enumerate_records(m);
1559 (void) manager_enumerate_images(m);
1560 (void) manager_enumerate_devices(m);
1561
1562 /* Let's clean up home directories whose devices got removed while we were not running */
1563 (void) manager_enqueue_gc(m, NULL);
1564
1565 return 0;
1566}
1567
1568void manager_revalidate_image(Manager *m, Home *h) {
1569 int r;
1570
1571 assert(m);
1572 assert(h);
1573
1574 /* Frees an automatically discovered image, if it's synthetic and its image disappeared. Unmounts any
1575 * image if it's mounted but it's image vanished. */
1576
1577 if (h->current_operation || !ordered_set_isempty(h->pending_operations))
1578 return;
1579
1580 if (h->state == HOME_UNFIXATED) {
1581 r = user_record_test_image_path(h->record);
1582 if (r < 0)
1583 log_warning_errno(r, "Can't determine if image of %s exists, freeing unfixated user: %m", h->user_name);
1584 else if (r == USER_TEST_ABSENT)
1585 log_info("Image for %s disappeared, freeing unfixated user.", h->user_name);
1586 else
1587 return;
1588
1589 home_free(h);
1590
1591 } else if (h->state < 0) {
1592
1593 r = user_record_test_home_directory(h->record);
1594 if (r < 0) {
1595 log_warning_errno(r, "Unable to determine state of home directory, ignoring: %m");
1596 return;
1597 }
1598
1599 if (r == USER_TEST_MOUNTED) {
1600 r = user_record_test_image_path(h->record);
1601 if (r < 0) {
1602 log_warning_errno(r, "Unable to determine state of image path, ignoring: %m");
1603 return;
1604 }
1605
1606 if (r == USER_TEST_ABSENT) {
1607 _cleanup_(operation_unrefp) Operation *o = NULL;
1608
1609 log_notice("Backing image disappeared while home directory %s was mounted, unmounting it forcibly.", h->user_name);
1610 /* Wowza, the thing is mounted, but the device is gone? Act on it. */
1611
1612 r = home_killall(h);
1613 if (r < 0)
1614 log_warning_errno(r, "Failed to kill processes of user %s, ignoring: %m", h->user_name);
1615
1616 /* We enqueue the operation here, after all the home directory might
1617 * currently already run some operation, and we can deactivate it only after
1618 * that's complete. */
1619 o = operation_new(OPERATION_DEACTIVATE_FORCE, NULL);
1620 if (!o) {
1621 log_oom();
1622 return;
1623 }
1624
1625 r = home_schedule_operation(h, o, NULL);
1626 if (r < 0)
1627 log_warning_errno(r, "Failed to enqueue forced home directory %s deactivation, ignoring: %m", h->user_name);
1628 }
1629 }
1630 }
1631}
1632
1633int manager_gc_images(Manager *m) {
1634 Home *h;
1635
1636 assert_se(m);
1637
1638 if (m->gc_focus) {
1639 /* Focus on a specific home */
1640
1641 h = TAKE_PTR(m->gc_focus);
1642 manager_revalidate_image(m, h);
1643 } else {
1644 /* Gc all */
70a5db58 1645
90e74a66 1646 HASHMAP_FOREACH(h, m->homes_by_name)
70a5db58
LP
1647 manager_revalidate_image(m, h);
1648 }
1649
1650 return 0;
1651}
1652
1653static int on_deferred_rescan(sd_event_source *s, void *userdata) {
1654 Manager *m = userdata;
1655
1656 assert(m);
1657
1658 m->deferred_rescan_event_source = sd_event_source_unref(m->deferred_rescan_event_source);
1659
1660 manager_enumerate_devices(m);
1661 manager_enumerate_images(m);
1662 return 0;
1663}
1664
1665int manager_enqueue_rescan(Manager *m) {
1666 int r;
1667
1668 assert(m);
1669
1670 if (m->deferred_rescan_event_source)
1671 return 0;
1672
1673 if (!m->event)
1674 return 0;
1675
1676 if (IN_SET(sd_event_get_state(m->event), SD_EVENT_FINISHED, SD_EVENT_EXITING))
1677 return 0;
1678
1679 r = sd_event_add_defer(m->event, &m->deferred_rescan_event_source, on_deferred_rescan, m);
1680 if (r < 0)
1681 return log_error_errno(r, "Failed to allocate rescan event source: %m");
1682
1683 r = sd_event_source_set_priority(m->deferred_rescan_event_source, SD_EVENT_PRIORITY_IDLE+1);
1684 if (r < 0)
1685 log_warning_errno(r, "Failed to tweak priority of event source, ignoring: %m");
1686
1687 (void) sd_event_source_set_description(m->deferred_rescan_event_source, "deferred-rescan");
1688 return 1;
1689}
1690
1691static int on_deferred_gc(sd_event_source *s, void *userdata) {
1692 Manager *m = userdata;
1693
1694 assert(m);
1695
1696 m->deferred_gc_event_source = sd_event_source_unref(m->deferred_gc_event_source);
1697
1698 manager_gc_images(m);
1699 return 0;
1700}
1701
1702int manager_enqueue_gc(Manager *m, Home *focus) {
1703 int r;
1704
1705 assert(m);
1706
1707 /* This enqueues a request to GC dead homes. It may be called with focus=NULL in which case all homes
1708 * will be scanned, or with the parameter set, in which case only that home is checked. */
1709
1710 if (!m->event)
1711 return 0;
1712
1713 if (IN_SET(sd_event_get_state(m->event), SD_EVENT_FINISHED, SD_EVENT_EXITING))
1714 return 0;
1715
1716 /* If a focus home is specified, then remember to focus just on this home. Otherwise invalidate any
1717 * focus that might be set to look at all homes. */
1718
1719 if (m->deferred_gc_event_source) {
1720 if (m->gc_focus != focus) /* not the same focus, then look at everything */
1721 m->gc_focus = NULL;
1722
1723 return 0;
1724 } else
162392b7 1725 m->gc_focus = focus; /* start focused */
70a5db58
LP
1726
1727 r = sd_event_add_defer(m->event, &m->deferred_gc_event_source, on_deferred_gc, m);
1728 if (r < 0)
80ace4f2 1729 return log_error_errno(r, "Failed to allocate GC event source: %m");
70a5db58
LP
1730
1731 r = sd_event_source_set_priority(m->deferred_gc_event_source, SD_EVENT_PRIORITY_IDLE);
1732 if (r < 0)
1733 log_warning_errno(r, "Failed to tweak priority of event source, ignoring: %m");
1734
1735 (void) sd_event_source_set_description(m->deferred_gc_event_source, "deferred-gc");
1736 return 1;
1737}