]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/home/homework.c
homework: support uidmapping in the "directory" backend
[thirdparty/systemd.git] / src / home / homework.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stddef.h>
4 #include <sys/mount.h>
5
6 #include "blockdev-util.h"
7 #include "chown-recursive.h"
8 #include "copy.h"
9 #include "fd-util.h"
10 #include "fileio.h"
11 #include "fs-util.h"
12 #include "home-util.h"
13 #include "homework-cifs.h"
14 #include "homework-directory.h"
15 #include "homework-fido2.h"
16 #include "homework-fscrypt.h"
17 #include "homework-luks.h"
18 #include "homework-mount.h"
19 #include "homework-pkcs11.h"
20 #include "homework.h"
21 #include "libcrypt-util.h"
22 #include "main-func.h"
23 #include "memory-util.h"
24 #include "missing_magic.h"
25 #include "mount-util.h"
26 #include "path-util.h"
27 #include "recovery-key.h"
28 #include "rm-rf.h"
29 #include "stat-util.h"
30 #include "strv.h"
31 #include "sync-util.h"
32 #include "tmpfile-util.h"
33 #include "user-util.h"
34 #include "virt.h"
35
36 /* Make sure a bad password always results in a 3s delay, no matter what */
37 #define BAD_PASSWORD_DELAY_USEC (3 * USEC_PER_SEC)
38
39 void password_cache_free(PasswordCache *cache) {
40 if (!cache)
41 return;
42
43 cache->pkcs11_passwords = strv_free_erase(cache->pkcs11_passwords);
44 cache->fido2_passwords = strv_free_erase(cache->fido2_passwords);
45 }
46
47 int user_record_authenticate(
48 UserRecord *h,
49 UserRecord *secret,
50 PasswordCache *cache,
51 bool strict_verify) {
52
53 bool need_password = false, need_recovery_key = false, need_token = false, need_pin = false,
54 need_protected_authentication_path_permitted = false, need_user_presence_permitted = false,
55 need_user_verification_permitted = false, pin_locked = false, pin_incorrect = false,
56 pin_incorrect_few_tries_left = false, pin_incorrect_one_try_left = false, token_action_timeout = false;
57 int r;
58
59 assert(h);
60 assert(secret);
61
62 /* Tries to authenticate a user record with the supplied secrets. i.e. checks whether at least one
63 * supplied plaintext passwords matches a hashed password field of the user record. Or if a
64 * configured PKCS#11 or FIDO2 token is around and can unlock the record.
65 *
66 * Note that the 'cache' parameter is both an input and output parameter: it contains lists of
67 * configured, decrypted PKCS#11/FIDO2 passwords. We typically have to call this function multiple
68 * times over the course of an operation (think: on login we authenticate the host user record, the
69 * record embedded in the LUKS record and the one embedded in $HOME). Hence we keep a list of
70 * passwords we already decrypted, so that we don't have to do the (slow and potentially interactive)
71 * PKCS#11/FIDO2 dance for the relevant token again and again. */
72
73 /* First, let's see if the supplied plain-text passwords work? */
74 r = user_record_test_password(h, secret);
75 if (r == -ENOKEY)
76 need_password = true;
77 else if (r == -ENXIO)
78 log_debug_errno(r, "User record has no hashed passwords, plaintext passwords not tested.");
79 else if (r < 0)
80 return log_error_errno(r, "Failed to validate password of record: %m");
81 else {
82 log_info("Provided password unlocks user record.");
83 return 1;
84 }
85
86 /* Similar, but test against the recovery keys */
87 r = user_record_test_recovery_key(h, secret);
88 if (r == -ENOKEY)
89 need_recovery_key = true;
90 else if (r == -ENXIO)
91 log_debug_errno(r, "User record has no recovery keys, plaintext passwords not tested against it.");
92 else if (r < 0)
93 return log_error_errno(r, "Failed to validate the recovery key of the record: %m");
94 else {
95 log_info("Provided password is a recovery key that unlocks the user record.");
96 return 1;
97 }
98
99 if (need_password && need_recovery_key)
100 log_info("None of the supplied plaintext passwords unlock the user record's hashed passwords or recovery keys.");
101 else if (need_password)
102 log_info("None of the supplied plaintext passwords unlock the user record's hashed passwords.");
103 else
104 log_info("None of the supplied plaintext passwords unlock the user record's hashed recovery keys.");
105
106 /* Second, test cached PKCS#11 passwords */
107 for (size_t n = 0; n < h->n_pkcs11_encrypted_key; n++) {
108 char **pp;
109
110 STRV_FOREACH(pp, cache->pkcs11_passwords) {
111 r = test_password_one(h->pkcs11_encrypted_key[n].hashed_password, *pp);
112 if (r < 0)
113 return log_error_errno(r, "Failed to check supplied PKCS#11 password: %m");
114 if (r > 0) {
115 log_info("Previously acquired PKCS#11 password unlocks user record.");
116 return 1;
117 }
118 }
119 }
120
121 /* Third, test cached FIDO2 passwords */
122 for (size_t n = 0; n < h->n_fido2_hmac_salt; n++) {
123 char **pp;
124
125 /* See if any of the previously calculated passwords work */
126 STRV_FOREACH(pp, cache->fido2_passwords) {
127 r = test_password_one(h->fido2_hmac_salt[n].hashed_password, *pp);
128 if (r < 0)
129 return log_error_errno(r, "Failed to check supplied FIDO2 password: %m");
130 if (r > 0) {
131 log_info("Previously acquired FIDO2 password unlocks user record.");
132 return 1;
133 }
134 }
135 }
136
137 /* Fourth, let's see if any of the PKCS#11 security tokens are plugged in and help us */
138 for (size_t n = 0; n < h->n_pkcs11_encrypted_key; n++) {
139 #if HAVE_P11KIT
140 _cleanup_(pkcs11_callback_data_release) struct pkcs11_callback_data data = {
141 .user_record = h,
142 .secret = secret,
143 .encrypted_key = h->pkcs11_encrypted_key + n,
144 };
145
146 r = pkcs11_find_token(data.encrypted_key->uri, pkcs11_callback, &data);
147 switch (r) {
148 case -EAGAIN:
149 need_token = true;
150 break;
151 case -ENOANO:
152 need_pin = true;
153 break;
154 case -ERFKILL:
155 need_protected_authentication_path_permitted = true;
156 break;
157 case -EOWNERDEAD:
158 pin_locked = true;
159 break;
160 case -ENOLCK:
161 pin_incorrect = true;
162 break;
163 case -ETOOMANYREFS:
164 pin_incorrect = pin_incorrect_few_tries_left = true;
165 break;
166 case -EUCLEAN:
167 pin_incorrect = pin_incorrect_few_tries_left = pin_incorrect_one_try_left = true;
168 break;
169 default:
170 if (r < 0)
171 return r;
172
173 r = test_password_one(data.encrypted_key->hashed_password, data.decrypted_password);
174 if (r < 0)
175 return log_error_errno(r, "Failed to test PKCS#11 password: %m");
176 if (r == 0)
177 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Configured PKCS#11 security token %s does not decrypt encrypted key correctly.", data.encrypted_key->uri);
178
179 log_info("Decrypted password from PKCS#11 security token %s unlocks user record.", data.encrypted_key->uri);
180
181 r = strv_extend(&cache->pkcs11_passwords, data.decrypted_password);
182 if (r < 0)
183 return log_oom();
184
185 return 1;
186 }
187 #else
188 need_token = true;
189 break;
190 #endif
191 }
192
193 /* Fifth, let's see if any of the FIDO2 security tokens are plugged in and help us */
194 for (size_t n = 0; n < h->n_fido2_hmac_salt; n++) {
195 #if HAVE_LIBFIDO2
196 _cleanup_(erase_and_freep) char *decrypted_password = NULL;
197
198 r = fido2_use_token(h, secret, h->fido2_hmac_salt + n, &decrypted_password);
199 switch (r) {
200 case -EAGAIN:
201 need_token = true;
202 break;
203 case -ENOANO:
204 need_pin = true;
205 break;
206 case -EOWNERDEAD:
207 pin_locked = true;
208 break;
209 case -ENOLCK:
210 pin_incorrect = true;
211 break;
212 case -EMEDIUMTYPE:
213 need_user_presence_permitted = true;
214 break;
215 case -ENOCSI:
216 need_user_verification_permitted = true;
217 break;
218 case -ENOSTR:
219 token_action_timeout = true;
220 break;
221 default:
222 if (r < 0)
223 return r;
224
225 r = test_password_one(h->fido2_hmac_salt[n].hashed_password, decrypted_password);
226 if (r < 0)
227 return log_error_errno(r, "Failed to test FIDO2 password: %m");
228 if (r == 0)
229 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Configured FIDO2 security token does not decrypt encrypted key correctly.");
230
231 log_info("Decrypted password from FIDO2 security token unlocks user record.");
232
233 r = strv_extend(&cache->fido2_passwords, decrypted_password);
234 if (r < 0)
235 return log_oom();
236
237 return 1;
238 }
239 #else
240 need_token = true;
241 break;
242 #endif
243 }
244
245 /* Ordered by "relevance", i.e. the most "important" or "interesting" error condition is returned. */
246 if (pin_incorrect_one_try_left)
247 return -EUCLEAN;
248 if (pin_incorrect_few_tries_left)
249 return -ETOOMANYREFS;
250 if (pin_incorrect)
251 return -ENOLCK;
252 if (pin_locked)
253 return -EOWNERDEAD;
254 if (token_action_timeout)
255 return -ENOSTR;
256 if (need_protected_authentication_path_permitted)
257 return -ERFKILL;
258 if (need_user_presence_permitted)
259 return -EMEDIUMTYPE;
260 if (need_user_verification_permitted)
261 return -ENOCSI;
262 if (need_pin)
263 return -ENOANO;
264 if (need_token)
265 return -EBADSLT;
266 if (need_password)
267 return -ENOKEY;
268 if (need_recovery_key)
269 return -EREMOTEIO;
270
271 /* Hmm, this means neither PCKS#11/FIDO2 nor classic hashed passwords or recovery keys were supplied,
272 * we cannot authenticate this reasonably */
273 if (strict_verify)
274 return log_debug_errno(SYNTHETIC_ERRNO(EKEYREVOKED),
275 "No hashed passwords, no recovery keys and no PKCS#11/FIDO2 tokens defined, cannot authenticate user record, refusing.");
276
277 /* If strict verification is off this means we are possibly in the case where we encountered an
278 * unfixated record, i.e. a synthetic one that accordingly lacks any authentication data. In this
279 * case, allow the authentication to pass for now, so that the second (or third) authentication level
280 * (the ones of the user record in the LUKS header or inside the home directory) will then catch
281 * invalid passwords. The second/third authentication always runs in strict verification mode. */
282 log_debug("No hashed passwords, not recovery keys and no PKCS#11 tokens defined in record, cannot authenticate user record. "
283 "Deferring to embedded user record.");
284 return 0;
285 }
286
287 static void drop_caches_now(void) {
288 int r;
289
290 /* Drop file system caches now. See https://www.kernel.org/doc/Documentation/sysctl/vm.txt for
291 * details. We write "2" into /proc/sys/vm/drop_caches to ensure dentries/inodes are flushed, but not
292 * more. */
293
294 r = write_string_file("/proc/sys/vm/drop_caches", "2\n", WRITE_STRING_FILE_DISABLE_BUFFER);
295 if (r < 0)
296 log_warning_errno(r, "Failed to drop caches, ignoring: %m");
297 else
298 log_debug("Dropped caches.");
299 }
300
301 int home_setup_done(HomeSetup *setup) {
302 int r = 0, q;
303
304 assert(setup);
305
306 if (setup->root_fd >= 0) {
307 if (setup->do_offline_fitrim) {
308 q = run_fitrim(setup->root_fd);
309 if (q < 0)
310 r = q;
311 }
312
313 if (syncfs(setup->root_fd) < 0)
314 log_debug_errno(errno, "Failed to synchronize home directory, ignoring: %m");
315
316 setup->root_fd = safe_close(setup->root_fd);
317 }
318
319 if (setup->undo_mount) {
320 q = umount_verbose(LOG_DEBUG, HOME_RUNTIME_WORK_DIR, UMOUNT_NOFOLLOW);
321 if (q < 0)
322 r = q;
323 }
324
325 if (setup->undo_dm && setup->crypt_device && setup->dm_name) {
326 q = sym_crypt_deactivate_by_name(setup->crypt_device, setup->dm_name, 0);
327 if (q < 0)
328 r = q;
329 }
330
331 if (setup->image_fd >= 0) {
332 if (setup->do_offline_fallocate) {
333 q = run_fallocate(setup->image_fd, NULL);
334 if (q < 0)
335 r = q;
336 }
337
338 if (setup->do_mark_clean) {
339 q = run_mark_dirty(setup->image_fd, false);
340 if (q < 0)
341 r = q;
342 }
343
344 setup->image_fd = safe_close(setup->image_fd);
345 }
346
347 setup->undo_mount = false;
348 setup->undo_dm = false;
349 setup->do_offline_fitrim = false;
350 setup->do_offline_fallocate = false;
351 setup->do_mark_clean = false;
352
353 setup->dm_name = mfree(setup->dm_name);
354 setup->dm_node = mfree(setup->dm_node);
355
356 setup->loop = loop_device_unref(setup->loop);
357 if (setup->crypt_device) {
358 sym_crypt_free(setup->crypt_device);
359 setup->crypt_device = NULL;
360 }
361
362 setup->volume_key = erase_and_free(setup->volume_key);
363 setup->volume_key_size = 0;
364
365 if (setup->do_drop_caches)
366 drop_caches_now();
367
368 return r;
369 }
370
371 int home_setup(
372 UserRecord *h,
373 HomeSetupFlags flags,
374 PasswordCache *cache,
375 HomeSetup *setup,
376 UserRecord **ret_header_home) {
377
378 int r;
379
380 assert(h);
381 assert(setup);
382 assert(!setup->loop);
383 assert(!setup->crypt_device);
384 assert(setup->root_fd < 0);
385 assert(!setup->undo_dm);
386 assert(!setup->undo_mount);
387
388 /* Makes a home directory accessible (through the root_fd file descriptor, not by path!). */
389
390 if (!FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED)) /* If we set up the directory, we should also drop caches once we are done */
391 setup->do_drop_caches = setup->do_drop_caches || user_record_drop_caches(h);
392
393 switch (user_record_storage(h)) {
394
395 case USER_LUKS:
396 return home_setup_luks(h, flags, NULL, cache, setup, ret_header_home);
397
398 case USER_SUBVOLUME:
399 case USER_DIRECTORY:
400 r = home_setup_directory(h, setup);
401 break;
402
403 case USER_FSCRYPT:
404 r = home_setup_fscrypt(h, cache, setup);
405 break;
406
407 case USER_CIFS:
408 r = home_setup_cifs(h, flags, setup);
409 break;
410
411 default:
412 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK), "Processing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
413 }
414
415 if (r < 0)
416 return r;
417
418 if (ret_header_home)
419 *ret_header_home = NULL;
420
421 return r;
422 }
423
424 int home_sync_and_statfs(int root_fd, struct statfs *ret) {
425 assert(root_fd >= 0);
426
427 /* Let's sync this to disk, so that the disk space reported by fstatfs() below is accurate (for file
428 * systems such as btrfs where this is determined lazily). */
429
430 if (syncfs(root_fd) < 0)
431 return log_error_errno(errno, "Failed to synchronize file system: %m");
432
433 if (ret)
434 if (fstatfs(root_fd, ret) < 0)
435 return log_error_errno(errno, "Failed to statfs() file system: %m");
436
437 log_info("Synchronized disk.");
438
439 return 0;
440 }
441
442 static int read_identity_file(int root_fd, JsonVariant **ret) {
443 _cleanup_(fclosep) FILE *identity_file = NULL;
444 _cleanup_close_ int identity_fd = -1;
445 unsigned line, column;
446 int r;
447
448 assert(root_fd >= 0);
449 assert(ret);
450
451 identity_fd = openat(root_fd, ".identity", O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_NONBLOCK);
452 if (identity_fd < 0)
453 return log_error_errno(errno, "Failed to open .identity file in home directory: %m");
454
455 r = fd_verify_regular(identity_fd);
456 if (r < 0)
457 return log_error_errno(r, "Embedded identity file is not a regular file, refusing: %m");
458
459 identity_file = take_fdopen(&identity_fd, "r");
460 if (!identity_file)
461 return log_oom();
462
463 r = json_parse_file(identity_file, ".identity", JSON_PARSE_SENSITIVE, ret, &line, &column);
464 if (r < 0)
465 return log_error_errno(r, "[.identity:%u:%u] Failed to parse JSON data: %m", line, column);
466
467 log_info("Read embedded .identity file.");
468
469 return 0;
470 }
471
472 static int write_identity_file(int root_fd, JsonVariant *v, uid_t uid) {
473 _cleanup_(json_variant_unrefp) JsonVariant *normalized = NULL;
474 _cleanup_(fclosep) FILE *identity_file = NULL;
475 _cleanup_close_ int identity_fd = -1;
476 _cleanup_free_ char *fn = NULL;
477 int r;
478
479 assert(root_fd >= 0);
480 assert(v);
481
482 normalized = json_variant_ref(v);
483
484 r = json_variant_normalize(&normalized);
485 if (r < 0)
486 log_warning_errno(r, "Failed to normalize user record, ignoring: %m");
487
488 r = tempfn_random(".identity", NULL, &fn);
489 if (r < 0)
490 return r;
491
492 identity_fd = openat(root_fd, fn, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
493 if (identity_fd < 0)
494 return log_error_errno(errno, "Failed to create .identity file in home directory: %m");
495
496 identity_file = take_fdopen(&identity_fd, "w");
497 if (!identity_file) {
498 r = log_oom();
499 goto fail;
500 }
501
502 json_variant_dump(normalized, JSON_FORMAT_PRETTY, identity_file, NULL);
503
504 r = fflush_and_check(identity_file);
505 if (r < 0) {
506 log_error_errno(r, "Failed to write .identity file: %m");
507 goto fail;
508 }
509
510 if (fchown(fileno(identity_file), uid, uid) < 0) {
511 log_error_errno(r, "Failed to change ownership of identity file: %m");
512 goto fail;
513 }
514
515 if (renameat(root_fd, fn, root_fd, ".identity") < 0) {
516 r = log_error_errno(errno, "Failed to move identity file into place: %m");
517 goto fail;
518 }
519
520 log_info("Wrote embedded .identity file.");
521
522 return 0;
523
524 fail:
525 (void) unlinkat(root_fd, fn, 0);
526 return r;
527 }
528
529 int home_load_embedded_identity(
530 UserRecord *h,
531 int root_fd,
532 UserRecord *header_home,
533 UserReconcileMode mode,
534 PasswordCache *cache,
535 UserRecord **ret_embedded_home,
536 UserRecord **ret_new_home) {
537
538 _cleanup_(user_record_unrefp) UserRecord *embedded_home = NULL, *intermediate_home = NULL, *new_home = NULL;
539 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
540 int r;
541
542 assert(h);
543 assert(root_fd >= 0);
544
545 r = read_identity_file(root_fd, &v);
546 if (r < 0)
547 return r;
548
549 embedded_home = user_record_new();
550 if (!embedded_home)
551 return log_oom();
552
553 r = user_record_load(embedded_home, v, USER_RECORD_LOAD_EMBEDDED|USER_RECORD_PERMISSIVE);
554 if (r < 0)
555 return r;
556
557 if (!user_record_compatible(h, embedded_home))
558 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG), "Embedded home record not compatible with host record, refusing.");
559
560 /* Insist that credentials the user supplies also unlocks any embedded records. */
561 r = user_record_authenticate(embedded_home, h, cache, /* strict_verify= */ true);
562 if (r < 0)
563 return r;
564 assert(r > 0); /* Insist that a password was verified */
565
566 /* At this point we have three records to deal with:
567 *
568 * · The record we got passed from the host
569 * · The record included in the LUKS header (only if LUKS is used)
570 * · The record in the home directory itself (~.identity)
571 *
572 * Now we have to reconcile all three, and let the newest one win. */
573
574 if (header_home) {
575 /* Note we relax the requirements here. Instead of insisting that the host record is strictly
576 * newer, let's also be OK if its equally new. If it is, we'll however insist that the
577 * embedded record must be newer, so that we update at least one of the two. */
578
579 r = user_record_reconcile(h, header_home, mode == USER_RECONCILE_REQUIRE_NEWER ? USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL : mode, &intermediate_home);
580 if (r == -EREMCHG) /* this was supposed to be checked earlier already, but let's check this again */
581 return log_error_errno(r, "Identity stored on host and in header don't match, refusing.");
582 if (r == -ESTALE)
583 return log_error_errno(r, "Embedded identity record is newer than supplied record, refusing.");
584 if (r < 0)
585 return log_error_errno(r, "Failed to reconcile host and header identities: %m");
586 if (r == USER_RECONCILE_EMBEDDED_WON)
587 log_info("Reconciling header user identity completed (header version was newer).");
588 else if (r == USER_RECONCILE_HOST_WON) {
589 log_info("Reconciling header user identity completed (host version was newer).");
590
591 if (mode == USER_RECONCILE_REQUIRE_NEWER) /* Host version is newer than the header
592 * version, hence we'll update
593 * something. This means we can relax the
594 * requirements on the embedded
595 * identity. */
596 mode = USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL;
597 } else {
598 assert(r == USER_RECONCILE_IDENTICAL);
599 log_info("Reconciling user identities completed (host and header version were identical).");
600 }
601
602 h = intermediate_home;
603 }
604
605 r = user_record_reconcile(h, embedded_home, mode, &new_home);
606 if (r == -EREMCHG)
607 return log_error_errno(r, "Identity stored on host and in home don't match, refusing.");
608 if (r == -ESTALE)
609 return log_error_errno(r, "Embedded identity record is equally new or newer than supplied record, refusing.");
610 if (r < 0)
611 return log_error_errno(r, "Failed to reconcile host and embedded identities: %m");
612 if (r == USER_RECONCILE_EMBEDDED_WON)
613 log_info("Reconciling embedded user identity completed (embedded version was newer).");
614 else if (r == USER_RECONCILE_HOST_WON)
615 log_info("Reconciling embedded user identity completed (host version was newer).");
616 else {
617 assert(r == USER_RECONCILE_IDENTICAL);
618 log_info("Reconciling embedded user identity completed (host and embedded version were identical).");
619 }
620
621 if (ret_embedded_home)
622 *ret_embedded_home = TAKE_PTR(embedded_home);
623
624 if (ret_new_home)
625 *ret_new_home = TAKE_PTR(new_home);
626
627 return 0;
628 }
629
630 int home_store_embedded_identity(UserRecord *h, int root_fd, uid_t uid, UserRecord *old_home) {
631 _cleanup_(user_record_unrefp) UserRecord *embedded = NULL;
632 int r;
633
634 assert(h);
635 assert(root_fd >= 0);
636 assert(uid_is_valid(uid));
637
638 r = user_record_clone(h, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &embedded);
639 if (r < 0)
640 return log_error_errno(r, "Failed to determine new embedded record: %m");
641
642 if (old_home && user_record_equal(old_home, embedded)) {
643 log_debug("Not updating embedded home record.");
644 return 0;
645 }
646
647 /* The identity has changed, let's update it in the image */
648 r = write_identity_file(root_fd, embedded->json, h->uid);
649 if (r < 0)
650 return r;
651
652 return 1;
653 }
654
655 static const char *file_system_type_fd(int fd) {
656 struct statfs sfs;
657
658 assert(fd >= 0);
659
660 if (fstatfs(fd, &sfs) < 0) {
661 log_debug_errno(errno, "Failed to statfs(): %m");
662 return NULL;
663 }
664
665 if (is_fs_type(&sfs, XFS_SB_MAGIC))
666 return "xfs";
667 if (is_fs_type(&sfs, EXT4_SUPER_MAGIC))
668 return "ext4";
669 if (is_fs_type(&sfs, BTRFS_SUPER_MAGIC))
670 return "btrfs";
671
672 return NULL;
673 }
674
675 int home_extend_embedded_identity(UserRecord *h, UserRecord *used, HomeSetup *setup) {
676 int r;
677
678 assert(h);
679 assert(used);
680 assert(setup);
681
682 r = user_record_add_binding(
683 h,
684 user_record_storage(used),
685 user_record_image_path(used),
686 setup->found_partition_uuid,
687 setup->found_luks_uuid,
688 setup->found_fs_uuid,
689 setup->crypt_device ? sym_crypt_get_cipher(setup->crypt_device) : NULL,
690 setup->crypt_device ? sym_crypt_get_cipher_mode(setup->crypt_device) : NULL,
691 setup->crypt_device ? luks_volume_key_size_convert(setup->crypt_device) : UINT64_MAX,
692 file_system_type_fd(setup->root_fd),
693 user_record_home_directory(used),
694 used->uid,
695 (gid_t) used->uid);
696 if (r < 0)
697 return log_error_errno(r, "Failed to update binding in record: %m");
698
699 return 0;
700 }
701
702 static int chown_recursive_directory(int root_fd, uid_t uid) {
703 int r;
704
705 assert(root_fd >= 0);
706 assert(uid_is_valid(uid));
707
708 r = fd_chown_recursive(root_fd, uid, (gid_t) uid, 0777);
709 if (r < 0)
710 return log_error_errno(r, "Failed to change ownership of files and directories: %m");
711 if (r == 0)
712 log_info("Recursive changing of ownership not necessary, skipped.");
713 else
714 log_info("Recursive changing of ownership completed.");
715
716 return 0;
717 }
718
719 int home_maybe_shift_uid(
720 UserRecord *h,
721 HomeSetup *setup) {
722
723 _cleanup_close_ int mount_fd = -1;
724 struct stat st;
725
726 assert(h);
727 assert(setup);
728 assert(setup->root_fd >= 0);
729
730 if (fstat(setup->root_fd, &st) < 0)
731 return log_error_errno(errno, "Failed to stat() home directory: %m");
732
733 /* Let's shift UIDs of this mount. Hopefully this makes the later chowning unnecessary. (Note that we
734 * also prefer to do UID mapping even if the UID already matches our goal UID. That's because we want
735 * to leave UIDs in the homed managed range unmapped.) */
736 (void) home_shift_uid(setup->root_fd, NULL, st.st_uid, h->uid, &mount_fd);
737
738 /* If this worked, then we'll have a reference to the mount now, which we can also use like an O_PATH
739 * fd to the new dir. Let's convert it into a proper O_DIRECTORY fd. */
740 if (mount_fd >= 0) {
741 safe_close(setup->root_fd);
742
743 setup->root_fd = fd_reopen(mount_fd, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
744 if (setup->root_fd < 0)
745 return log_error_errno(setup->root_fd, "Failed to convert mount fd into regular directory fd: %m");
746 }
747
748 return 0;
749 }
750
751 int home_refresh(
752 UserRecord *h,
753 HomeSetup *setup,
754 UserRecord *header_home,
755 PasswordCache *cache,
756 struct statfs *ret_statfs,
757 UserRecord **ret_new_home) {
758
759 _cleanup_(user_record_unrefp) UserRecord *embedded_home = NULL, *new_home = NULL;
760 int r;
761
762 assert(h);
763 assert(setup);
764 assert(ret_new_home);
765
766 /* When activating a home directory, does the identity work: loads the identity from the $HOME
767 * directory, reconciles it with our idea, chown()s everything. */
768
769 r = home_load_embedded_identity(h, setup->root_fd, header_home, USER_RECONCILE_ANY, cache, &embedded_home, &new_home);
770 if (r < 0)
771 return r;
772
773 r = home_maybe_shift_uid(h, setup);
774 if (r < 0)
775 return r;
776
777 r = home_store_header_identity_luks(new_home, setup, header_home);
778 if (r < 0)
779 return r;
780
781 r = home_store_embedded_identity(new_home, setup->root_fd, h->uid, embedded_home);
782 if (r < 0)
783 return r;
784
785 r = chown_recursive_directory(setup->root_fd, h->uid);
786 if (r < 0)
787 return r;
788
789 r = home_sync_and_statfs(setup->root_fd, ret_statfs);
790 if (r < 0)
791 return r;
792
793 *ret_new_home = TAKE_PTR(new_home);
794 return 0;
795 }
796
797 static int home_activate(UserRecord *h, UserRecord **ret_home) {
798 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
799 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
800 _cleanup_(password_cache_free) PasswordCache cache = {};
801 int r;
802
803 assert(h);
804
805 if (!h->user_name)
806 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, refusing.");
807 if (!uid_is_valid(h->uid))
808 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
809 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
810 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Activating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
811
812 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
813 if (r < 0)
814 return r;
815
816 r = user_record_test_home_directory_and_warn(h);
817 if (r < 0)
818 return r;
819 if (r == USER_TEST_MOUNTED)
820 return log_error_errno(SYNTHETIC_ERRNO(EALREADY), "Home directory %s is already mounted, refusing.", user_record_home_directory(h));
821
822 r = user_record_test_image_path_and_warn(h);
823 if (r < 0)
824 return r;
825 if (r == USER_TEST_ABSENT)
826 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Image path %s is missing, refusing.", user_record_image_path(h));
827
828 switch (user_record_storage(h)) {
829
830 case USER_LUKS:
831 r = home_activate_luks(h, &setup, &cache, &new_home);
832 if (r < 0)
833 return r;
834
835 break;
836
837 case USER_SUBVOLUME:
838 case USER_DIRECTORY:
839 case USER_FSCRYPT:
840 r = home_activate_directory(h, &setup, &cache, &new_home);
841 if (r < 0)
842 return r;
843
844 break;
845
846 case USER_CIFS:
847 r = home_activate_cifs(h, &setup, &cache, &new_home);
848 if (r < 0)
849 return r;
850
851 break;
852
853 default:
854 assert_not_reached();
855 }
856
857 /* Note that the returned object might either be a reference to an updated version of the existing
858 * home object, or a reference to a newly allocated home object. The caller has to be able to deal
859 * with both, and consider the old object out-of-date. */
860 if (user_record_equal(h, new_home)) {
861 *ret_home = NULL;
862 return 0; /* no identity change */
863 }
864
865 *ret_home = TAKE_PTR(new_home);
866 return 1; /* identity updated */
867 }
868
869 static int home_deactivate(UserRecord *h, bool force) {
870 bool done = false;
871 int r;
872
873 assert(h);
874
875 if (!h->user_name)
876 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
877 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
878 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Deactivating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
879
880 r = user_record_test_home_directory_and_warn(h);
881 if (r < 0)
882 return r;
883 if (r == USER_TEST_MOUNTED) {
884 if (user_record_storage(h) == USER_LUKS) {
885 r = home_trim_luks(h);
886 if (r < 0)
887 return r;
888 }
889
890 /* Sync explicitly, so that the drop caches logic below can work as documented */
891 r = syncfs_path(AT_FDCWD, user_record_home_directory(h));
892 if (r < 0)
893 log_debug_errno(r, "Failed to synchronize home directory, ignoring: %m");
894 else
895 log_info("Syncing completed.");
896
897 if (umount2(user_record_home_directory(h), UMOUNT_NOFOLLOW | (force ? MNT_FORCE|MNT_DETACH : 0)) < 0)
898 return log_error_errno(errno, "Failed to unmount %s: %m", user_record_home_directory(h));
899
900 log_info("Unmounting completed.");
901 done = true;
902 } else
903 log_info("Directory %s is already unmounted.", user_record_home_directory(h));
904
905 if (user_record_storage(h) == USER_LUKS) {
906 r = home_deactivate_luks(h);
907 if (r < 0)
908 return r;
909 if (r > 0)
910 done = true;
911 }
912
913 if (!done)
914 return log_error_errno(SYNTHETIC_ERRNO(ENOEXEC), "Home is not active.");
915
916 if (user_record_drop_caches(h))
917 drop_caches_now();
918
919 log_info("Everything completed.");
920 return 0;
921 }
922
923 static int copy_skel(int root_fd, const char *skel) {
924 int r;
925
926 assert(root_fd >= 0);
927
928 r = copy_tree_at(AT_FDCWD, skel, root_fd, ".", UID_INVALID, GID_INVALID, COPY_MERGE|COPY_REPLACE);
929 if (r == -ENOENT) {
930 log_info("Skeleton directory %s missing, ignoring.", skel);
931 return 0;
932 }
933 if (r < 0)
934 return log_error_errno(r, "Failed to copy in %s: %m", skel);
935
936 log_info("Copying in %s completed.", skel);
937 return 0;
938 }
939
940 static int change_access_mode(int root_fd, mode_t m) {
941 assert(root_fd >= 0);
942
943 if (fchmod(root_fd, m) < 0)
944 return log_error_errno(errno, "Failed to change access mode of top-level directory: %m");
945
946 log_info("Changed top-level directory access mode to 0%o.", m);
947 return 0;
948 }
949
950 int home_populate(UserRecord *h, int dir_fd) {
951 int r;
952
953 assert(h);
954 assert(dir_fd >= 0);
955
956 r = copy_skel(dir_fd, user_record_skeleton_directory(h));
957 if (r < 0)
958 return r;
959
960 r = home_store_embedded_identity(h, dir_fd, h->uid, NULL);
961 if (r < 0)
962 return r;
963
964 r = chown_recursive_directory(dir_fd, h->uid);
965 if (r < 0)
966 return r;
967
968 r = change_access_mode(dir_fd, user_record_access_mode(h));
969 if (r < 0)
970 return r;
971
972 return 0;
973 }
974
975 static int user_record_compile_effective_passwords(
976 UserRecord *h,
977 PasswordCache *cache,
978 char ***ret_effective_passwords) {
979
980 _cleanup_(strv_free_erasep) char **effective = NULL;
981 size_t n;
982 char **i;
983 int r;
984
985 assert(h);
986 assert(cache);
987
988 /* We insist on at least one classic hashed password to be defined in addition to any PKCS#11 one, as
989 * a safe fallback, but also to simplify the password changing algorithm: there we require providing
990 * the old literal password only (and do not care for the old PKCS#11 token) */
991
992 if (strv_isempty(h->hashed_password))
993 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
994 "User record has no hashed passwords, refusing.");
995
996 /* Generates the list of plaintext passwords to propagate to LUKS/fscrypt devices, and checks whether
997 * we have a plaintext password for each hashed one. If we are missing one we'll fail, since we
998 * couldn't sync fscrypt/LUKS to the login account properly. */
999
1000 STRV_FOREACH(i, h->hashed_password) {
1001 bool found = false;
1002 char **j;
1003
1004 log_debug("Looking for plaintext password for: %s", *i);
1005
1006 /* Let's scan all provided plaintext passwords */
1007 STRV_FOREACH(j, h->password) {
1008 r = test_password_one(*i, *j);
1009 if (r < 0)
1010 return log_error_errno(r, "Failed to test plaintext password: %m");
1011 if (r > 0) {
1012 if (ret_effective_passwords) {
1013 r = strv_extend(&effective, *j);
1014 if (r < 0)
1015 return log_oom();
1016 }
1017
1018 log_debug("Found literal plaintext password.");
1019 found = true;
1020 break;
1021 }
1022 }
1023
1024 if (!found)
1025 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Missing plaintext password for defined hashed password");
1026 }
1027
1028 for (n = 0; n < h->n_recovery_key; n++) {
1029 bool found = false;
1030 char **j;
1031
1032 log_debug("Looking for plaintext recovery key for: %s", h->recovery_key[n].hashed_password);
1033
1034 STRV_FOREACH(j, h->password) {
1035 _cleanup_(erase_and_freep) char *mangled = NULL;
1036 const char *p;
1037
1038 if (streq(h->recovery_key[n].type, "modhex64")) {
1039
1040 r = normalize_recovery_key(*j, &mangled);
1041 if (r == -EINVAL) /* Not properly formatted, probably a regular password. */
1042 continue;
1043 if (r < 0)
1044 return log_error_errno(r, "Failed to normalize recovery key: %m");
1045
1046 p = mangled;
1047 } else
1048 p = *j;
1049
1050 r = test_password_one(h->recovery_key[n].hashed_password, p);
1051 if (r < 0)
1052 return log_error_errno(r, "Failed to test plaintext recovery key: %m");
1053 if (r > 0) {
1054 if (ret_effective_passwords) {
1055 r = strv_extend(&effective, p);
1056 if (r < 0)
1057 return log_oom();
1058 }
1059
1060 log_debug("Found plaintext recovery key.");
1061 found = true;
1062 break;
1063 }
1064 }
1065
1066 if (!found)
1067 return log_error_errno(SYNTHETIC_ERRNO(EREMOTEIO), "Missing plaintext recovery key for defined recovery key");
1068 }
1069
1070 for (n = 0; n < h->n_pkcs11_encrypted_key; n++) {
1071 #if HAVE_P11KIT
1072 _cleanup_(pkcs11_callback_data_release) struct pkcs11_callback_data data = {
1073 .user_record = h,
1074 .secret = h,
1075 .encrypted_key = h->pkcs11_encrypted_key + n,
1076 };
1077
1078 r = pkcs11_find_token(data.encrypted_key->uri, pkcs11_callback, &data);
1079 if (r == -EAGAIN)
1080 return -EBADSLT;
1081 if (r < 0)
1082 return r;
1083
1084 r = test_password_one(data.encrypted_key->hashed_password, data.decrypted_password);
1085 if (r < 0)
1086 return log_error_errno(r, "Failed to test PKCS#11 password: %m");
1087 if (r == 0)
1088 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Decrypted password from token is not correct, refusing.");
1089
1090 if (ret_effective_passwords) {
1091 r = strv_extend(&effective, data.decrypted_password);
1092 if (r < 0)
1093 return log_oom();
1094 }
1095
1096 r = strv_extend(&cache->pkcs11_passwords, data.decrypted_password);
1097 if (r < 0)
1098 return log_oom();
1099 #else
1100 return -EBADSLT;
1101 #endif
1102 }
1103
1104 for (n = 0; n < h->n_fido2_hmac_salt; n++) {
1105 #if HAVE_LIBFIDO2
1106 _cleanup_(erase_and_freep) char *decrypted_password = NULL;
1107
1108 r = fido2_use_token(h, h, h->fido2_hmac_salt + n, &decrypted_password);
1109 if (r < 0)
1110 return r;
1111
1112 r = test_password_one(h->fido2_hmac_salt[n].hashed_password, decrypted_password);
1113 if (r < 0)
1114 return log_error_errno(r, "Failed to test FIDO2 password: %m");
1115 if (r == 0)
1116 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Decrypted password from token is not correct, refusing.");
1117
1118 if (ret_effective_passwords) {
1119 r = strv_extend(&effective, decrypted_password);
1120 if (r < 0)
1121 return log_oom();
1122 }
1123
1124 r = strv_extend(&cache->fido2_passwords, decrypted_password);
1125 if (r < 0)
1126 return log_oom();
1127 #else
1128 return -EBADSLT;
1129 #endif
1130 }
1131
1132 if (ret_effective_passwords)
1133 *ret_effective_passwords = TAKE_PTR(effective);
1134
1135 return 0;
1136 }
1137
1138 static int determine_default_storage(UserStorage *ret) {
1139 UserStorage storage = _USER_STORAGE_INVALID;
1140 const char *e;
1141 int r;
1142
1143 assert(ret);
1144
1145 /* homed tells us via an environment variable which default storage to use */
1146 e = getenv("SYSTEMD_HOME_DEFAULT_STORAGE");
1147 if (e) {
1148 storage = user_storage_from_string(e);
1149 if (storage < 0)
1150 log_warning("$SYSTEMD_HOME_DEFAULT_STORAGE set to invalid storage type, ignoring: %s", e);
1151 else {
1152 log_info("Using configured default storage '%s'.", user_storage_to_string(storage));
1153 *ret = storage;
1154 return 0;
1155 }
1156 }
1157
1158 /* When neither user nor admin specified the storage type to use, fix it to be LUKS — unless we run
1159 * in a container where loopback devices and LUKS/DM are not available. Also, if /home is encrypted
1160 * anyway, let's avoid duplicate encryption. Note that we typically default to the assumption of
1161 * "classic" storage for most operations. However, if we create a new home, then let's user LUKS if
1162 * nothing is specified. */
1163
1164 r = detect_container();
1165 if (r < 0)
1166 return log_error_errno(r, "Failed to determine whether we are in a container: %m");
1167 if (r == 0) {
1168 r = path_is_encrypted(get_home_root());
1169 if (r > 0)
1170 log_info("%s is encrypted, not using '%s' storage, in order to avoid double encryption.", get_home_root(), user_storage_to_string(USER_LUKS));
1171 else {
1172 if (r < 0)
1173 log_warning_errno(r, "Failed to determine if %s is encrypted, ignoring: %m", get_home_root());
1174
1175 r = dlopen_cryptsetup();
1176 if (r < 0)
1177 log_info("Not using '%s' storage, since libcryptsetup could not be loaded.", user_storage_to_string(USER_LUKS));
1178 else {
1179 log_info("Using automatic default storage of '%s'.", user_storage_to_string(USER_LUKS));
1180 *ret = USER_LUKS;
1181 return 0;
1182 }
1183 }
1184 } else
1185 log_info("Running in container, not using '%s' storage.", user_storage_to_string(USER_LUKS));
1186
1187 r = path_is_fs_type(get_home_root(), BTRFS_SUPER_MAGIC);
1188 if (r < 0)
1189 log_warning_errno(r, "Failed to determine file system of %s, ignoring: %m", get_home_root());
1190 if (r > 0) {
1191 log_info("%s is on btrfs, using '%s' as storage.", get_home_root(), user_storage_to_string(USER_SUBVOLUME));
1192 *ret = USER_SUBVOLUME;
1193 } else {
1194 log_info("%s is on simple file system, using '%s' as storage.", get_home_root(), user_storage_to_string(USER_DIRECTORY));
1195 *ret = USER_DIRECTORY;
1196 }
1197
1198 return 0;
1199 }
1200
1201 static int home_create(UserRecord *h, UserRecord **ret_home) {
1202 _cleanup_(strv_free_erasep) char **effective_passwords = NULL;
1203 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
1204 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
1205 _cleanup_(password_cache_free) PasswordCache cache = {};
1206 UserStorage new_storage = _USER_STORAGE_INVALID;
1207 const char *new_fs = NULL;
1208 int r;
1209
1210 assert(h);
1211
1212 if (!h->user_name)
1213 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks name, refusing.");
1214 if (!uid_is_valid(h->uid))
1215 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
1216
1217 r = user_record_compile_effective_passwords(h, &cache, &effective_passwords);
1218 if (r < 0)
1219 return r;
1220
1221 r = user_record_test_home_directory_and_warn(h);
1222 if (r < 0)
1223 return r;
1224 if (r != USER_TEST_ABSENT)
1225 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Home directory %s already exists, refusing.", user_record_home_directory(h));
1226
1227 if (h->storage < 0) {
1228 r = determine_default_storage(&new_storage);
1229 if (r < 0)
1230 return r;
1231 }
1232
1233 if ((h->storage == USER_LUKS ||
1234 (h->storage < 0 && new_storage == USER_LUKS)) &&
1235 !h->file_system_type)
1236 new_fs = getenv("SYSTEMD_HOME_DEFAULT_FILE_SYSTEM_TYPE");
1237
1238 if (new_storage >= 0 || new_fs) {
1239 r = user_record_add_binding(
1240 h,
1241 new_storage,
1242 NULL,
1243 SD_ID128_NULL,
1244 SD_ID128_NULL,
1245 SD_ID128_NULL,
1246 NULL,
1247 NULL,
1248 UINT64_MAX,
1249 new_fs,
1250 NULL,
1251 UID_INVALID,
1252 GID_INVALID);
1253 if (r < 0)
1254 return log_error_errno(r, "Failed to change storage type to LUKS: %m");
1255 }
1256
1257 r = user_record_test_image_path_and_warn(h);
1258 if (r < 0)
1259 return r;
1260 if (!IN_SET(r, USER_TEST_ABSENT, USER_TEST_UNDEFINED, USER_TEST_MAYBE))
1261 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Image path %s already exists, refusing.", user_record_image_path(h));
1262
1263 switch (user_record_storage(h)) {
1264
1265 case USER_LUKS:
1266 r = home_create_luks(h, &cache, effective_passwords, &new_home);
1267 break;
1268
1269 case USER_DIRECTORY:
1270 case USER_SUBVOLUME:
1271 r = home_create_directory_or_subvolume(h, &setup, &new_home);
1272 break;
1273
1274 case USER_FSCRYPT:
1275 r = home_create_fscrypt(h, effective_passwords, &new_home);
1276 break;
1277
1278 case USER_CIFS:
1279 r = home_create_cifs(h, &setup, &new_home);
1280 break;
1281
1282 default:
1283 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY),
1284 "Creating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1285 }
1286 if (r < 0)
1287 return r;
1288
1289 if (user_record_equal(h, new_home)) {
1290 *ret_home = NULL;
1291 return 0;
1292 }
1293
1294 *ret_home = TAKE_PTR(new_home);
1295 return 1;
1296 }
1297
1298 static int home_remove(UserRecord *h) {
1299 bool deleted = false;
1300 const char *ip, *hd;
1301 int r;
1302
1303 assert(h);
1304
1305 if (!h->user_name)
1306 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, refusing.");
1307 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
1308 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Removing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1309
1310 hd = user_record_home_directory(h);
1311
1312 r = user_record_test_home_directory_and_warn(h);
1313 if (r < 0)
1314 return r;
1315 if (r == USER_TEST_MOUNTED)
1316 return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Directory %s is still mounted, refusing.", hd);
1317
1318 assert(hd);
1319
1320 r = user_record_test_image_path_and_warn(h);
1321 if (r < 0)
1322 return r;
1323
1324 ip = user_record_image_path(h);
1325
1326 switch (user_record_storage(h)) {
1327
1328 case USER_LUKS: {
1329 struct stat st;
1330
1331 assert(ip);
1332
1333 if (stat(ip, &st) < 0) {
1334 if (errno != ENOENT)
1335 return log_error_errno(errno, "Failed to stat() %s: %m", ip);
1336
1337 } else {
1338 if (S_ISREG(st.st_mode)) {
1339 if (unlink(ip) < 0) {
1340 if (errno != ENOENT)
1341 return log_error_errno(errno, "Failed to remove %s: %m", ip);
1342 } else {
1343 _cleanup_free_ char *parent = NULL;
1344
1345 deleted = true;
1346
1347 r = path_extract_directory(ip, &parent);
1348 if (r < 0)
1349 log_debug_errno(r, "Failed to determine parent directory of '%s': %m", ip);
1350 else {
1351 r = fsync_path_at(AT_FDCWD, parent);
1352 if (r < 0)
1353 log_debug_errno(r, "Failed to synchronize disk after deleting '%s', ignoring: %m", ip);
1354 }
1355 }
1356
1357 } else if (S_ISBLK(st.st_mode))
1358 log_info("Not removing file system on block device %s.", ip);
1359 else
1360 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Image file %s is neither block device, nor regular, refusing removal.", ip);
1361 }
1362
1363 break;
1364 }
1365
1366 case USER_SUBVOLUME:
1367 case USER_DIRECTORY:
1368 case USER_FSCRYPT:
1369 assert(ip);
1370
1371 r = rm_rf(ip, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_SYNCFS);
1372 if (r < 0) {
1373 if (r != -ENOENT)
1374 return log_warning_errno(r, "Failed to remove %s: %m", ip);
1375 } else
1376 deleted = true;
1377
1378 /* If the image path and the home directory are the same invalidate the home directory, so
1379 * that we don't remove it anymore */
1380 if (path_equal(ip, hd))
1381 hd = NULL;
1382
1383 break;
1384
1385 case USER_CIFS:
1386 /* Nothing else to do here: we won't remove remote stuff. */
1387 log_info("Not removing home directory on remote server.");
1388 break;
1389
1390 default:
1391 assert_not_reached();
1392 }
1393
1394 if (hd) {
1395 if (rmdir(hd) < 0) {
1396 if (errno != ENOENT)
1397 return log_error_errno(errno, "Failed to remove %s, ignoring: %m", hd);
1398 } else
1399 deleted = true;
1400 }
1401
1402 if (deleted) {
1403 if (user_record_drop_caches(h))
1404 drop_caches_now();
1405
1406 log_info("Everything completed.");
1407 } else
1408 return log_notice_errno(SYNTHETIC_ERRNO(EALREADY),
1409 "Nothing to remove.");
1410
1411 return 0;
1412 }
1413
1414 static int home_validate_update(UserRecord *h, HomeSetup *setup, HomeSetupFlags *flags) {
1415 bool has_mount = false;
1416 int r;
1417
1418 assert(h);
1419 assert(setup);
1420
1421 if (!h->user_name)
1422 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, refusing.");
1423 if (!uid_is_valid(h->uid))
1424 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
1425 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
1426 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Processing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1427
1428 r = user_record_test_home_directory_and_warn(h);
1429 if (r < 0)
1430 return r;
1431
1432 has_mount = r == USER_TEST_MOUNTED;
1433
1434 r = user_record_test_image_path_and_warn(h);
1435 if (r < 0)
1436 return r;
1437 if (r == USER_TEST_ABSENT)
1438 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Image path %s does not exist", user_record_image_path(h));
1439
1440 switch (user_record_storage(h)) {
1441
1442 case USER_DIRECTORY:
1443 case USER_SUBVOLUME:
1444 case USER_FSCRYPT:
1445 case USER_CIFS:
1446 break;
1447
1448 case USER_LUKS: {
1449 r = home_get_state_luks(h, setup);
1450 if (r < 0)
1451 return r;
1452 if ((r > 0) != has_mount)
1453 return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Home mount incompletely set up.");
1454
1455 break;
1456 }
1457
1458 default:
1459 assert_not_reached();
1460 }
1461
1462 if (flags)
1463 SET_FLAG(*flags, HOME_SETUP_ALREADY_ACTIVATED, has_mount);
1464
1465 return has_mount; /* return true if the home record is already active */
1466 }
1467
1468 static int home_update(UserRecord *h, UserRecord **ret) {
1469 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL, *header_home = NULL, *embedded_home = NULL;
1470 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
1471 _cleanup_(password_cache_free) PasswordCache cache = {};
1472 HomeSetupFlags flags = 0;
1473 int r;
1474
1475 assert(h);
1476 assert(ret);
1477
1478 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ true);
1479 if (r < 0)
1480 return r;
1481 assert(r > 0); /* Insist that a password was verified */
1482
1483 r = home_validate_update(h, &setup, &flags);
1484 if (r < 0)
1485 return r;
1486
1487 r = home_setup(h, flags, &cache, &setup, &header_home);
1488 if (r < 0)
1489 return r;
1490
1491 r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER, &cache, &embedded_home, &new_home);
1492 if (r < 0)
1493 return r;
1494
1495 r = home_store_header_identity_luks(new_home, &setup, header_home);
1496 if (r < 0)
1497 return r;
1498
1499 r = home_store_embedded_identity(new_home, setup.root_fd, h->uid, embedded_home);
1500 if (r < 0)
1501 return r;
1502
1503 r = home_extend_embedded_identity(new_home, h, &setup);
1504 if (r < 0)
1505 return r;
1506
1507 r = home_sync_and_statfs(setup.root_fd, NULL);
1508 if (r < 0)
1509 return r;
1510
1511 r = home_setup_done(&setup);
1512 if (r < 0)
1513 return r;
1514
1515 log_info("Everything completed.");
1516
1517 *ret = TAKE_PTR(new_home);
1518 return 0;
1519 }
1520
1521 static int home_resize(UserRecord *h, UserRecord **ret) {
1522 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
1523 _cleanup_(password_cache_free) PasswordCache cache = {};
1524 HomeSetupFlags flags = 0;
1525 int r;
1526
1527 assert(h);
1528 assert(ret);
1529
1530 if (h->disk_size == UINT64_MAX)
1531 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No target size specified, refusing.");
1532
1533 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ true);
1534 if (r < 0)
1535 return r;
1536 assert(r > 0); /* Insist that a password was verified */
1537
1538 r = home_validate_update(h, &setup, &flags);
1539 if (r < 0)
1540 return r;
1541
1542 switch (user_record_storage(h)) {
1543
1544 case USER_LUKS:
1545 return home_resize_luks(h, flags, &cache, &setup, ret);
1546
1547 case USER_DIRECTORY:
1548 case USER_SUBVOLUME:
1549 case USER_FSCRYPT:
1550 return home_resize_directory(h, flags, &cache, &setup, ret);
1551
1552 default:
1553 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Resizing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1554 }
1555 }
1556
1557 static int home_passwd(UserRecord *h, UserRecord **ret_home) {
1558 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL;
1559 _cleanup_(strv_free_erasep) char **effective_passwords = NULL;
1560 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
1561 _cleanup_(password_cache_free) PasswordCache cache = {};
1562 HomeSetupFlags flags = 0;
1563 int r;
1564
1565 assert(h);
1566 assert(ret_home);
1567
1568 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT))
1569 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Changing password of home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1570
1571 r = user_record_compile_effective_passwords(h, &cache, &effective_passwords);
1572 if (r < 0)
1573 return r;
1574
1575 r = home_validate_update(h, &setup, &flags);
1576 if (r < 0)
1577 return r;
1578
1579 r = home_setup(h, flags, &cache, &setup, &header_home);
1580 if (r < 0)
1581 return r;
1582
1583 r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL, &cache, &embedded_home, &new_home);
1584 if (r < 0)
1585 return r;
1586
1587 switch (user_record_storage(h)) {
1588
1589 case USER_LUKS:
1590 r = home_passwd_luks(h, &setup, &cache, effective_passwords);
1591 if (r < 0)
1592 return r;
1593 break;
1594
1595 case USER_FSCRYPT:
1596 r = home_passwd_fscrypt(h, &setup, &cache, effective_passwords);
1597 if (r < 0)
1598 return r;
1599 break;
1600
1601 default:
1602 break;
1603 }
1604
1605 r = home_store_header_identity_luks(new_home, &setup, header_home);
1606 if (r < 0)
1607 return r;
1608
1609 r = home_store_embedded_identity(new_home, setup.root_fd, h->uid, embedded_home);
1610 if (r < 0)
1611 return r;
1612
1613 r = home_extend_embedded_identity(new_home, h, &setup);
1614 if (r < 0)
1615 return r;
1616
1617 r = home_sync_and_statfs(setup.root_fd, NULL);
1618 if (r < 0)
1619 return r;
1620
1621 r = home_setup_done(&setup);
1622 if (r < 0)
1623 return r;
1624
1625 log_info("Everything completed.");
1626
1627 *ret_home = TAKE_PTR(new_home);
1628 return 1;
1629 }
1630
1631 static int home_inspect(UserRecord *h, UserRecord **ret_home) {
1632 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *new_home = NULL;
1633 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
1634 _cleanup_(password_cache_free) PasswordCache cache = {};
1635 HomeSetupFlags flags = 0;
1636 int r;
1637
1638 assert(h);
1639 assert(ret_home);
1640
1641 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
1642 if (r < 0)
1643 return r;
1644
1645 r = home_validate_update(h, &setup, &flags);
1646 if (r < 0)
1647 return r;
1648
1649 r = home_setup(h, flags, &cache, &setup, &header_home);
1650 if (r < 0)
1651 return r;
1652
1653 r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_ANY, &cache, NULL, &new_home);
1654 if (r < 0)
1655 return r;
1656
1657 r = home_extend_embedded_identity(new_home, h, &setup);
1658 if (r < 0)
1659 return r;
1660
1661 r = home_setup_done(&setup);
1662 if (r < 0)
1663 return r;
1664
1665 log_info("Everything completed.");
1666
1667 *ret_home = TAKE_PTR(new_home);
1668 return 1;
1669 }
1670
1671 static int home_lock(UserRecord *h) {
1672 int r;
1673
1674 assert(h);
1675
1676 if (!h->user_name)
1677 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
1678 if (user_record_storage(h) != USER_LUKS)
1679 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Locking home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1680
1681 r = user_record_test_home_directory_and_warn(h);
1682 if (r < 0)
1683 return r;
1684 if (r != USER_TEST_MOUNTED)
1685 return log_error_errno(SYNTHETIC_ERRNO(ENOEXEC), "Home directory of %s is not mounted, can't lock.", h->user_name);
1686
1687 r = home_lock_luks(h);
1688 if (r < 0)
1689 return r;
1690
1691 log_info("Everything completed.");
1692 return 1;
1693 }
1694
1695 static int home_unlock(UserRecord *h) {
1696 _cleanup_(password_cache_free) PasswordCache cache = {};
1697 int r;
1698
1699 assert(h);
1700
1701 if (!h->user_name)
1702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
1703 if (user_record_storage(h) != USER_LUKS)
1704 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Unlocking home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1705
1706 /* Note that we don't check if $HOME is actually mounted, since we want to avoid disk accesses on
1707 * that mount until we have resumed the device. */
1708
1709 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
1710 if (r < 0)
1711 return r;
1712
1713 r = home_unlock_luks(h, &cache);
1714 if (r < 0)
1715 return r;
1716
1717 log_info("Everything completed.");
1718 return 1;
1719 }
1720
1721 static int run(int argc, char *argv[]) {
1722 _cleanup_(user_record_unrefp) UserRecord *home = NULL, *new_home = NULL;
1723 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
1724 _cleanup_(fclosep) FILE *opened_file = NULL;
1725 unsigned line = 0, column = 0;
1726 const char *json_path = NULL;
1727 FILE *json_file;
1728 usec_t start;
1729 int r;
1730
1731 start = now(CLOCK_MONOTONIC);
1732
1733 log_setup();
1734
1735 umask(0022);
1736
1737 if (argc < 2 || argc > 3)
1738 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes one or two arguments.");
1739
1740 if (argc > 2) {
1741 json_path = argv[2];
1742
1743 opened_file = fopen(json_path, "re");
1744 if (!opened_file)
1745 return log_error_errno(errno, "Failed to open %s: %m", json_path);
1746
1747 json_file = opened_file;
1748 } else {
1749 json_path = "<stdin>";
1750 json_file = stdin;
1751 }
1752
1753 r = json_parse_file(json_file, json_path, JSON_PARSE_SENSITIVE, &v, &line, &column);
1754 if (r < 0)
1755 return log_error_errno(r, "[%s:%u:%u] Failed to parse JSON data: %m", json_path, line, column);
1756
1757 home = user_record_new();
1758 if (!home)
1759 return log_oom();
1760
1761 r = user_record_load(home, v, USER_RECORD_LOAD_FULL|USER_RECORD_LOG|USER_RECORD_PERMISSIVE);
1762 if (r < 0)
1763 return r;
1764
1765 /* Well known return values of these operations, that systemd-homed knows and converts to proper D-Bus errors:
1766 *
1767 * EMSGSIZE → file systems of this type cannot be shrunk
1768 * ETXTBSY → file systems of this type can only be shrunk offline
1769 * ERANGE → file system size too small
1770 * ENOLINK → system does not support selected storage backend
1771 * EPROTONOSUPPORT → system does not support selected file system
1772 * ENOTTY → operation not support on this storage
1773 * ESOCKTNOSUPPORT → operation not support on this file system
1774 * ENOKEY → password incorrect (or not sufficient, or not supplied)
1775 * EREMOTEIO → recovery key incorrect (or not sufficeint, or not supplied — only if no passwords defined)
1776 * EBADSLT → similar, but PKCS#11 device is defined and might be able to provide password, if it was plugged in which it is not
1777 * ENOANO → suitable PKCS#11/FIDO2 device found, but PIN is missing to unlock it
1778 * ERFKILL → suitable PKCS#11 device found, but OK to ask for on-device interactive authentication not given
1779 * EMEDIUMTYPE → suitable FIDO2 device found, but OK to ask for user presence not given
1780 * ENOCSI → suitable FIDO2 device found, but OK to ask for user verification not given
1781 * ENOSTR → suitable FIDO2 device found, but user didn't react to action request on token quickly enough
1782 * EOWNERDEAD → suitable PKCS#11/FIDO2 device found, but its PIN is locked
1783 * ENOLCK → suitable PKCS#11/FIDO2 device found, but PIN incorrect
1784 * ETOOMANYREFS → suitable PKCS#11 device found, but PIN incorrect, and only few tries left
1785 * EUCLEAN → suitable PKCS#11 device found, but PIN incorrect, and only one try left
1786 * EBUSY → file system is currently active
1787 * ENOEXEC → file system is currently not active
1788 * ENOSPC → not enough disk space for operation
1789 * EKEYREVOKED → user record has not suitable hashed password or pkcs#11 entry, we cannot authenticate
1790 * EADDRINUSE → home image is already used elsewhere (lock taken)
1791 */
1792
1793 if (streq(argv[1], "activate"))
1794 r = home_activate(home, &new_home);
1795 else if (streq(argv[1], "deactivate"))
1796 r = home_deactivate(home, false);
1797 else if (streq(argv[1], "deactivate-force"))
1798 r = home_deactivate(home, true);
1799 else if (streq(argv[1], "create"))
1800 r = home_create(home, &new_home);
1801 else if (streq(argv[1], "remove"))
1802 r = home_remove(home);
1803 else if (streq(argv[1], "update"))
1804 r = home_update(home, &new_home);
1805 else if (streq(argv[1], "resize"))
1806 r = home_resize(home, &new_home);
1807 else if (streq(argv[1], "passwd"))
1808 r = home_passwd(home, &new_home);
1809 else if (streq(argv[1], "inspect"))
1810 r = home_inspect(home, &new_home);
1811 else if (streq(argv[1], "lock"))
1812 r = home_lock(home);
1813 else if (streq(argv[1], "unlock"))
1814 r = home_unlock(home);
1815 else
1816 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb '%s'.", argv[1]);
1817 if (IN_SET(r, -ENOKEY, -EREMOTEIO) && !strv_isempty(home->password) ) { /* There were passwords specified but they were incorrect */
1818 usec_t end, n, d;
1819
1820 /* Make sure bad password replies always take at least 3s, and if longer multiples of 3s, so
1821 * that it's not clear how long we actually needed for our calculations. */
1822 n = now(CLOCK_MONOTONIC);
1823 assert(n >= start);
1824
1825 d = usec_sub_unsigned(n, start);
1826 if (d > BAD_PASSWORD_DELAY_USEC)
1827 end = start + DIV_ROUND_UP(d, BAD_PASSWORD_DELAY_USEC) * BAD_PASSWORD_DELAY_USEC;
1828 else
1829 end = start + BAD_PASSWORD_DELAY_USEC;
1830
1831 if (n < end)
1832 (void) usleep(usec_sub_unsigned(end, n));
1833 }
1834 if (r < 0)
1835 return r;
1836
1837 /* We always pass the new record back, regardless if it changed or not. This allows our caller to
1838 * prepare a fresh record, send to us, and only if it works use it without having to keep a local
1839 * copy. */
1840 if (new_home)
1841 json_variant_dump(new_home->json, JSON_FORMAT_NEWLINE, stdout, NULL);
1842
1843 return 0;
1844 }
1845
1846 DEFINE_MAIN_FUNCTION(run);