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