]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/home/homework.c
Merge pull request #21038 from yuwata/network-dhcp6-pd-fix-address-check
[thirdparty/systemd.git] / src / home / homework.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
70a5db58
LP
2
3#include <stddef.h>
4#include <sys/mount.h>
5
b25a930f 6#include "blockdev-util.h"
70a5db58
LP
7#include "chown-recursive.h"
8#include "copy.h"
9#include "fd-util.h"
10#include "fileio.h"
1dfe5de0 11#include "fs-util.h"
70a5db58
LP
12#include "home-util.h"
13#include "homework-cifs.h"
14#include "homework-directory.h"
7b78db28 15#include "homework-fido2.h"
70a5db58
LP
16#include "homework-fscrypt.h"
17#include "homework-luks.h"
18#include "homework-mount.h"
19#include "homework-pkcs11.h"
20#include "homework.h"
0e98d17e 21#include "libcrypt-util.h"
70a5db58
LP
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"
73d874ba 27#include "recovery-key.h"
70a5db58
LP
28#include "rm-rf.h"
29#include "stat-util.h"
30#include "strv.h"
86019efa 31#include "sync-util.h"
70a5db58
LP
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
7b78db28
LP
39void 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
70a5db58
LP
47int user_record_authenticate(
48 UserRecord *h,
49 UserRecord *secret,
7b78db28 50 PasswordCache *cache,
c8f145ad 51 bool strict_verify) {
70a5db58 52
17e7561a
LP
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;
70a5db58
LP
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
7b78db28 64 * configured PKCS#11 or FIDO2 token is around and can unlock the record.
70a5db58 65 *
7b78db28
LP
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. */
70a5db58
LP
72
73 /* First, let's see if the supplied plain-text passwords work? */
87d7893c
LP
74 r = user_record_test_password(h, secret);
75 if (r == -ENOKEY)
70a5db58 76 need_password = true;
87d7893c 77 else if (r == -ENXIO)
70a5db58
LP
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.");
c8f145ad 83 return 1;
70a5db58
LP
84 }
85
87d7893c
LP
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
7b78db28 106 /* Second, test cached PKCS#11 passwords */
3aeea37d 107 for (size_t n = 0; n < h->n_pkcs11_encrypted_key; n++) {
70a5db58
LP
108 char **pp;
109
7b78db28
LP
110 STRV_FOREACH(pp, cache->pkcs11_passwords) {
111 r = test_password_one(h->pkcs11_encrypted_key[n].hashed_password, *pp);
70a5db58
LP
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.");
c8f145ad 116 return 1;
70a5db58
LP
117 }
118 }
7b78db28
LP
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.");
e4961427 132 return 1;
7b78db28
LP
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 };
70a5db58
LP
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
7b78db28
LP
181 r = strv_extend(&cache->pkcs11_passwords, data.decrypted_password);
182 if (r < 0)
183 return log_oom();
184
e4961427 185 return 1;
7b78db28
LP
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;
17e7561a
LP
215 case -ENOCSI:
216 need_user_verification_permitted = true;
217 break;
7b78db28
LP
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);
70a5db58
LP
234 if (r < 0)
235 return log_oom();
236
c8f145ad 237 return 1;
70a5db58
LP
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;
7b78db28
LP
254 if (token_action_timeout)
255 return -ENOSTR;
70a5db58
LP
256 if (need_protected_authentication_path_permitted)
257 return -ERFKILL;
7b78db28
LP
258 if (need_user_presence_permitted)
259 return -EMEDIUMTYPE;
17e7561a
LP
260 if (need_user_verification_permitted)
261 return -ENOCSI;
70a5db58
LP
262 if (need_pin)
263 return -ENOANO;
264 if (need_token)
265 return -EBADSLT;
266 if (need_password)
267 return -ENOKEY;
87d7893c
LP
268 if (need_recovery_key)
269 return -EREMOTEIO;
70a5db58 270
87d7893c
LP
271 /* Hmm, this means neither PCKS#11/FIDO2 nor classic hashed passwords or recovery keys were supplied,
272 * we cannot authenticate this reasonably */
c8f145ad
LP
273 if (strict_verify)
274 return log_debug_errno(SYNTHETIC_ERRNO(EKEYREVOKED),
87d7893c 275 "No hashed passwords, no recovery keys and no PKCS#11/FIDO2 tokens defined, cannot authenticate user record, refusing.");
c8f145ad
LP
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. */
87d7893c 282 log_debug("No hashed passwords, not recovery keys and no PKCS#11 tokens defined in record, cannot authenticate user record. "
c8f145ad
LP
283 "Deferring to embedded user record.");
284 return 0;
70a5db58
LP
285}
286
86019efa
LP
287static 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
66aa51f8 301int home_setup_done(HomeSetup *setup) {
70a5db58
LP
302 int r = 0, q;
303
304 assert(setup);
305
28a7f106
LP
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
86019efa
LP
313 if (syncfs(setup->root_fd) < 0)
314 log_debug_errno(errno, "Failed to synchronize home directory, ignoring: %m");
315
28a7f106
LP
316 setup->root_fd = safe_close(setup->root_fd);
317 }
70a5db58
LP
318
319 if (setup->undo_mount) {
30f5d104 320 q = umount_verbose(LOG_DEBUG, "/run/systemd/user-home-mount", UMOUNT_NOFOLLOW);
70a5db58
LP
321 if (q < 0)
322 r = q;
323 }
324
325 if (setup->undo_dm && setup->crypt_device && setup->dm_name) {
71eceff6 326 q = sym_crypt_deactivate_by_name(setup->crypt_device, setup->dm_name, 0);
70a5db58
LP
327 if (q < 0)
328 r = q;
329 }
330
28a7f106
LP
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
565ac8b1
LP
338 if (setup->do_mark_clean) {
339 q = run_mark_dirty(setup->image_fd, false);
340 if (q < 0)
341 r = q;
342 }
343
28a7f106
LP
344 setup->image_fd = safe_close(setup->image_fd);
345 }
346
70a5db58
LP
347 setup->undo_mount = false;
348 setup->undo_dm = false;
28a7f106
LP
349 setup->do_offline_fitrim = false;
350 setup->do_offline_fallocate = false;
565ac8b1 351 setup->do_mark_clean = false;
70a5db58
LP
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);
71eceff6
LP
357 if (setup->crypt_device) {
358 sym_crypt_free(setup->crypt_device);
359 setup->crypt_device = NULL;
360 }
70a5db58 361
fc4941d6 362 setup->volume_key = erase_and_free(setup->volume_key);
70a5db58
LP
363 setup->volume_key_size = 0;
364
86019efa
LP
365 if (setup->do_drop_caches)
366 drop_caches_now();
367
70a5db58
LP
368 return r;
369}
370
aa0a6214 371int home_setup(
70a5db58 372 UserRecord *h,
e1df968b 373 HomeSetupFlags flags,
7b78db28 374 PasswordCache *cache,
70a5db58
LP
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
e1df968b 390 if (!FLAGS_SET(flags, HOME_SETUP_ALREADY_ACTIVATED)) /* If we set up the directory, we should also drop caches once we are done */
86019efa
LP
391 setup->do_drop_caches = setup->do_drop_caches || user_record_drop_caches(h);
392
70a5db58
LP
393 switch (user_record_storage(h)) {
394
395 case USER_LUKS:
e1df968b 396 return home_setup_luks(h, flags, NULL, cache, setup, ret_header_home);
70a5db58
LP
397
398 case USER_SUBVOLUME:
399 case USER_DIRECTORY:
e1df968b 400 r = home_setup_directory(h, setup);
70a5db58
LP
401 break;
402
403 case USER_FSCRYPT:
e1df968b 404 r = home_setup_fscrypt(h, cache, setup);
70a5db58
LP
405 break;
406
407 case USER_CIFS:
e1df968b 408 r = home_setup_cifs(h, flags, setup);
70a5db58
LP
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
424int 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
442static 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
4fa744a3 459 identity_file = take_fdopen(&identity_fd, "r");
70a5db58
LP
460 if (!identity_file)
461 return log_oom();
462
70a5db58
LP
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
472static 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
4fa744a3 496 identity_file = take_fdopen(&identity_fd, "w");
70a5db58
LP
497 if (!identity_file) {
498 r = log_oom();
499 goto fail;
500 }
501
70a5db58
LP
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
524fail:
525 (void) unlinkat(root_fd, fn, 0);
526 return r;
527}
528
529int home_load_embedded_identity(
530 UserRecord *h,
531 int root_fd,
532 UserRecord *header_home,
533 UserReconcileMode mode,
7b78db28 534 PasswordCache *cache,
70a5db58
LP
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
bfc0cc1a 553 r = user_record_load(embedded_home, v, USER_RECORD_LOAD_EMBEDDED|USER_RECORD_PERMISSIVE);
70a5db58
LP
554 if (r < 0)
555 return r;
556
557 if (!user_record_compatible(h, embedded_home))
80ace4f2 558 return log_error_errno(SYNTHETIC_ERRNO(EREMCHG), "Embedded home record not compatible with host record, refusing.");
70a5db58
LP
559
560 /* Insist that credentials the user supplies also unlocks any embedded records. */
7b78db28 561 r = user_record_authenticate(embedded_home, h, cache, /* strict_verify= */ true);
70a5db58
LP
562 if (r < 0)
563 return r;
c8f145ad 564 assert(r > 0); /* Insist that a password was verified */
70a5db58
LP
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
630int 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
bfc0cc1a 638 r = user_record_clone(h, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &embedded);
70a5db58
LP
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
655static 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
675int 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,
71eceff6
LP
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,
70a5db58
LP
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
702static 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
719int home_refresh(
720 UserRecord *h,
721 HomeSetup *setup,
722 UserRecord *header_home,
7b78db28 723 PasswordCache *cache,
70a5db58
LP
724 struct statfs *ret_statfs,
725 UserRecord **ret_new_home) {
726
727 _cleanup_(user_record_unrefp) UserRecord *embedded_home = NULL, *new_home = NULL;
728 int r;
729
730 assert(h);
731 assert(setup);
732 assert(ret_new_home);
733
734 /* When activating a home directory, does the identity work: loads the identity from the $HOME
735 * directory, reconciles it with our idea, chown()s everything. */
736
7b78db28 737 r = home_load_embedded_identity(h, setup->root_fd, header_home, USER_RECONCILE_ANY, cache, &embedded_home, &new_home);
70a5db58
LP
738 if (r < 0)
739 return r;
740
741 r = home_store_header_identity_luks(new_home, setup, header_home);
742 if (r < 0)
743 return r;
744
745 r = home_store_embedded_identity(new_home, setup->root_fd, h->uid, embedded_home);
746 if (r < 0)
747 return r;
748
749 r = chown_recursive_directory(setup->root_fd, h->uid);
750 if (r < 0)
751 return r;
752
753 r = home_sync_and_statfs(setup->root_fd, ret_statfs);
754 if (r < 0)
755 return r;
756
757 *ret_new_home = TAKE_PTR(new_home);
758 return 0;
759}
760
761static int home_activate(UserRecord *h, UserRecord **ret_home) {
a74e2e44 762 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
70a5db58 763 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
a74e2e44 764 _cleanup_(password_cache_free) PasswordCache cache = {};
70a5db58
LP
765 int r;
766
767 assert(h);
768
769 if (!h->user_name)
770 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, refusing.");
771 if (!uid_is_valid(h->uid))
772 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
773 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
774 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Activating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
775
7b78db28 776 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
70a5db58
LP
777 if (r < 0)
778 return r;
779
780 r = user_record_test_home_directory_and_warn(h);
781 if (r < 0)
782 return r;
783 if (r == USER_TEST_MOUNTED)
784 return log_error_errno(SYNTHETIC_ERRNO(EALREADY), "Home directory %s is already mounted, refusing.", user_record_home_directory(h));
785
786 r = user_record_test_image_path_and_warn(h);
787 if (r < 0)
788 return r;
789 if (r == USER_TEST_ABSENT)
790 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Image path %s is missing, refusing.", user_record_image_path(h));
791
792 switch (user_record_storage(h)) {
793
794 case USER_LUKS:
a74e2e44 795 r = home_activate_luks(h, &setup, &cache, &new_home);
70a5db58
LP
796 if (r < 0)
797 return r;
798
799 break;
800
801 case USER_SUBVOLUME:
802 case USER_DIRECTORY:
803 case USER_FSCRYPT:
a74e2e44 804 r = home_activate_directory(h, &setup, &cache, &new_home);
70a5db58
LP
805 if (r < 0)
806 return r;
807
808 break;
809
810 case USER_CIFS:
a74e2e44 811 r = home_activate_cifs(h, &setup, &cache, &new_home);
70a5db58
LP
812 if (r < 0)
813 return r;
814
815 break;
816
817 default:
04499a70 818 assert_not_reached();
70a5db58
LP
819 }
820
821 /* Note that the returned object might either be a reference to an updated version of the existing
822 * home object, or a reference to a newly allocated home object. The caller has to be able to deal
823 * with both, and consider the old object out-of-date. */
824 if (user_record_equal(h, new_home)) {
825 *ret_home = NULL;
826 return 0; /* no identity change */
827 }
828
829 *ret_home = TAKE_PTR(new_home);
830 return 1; /* identity updated */
831}
832
833static int home_deactivate(UserRecord *h, bool force) {
834 bool done = false;
835 int r;
836
837 assert(h);
838
839 if (!h->user_name)
840 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
841 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
842 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Deactivating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
843
844 r = user_record_test_home_directory_and_warn(h);
845 if (r < 0)
846 return r;
847 if (r == USER_TEST_MOUNTED) {
28a7f106
LP
848 if (user_record_storage(h) == USER_LUKS) {
849 r = home_trim_luks(h);
850 if (r < 0)
851 return r;
852 }
853
86019efa
LP
854 /* Sync explicitly, so that the drop caches logic below can work as documented */
855 r = syncfs_path(AT_FDCWD, user_record_home_directory(h));
856 if (r < 0)
857 log_debug_errno(r, "Failed to synchronize home directory, ignoring: %m");
858 else
859 log_info("Syncing completed.");
860
70a5db58
LP
861 if (umount2(user_record_home_directory(h), UMOUNT_NOFOLLOW | (force ? MNT_FORCE|MNT_DETACH : 0)) < 0)
862 return log_error_errno(errno, "Failed to unmount %s: %m", user_record_home_directory(h));
863
864 log_info("Unmounting completed.");
865 done = true;
866 } else
867 log_info("Directory %s is already unmounted.", user_record_home_directory(h));
868
869 if (user_record_storage(h) == USER_LUKS) {
870 r = home_deactivate_luks(h);
871 if (r < 0)
872 return r;
873 if (r > 0)
874 done = true;
875 }
876
877 if (!done)
878 return log_error_errno(SYNTHETIC_ERRNO(ENOEXEC), "Home is not active.");
879
86019efa
LP
880 if (user_record_drop_caches(h))
881 drop_caches_now();
882
70a5db58
LP
883 log_info("Everything completed.");
884 return 0;
885}
886
887static int copy_skel(int root_fd, const char *skel) {
888 int r;
889
890 assert(root_fd >= 0);
891
892 r = copy_tree_at(AT_FDCWD, skel, root_fd, ".", UID_INVALID, GID_INVALID, COPY_MERGE|COPY_REPLACE);
893 if (r == -ENOENT) {
894 log_info("Skeleton directory %s missing, ignoring.", skel);
895 return 0;
896 }
897 if (r < 0)
898 return log_error_errno(r, "Failed to copy in %s: %m", skel);
899
900 log_info("Copying in %s completed.", skel);
901 return 0;
902}
903
904static int change_access_mode(int root_fd, mode_t m) {
905 assert(root_fd >= 0);
906
907 if (fchmod(root_fd, m) < 0)
908 return log_error_errno(errno, "Failed to change access mode of top-level directory: %m");
909
910 log_info("Changed top-level directory access mode to 0%o.", m);
911 return 0;
912}
913
914int home_populate(UserRecord *h, int dir_fd) {
915 int r;
916
917 assert(h);
918 assert(dir_fd >= 0);
919
920 r = copy_skel(dir_fd, user_record_skeleton_directory(h));
921 if (r < 0)
922 return r;
923
924 r = home_store_embedded_identity(h, dir_fd, h->uid, NULL);
925 if (r < 0)
926 return r;
927
928 r = chown_recursive_directory(dir_fd, h->uid);
929 if (r < 0)
930 return r;
931
932 r = change_access_mode(dir_fd, user_record_access_mode(h));
933 if (r < 0)
934 return r;
935
936 return 0;
937}
938
939static int user_record_compile_effective_passwords(
940 UserRecord *h,
7b78db28
LP
941 PasswordCache *cache,
942 char ***ret_effective_passwords) {
70a5db58 943
7b78db28 944 _cleanup_(strv_free_erasep) char **effective = NULL;
70a5db58
LP
945 size_t n;
946 char **i;
947 int r;
948
949 assert(h);
7b78db28 950 assert(cache);
70a5db58
LP
951
952 /* We insist on at least one classic hashed password to be defined in addition to any PKCS#11 one, as
953 * a safe fallback, but also to simplify the password changing algorithm: there we require providing
954 * the old literal password only (and do not care for the old PKCS#11 token) */
955
956 if (strv_isempty(h->hashed_password))
d7a0f1f4
FS
957 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
958 "User record has no hashed passwords, refusing.");
70a5db58
LP
959
960 /* Generates the list of plaintext passwords to propagate to LUKS/fscrypt devices, and checks whether
961 * we have a plaintext password for each hashed one. If we are missing one we'll fail, since we
962 * couldn't sync fscrypt/LUKS to the login account properly. */
963
964 STRV_FOREACH(i, h->hashed_password) {
965 bool found = false;
966 char **j;
967
968 log_debug("Looking for plaintext password for: %s", *i);
969
970 /* Let's scan all provided plaintext passwords */
971 STRV_FOREACH(j, h->password) {
972 r = test_password_one(*i, *j);
973 if (r < 0)
87d7893c 974 return log_error_errno(r, "Failed to test plaintext password: %m");
70a5db58
LP
975 if (r > 0) {
976 if (ret_effective_passwords) {
977 r = strv_extend(&effective, *j);
978 if (r < 0)
979 return log_oom();
980 }
981
982 log_debug("Found literal plaintext password.");
983 found = true;
984 break;
985 }
986 }
987
988 if (!found)
989 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Missing plaintext password for defined hashed password");
990 }
991
87d7893c
LP
992 for (n = 0; n < h->n_recovery_key; n++) {
993 bool found = false;
994 char **j;
995
996 log_debug("Looking for plaintext recovery key for: %s", h->recovery_key[n].hashed_password);
997
998 STRV_FOREACH(j, h->password) {
999 _cleanup_(erase_and_freep) char *mangled = NULL;
1000 const char *p;
1001
1002 if (streq(h->recovery_key[n].type, "modhex64")) {
1003
1004 r = normalize_recovery_key(*j, &mangled);
1005 if (r == -EINVAL) /* Not properly formatted, probably a regular password. */
1006 continue;
1007 if (r < 0)
1008 return log_error_errno(r, "Failed to normalize recovery key: %m");
1009
1010 p = mangled;
1011 } else
1012 p = *j;
1013
1014 r = test_password_one(h->recovery_key[n].hashed_password, p);
1015 if (r < 0)
1016 return log_error_errno(r, "Failed to test plaintext recovery key: %m");
1017 if (r > 0) {
1018 if (ret_effective_passwords) {
1019 r = strv_extend(&effective, p);
1020 if (r < 0)
1021 return log_oom();
1022 }
1023
1024 log_debug("Found plaintext recovery key.");
1025 found = true;
1026 break;
1027 }
1028 }
1029
1030 if (!found)
1031 return log_error_errno(SYNTHETIC_ERRNO(EREMOTEIO), "Missing plaintext recovery key for defined recovery key");
1032 }
1033
70a5db58
LP
1034 for (n = 0; n < h->n_pkcs11_encrypted_key; n++) {
1035#if HAVE_P11KIT
1036 _cleanup_(pkcs11_callback_data_release) struct pkcs11_callback_data data = {
1037 .user_record = h,
1038 .secret = h,
1039 .encrypted_key = h->pkcs11_encrypted_key + n,
1040 };
1041
1042 r = pkcs11_find_token(data.encrypted_key->uri, pkcs11_callback, &data);
1043 if (r == -EAGAIN)
1044 return -EBADSLT;
1045 if (r < 0)
1046 return r;
1047
1048 r = test_password_one(data.encrypted_key->hashed_password, data.decrypted_password);
1049 if (r < 0)
1050 return log_error_errno(r, "Failed to test PKCS#11 password: %m");
1051 if (r == 0)
1052 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Decrypted password from token is not correct, refusing.");
1053
1054 if (ret_effective_passwords) {
1055 r = strv_extend(&effective, data.decrypted_password);
1056 if (r < 0)
1057 return log_oom();
1058 }
1059
7b78db28
LP
1060 r = strv_extend(&cache->pkcs11_passwords, data.decrypted_password);
1061 if (r < 0)
1062 return log_oom();
1063#else
1064 return -EBADSLT;
1065#endif
1066 }
1067
1068 for (n = 0; n < h->n_fido2_hmac_salt; n++) {
1069#if HAVE_LIBFIDO2
1070 _cleanup_(erase_and_freep) char *decrypted_password = NULL;
1071
1072 r = fido2_use_token(h, h, h->fido2_hmac_salt + n, &decrypted_password);
1073 if (r < 0)
1074 return r;
1075
1076 r = test_password_one(h->fido2_hmac_salt[n].hashed_password, decrypted_password);
1077 if (r < 0)
1078 return log_error_errno(r, "Failed to test FIDO2 password: %m");
1079 if (r == 0)
1080 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Decrypted password from token is not correct, refusing.");
1081
1082 if (ret_effective_passwords) {
1083 r = strv_extend(&effective, decrypted_password);
70a5db58
LP
1084 if (r < 0)
1085 return log_oom();
1086 }
7b78db28
LP
1087
1088 r = strv_extend(&cache->fido2_passwords, decrypted_password);
1089 if (r < 0)
1090 return log_oom();
70a5db58
LP
1091#else
1092 return -EBADSLT;
1093#endif
1094 }
1095
1096 if (ret_effective_passwords)
1097 *ret_effective_passwords = TAKE_PTR(effective);
70a5db58
LP
1098
1099 return 0;
1100}
1101
1dfe5de0
LP
1102static int determine_default_storage(UserStorage *ret) {
1103 UserStorage storage = _USER_STORAGE_INVALID;
1104 const char *e;
1105 int r;
1106
1107 assert(ret);
1108
1109 /* homed tells us via an environment variable which default storage to use */
1110 e = getenv("SYSTEMD_HOME_DEFAULT_STORAGE");
1111 if (e) {
1112 storage = user_storage_from_string(e);
1113 if (storage < 0)
1114 log_warning("$SYSTEMD_HOME_DEFAULT_STORAGE set to invalid storage type, ignoring: %s", e);
1115 else {
1116 log_info("Using configured default storage '%s'.", user_storage_to_string(storage));
1117 *ret = storage;
1118 return 0;
1119 }
1120 }
1121
1122 /* When neither user nor admin specified the storage type to use, fix it to be LUKS — unless we run
1123 * in a container where loopback devices and LUKS/DM are not available. Also, if /home is encrypted
1124 * anyway, let's avoid duplicate encryption. Note that we typically default to the assumption of
1125 * "classic" storage for most operations. However, if we create a new home, then let's user LUKS if
1126 * nothing is specified. */
1127
1128 r = detect_container();
1129 if (r < 0)
1130 return log_error_errno(r, "Failed to determine whether we are in a container: %m");
1131 if (r == 0) {
2700fecd 1132 r = path_is_encrypted(get_home_root());
0608e2d3 1133 if (r > 0)
2700fecd 1134 log_info("%s is encrypted, not using '%s' storage, in order to avoid double encryption.", get_home_root(), user_storage_to_string(USER_LUKS));
0608e2d3
LP
1135 else {
1136 if (r < 0)
2700fecd 1137 log_warning_errno(r, "Failed to determine if %s is encrypted, ignoring: %m", get_home_root());
1dfe5de0 1138
0608e2d3
LP
1139 r = dlopen_cryptsetup();
1140 if (r < 0)
1141 log_info("Not using '%s' storage, since libcryptsetup could not be loaded.", user_storage_to_string(USER_LUKS));
1142 else {
1143 log_info("Using automatic default storage of '%s'.", user_storage_to_string(USER_LUKS));
1144 *ret = USER_LUKS;
1145 return 0;
1146 }
1147 }
1dfe5de0
LP
1148 } else
1149 log_info("Running in container, not using '%s' storage.", user_storage_to_string(USER_LUKS));
1150
2700fecd 1151 r = path_is_fs_type(get_home_root(), BTRFS_SUPER_MAGIC);
1dfe5de0 1152 if (r < 0)
2700fecd 1153 log_warning_errno(r, "Failed to determine file system of %s, ignoring: %m", get_home_root());
1dfe5de0 1154 if (r > 0) {
2700fecd 1155 log_info("%s is on btrfs, using '%s' as storage.", get_home_root(), user_storage_to_string(USER_SUBVOLUME));
1dfe5de0
LP
1156 *ret = USER_SUBVOLUME;
1157 } else {
2700fecd 1158 log_info("%s is on simple file system, using '%s' as storage.", get_home_root(), user_storage_to_string(USER_DIRECTORY));
1dfe5de0
LP
1159 *ret = USER_DIRECTORY;
1160 }
1161
1162 return 0;
1163}
1164
70a5db58 1165static int home_create(UserRecord *h, UserRecord **ret_home) {
7b78db28 1166 _cleanup_(strv_free_erasep) char **effective_passwords = NULL;
a74e2e44 1167 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
70a5db58 1168 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL;
7b78db28 1169 _cleanup_(password_cache_free) PasswordCache cache = {};
1dfe5de0
LP
1170 UserStorage new_storage = _USER_STORAGE_INVALID;
1171 const char *new_fs = NULL;
70a5db58
LP
1172 int r;
1173
1174 assert(h);
1175
1176 if (!h->user_name)
1177 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks name, refusing.");
1178 if (!uid_is_valid(h->uid))
1179 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
1180
7b78db28 1181 r = user_record_compile_effective_passwords(h, &cache, &effective_passwords);
70a5db58
LP
1182 if (r < 0)
1183 return r;
1184
1185 r = user_record_test_home_directory_and_warn(h);
1186 if (r < 0)
1187 return r;
1188 if (r != USER_TEST_ABSENT)
1189 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Home directory %s already exists, refusing.", user_record_home_directory(h));
1190
70a5db58 1191 if (h->storage < 0) {
1dfe5de0 1192 r = determine_default_storage(&new_storage);
70a5db58 1193 if (r < 0)
1dfe5de0
LP
1194 return r;
1195 }
70a5db58 1196
1dfe5de0
LP
1197 if ((h->storage == USER_LUKS ||
1198 (h->storage < 0 && new_storage == USER_LUKS)) &&
1199 !h->file_system_type)
1200 new_fs = getenv("SYSTEMD_HOME_DEFAULT_FILE_SYSTEM_TYPE");
70a5db58 1201
1dfe5de0 1202 if (new_storage >= 0 || new_fs) {
70a5db58
LP
1203 r = user_record_add_binding(
1204 h,
1205 new_storage,
1206 NULL,
1207 SD_ID128_NULL,
1208 SD_ID128_NULL,
1209 SD_ID128_NULL,
1210 NULL,
1211 NULL,
1212 UINT64_MAX,
1dfe5de0 1213 new_fs,
70a5db58
LP
1214 NULL,
1215 UID_INVALID,
1216 GID_INVALID);
1217 if (r < 0)
1218 return log_error_errno(r, "Failed to change storage type to LUKS: %m");
70a5db58
LP
1219 }
1220
1221 r = user_record_test_image_path_and_warn(h);
1222 if (r < 0)
1223 return r;
1224 if (!IN_SET(r, USER_TEST_ABSENT, USER_TEST_UNDEFINED, USER_TEST_MAYBE))
1225 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Image path %s already exists, refusing.", user_record_image_path(h));
1226
1227 switch (user_record_storage(h)) {
1228
1229 case USER_LUKS:
7b78db28 1230 r = home_create_luks(h, &cache, effective_passwords, &new_home);
70a5db58
LP
1231 break;
1232
1233 case USER_DIRECTORY:
1234 case USER_SUBVOLUME:
1235 r = home_create_directory_or_subvolume(h, &new_home);
1236 break;
1237
1238 case USER_FSCRYPT:
1239 r = home_create_fscrypt(h, effective_passwords, &new_home);
1240 break;
1241
1242 case USER_CIFS:
a74e2e44 1243 r = home_create_cifs(h, &setup, &new_home);
70a5db58
LP
1244 break;
1245
1246 default:
1247 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY),
1248 "Creating home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1249 }
1250 if (r < 0)
1251 return r;
1252
1253 if (user_record_equal(h, new_home)) {
1254 *ret_home = NULL;
1255 return 0;
1256 }
1257
1258 *ret_home = TAKE_PTR(new_home);
1259 return 1;
1260}
1261
1262static int home_remove(UserRecord *h) {
1263 bool deleted = false;
1264 const char *ip, *hd;
1265 int r;
1266
1267 assert(h);
1268
1269 if (!h->user_name)
1270 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, refusing.");
1271 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
1272 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Removing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1273
1274 hd = user_record_home_directory(h);
1275
1276 r = user_record_test_home_directory_and_warn(h);
1277 if (r < 0)
1278 return r;
1279 if (r == USER_TEST_MOUNTED)
1280 return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Directory %s is still mounted, refusing.", hd);
1281
1282 assert(hd);
1283
1284 r = user_record_test_image_path_and_warn(h);
1285 if (r < 0)
1286 return r;
1287
1288 ip = user_record_image_path(h);
1289
1290 switch (user_record_storage(h)) {
1291
1292 case USER_LUKS: {
1293 struct stat st;
1294
1295 assert(ip);
1296
1297 if (stat(ip, &st) < 0) {
6b8664cb 1298 if (errno != ENOENT)
80ace4f2 1299 return log_error_errno(errno, "Failed to stat() %s: %m", ip);
70a5db58
LP
1300
1301 } else {
1302 if (S_ISREG(st.st_mode)) {
1303 if (unlink(ip) < 0) {
1304 if (errno != ENOENT)
1305 return log_error_errno(errno, "Failed to remove %s: %m", ip);
86019efa
LP
1306 } else {
1307 _cleanup_free_ char *parent = NULL;
1308
70a5db58
LP
1309 deleted = true;
1310
86019efa
LP
1311 r = path_extract_directory(ip, &parent);
1312 if (r < 0)
1313 log_debug_errno(r, "Failed to determine parent directory of '%s': %m", ip);
1314 else {
1315 r = fsync_path_at(AT_FDCWD, parent);
1316 if (r < 0)
1317 log_debug_errno(r, "Failed to synchronize disk after deleting '%s', ignoring: %m", ip);
1318 }
1319 }
1320
70a5db58
LP
1321 } else if (S_ISBLK(st.st_mode))
1322 log_info("Not removing file system on block device %s.", ip);
1323 else
1324 return log_error_errno(SYNTHETIC_ERRNO(ENOTBLK), "Image file %s is neither block device, nor regular, refusing removal.", ip);
1325 }
1326
1327 break;
1328 }
1329
1330 case USER_SUBVOLUME:
1331 case USER_DIRECTORY:
1332 case USER_FSCRYPT:
1333 assert(ip);
1334
86019efa 1335 r = rm_rf(ip, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_SYNCFS);
70a5db58
LP
1336 if (r < 0) {
1337 if (r != -ENOENT)
1338 return log_warning_errno(r, "Failed to remove %s: %m", ip);
1339 } else
1340 deleted = true;
1341
1342 /* If the image path and the home directory are the same invalidate the home directory, so
1343 * that we don't remove it anymore */
1344 if (path_equal(ip, hd))
1345 hd = NULL;
1346
1347 break;
1348
1349 case USER_CIFS:
1350 /* Nothing else to do here: we won't remove remote stuff. */
1351 log_info("Not removing home directory on remote server.");
1352 break;
1353
1354 default:
04499a70 1355 assert_not_reached();
70a5db58
LP
1356 }
1357
1358 if (hd) {
1359 if (rmdir(hd) < 0) {
1360 if (errno != ENOENT)
1361 return log_error_errno(errno, "Failed to remove %s, ignoring: %m", hd);
1362 } else
1363 deleted = true;
1364 }
1365
86019efa
LP
1366 if (deleted) {
1367 if (user_record_drop_caches(h))
1368 drop_caches_now();
1369
70a5db58 1370 log_info("Everything completed.");
86019efa 1371 } else
e4ff0393
FS
1372 return log_notice_errno(SYNTHETIC_ERRNO(EALREADY),
1373 "Nothing to remove.");
70a5db58
LP
1374
1375 return 0;
1376}
1377
e1df968b 1378static int home_validate_update(UserRecord *h, HomeSetup *setup, HomeSetupFlags *flags) {
70a5db58
LP
1379 bool has_mount = false;
1380 int r;
1381
1382 assert(h);
1383 assert(setup);
1384
1385 if (!h->user_name)
1386 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks user name, refusing.");
1387 if (!uid_is_valid(h->uid))
1388 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record lacks UID, refusing.");
1389 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT, USER_CIFS))
1390 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Processing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1391
1392 r = user_record_test_home_directory_and_warn(h);
1393 if (r < 0)
1394 return r;
1395
1396 has_mount = r == USER_TEST_MOUNTED;
1397
1398 r = user_record_test_image_path_and_warn(h);
1399 if (r < 0)
1400 return r;
1401 if (r == USER_TEST_ABSENT)
1402 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "Image path %s does not exist", user_record_image_path(h));
1403
1404 switch (user_record_storage(h)) {
1405
1406 case USER_DIRECTORY:
1407 case USER_SUBVOLUME:
1408 case USER_FSCRYPT:
1409 case USER_CIFS:
1410 break;
1411
1412 case USER_LUKS: {
e1ab6635 1413 r = home_get_state_luks(h, setup);
70a5db58
LP
1414 if (r < 0)
1415 return r;
1416 if ((r > 0) != has_mount)
1417 return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Home mount incompletely set up.");
1418
1419 break;
1420 }
1421
1422 default:
04499a70 1423 assert_not_reached();
70a5db58
LP
1424 }
1425
e1df968b
LP
1426 if (flags)
1427 SET_FLAG(*flags, HOME_SETUP_ALREADY_ACTIVATED, has_mount);
1428
70a5db58
LP
1429 return has_mount; /* return true if the home record is already active */
1430}
1431
1432static int home_update(UserRecord *h, UserRecord **ret) {
1433 _cleanup_(user_record_unrefp) UserRecord *new_home = NULL, *header_home = NULL, *embedded_home = NULL;
66aa51f8 1434 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
7b78db28 1435 _cleanup_(password_cache_free) PasswordCache cache = {};
e1df968b 1436 HomeSetupFlags flags = 0;
70a5db58
LP
1437 int r;
1438
1439 assert(h);
1440 assert(ret);
1441
7b78db28 1442 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ true);
70a5db58
LP
1443 if (r < 0)
1444 return r;
c8f145ad 1445 assert(r > 0); /* Insist that a password was verified */
70a5db58 1446
e1df968b 1447 r = home_validate_update(h, &setup, &flags);
70a5db58
LP
1448 if (r < 0)
1449 return r;
1450
e1df968b 1451 r = home_setup(h, flags, &cache, &setup, &header_home);
70a5db58
LP
1452 if (r < 0)
1453 return r;
1454
7b78db28 1455 r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER, &cache, &embedded_home, &new_home);
70a5db58
LP
1456 if (r < 0)
1457 return r;
1458
1459 r = home_store_header_identity_luks(new_home, &setup, header_home);
1460 if (r < 0)
1461 return r;
1462
1463 r = home_store_embedded_identity(new_home, setup.root_fd, h->uid, embedded_home);
1464 if (r < 0)
1465 return r;
1466
1467 r = home_extend_embedded_identity(new_home, h, &setup);
1468 if (r < 0)
1469 return r;
1470
1471 r = home_sync_and_statfs(setup.root_fd, NULL);
1472 if (r < 0)
1473 return r;
1474
66aa51f8 1475 r = home_setup_done(&setup);
70a5db58
LP
1476 if (r < 0)
1477 return r;
1478
1479 log_info("Everything completed.");
1480
1481 *ret = TAKE_PTR(new_home);
1482 return 0;
1483}
1484
1485static int home_resize(UserRecord *h, UserRecord **ret) {
66aa51f8 1486 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
7b78db28 1487 _cleanup_(password_cache_free) PasswordCache cache = {};
e1df968b 1488 HomeSetupFlags flags = 0;
70a5db58
LP
1489 int r;
1490
1491 assert(h);
1492 assert(ret);
1493
1494 if (h->disk_size == UINT64_MAX)
1495 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No target size specified, refusing.");
1496
7b78db28 1497 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ true);
70a5db58
LP
1498 if (r < 0)
1499 return r;
c8f145ad 1500 assert(r > 0); /* Insist that a password was verified */
70a5db58 1501
e1df968b 1502 r = home_validate_update(h, &setup, &flags);
70a5db58
LP
1503 if (r < 0)
1504 return r;
1505
70a5db58
LP
1506 switch (user_record_storage(h)) {
1507
1508 case USER_LUKS:
e1df968b 1509 return home_resize_luks(h, flags, &cache, &setup, ret);
70a5db58
LP
1510
1511 case USER_DIRECTORY:
1512 case USER_SUBVOLUME:
1513 case USER_FSCRYPT:
e1df968b 1514 return home_resize_directory(h, flags, &cache, &setup, ret);
70a5db58
LP
1515
1516 default:
1517 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Resizing home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1518 }
1519}
1520
1521static int home_passwd(UserRecord *h, UserRecord **ret_home) {
1522 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL;
7b78db28 1523 _cleanup_(strv_free_erasep) char **effective_passwords = NULL;
66aa51f8 1524 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
7b78db28 1525 _cleanup_(password_cache_free) PasswordCache cache = {};
e1df968b 1526 HomeSetupFlags flags = 0;
70a5db58
LP
1527 int r;
1528
1529 assert(h);
1530 assert(ret_home);
1531
1532 if (!IN_SET(user_record_storage(h), USER_LUKS, USER_DIRECTORY, USER_SUBVOLUME, USER_FSCRYPT))
1533 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)));
1534
7b78db28 1535 r = user_record_compile_effective_passwords(h, &cache, &effective_passwords);
70a5db58
LP
1536 if (r < 0)
1537 return r;
1538
e1df968b 1539 r = home_validate_update(h, &setup, &flags);
70a5db58
LP
1540 if (r < 0)
1541 return r;
1542
e1df968b 1543 r = home_setup(h, flags, &cache, &setup, &header_home);
70a5db58
LP
1544 if (r < 0)
1545 return r;
1546
7b78db28 1547 r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_REQUIRE_NEWER_OR_EQUAL, &cache, &embedded_home, &new_home);
70a5db58
LP
1548 if (r < 0)
1549 return r;
1550
1551 switch (user_record_storage(h)) {
1552
1553 case USER_LUKS:
7b78db28 1554 r = home_passwd_luks(h, &setup, &cache, effective_passwords);
70a5db58
LP
1555 if (r < 0)
1556 return r;
1557 break;
1558
1559 case USER_FSCRYPT:
7b78db28 1560 r = home_passwd_fscrypt(h, &setup, &cache, effective_passwords);
70a5db58
LP
1561 if (r < 0)
1562 return r;
1563 break;
1564
1565 default:
1566 break;
1567 }
1568
1569 r = home_store_header_identity_luks(new_home, &setup, header_home);
1570 if (r < 0)
1571 return r;
1572
1573 r = home_store_embedded_identity(new_home, setup.root_fd, h->uid, embedded_home);
1574 if (r < 0)
1575 return r;
1576
1577 r = home_extend_embedded_identity(new_home, h, &setup);
1578 if (r < 0)
1579 return r;
1580
1581 r = home_sync_and_statfs(setup.root_fd, NULL);
1582 if (r < 0)
1583 return r;
1584
66aa51f8 1585 r = home_setup_done(&setup);
70a5db58
LP
1586 if (r < 0)
1587 return r;
1588
1589 log_info("Everything completed.");
1590
1591 *ret_home = TAKE_PTR(new_home);
1592 return 1;
1593}
1594
1595static int home_inspect(UserRecord *h, UserRecord **ret_home) {
1596 _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *new_home = NULL;
66aa51f8 1597 _cleanup_(home_setup_done) HomeSetup setup = HOME_SETUP_INIT;
7b78db28 1598 _cleanup_(password_cache_free) PasswordCache cache = {};
e1df968b 1599 HomeSetupFlags flags = 0;
70a5db58
LP
1600 int r;
1601
1602 assert(h);
1603 assert(ret_home);
1604
7b78db28 1605 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
70a5db58
LP
1606 if (r < 0)
1607 return r;
1608
e1df968b 1609 r = home_validate_update(h, &setup, &flags);
70a5db58
LP
1610 if (r < 0)
1611 return r;
1612
e1df968b 1613 r = home_setup(h, flags, &cache, &setup, &header_home);
70a5db58
LP
1614 if (r < 0)
1615 return r;
1616
7b78db28 1617 r = home_load_embedded_identity(h, setup.root_fd, header_home, USER_RECONCILE_ANY, &cache, NULL, &new_home);
70a5db58
LP
1618 if (r < 0)
1619 return r;
1620
1621 r = home_extend_embedded_identity(new_home, h, &setup);
1622 if (r < 0)
1623 return r;
1624
66aa51f8 1625 r = home_setup_done(&setup);
70a5db58
LP
1626 if (r < 0)
1627 return r;
1628
1629 log_info("Everything completed.");
1630
1631 *ret_home = TAKE_PTR(new_home);
1632 return 1;
1633}
1634
1635static int home_lock(UserRecord *h) {
1636 int r;
1637
1638 assert(h);
1639
1640 if (!h->user_name)
1641 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
1642 if (user_record_storage(h) != USER_LUKS)
1643 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Locking home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1644
1645 r = user_record_test_home_directory_and_warn(h);
1646 if (r < 0)
1647 return r;
1648 if (r != USER_TEST_MOUNTED)
1649 return log_error_errno(SYNTHETIC_ERRNO(ENOEXEC), "Home directory of %s is not mounted, can't lock.", h->user_name);
1650
1651 r = home_lock_luks(h);
1652 if (r < 0)
1653 return r;
1654
1655 log_info("Everything completed.");
1656 return 1;
1657}
1658
1659static int home_unlock(UserRecord *h) {
7b78db28 1660 _cleanup_(password_cache_free) PasswordCache cache = {};
70a5db58
LP
1661 int r;
1662
1663 assert(h);
1664
1665 if (!h->user_name)
1666 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User record incomplete, refusing.");
1667 if (user_record_storage(h) != USER_LUKS)
1668 return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Unlocking home directories of type '%s' currently not supported.", user_storage_to_string(user_record_storage(h)));
1669
1670 /* Note that we don't check if $HOME is actually mounted, since we want to avoid disk accesses on
1671 * that mount until we have resumed the device. */
1672
7b78db28 1673 r = user_record_authenticate(h, h, &cache, /* strict_verify= */ false);
70a5db58
LP
1674 if (r < 0)
1675 return r;
1676
7b78db28 1677 r = home_unlock_luks(h, &cache);
70a5db58
LP
1678 if (r < 0)
1679 return r;
1680
1681 log_info("Everything completed.");
1682 return 1;
1683}
1684
1685static int run(int argc, char *argv[]) {
1686 _cleanup_(user_record_unrefp) UserRecord *home = NULL, *new_home = NULL;
1687 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
1688 _cleanup_(fclosep) FILE *opened_file = NULL;
1689 unsigned line = 0, column = 0;
1690 const char *json_path = NULL;
1691 FILE *json_file;
1692 usec_t start;
1693 int r;
1694
1695 start = now(CLOCK_MONOTONIC);
1696
d2acb93d 1697 log_setup();
70a5db58
LP
1698
1699 umask(0022);
1700
1701 if (argc < 2 || argc > 3)
1702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes one or two arguments.");
1703
1704 if (argc > 2) {
1705 json_path = argv[2];
1706
1707 opened_file = fopen(json_path, "re");
1708 if (!opened_file)
1709 return log_error_errno(errno, "Failed to open %s: %m", json_path);
1710
1711 json_file = opened_file;
1712 } else {
1713 json_path = "<stdin>";
1714 json_file = stdin;
1715 }
1716
1717 r = json_parse_file(json_file, json_path, JSON_PARSE_SENSITIVE, &v, &line, &column);
1718 if (r < 0)
1719 return log_error_errno(r, "[%s:%u:%u] Failed to parse JSON data: %m", json_path, line, column);
1720
1721 home = user_record_new();
1722 if (!home)
1723 return log_oom();
1724
bfc0cc1a 1725 r = user_record_load(home, v, USER_RECORD_LOAD_FULL|USER_RECORD_LOG|USER_RECORD_PERMISSIVE);
70a5db58
LP
1726 if (r < 0)
1727 return r;
1728
1729 /* Well known return values of these operations, that systemd-homed knows and converts to proper D-Bus errors:
1730 *
162392b7
ZJS
1731 * EMSGSIZE → file systems of this type cannot be shrunk
1732 * ETXTBSY → file systems of this type can only be shrunk offline
70a5db58
LP
1733 * ERANGE → file system size too small
1734 * ENOLINK → system does not support selected storage backend
1735 * EPROTONOSUPPORT → system does not support selected file system
1736 * ENOTTY → operation not support on this storage
1737 * ESOCKTNOSUPPORT → operation not support on this file system
1738 * ENOKEY → password incorrect (or not sufficient, or not supplied)
87d7893c 1739 * EREMOTEIO → recovery key incorrect (or not sufficeint, or not supplied — only if no passwords defined)
70a5db58 1740 * EBADSLT → similar, but PKCS#11 device is defined and might be able to provide password, if it was plugged in which it is not
7b78db28 1741 * ENOANO → suitable PKCS#11/FIDO2 device found, but PIN is missing to unlock it
70a5db58 1742 * ERFKILL → suitable PKCS#11 device found, but OK to ask for on-device interactive authentication not given
7b78db28 1743 * EMEDIUMTYPE → suitable FIDO2 device found, but OK to ask for user presence not given
17e7561a 1744 * ENOCSI → suitable FIDO2 device found, but OK to ask for user verification not given
7b78db28
LP
1745 * ENOSTR → suitable FIDO2 device found, but user didn't react to action request on token quickly enough
1746 * EOWNERDEAD → suitable PKCS#11/FIDO2 device found, but its PIN is locked
1747 * ENOLCK → suitable PKCS#11/FIDO2 device found, but PIN incorrect
70a5db58
LP
1748 * ETOOMANYREFS → suitable PKCS#11 device found, but PIN incorrect, and only few tries left
1749 * EUCLEAN → suitable PKCS#11 device found, but PIN incorrect, and only one try left
1750 * EBUSY → file system is currently active
1751 * ENOEXEC → file system is currently not active
1752 * ENOSPC → not enough disk space for operation
cbffdcec 1753 * EKEYREVOKED → user record has not suitable hashed password or pkcs#11 entry, we cannot authenticate
2aaf565a 1754 * EADDRINUSE → home image is already used elsewhere (lock taken)
70a5db58
LP
1755 */
1756
1757 if (streq(argv[1], "activate"))
1758 r = home_activate(home, &new_home);
1759 else if (streq(argv[1], "deactivate"))
1760 r = home_deactivate(home, false);
1761 else if (streq(argv[1], "deactivate-force"))
1762 r = home_deactivate(home, true);
1763 else if (streq(argv[1], "create"))
1764 r = home_create(home, &new_home);
1765 else if (streq(argv[1], "remove"))
1766 r = home_remove(home);
1767 else if (streq(argv[1], "update"))
1768 r = home_update(home, &new_home);
1769 else if (streq(argv[1], "resize"))
1770 r = home_resize(home, &new_home);
1771 else if (streq(argv[1], "passwd"))
1772 r = home_passwd(home, &new_home);
1773 else if (streq(argv[1], "inspect"))
1774 r = home_inspect(home, &new_home);
1775 else if (streq(argv[1], "lock"))
1776 r = home_lock(home);
1777 else if (streq(argv[1], "unlock"))
1778 r = home_unlock(home);
1779 else
1780 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb '%s'.", argv[1]);
87d7893c 1781 if (IN_SET(r, -ENOKEY, -EREMOTEIO) && !strv_isempty(home->password) ) { /* There were passwords specified but they were incorrect */
70a5db58
LP
1782 usec_t end, n, d;
1783
1784 /* Make sure bad password replies always take at least 3s, and if longer multiples of 3s, so
1785 * that it's not clear how long we actually needed for our calculations. */
1786 n = now(CLOCK_MONOTONIC);
1787 assert(n >= start);
1788
1789 d = usec_sub_unsigned(n, start);
1790 if (d > BAD_PASSWORD_DELAY_USEC)
1791 end = start + DIV_ROUND_UP(d, BAD_PASSWORD_DELAY_USEC) * BAD_PASSWORD_DELAY_USEC;
1792 else
1793 end = start + BAD_PASSWORD_DELAY_USEC;
1794
1795 if (n < end)
1796 (void) usleep(usec_sub_unsigned(end, n));
1797 }
1798 if (r < 0)
1799 return r;
1800
1801 /* We always pass the new record back, regardless if it changed or not. This allows our caller to
1802 * prepare a fresh record, send to us, and only if it works use it without having to keep a local
1803 * copy. */
1804 if (new_home)
1805 json_variant_dump(new_home->json, JSON_FORMAT_NEWLINE, stdout, NULL);
1806
1807 return 0;
1808}
1809
1810DEFINE_MAIN_FUNCTION(run);