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