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