]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/home/homectl.c
Merge pull request #21440 from poettering/homed-initial-fs-size
[thirdparty/systemd.git] / src / home / homectl.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <getopt.h>
4
5 #include "sd-bus.h"
6
7 #include "ask-password-api.h"
8 #include "bus-common-errors.h"
9 #include "bus-error.h"
10 #include "bus-locator.h"
11 #include "cgroup-util.h"
12 #include "dns-domain.h"
13 #include "env-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "format-table.h"
17 #include "fs-util.h"
18 #include "glyph-util.h"
19 #include "home-util.h"
20 #include "homectl-fido2.h"
21 #include "homectl-pkcs11.h"
22 #include "homectl-recovery-key.h"
23 #include "libfido2-util.h"
24 #include "locale-util.h"
25 #include "main-func.h"
26 #include "memory-util.h"
27 #include "pager.h"
28 #include "parse-argument.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "percent-util.h"
32 #include "pkcs11-util.h"
33 #include "pretty-print.h"
34 #include "process-util.h"
35 #include "pwquality-util.h"
36 #include "rlimit-util.h"
37 #include "spawn-polkit-agent.h"
38 #include "terminal-util.h"
39 #include "uid-alloc-range.h"
40 #include "user-record-pwquality.h"
41 #include "user-record-show.h"
42 #include "user-record-util.h"
43 #include "user-record.h"
44 #include "user-util.h"
45 #include "verbs.h"
46
47 static PagerFlags arg_pager_flags = 0;
48 static bool arg_legend = true;
49 static bool arg_ask_password = true;
50 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
51 static const char *arg_host = NULL;
52 static const char *arg_identity = NULL;
53 static JsonVariant *arg_identity_extra = NULL;
54 static JsonVariant *arg_identity_extra_privileged = NULL;
55 static JsonVariant *arg_identity_extra_this_machine = NULL;
56 static JsonVariant *arg_identity_extra_rlimits = NULL;
57 static char **arg_identity_filter = NULL; /* this one is also applied to 'privileged' and 'thisMachine' subobjects */
58 static char **arg_identity_filter_rlimits = NULL;
59 static uint64_t arg_disk_size = UINT64_MAX;
60 static uint64_t arg_disk_size_relative = UINT64_MAX;
61 static char **arg_pkcs11_token_uri = NULL;
62 static char **arg_fido2_device = NULL;
63 static Fido2EnrollFlags arg_fido2_lock_with = FIDO2ENROLL_PIN | FIDO2ENROLL_UP;
64 static bool arg_recovery_key = false;
65 static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
66 static bool arg_and_resize = false;
67 static bool arg_and_change_password = false;
68 static enum {
69 EXPORT_FORMAT_FULL, /* export the full record */
70 EXPORT_FORMAT_STRIPPED, /* strip "state" + "binding", but leave signature in place */
71 EXPORT_FORMAT_MINIMAL, /* also strip signature */
72 } arg_export_format = EXPORT_FORMAT_FULL;
73
74 STATIC_DESTRUCTOR_REGISTER(arg_identity_extra, json_variant_unrefp);
75 STATIC_DESTRUCTOR_REGISTER(arg_identity_extra_this_machine, json_variant_unrefp);
76 STATIC_DESTRUCTOR_REGISTER(arg_identity_extra_privileged, json_variant_unrefp);
77 STATIC_DESTRUCTOR_REGISTER(arg_identity_extra_rlimits, json_variant_unrefp);
78 STATIC_DESTRUCTOR_REGISTER(arg_identity_filter, strv_freep);
79 STATIC_DESTRUCTOR_REGISTER(arg_identity_filter_rlimits, strv_freep);
80 STATIC_DESTRUCTOR_REGISTER(arg_pkcs11_token_uri, strv_freep);
81 STATIC_DESTRUCTOR_REGISTER(arg_fido2_device, strv_freep);
82
83 static const BusLocator *bus_mgr;
84
85 static bool identity_properties_specified(void) {
86 return
87 arg_identity ||
88 !json_variant_is_blank_object(arg_identity_extra) ||
89 !json_variant_is_blank_object(arg_identity_extra_privileged) ||
90 !json_variant_is_blank_object(arg_identity_extra_this_machine) ||
91 !json_variant_is_blank_object(arg_identity_extra_rlimits) ||
92 !strv_isempty(arg_identity_filter) ||
93 !strv_isempty(arg_identity_filter_rlimits) ||
94 !strv_isempty(arg_pkcs11_token_uri) ||
95 !strv_isempty(arg_fido2_device);
96 }
97
98 static int acquire_bus(sd_bus **bus) {
99 int r;
100
101 assert(bus);
102
103 if (*bus)
104 return 0;
105
106 r = bus_connect_transport(arg_transport, arg_host, false, bus);
107 if (r < 0)
108 return bus_log_connect_error(r, arg_transport);
109
110 (void) sd_bus_set_allow_interactive_authorization(*bus, arg_ask_password);
111
112 return 0;
113 }
114
115 static int list_homes(int argc, char *argv[], void *userdata) {
116 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
117 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
118 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
119 _cleanup_(table_unrefp) Table *table = NULL;
120 int r;
121
122 r = acquire_bus(&bus);
123 if (r < 0)
124 return r;
125
126 r = bus_call_method(bus, bus_mgr, "ListHomes", &error, &reply, NULL);
127 if (r < 0)
128 return log_error_errno(r, "Failed to list homes: %s", bus_error_message(&error, r));
129
130 table = table_new("name", "uid", "gid", "state", "realname", "home", "shell");
131 if (!table)
132 return log_oom();
133
134 r = sd_bus_message_enter_container(reply, 'a', "(susussso)");
135 if (r < 0)
136 return bus_log_parse_error(r);
137
138 for (;;) {
139 const char *name, *state, *realname, *home, *shell, *color;
140 TableCell *cell;
141 uint32_t uid, gid;
142
143 r = sd_bus_message_read(reply, "(susussso)", &name, &uid, &state, &gid, &realname, &home, &shell, NULL);
144 if (r < 0)
145 return bus_log_parse_error(r);
146 if (r == 0)
147 break;
148
149 r = table_add_many(table,
150 TABLE_STRING, name,
151 TABLE_UID, uid,
152 TABLE_GID, gid);
153 if (r < 0)
154 return table_log_add_error(r);
155
156
157 r = table_add_cell(table, &cell, TABLE_STRING, state);
158 if (r < 0)
159 return table_log_add_error(r);
160
161 color = user_record_state_color(state);
162 if (color)
163 (void) table_set_color(table, cell, color);
164
165 r = table_add_many(table,
166 TABLE_STRING, strna(empty_to_null(realname)),
167 TABLE_STRING, home,
168 TABLE_STRING, strna(empty_to_null(shell)));
169 if (r < 0)
170 return table_log_add_error(r);
171 }
172
173 r = sd_bus_message_exit_container(reply);
174 if (r < 0)
175 return bus_log_parse_error(r);
176
177 if (table_get_rows(table) > 1 || !FLAGS_SET(arg_json_format_flags, JSON_FORMAT_OFF)) {
178 r = table_set_sort(table, (size_t) 0);
179 if (r < 0)
180 return table_log_sort_error(r);
181
182 r = table_print_with_pager(table, arg_json_format_flags, arg_pager_flags, arg_legend);
183 if (r < 0)
184 return r;
185 }
186
187 if (arg_legend && (arg_json_format_flags & JSON_FORMAT_OFF)) {
188 if (table_get_rows(table) > 1)
189 printf("\n%zu home areas listed.\n", table_get_rows(table) - 1);
190 else
191 printf("No home areas.\n");
192 }
193
194 return 0;
195 }
196
197 static int acquire_existing_password(
198 const char *user_name,
199 UserRecord *hr,
200 bool emphasize_current,
201 AskPasswordFlags flags) {
202
203 _cleanup_(strv_free_erasep) char **password = NULL;
204 _cleanup_free_ char *question = NULL;
205 char *e;
206 int r;
207
208 assert(user_name);
209 assert(hr);
210
211 e = getenv("PASSWORD");
212 if (e) {
213 /* People really shouldn't use environment variables for passing passwords. We support this
214 * only for testing purposes, and do not document the behaviour, so that people won't
215 * actually use this outside of testing. */
216
217 r = user_record_set_password(hr, STRV_MAKE(e), true);
218 if (r < 0)
219 return log_error_errno(r, "Failed to store password: %m");
220
221 assert_se(unsetenv_erase("PASSWORD") >= 0);
222 return 1;
223 }
224
225 /* If this is not our own user, then don't use the password cache */
226 if (is_this_me(user_name) <= 0)
227 SET_FLAG(flags, ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE, false);
228
229 if (asprintf(&question, emphasize_current ?
230 "Please enter current password for user %s:" :
231 "Please enter password for user %s:",
232 user_name) < 0)
233 return log_oom();
234
235 r = ask_password_auto(question,
236 /* icon= */ "user-home",
237 NULL,
238 /* key_name= */ "home-password",
239 /* credential_name= */ "home.password",
240 USEC_INFINITY,
241 flags,
242 &password);
243 if (r == -EUNATCH) { /* EUNATCH is returned if no password was found and asking interactively was
244 * disabled via the flags. Not an error for us. */
245 log_debug_errno(r, "No passwords acquired.");
246 return 0;
247 }
248 if (r < 0)
249 return log_error_errno(r, "Failed to acquire password: %m");
250
251 r = user_record_set_password(hr, password, true);
252 if (r < 0)
253 return log_error_errno(r, "Failed to store password: %m");
254
255 return 1;
256 }
257
258 static int acquire_recovery_key(
259 const char *user_name,
260 UserRecord *hr,
261 AskPasswordFlags flags) {
262
263 _cleanup_(strv_free_erasep) char **recovery_key = NULL;
264 _cleanup_free_ char *question = NULL;
265 char *e;
266 int r;
267
268 assert(user_name);
269 assert(hr);
270
271 e = getenv("RECOVERY_KEY");
272 if (e) {
273 /* People really shouldn't use environment variables for passing secrets. We support this
274 * only for testing purposes, and do not document the behaviour, so that people won't
275 * actually use this outside of testing. */
276
277 r = user_record_set_password(hr, STRV_MAKE(e), true); /* recovery keys are stored in the record exactly like regular passwords! */
278 if (r < 0)
279 return log_error_errno(r, "Failed to store recovery key: %m");
280
281 assert_se(unsetenv_erase("RECOVERY_KEY") >= 0);
282 return 1;
283 }
284
285 /* If this is not our own user, then don't use the password cache */
286 if (is_this_me(user_name) <= 0)
287 SET_FLAG(flags, ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE, false);
288
289 if (asprintf(&question, "Please enter recovery key for user %s:", user_name) < 0)
290 return log_oom();
291
292 r = ask_password_auto(question,
293 /* icon= */ "user-home",
294 NULL,
295 /* key_name= */ "home-recovery-key",
296 /* credential_name= */ "home.recovery-key",
297 USEC_INFINITY,
298 flags,
299 &recovery_key);
300 if (r == -EUNATCH) { /* EUNATCH is returned if no recovery key was found and asking interactively was
301 * disabled via the flags. Not an error for us. */
302 log_debug_errno(r, "No recovery keys acquired.");
303 return 0;
304 }
305 if (r < 0)
306 return log_error_errno(r, "Failed to acquire recovery keys: %m");
307
308 r = user_record_set_password(hr, recovery_key, true);
309 if (r < 0)
310 return log_error_errno(r, "Failed to store recovery keys: %m");
311
312 return 1;
313 }
314
315 static int acquire_token_pin(
316 const char *user_name,
317 UserRecord *hr,
318 AskPasswordFlags flags) {
319
320 _cleanup_(strv_free_erasep) char **pin = NULL;
321 _cleanup_free_ char *question = NULL;
322 char *e;
323 int r;
324
325 assert(user_name);
326 assert(hr);
327
328 e = getenv("PIN");
329 if (e) {
330 r = user_record_set_token_pin(hr, STRV_MAKE(e), false);
331 if (r < 0)
332 return log_error_errno(r, "Failed to store token PIN: %m");
333
334 assert_se(unsetenv_erase("PIN") >= 0);
335 return 1;
336 }
337
338 /* If this is not our own user, then don't use the password cache */
339 if (is_this_me(user_name) <= 0)
340 SET_FLAG(flags, ASK_PASSWORD_ACCEPT_CACHED|ASK_PASSWORD_PUSH_CACHE, false);
341
342 if (asprintf(&question, "Please enter security token PIN for user %s:", user_name) < 0)
343 return log_oom();
344
345 r = ask_password_auto(
346 question,
347 /* icon= */ "user-home",
348 NULL,
349 /* key_name= */ "token-pin",
350 /* credential_name= */ "home.token-pin",
351 USEC_INFINITY,
352 flags,
353 &pin);
354 if (r == -EUNATCH) { /* EUNATCH is returned if no PIN was found and asking interactively was disabled
355 * via the flags. Not an error for us. */
356 log_debug_errno(r, "No security token PINs acquired.");
357 return 0;
358 }
359 if (r < 0)
360 return log_error_errno(r, "Failed to acquire security token PIN: %m");
361
362 r = user_record_set_token_pin(hr, pin, false);
363 if (r < 0)
364 return log_error_errno(r, "Failed to store security token PIN: %m");
365
366 return 1;
367 }
368
369 static int handle_generic_user_record_error(
370 const char *user_name,
371 UserRecord *hr,
372 const sd_bus_error *error,
373 int ret,
374 bool emphasize_current_password) {
375 int r;
376
377 assert(user_name);
378 assert(hr);
379
380 if (sd_bus_error_has_name(error, BUS_ERROR_HOME_ABSENT))
381 return log_error_errno(SYNTHETIC_ERRNO(EREMOTE),
382 "Home of user %s is currently absent, please plug in the necessary storage device or backing file system.", user_name);
383
384 else if (sd_bus_error_has_name(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT))
385 return log_error_errno(SYNTHETIC_ERRNO(ETOOMANYREFS),
386 "Too frequent unsuccessful login attempts for user %s, try again later.", user_name);
387
388 else if (sd_bus_error_has_name(error, BUS_ERROR_BAD_PASSWORD)) {
389
390 if (!strv_isempty(hr->password))
391 log_notice("Password incorrect or not sufficient, please try again.");
392
393 /* Don't consume cache entries or credentials here, we already tried that unsuccessfully. But
394 * let's push what we acquire here into the cache */
395 r = acquire_existing_password(
396 user_name,
397 hr,
398 emphasize_current_password,
399 ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_NO_CREDENTIAL);
400 if (r < 0)
401 return r;
402
403 } else if (sd_bus_error_has_name(error, BUS_ERROR_BAD_RECOVERY_KEY)) {
404
405 if (!strv_isempty(hr->password))
406 log_notice("Recovery key incorrect or not sufficient, please try again.");
407
408 /* Don't consume cache entries or credentials here, we already tried that unsuccessfully. But
409 * let's push what we acquire here into the cache */
410 r = acquire_recovery_key(
411 user_name,
412 hr,
413 ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_NO_CREDENTIAL);
414 if (r < 0)
415 return r;
416
417 } else if (sd_bus_error_has_name(error, BUS_ERROR_BAD_PASSWORD_AND_NO_TOKEN)) {
418
419 if (strv_isempty(hr->password))
420 log_notice("Security token not inserted, please enter password.");
421 else
422 log_notice("Password incorrect or not sufficient, and configured security token not inserted, please try again.");
423
424 r = acquire_existing_password(
425 user_name,
426 hr,
427 emphasize_current_password,
428 ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_NO_CREDENTIAL);
429 if (r < 0)
430 return r;
431
432 } else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_PIN_NEEDED)) {
433
434 /* First time the PIN is requested, let's accept cached data, and allow using credential store */
435 r = acquire_token_pin(
436 user_name,
437 hr,
438 ASK_PASSWORD_ACCEPT_CACHED | ASK_PASSWORD_PUSH_CACHE);
439 if (r < 0)
440 return r;
441
442 } else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_PROTECTED_AUTHENTICATION_PATH_NEEDED)) {
443
444 log_notice("%s%sPlease authenticate physically on security token.",
445 emoji_enabled() ? special_glyph(SPECIAL_GLYPH_TOUCH) : "",
446 emoji_enabled() ? " " : "");
447
448 r = user_record_set_pkcs11_protected_authentication_path_permitted(hr, true);
449 if (r < 0)
450 return log_error_errno(r, "Failed to set PKCS#11 protected authentication path permitted flag: %m");
451
452 } else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_USER_PRESENCE_NEEDED)) {
453
454 log_notice("%s%sPlease confirm presence on security token.",
455 emoji_enabled() ? special_glyph(SPECIAL_GLYPH_TOUCH) : "",
456 emoji_enabled() ? " " : "");
457
458 r = user_record_set_fido2_user_presence_permitted(hr, true);
459 if (r < 0)
460 return log_error_errno(r, "Failed to set FIDO2 user presence permitted flag: %m");
461
462 } else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_USER_VERIFICATION_NEEDED)) {
463
464 log_notice("%s%sPlease verify user on security token.",
465 emoji_enabled() ? special_glyph(SPECIAL_GLYPH_TOUCH) : "",
466 emoji_enabled() ? " " : "");
467
468 r = user_record_set_fido2_user_verification_permitted(hr, true);
469 if (r < 0)
470 return log_error_errno(r, "Failed to set FIDO2 user verification permitted flag: %m");
471
472 } else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_PIN_LOCKED))
473 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Security token PIN is locked, please unlock it first. (Hint: Removal and re-insertion might suffice.)");
474
475 else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_BAD_PIN)) {
476
477 log_notice("Security token PIN incorrect, please try again.");
478
479 /* If the previous PIN was wrong don't accept cached info anymore, but add to cache. Also, don't use the credential data */
480 r = acquire_token_pin(
481 user_name,
482 hr,
483 ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_NO_CREDENTIAL);
484 if (r < 0)
485 return r;
486
487 } else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_BAD_PIN_FEW_TRIES_LEFT)) {
488
489 log_notice("Security token PIN incorrect, please try again (only a few tries left!).");
490
491 r = acquire_token_pin(
492 user_name,
493 hr,
494 ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_NO_CREDENTIAL);
495 if (r < 0)
496 return r;
497
498 } else if (sd_bus_error_has_name(error, BUS_ERROR_TOKEN_BAD_PIN_ONE_TRY_LEFT)) {
499
500 log_notice("Security token PIN incorrect, please try again (only one try left!).");
501
502 r = acquire_token_pin(
503 user_name,
504 hr,
505 ASK_PASSWORD_PUSH_CACHE | ASK_PASSWORD_NO_CREDENTIAL);
506 if (r < 0)
507 return r;
508 } else
509 return log_error_errno(ret, "Operation on home %s failed: %s", user_name, bus_error_message(error, ret));
510
511 return 0;
512 }
513
514 static int acquire_passed_secrets(const char *user_name, UserRecord **ret) {
515 _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
516 int r;
517
518 assert(ret);
519
520 /* Generates an initial secret objects that contains passwords supplied via $PASSWORD, the password
521 * cache or the credentials subsystem, but excluding any interactive stuff. If nothing is passed,
522 * returns an empty secret object. */
523
524 secret = user_record_new();
525 if (!secret)
526 return log_oom();
527
528 r = acquire_existing_password(
529 user_name,
530 secret,
531 /* emphasize_current_password = */ false,
532 ASK_PASSWORD_ACCEPT_CACHED | ASK_PASSWORD_NO_TTY | ASK_PASSWORD_NO_AGENT);
533 if (r < 0)
534 return r;
535
536 r = acquire_token_pin(
537 user_name,
538 secret,
539 ASK_PASSWORD_ACCEPT_CACHED | ASK_PASSWORD_NO_TTY | ASK_PASSWORD_NO_AGENT);
540 if (r < 0)
541 return r;
542
543 r = acquire_recovery_key(
544 user_name,
545 secret,
546 ASK_PASSWORD_ACCEPT_CACHED | ASK_PASSWORD_NO_TTY | ASK_PASSWORD_NO_AGENT);
547 if (r < 0)
548 return r;
549
550 *ret = TAKE_PTR(secret);
551 return 0;
552 }
553
554 static int activate_home(int argc, char *argv[], void *userdata) {
555 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
556 int r, ret = 0;
557 char **i;
558
559 r = acquire_bus(&bus);
560 if (r < 0)
561 return r;
562
563 STRV_FOREACH(i, strv_skip(argv, 1)) {
564 _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
565
566 r = acquire_passed_secrets(*i, &secret);
567 if (r < 0)
568 return r;
569
570 for (;;) {
571 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
572 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
573
574 r = bus_message_new_method_call(bus, &m, bus_mgr, "ActivateHome");
575 if (r < 0)
576 return bus_log_create_error(r);
577
578 r = sd_bus_message_append(m, "s", *i);
579 if (r < 0)
580 return bus_log_create_error(r);
581
582 r = bus_message_append_secret(m, secret);
583 if (r < 0)
584 return bus_log_create_error(r);
585
586 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
587 if (r < 0) {
588 r = handle_generic_user_record_error(*i, secret, &error, r, /* emphasize_current_password= */ false);
589 if (r < 0) {
590 if (ret == 0)
591 ret = r;
592
593 break;
594 }
595 } else
596 break;
597 }
598 }
599
600 return ret;
601 }
602
603 static int deactivate_home(int argc, char *argv[], void *userdata) {
604 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
605 int r, ret = 0;
606 char **i;
607
608 r = acquire_bus(&bus);
609 if (r < 0)
610 return r;
611
612 STRV_FOREACH(i, strv_skip(argv, 1)) {
613 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
614 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
615
616 r = bus_message_new_method_call(bus, &m, bus_mgr, "DeactivateHome");
617 if (r < 0)
618 return bus_log_create_error(r);
619
620 r = sd_bus_message_append(m, "s", *i);
621 if (r < 0)
622 return bus_log_create_error(r);
623
624 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
625 if (r < 0) {
626 log_error_errno(r, "Failed to deactivate user home: %s", bus_error_message(&error, r));
627 if (ret == 0)
628 ret = r;
629 }
630 }
631
632 return ret;
633 }
634
635 static void dump_home_record(UserRecord *hr) {
636 int r;
637
638 assert(hr);
639
640 if (hr->incomplete) {
641 fflush(stdout);
642 log_warning("Warning: lacking rights to acquire privileged fields of user record of '%s', output incomplete.", hr->user_name);
643 }
644
645 if (arg_json_format_flags & JSON_FORMAT_OFF)
646 user_record_show(hr, true);
647 else {
648 _cleanup_(user_record_unrefp) UserRecord *stripped = NULL;
649
650 if (arg_export_format == EXPORT_FORMAT_STRIPPED)
651 r = user_record_clone(hr, USER_RECORD_EXTRACT_EMBEDDED|USER_RECORD_PERMISSIVE, &stripped);
652 else if (arg_export_format == EXPORT_FORMAT_MINIMAL)
653 r = user_record_clone(hr, USER_RECORD_EXTRACT_SIGNABLE|USER_RECORD_PERMISSIVE, &stripped);
654 else
655 r = 0;
656 if (r < 0)
657 log_warning_errno(r, "Failed to strip user record, ignoring: %m");
658 if (stripped)
659 hr = stripped;
660
661 json_variant_dump(hr->json, arg_json_format_flags, stdout, NULL);
662 }
663 }
664
665 static char **mangle_user_list(char **list, char ***ret_allocated) {
666 _cleanup_free_ char *myself = NULL;
667 char **l;
668
669 if (!strv_isempty(list)) {
670 *ret_allocated = NULL;
671 return list;
672 }
673
674 myself = getusername_malloc();
675 if (!myself)
676 return NULL;
677
678 l = new(char*, 2);
679 if (!l)
680 return NULL;
681
682 l[0] = TAKE_PTR(myself);
683 l[1] = NULL;
684
685 *ret_allocated = l;
686 return l;
687 }
688
689 static int inspect_home(int argc, char *argv[], void *userdata) {
690 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
691 _cleanup_(strv_freep) char **mangled_list = NULL;
692 int r, ret = 0;
693 char **items, **i;
694
695 pager_open(arg_pager_flags);
696
697 r = acquire_bus(&bus);
698 if (r < 0)
699 return r;
700
701 items = mangle_user_list(strv_skip(argv, 1), &mangled_list);
702 if (!items)
703 return log_oom();
704
705 STRV_FOREACH(i, items) {
706 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
707 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
708 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
709 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
710 const char *json;
711 int incomplete;
712 uid_t uid;
713
714 r = parse_uid(*i, &uid);
715 if (r < 0) {
716 if (!valid_user_group_name(*i, 0)) {
717 log_error("Invalid user name '%s'.", *i);
718 if (ret == 0)
719 ret = -EINVAL;
720
721 continue;
722 }
723
724 r = bus_call_method(bus, bus_mgr, "GetUserRecordByName", &error, &reply, "s", *i);
725 } else
726 r = bus_call_method(bus, bus_mgr, "GetUserRecordByUID", &error, &reply, "u", (uint32_t) uid);
727
728 if (r < 0) {
729 log_error_errno(r, "Failed to inspect home: %s", bus_error_message(&error, r));
730 if (ret == 0)
731 ret = r;
732
733 continue;
734 }
735
736 r = sd_bus_message_read(reply, "sbo", &json, &incomplete, NULL);
737 if (r < 0) {
738 bus_log_parse_error(r);
739 if (ret == 0)
740 ret = r;
741
742 continue;
743 }
744
745 r = json_parse(json, JSON_PARSE_SENSITIVE, &v, NULL, NULL);
746 if (r < 0) {
747 log_error_errno(r, "Failed to parse JSON identity: %m");
748 if (ret == 0)
749 ret = r;
750
751 continue;
752 }
753
754 hr = user_record_new();
755 if (!hr)
756 return log_oom();
757
758 r = user_record_load(hr, v, USER_RECORD_LOAD_REFUSE_SECRET|USER_RECORD_LOG|USER_RECORD_PERMISSIVE);
759 if (r < 0) {
760 if (ret == 0)
761 ret = r;
762
763 continue;
764 }
765
766 hr->incomplete = incomplete;
767 dump_home_record(hr);
768 }
769
770 return ret;
771 }
772
773 static int authenticate_home(int argc, char *argv[], void *userdata) {
774 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
775 _cleanup_(strv_freep) char **mangled_list = NULL;
776 int r, ret = 0;
777 char **i, **items;
778
779 items = mangle_user_list(strv_skip(argv, 1), &mangled_list);
780 if (!items)
781 return log_oom();
782
783 r = acquire_bus(&bus);
784 if (r < 0)
785 return r;
786
787 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
788
789 STRV_FOREACH(i, items) {
790 _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
791
792 r = acquire_passed_secrets(*i, &secret);
793 if (r < 0)
794 return r;
795
796 for (;;) {
797 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
798 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
799
800 r = bus_message_new_method_call(bus, &m, bus_mgr, "AuthenticateHome");
801 if (r < 0)
802 return bus_log_create_error(r);
803
804 r = sd_bus_message_append(m, "s", *i);
805 if (r < 0)
806 return bus_log_create_error(r);
807
808 r = bus_message_append_secret(m, secret);
809 if (r < 0)
810 return bus_log_create_error(r);
811
812 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
813 if (r < 0) {
814 r = handle_generic_user_record_error(*i, secret, &error, r, false);
815 if (r < 0) {
816 if (ret == 0)
817 ret = r;
818
819 break;
820 }
821 } else
822 break;
823 }
824 }
825
826 return ret;
827 }
828
829 static int update_last_change(JsonVariant **v, bool with_password, bool override) {
830 JsonVariant *c;
831 usec_t n;
832 int r;
833
834 assert(v);
835
836 n = now(CLOCK_REALTIME);
837
838 c = json_variant_by_key(*v, "lastChangeUSec");
839 if (c) {
840 uint64_t u;
841
842 if (!override)
843 goto update_password;
844
845 if (!json_variant_is_unsigned(c))
846 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "lastChangeUSec field is not an unsigned integer, refusing.");
847
848 u = json_variant_unsigned(c);
849 if (u >= n)
850 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "lastChangeUSec is from the future, can't update.");
851 }
852
853 r = json_variant_set_field_unsigned(v, "lastChangeUSec", n);
854 if (r < 0)
855 return log_error_errno(r, "Failed to update lastChangeUSec: %m");
856
857 update_password:
858 if (!with_password)
859 return 0;
860
861 c = json_variant_by_key(*v, "lastPasswordChangeUSec");
862 if (c) {
863 uint64_t u;
864
865 if (!override)
866 return 0;
867
868 if (!json_variant_is_unsigned(c))
869 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "lastPasswordChangeUSec field is not an unsigned integer, refusing.");
870
871 u = json_variant_unsigned(c);
872 if (u >= n)
873 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "lastPasswordChangeUSec is from the future, can't update.");
874 }
875
876 r = json_variant_set_field_unsigned(v, "lastPasswordChangeUSec", n);
877 if (r < 0)
878 return log_error_errno(r, "Failed to update lastPasswordChangeUSec: %m");
879
880 return 1;
881 }
882
883 static int apply_identity_changes(JsonVariant **_v) {
884 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
885 int r;
886
887 assert(_v);
888
889 v = json_variant_ref(*_v);
890
891 r = json_variant_filter(&v, arg_identity_filter);
892 if (r < 0)
893 return log_error_errno(r, "Failed to filter identity: %m");
894
895 r = json_variant_merge(&v, arg_identity_extra);
896 if (r < 0)
897 return log_error_errno(r, "Failed to merge identities: %m");
898
899 if (arg_identity_extra_this_machine || !strv_isempty(arg_identity_filter)) {
900 _cleanup_(json_variant_unrefp) JsonVariant *per_machine = NULL, *mmid = NULL;
901 sd_id128_t mid;
902
903 r = sd_id128_get_machine(&mid);
904 if (r < 0)
905 return log_error_errno(r, "Failed to acquire machine ID: %m");
906
907 r = json_variant_new_string(&mmid, SD_ID128_TO_STRING(mid));
908 if (r < 0)
909 return log_error_errno(r, "Failed to allocate matchMachineId object: %m");
910
911 per_machine = json_variant_ref(json_variant_by_key(v, "perMachine"));
912 if (per_machine) {
913 _cleanup_(json_variant_unrefp) JsonVariant *npm = NULL, *add = NULL;
914 _cleanup_free_ JsonVariant **array = NULL;
915 JsonVariant *z;
916 size_t i = 0;
917
918 if (!json_variant_is_array(per_machine))
919 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "perMachine field is not an array, refusing.");
920
921 array = new(JsonVariant*, json_variant_elements(per_machine) + 1);
922 if (!array)
923 return log_oom();
924
925 JSON_VARIANT_ARRAY_FOREACH(z, per_machine) {
926 JsonVariant *u;
927
928 if (!json_variant_is_object(z))
929 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "perMachine entry is not an object, refusing.");
930
931 array[i++] = z;
932
933 u = json_variant_by_key(z, "matchMachineId");
934 if (!u)
935 continue;
936
937 if (!json_variant_equal(u, mmid))
938 continue;
939
940 r = json_variant_merge(&add, z);
941 if (r < 0)
942 return log_error_errno(r, "Failed to merge perMachine entry: %m");
943
944 i--;
945 }
946
947 r = json_variant_filter(&add, arg_identity_filter);
948 if (r < 0)
949 return log_error_errno(r, "Failed to filter perMachine: %m");
950
951 r = json_variant_merge(&add, arg_identity_extra_this_machine);
952 if (r < 0)
953 return log_error_errno(r, "Failed to merge in perMachine fields: %m");
954
955 if (arg_identity_filter_rlimits || arg_identity_extra_rlimits) {
956 _cleanup_(json_variant_unrefp) JsonVariant *rlv = NULL;
957
958 rlv = json_variant_ref(json_variant_by_key(add, "resourceLimits"));
959
960 r = json_variant_filter(&rlv, arg_identity_filter_rlimits);
961 if (r < 0)
962 return log_error_errno(r, "Failed to filter resource limits: %m");
963
964 r = json_variant_merge(&rlv, arg_identity_extra_rlimits);
965 if (r < 0)
966 return log_error_errno(r, "Failed to set resource limits: %m");
967
968 if (json_variant_is_blank_object(rlv)) {
969 r = json_variant_filter(&add, STRV_MAKE("resourceLimits"));
970 if (r < 0)
971 return log_error_errno(r, "Failed to drop resource limits field from identity: %m");
972 } else {
973 r = json_variant_set_field(&add, "resourceLimits", rlv);
974 if (r < 0)
975 return log_error_errno(r, "Failed to update resource limits of identity: %m");
976 }
977 }
978
979 if (!json_variant_is_blank_object(add)) {
980 r = json_variant_set_field(&add, "matchMachineId", mmid);
981 if (r < 0)
982 return log_error_errno(r, "Failed to set matchMachineId field: %m");
983
984 array[i++] = add;
985 }
986
987 r = json_variant_new_array(&npm, array, i);
988 if (r < 0)
989 return log_error_errno(r, "Failed to allocate new perMachine array: %m");
990
991 json_variant_unref(per_machine);
992 per_machine = TAKE_PTR(npm);
993 } else {
994 _cleanup_(json_variant_unrefp) JsonVariant *item = json_variant_ref(arg_identity_extra_this_machine);
995
996 if (arg_identity_extra_rlimits) {
997 r = json_variant_set_field(&item, "resourceLimits", arg_identity_extra_rlimits);
998 if (r < 0)
999 return log_error_errno(r, "Failed to update resource limits of identity: %m");
1000 }
1001
1002 r = json_variant_set_field(&item, "matchMachineId", mmid);
1003 if (r < 0)
1004 return log_error_errno(r, "Failed to set matchMachineId field: %m");
1005
1006 r = json_variant_append_array(&per_machine, item);
1007 if (r < 0)
1008 return log_error_errno(r, "Failed to append to perMachine array: %m");
1009 }
1010
1011 r = json_variant_set_field(&v, "perMachine", per_machine);
1012 if (r < 0)
1013 return log_error_errno(r, "Failed to update per machine record: %m");
1014 }
1015
1016 if (arg_identity_extra_privileged || arg_identity_filter) {
1017 _cleanup_(json_variant_unrefp) JsonVariant *privileged = NULL;
1018
1019 privileged = json_variant_ref(json_variant_by_key(v, "privileged"));
1020
1021 r = json_variant_filter(&privileged, arg_identity_filter);
1022 if (r < 0)
1023 return log_error_errno(r, "Failed to filter identity (privileged part): %m");
1024
1025 r = json_variant_merge(&privileged, arg_identity_extra_privileged);
1026 if (r < 0)
1027 return log_error_errno(r, "Failed to merge identities (privileged part): %m");
1028
1029 if (json_variant_is_blank_object(privileged)) {
1030 r = json_variant_filter(&v, STRV_MAKE("privileged"));
1031 if (r < 0)
1032 return log_error_errno(r, "Failed to drop privileged part from identity: %m");
1033 } else {
1034 r = json_variant_set_field(&v, "privileged", privileged);
1035 if (r < 0)
1036 return log_error_errno(r, "Failed to update privileged part of identity: %m");
1037 }
1038 }
1039
1040 if (arg_identity_filter_rlimits) {
1041 _cleanup_(json_variant_unrefp) JsonVariant *rlv = NULL;
1042
1043 rlv = json_variant_ref(json_variant_by_key(v, "resourceLimits"));
1044
1045 r = json_variant_filter(&rlv, arg_identity_filter_rlimits);
1046 if (r < 0)
1047 return log_error_errno(r, "Failed to filter resource limits: %m");
1048
1049 /* Note that we only filter resource limits here, but don't apply them. We do that in the perMachine section */
1050
1051 if (json_variant_is_blank_object(rlv)) {
1052 r = json_variant_filter(&v, STRV_MAKE("resourceLimits"));
1053 if (r < 0)
1054 return log_error_errno(r, "Failed to drop resource limits field from identity: %m");
1055 } else {
1056 r = json_variant_set_field(&v, "resourceLimits", rlv);
1057 if (r < 0)
1058 return log_error_errno(r, "Failed to update resource limits of identity: %m");
1059 }
1060 }
1061
1062 json_variant_unref(*_v);
1063 *_v = TAKE_PTR(v);
1064
1065 return 0;
1066 }
1067
1068 static int add_disposition(JsonVariant **v) {
1069 int r;
1070
1071 assert(v);
1072
1073 if (json_variant_by_key(*v, "disposition"))
1074 return 0;
1075
1076 /* Set the disposition to regular, if not configured explicitly */
1077 r = json_variant_set_field_string(v, "disposition", "regular");
1078 if (r < 0)
1079 return log_error_errno(r, "Failed to set disposition field: %m");
1080
1081 return 1;
1082 }
1083
1084 static int acquire_new_home_record(UserRecord **ret) {
1085 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
1086 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
1087 char **i;
1088 int r;
1089
1090 assert(ret);
1091
1092 if (arg_identity) {
1093 unsigned line, column;
1094
1095 r = json_parse_file(
1096 streq(arg_identity, "-") ? stdin : NULL,
1097 streq(arg_identity, "-") ? "<stdin>" : arg_identity, JSON_PARSE_SENSITIVE, &v, &line, &column);
1098 if (r < 0)
1099 return log_error_errno(r, "Failed to parse identity at %u:%u: %m", line, column);
1100 }
1101
1102 r = apply_identity_changes(&v);
1103 if (r < 0)
1104 return r;
1105
1106 r = add_disposition(&v);
1107 if (r < 0)
1108 return r;
1109
1110 STRV_FOREACH(i, arg_pkcs11_token_uri) {
1111 r = identity_add_pkcs11_key_data(&v, *i);
1112 if (r < 0)
1113 return r;
1114 }
1115
1116 STRV_FOREACH(i, arg_fido2_device) {
1117 r = identity_add_fido2_parameters(&v, *i, arg_fido2_lock_with);
1118 if (r < 0)
1119 return r;
1120 }
1121
1122 if (arg_recovery_key) {
1123 r = identity_add_recovery_key(&v);
1124 if (r < 0)
1125 return r;
1126 }
1127
1128 r = update_last_change(&v, true, false);
1129 if (r < 0)
1130 return r;
1131
1132 if (DEBUG_LOGGING)
1133 json_variant_dump(v, JSON_FORMAT_PRETTY, NULL, NULL);
1134
1135 hr = user_record_new();
1136 if (!hr)
1137 return log_oom();
1138
1139 r = user_record_load(hr, v, USER_RECORD_REQUIRE_REGULAR|USER_RECORD_ALLOW_SECRET|USER_RECORD_ALLOW_PRIVILEGED|USER_RECORD_ALLOW_PER_MACHINE|USER_RECORD_ALLOW_SIGNATURE|USER_RECORD_LOG|USER_RECORD_PERMISSIVE);
1140 if (r < 0)
1141 return r;
1142
1143 *ret = TAKE_PTR(hr);
1144 return 0;
1145 }
1146
1147 static int acquire_new_password(
1148 const char *user_name,
1149 UserRecord *hr,
1150 bool suggest,
1151 char **ret) {
1152
1153 unsigned i = 5;
1154 char *e;
1155 int r;
1156
1157 assert(user_name);
1158 assert(hr);
1159
1160 e = getenv("NEWPASSWORD");
1161 if (e) {
1162 _cleanup_(erase_and_freep) char *copy = NULL;
1163
1164 /* As above, this is not for use, just for testing */
1165
1166 if (ret) {
1167 copy = strdup(e);
1168 if (!copy)
1169 return log_oom();
1170 }
1171
1172 r = user_record_set_password(hr, STRV_MAKE(e), /* prepend = */ true);
1173 if (r < 0)
1174 return log_error_errno(r, "Failed to store password: %m");
1175
1176 assert_se(unsetenv_erase("NEWPASSWORD") >= 0);
1177
1178 if (ret)
1179 *ret = TAKE_PTR(copy);
1180
1181 return 0;
1182 }
1183
1184 if (suggest)
1185 (void) suggest_passwords();
1186
1187 for (;;) {
1188 _cleanup_(strv_free_erasep) char **first = NULL, **second = NULL;
1189 _cleanup_free_ char *question = NULL;
1190
1191 if (--i == 0)
1192 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Too many attempts, giving up:");
1193
1194 if (asprintf(&question, "Please enter new password for user %s:", user_name) < 0)
1195 return log_oom();
1196
1197 r = ask_password_auto(
1198 question,
1199 /* icon= */ "user-home",
1200 NULL,
1201 /* key_name= */ "home-password",
1202 /* credential_name= */ "home.new-password",
1203 USEC_INFINITY,
1204 0, /* no caching, we want to collect a new password here after all */
1205 &first);
1206 if (r < 0)
1207 return log_error_errno(r, "Failed to acquire password: %m");
1208
1209 question = mfree(question);
1210 if (asprintf(&question, "Please enter new password for user %s (repeat):", user_name) < 0)
1211 return log_oom();
1212
1213 r = ask_password_auto(
1214 question,
1215 /* icon= */ "user-home",
1216 NULL,
1217 /* key_name= */ "home-password",
1218 /* credential_name= */ "home.new-password",
1219 USEC_INFINITY,
1220 0, /* no caching */
1221 &second);
1222 if (r < 0)
1223 return log_error_errno(r, "Failed to acquire password: %m");
1224
1225 if (strv_equal(first, second)) {
1226 _cleanup_(erase_and_freep) char *copy = NULL;
1227
1228 if (ret) {
1229 copy = strdup(first[0]);
1230 if (!copy)
1231 return log_oom();
1232 }
1233
1234 r = user_record_set_password(hr, first, /* prepend = */ true);
1235 if (r < 0)
1236 return log_error_errno(r, "Failed to store password: %m");
1237
1238 if (ret)
1239 *ret = TAKE_PTR(copy);
1240
1241 return 0;
1242 }
1243
1244 log_error("Password didn't match, try again.");
1245 }
1246 }
1247
1248 static int create_home(int argc, char *argv[], void *userdata) {
1249 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1250 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
1251 int r;
1252
1253 r = acquire_bus(&bus);
1254 if (r < 0)
1255 return r;
1256
1257 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1258
1259 if (argc >= 2) {
1260 /* If a username was specified, use it */
1261
1262 if (valid_user_group_name(argv[1], 0))
1263 r = json_variant_set_field_string(&arg_identity_extra, "userName", argv[1]);
1264 else {
1265 _cleanup_free_ char *un = NULL, *rr = NULL;
1266
1267 /* Before we consider the user name invalid, let's check if we can split it? */
1268 r = split_user_name_realm(argv[1], &un, &rr);
1269 if (r < 0)
1270 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User name '%s' is not valid: %m", argv[1]);
1271
1272 if (rr) {
1273 r = json_variant_set_field_string(&arg_identity_extra, "realm", rr);
1274 if (r < 0)
1275 return log_error_errno(r, "Failed to set realm field: %m");
1276 }
1277
1278 r = json_variant_set_field_string(&arg_identity_extra, "userName", un);
1279 }
1280 if (r < 0)
1281 return log_error_errno(r, "Failed to set userName field: %m");
1282 } else {
1283 /* If neither a username nor an identity have been specified we cannot operate. */
1284 if (!arg_identity)
1285 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User name required.");
1286 }
1287
1288 r = acquire_new_home_record(&hr);
1289 if (r < 0)
1290 return r;
1291
1292 /* If the JSON record carries no plain text password (besides the recovery key), then let's query it
1293 * manually. */
1294 if (strv_length(hr->password) <= arg_recovery_key) {
1295
1296 if (strv_isempty(hr->hashed_password)) {
1297 _cleanup_(erase_and_freep) char *new_password = NULL;
1298
1299 /* No regular (i.e. non-PKCS#11) hashed passwords set in the record, let's fix that. */
1300 r = acquire_new_password(hr->user_name, hr, /* suggest = */ true, &new_password);
1301 if (r < 0)
1302 return r;
1303
1304 r = user_record_make_hashed_password(hr, STRV_MAKE(new_password), /* extend = */ false);
1305 if (r < 0)
1306 return log_error_errno(r, "Failed to hash password: %m");
1307 } else {
1308 /* There's a hash password set in the record, acquire the unhashed version of it. */
1309 r = acquire_existing_password(
1310 hr->user_name,
1311 hr,
1312 /* emphasize_current= */ false,
1313 ASK_PASSWORD_ACCEPT_CACHED | ASK_PASSWORD_PUSH_CACHE);
1314 if (r < 0)
1315 return r;
1316 }
1317 }
1318
1319 if (hr->enforce_password_policy == 0) {
1320 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1321
1322 /* If password quality enforcement is disabled, let's at least warn client side */
1323
1324 r = user_record_quality_check_password(hr, hr, &error);
1325 if (r < 0)
1326 log_warning_errno(r, "Specified password does not pass quality checks (%s), proceeding anyway.", bus_error_message(&error, r));
1327 }
1328
1329 for (;;) {
1330 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1331 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1332 _cleanup_(erase_and_freep) char *formatted = NULL;
1333
1334 r = json_variant_format(hr->json, 0, &formatted);
1335 if (r < 0)
1336 return log_error_errno(r, "Failed to format user record: %m");
1337
1338 r = bus_message_new_method_call(bus, &m, bus_mgr, "CreateHome");
1339 if (r < 0)
1340 return bus_log_create_error(r);
1341
1342 (void) sd_bus_message_sensitive(m);
1343
1344 r = sd_bus_message_append(m, "s", formatted);
1345 if (r < 0)
1346 return bus_log_create_error(r);
1347
1348 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1349 if (r < 0) {
1350 if (sd_bus_error_has_name(&error, BUS_ERROR_LOW_PASSWORD_QUALITY)) {
1351 _cleanup_(erase_and_freep) char *new_password = NULL;
1352
1353 log_error_errno(r, "%s", bus_error_message(&error, r));
1354 log_info("(Use --enforce-password-policy=no to turn off password quality checks for this account.)");
1355
1356 r = acquire_new_password(hr->user_name, hr, /* suggest = */ false, &new_password);
1357 if (r < 0)
1358 return r;
1359
1360 r = user_record_make_hashed_password(hr, STRV_MAKE(new_password), /* extend = */ false);
1361 if (r < 0)
1362 return log_error_errno(r, "Failed to hash passwords: %m");
1363 } else {
1364 r = handle_generic_user_record_error(hr->user_name, hr, &error, r, false);
1365 if (r < 0)
1366 return r;
1367 }
1368 } else
1369 break; /* done */
1370 }
1371
1372 return 0;
1373 }
1374
1375 static int remove_home(int argc, char *argv[], void *userdata) {
1376 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1377 int r, ret = 0;
1378 char **i;
1379
1380 r = acquire_bus(&bus);
1381 if (r < 0)
1382 return r;
1383
1384 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1385
1386 STRV_FOREACH(i, strv_skip(argv, 1)) {
1387 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1388 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1389
1390 r = bus_message_new_method_call(bus, &m, bus_mgr, "RemoveHome");
1391 if (r < 0)
1392 return bus_log_create_error(r);
1393
1394 r = sd_bus_message_append(m, "s", *i);
1395 if (r < 0)
1396 return bus_log_create_error(r);
1397
1398 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1399 if (r < 0) {
1400 log_error_errno(r, "Failed to remove home: %s", bus_error_message(&error, r));
1401 if (ret == 0)
1402 ret = r;
1403 }
1404 }
1405
1406 return ret;
1407 }
1408
1409 static int acquire_updated_home_record(
1410 sd_bus *bus,
1411 const char *username,
1412 UserRecord **ret) {
1413
1414 _cleanup_(json_variant_unrefp) JsonVariant *json = NULL;
1415 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
1416 char **i;
1417 int r;
1418
1419 assert(ret);
1420
1421 if (arg_identity) {
1422 unsigned line, column;
1423 JsonVariant *un;
1424
1425 r = json_parse_file(
1426 streq(arg_identity, "-") ? stdin : NULL,
1427 streq(arg_identity, "-") ? "<stdin>" : arg_identity, JSON_PARSE_SENSITIVE, &json, &line, &column);
1428 if (r < 0)
1429 return log_error_errno(r, "Failed to parse identity at %u:%u: %m", line, column);
1430
1431 un = json_variant_by_key(json, "userName");
1432 if (un) {
1433 if (!json_variant_is_string(un) || (username && !streq(json_variant_string(un), username)))
1434 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "User name specified on command line and in JSON record do not match.");
1435 } else {
1436 if (!username)
1437 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No username specified.");
1438
1439 r = json_variant_set_field_string(&arg_identity_extra, "userName", username);
1440 if (r < 0)
1441 return log_error_errno(r, "Failed to set userName field: %m");
1442 }
1443
1444 } else {
1445 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1446 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1447 int incomplete;
1448 const char *text;
1449
1450 if (!identity_properties_specified())
1451 return log_error_errno(SYNTHETIC_ERRNO(EALREADY), "No field to change specified.");
1452
1453 r = bus_call_method(bus, bus_mgr, "GetUserRecordByName", &error, &reply, "s", username);
1454 if (r < 0)
1455 return log_error_errno(r, "Failed to acquire user home record: %s", bus_error_message(&error, r));
1456
1457 r = sd_bus_message_read(reply, "sbo", &text, &incomplete, NULL);
1458 if (r < 0)
1459 return bus_log_parse_error(r);
1460
1461 if (incomplete)
1462 return log_error_errno(SYNTHETIC_ERRNO(EACCES), "Lacking rights to acquire user record including privileged metadata, can't update record.");
1463
1464 r = json_parse(text, JSON_PARSE_SENSITIVE, &json, NULL, NULL);
1465 if (r < 0)
1466 return log_error_errno(r, "Failed to parse JSON identity: %m");
1467
1468 reply = sd_bus_message_unref(reply);
1469
1470 r = json_variant_filter(&json, STRV_MAKE("binding", "status", "signature"));
1471 if (r < 0)
1472 return log_error_errno(r, "Failed to strip binding and status from record to update: %m");
1473 }
1474
1475 r = apply_identity_changes(&json);
1476 if (r < 0)
1477 return r;
1478
1479 STRV_FOREACH(i, arg_pkcs11_token_uri) {
1480 r = identity_add_pkcs11_key_data(&json, *i);
1481 if (r < 0)
1482 return r;
1483 }
1484
1485 STRV_FOREACH(i, arg_fido2_device) {
1486 r = identity_add_fido2_parameters(&json, *i, arg_fido2_lock_with);
1487 if (r < 0)
1488 return r;
1489 }
1490
1491 /* If the user supplied a full record, then add in lastChange, but do not override. Otherwise always
1492 * override. */
1493 r = update_last_change(&json, arg_pkcs11_token_uri || arg_fido2_device, !arg_identity);
1494 if (r < 0)
1495 return r;
1496
1497 if (DEBUG_LOGGING)
1498 json_variant_dump(json, JSON_FORMAT_PRETTY, NULL, NULL);
1499
1500 hr = user_record_new();
1501 if (!hr)
1502 return log_oom();
1503
1504 r = user_record_load(hr, json, USER_RECORD_REQUIRE_REGULAR|USER_RECORD_ALLOW_PRIVILEGED|USER_RECORD_ALLOW_PER_MACHINE|USER_RECORD_ALLOW_SECRET|USER_RECORD_ALLOW_SIGNATURE|USER_RECORD_LOG|USER_RECORD_PERMISSIVE);
1505 if (r < 0)
1506 return r;
1507
1508 *ret = TAKE_PTR(hr);
1509 return 0;
1510 }
1511
1512 static int home_record_reset_human_interaction_permission(UserRecord *hr) {
1513 int r;
1514
1515 assert(hr);
1516
1517 /* When we execute multiple operations one after the other, let's reset the permission to ask the
1518 * user each time, so that if interaction is necessary we will be told so again and thus can print a
1519 * nice message to the user, telling the user so. */
1520
1521 r = user_record_set_pkcs11_protected_authentication_path_permitted(hr, -1);
1522 if (r < 0)
1523 return log_error_errno(r, "Failed to reset PKCS#11 protected authentication path permission flag: %m");
1524
1525 r = user_record_set_fido2_user_presence_permitted(hr, -1);
1526 if (r < 0)
1527 return log_error_errno(r, "Failed to reset FIDO2 user presence permission flag: %m");
1528
1529 r = user_record_set_fido2_user_verification_permitted(hr, -1);
1530 if (r < 0)
1531 return log_error_errno(r, "Failed to reset FIDO2 user verification permission flag: %m");
1532
1533 return 0;
1534 }
1535
1536 static int update_home(int argc, char *argv[], void *userdata) {
1537 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1538 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
1539 _cleanup_free_ char *buffer = NULL;
1540 const char *username;
1541 int r;
1542
1543 if (argc >= 2)
1544 username = argv[1];
1545 else if (!arg_identity) {
1546 buffer = getusername_malloc();
1547 if (!buffer)
1548 return log_oom();
1549
1550 username = buffer;
1551 } else
1552 username = NULL;
1553
1554 r = acquire_bus(&bus);
1555 if (r < 0)
1556 return r;
1557
1558 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1559
1560 r = acquire_updated_home_record(bus, username, &hr);
1561 if (r < 0)
1562 return r;
1563
1564 /* If we do multiple operations, let's output things more verbosely, since otherwise the repeated
1565 * authentication might be confusing. */
1566
1567 if (arg_and_resize || arg_and_change_password)
1568 log_info("Updating home directory.");
1569
1570 for (;;) {
1571 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1572 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1573 _cleanup_free_ char *formatted = NULL;
1574
1575 r = bus_message_new_method_call(bus, &m, bus_mgr, "UpdateHome");
1576 if (r < 0)
1577 return bus_log_create_error(r);
1578
1579 r = json_variant_format(hr->json, 0, &formatted);
1580 if (r < 0)
1581 return log_error_errno(r, "Failed to format user record: %m");
1582
1583 (void) sd_bus_message_sensitive(m);
1584
1585 r = sd_bus_message_append(m, "s", formatted);
1586 if (r < 0)
1587 return bus_log_create_error(r);
1588
1589 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1590 if (r < 0) {
1591 if (arg_and_change_password &&
1592 sd_bus_error_has_name(&error, BUS_ERROR_BAD_PASSWORD_AND_NO_TOKEN))
1593 /* In the generic handler we'd ask for a password in this case, but when
1594 * changing passwords that's not sufficient, as we need to acquire all keys
1595 * first. */
1596 return log_error_errno(r, "Security token not inserted, refusing.");
1597
1598 r = handle_generic_user_record_error(hr->user_name, hr, &error, r, false);
1599 if (r < 0)
1600 return r;
1601 } else
1602 break;
1603 }
1604
1605 if (arg_and_resize)
1606 log_info("Resizing home.");
1607
1608 (void) home_record_reset_human_interaction_permission(hr);
1609
1610 /* Also sync down disk size to underlying LUKS/fscrypt/quota */
1611 while (arg_and_resize) {
1612 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1613 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1614
1615 r = bus_message_new_method_call(bus, &m, bus_mgr, "ResizeHome");
1616 if (r < 0)
1617 return bus_log_create_error(r);
1618
1619 /* Specify UINT64_MAX as size, in which case the underlying disk size will just be synced */
1620 r = sd_bus_message_append(m, "st", hr->user_name, UINT64_MAX);
1621 if (r < 0)
1622 return bus_log_create_error(r);
1623
1624 r = bus_message_append_secret(m, hr);
1625 if (r < 0)
1626 return bus_log_create_error(r);
1627
1628 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1629 if (r < 0) {
1630 if (arg_and_change_password &&
1631 sd_bus_error_has_name(&error, BUS_ERROR_BAD_PASSWORD_AND_NO_TOKEN))
1632 return log_error_errno(r, "Security token not inserted, refusing.");
1633
1634 r = handle_generic_user_record_error(hr->user_name, hr, &error, r, false);
1635 if (r < 0)
1636 return r;
1637 } else
1638 break;
1639 }
1640
1641 if (arg_and_change_password)
1642 log_info("Synchronizing passwords and encryption keys.");
1643
1644 (void) home_record_reset_human_interaction_permission(hr);
1645
1646 /* Also sync down passwords to underlying LUKS/fscrypt */
1647 while (arg_and_change_password) {
1648 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1649 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1650
1651 r = bus_message_new_method_call(bus, &m, bus_mgr, "ChangePasswordHome");
1652 if (r < 0)
1653 return bus_log_create_error(r);
1654
1655 /* Specify an empty new secret, in which case the underlying LUKS/fscrypt password will just be synced */
1656 r = sd_bus_message_append(m, "ss", hr->user_name, "{}");
1657 if (r < 0)
1658 return bus_log_create_error(r);
1659
1660 r = bus_message_append_secret(m, hr);
1661 if (r < 0)
1662 return bus_log_create_error(r);
1663
1664 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1665 if (r < 0) {
1666 if (sd_bus_error_has_name(&error, BUS_ERROR_BAD_PASSWORD_AND_NO_TOKEN))
1667 return log_error_errno(r, "Security token not inserted, refusing.");
1668
1669 r = handle_generic_user_record_error(hr->user_name, hr, &error, r, false);
1670 if (r < 0)
1671 return r;
1672 } else
1673 break;
1674 }
1675
1676 return 0;
1677 }
1678
1679 static int passwd_home(int argc, char *argv[], void *userdata) {
1680 _cleanup_(user_record_unrefp) UserRecord *old_secret = NULL, *new_secret = NULL;
1681 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1682 _cleanup_free_ char *buffer = NULL;
1683 const char *username;
1684 int r;
1685
1686 if (arg_pkcs11_token_uri)
1687 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "To change the PKCS#11 security token use 'homectl update --pkcs11-token-uri=…'.");
1688 if (arg_fido2_device)
1689 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "To change the FIDO2 security token use 'homectl update --fido2-device=…'.");
1690 if (identity_properties_specified())
1691 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "The 'passwd' verb does not permit changing other record properties at the same time.");
1692
1693 if (argc >= 2)
1694 username = argv[1];
1695 else {
1696 buffer = getusername_malloc();
1697 if (!buffer)
1698 return log_oom();
1699
1700 username = buffer;
1701 }
1702
1703 r = acquire_bus(&bus);
1704 if (r < 0)
1705 return r;
1706
1707 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1708
1709 old_secret = user_record_new();
1710 if (!old_secret)
1711 return log_oom();
1712
1713 new_secret = user_record_new();
1714 if (!new_secret)
1715 return log_oom();
1716
1717 r = acquire_new_password(username, new_secret, /* suggest = */ true, NULL);
1718 if (r < 0)
1719 return r;
1720
1721 for (;;) {
1722 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1723 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1724
1725 r = bus_message_new_method_call(bus, &m, bus_mgr, "ChangePasswordHome");
1726 if (r < 0)
1727 return bus_log_create_error(r);
1728
1729 r = sd_bus_message_append(m, "s", username);
1730 if (r < 0)
1731 return bus_log_create_error(r);
1732
1733 r = bus_message_append_secret(m, new_secret);
1734 if (r < 0)
1735 return bus_log_create_error(r);
1736
1737 r = bus_message_append_secret(m, old_secret);
1738 if (r < 0)
1739 return bus_log_create_error(r);
1740
1741 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1742 if (r < 0) {
1743 if (sd_bus_error_has_name(&error, BUS_ERROR_LOW_PASSWORD_QUALITY)) {
1744
1745 log_error_errno(r, "%s", bus_error_message(&error, r));
1746
1747 r = acquire_new_password(username, new_secret, /* suggest = */ false, NULL);
1748
1749 } else if (sd_bus_error_has_name(&error, BUS_ERROR_BAD_PASSWORD_AND_NO_TOKEN))
1750
1751 /* In the generic handler we'd ask for a password in this case, but when
1752 * changing passwords that's not sufficeint, as we need to acquire all keys
1753 * first. */
1754 return log_error_errno(r, "Security token not inserted, refusing.");
1755 else
1756 r = handle_generic_user_record_error(username, old_secret, &error, r, true);
1757 if (r < 0)
1758 return r;
1759 } else
1760 break;
1761 }
1762
1763 return 0;
1764 }
1765
1766 static int parse_disk_size(const char *t, uint64_t *ret) {
1767 int r;
1768
1769 assert(t);
1770 assert(ret);
1771
1772 if (streq(t, "min"))
1773 *ret = 0;
1774 else if (streq(t, "max"))
1775 *ret = UINT64_MAX-1; /* Largest size that isn't UINT64_MAX special marker */
1776 else {
1777 uint64_t ds;
1778
1779 r = parse_size(t, 1024, &ds);
1780 if (r < 0)
1781 return log_error_errno(r, "Failed to parse disk size parameter: %s", t);
1782
1783 if (ds >= UINT64_MAX) /* UINT64_MAX has special meaning for us ("dont change"), refuse */
1784 return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Disk size out of range: %s", t);
1785
1786 *ret = ds;
1787 }
1788
1789 return 0;
1790 }
1791
1792 static int resize_home(int argc, char *argv[], void *userdata) {
1793 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1794 _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
1795 uint64_t ds = UINT64_MAX;
1796 int r;
1797
1798 r = acquire_bus(&bus);
1799 if (r < 0)
1800 return r;
1801
1802 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1803
1804 if (arg_disk_size_relative != UINT64_MAX ||
1805 (argc > 2 && parse_permyriad(argv[2]) >= 0))
1806 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
1807 "Relative disk size specification currently not supported when resizing.");
1808
1809 if (argc > 2) {
1810 r = parse_disk_size(argv[2], &ds);
1811 if (r < 0)
1812 return r;
1813 }
1814
1815 if (arg_disk_size != UINT64_MAX) {
1816 if (ds != UINT64_MAX && ds != arg_disk_size)
1817 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Disk size specified twice and doesn't match, refusing.");
1818
1819 ds = arg_disk_size;
1820 }
1821
1822 r = acquire_passed_secrets(argv[1], &secret);
1823 if (r < 0)
1824 return r;
1825
1826 for (;;) {
1827 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1828 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1829
1830 r = bus_message_new_method_call(bus, &m, bus_mgr, "ResizeHome");
1831 if (r < 0)
1832 return bus_log_create_error(r);
1833
1834 r = sd_bus_message_append(m, "st", argv[1], ds);
1835 if (r < 0)
1836 return bus_log_create_error(r);
1837
1838 r = bus_message_append_secret(m, secret);
1839 if (r < 0)
1840 return bus_log_create_error(r);
1841
1842 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1843 if (r < 0) {
1844 r = handle_generic_user_record_error(argv[1], secret, &error, r, false);
1845 if (r < 0)
1846 return r;
1847 } else
1848 break;
1849 }
1850
1851 return 0;
1852 }
1853
1854 static int lock_home(int argc, char *argv[], void *userdata) {
1855 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1856 int r, ret = 0;
1857 char **i;
1858
1859 r = acquire_bus(&bus);
1860 if (r < 0)
1861 return r;
1862
1863 STRV_FOREACH(i, strv_skip(argv, 1)) {
1864 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1865 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1866
1867 r = bus_message_new_method_call(bus, &m, bus_mgr, "LockHome");
1868 if (r < 0)
1869 return bus_log_create_error(r);
1870
1871 r = sd_bus_message_append(m, "s", *i);
1872 if (r < 0)
1873 return bus_log_create_error(r);
1874
1875 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1876 if (r < 0) {
1877 log_error_errno(r, "Failed to lock home: %s", bus_error_message(&error, r));
1878 if (ret == 0)
1879 ret = r;
1880 }
1881 }
1882
1883 return ret;
1884 }
1885
1886 static int unlock_home(int argc, char *argv[], void *userdata) {
1887 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1888 int r, ret = 0;
1889 char **i;
1890
1891 r = acquire_bus(&bus);
1892 if (r < 0)
1893 return r;
1894
1895 STRV_FOREACH(i, strv_skip(argv, 1)) {
1896 _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
1897
1898 r = acquire_passed_secrets(*i, &secret);
1899 if (r < 0)
1900 return r;
1901
1902 for (;;) {
1903 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1904 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1905
1906 r = bus_message_new_method_call(bus, &m, bus_mgr, "UnlockHome");
1907 if (r < 0)
1908 return bus_log_create_error(r);
1909
1910 r = sd_bus_message_append(m, "s", *i);
1911 if (r < 0)
1912 return bus_log_create_error(r);
1913
1914 r = bus_message_append_secret(m, secret);
1915 if (r < 0)
1916 return bus_log_create_error(r);
1917
1918 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
1919 if (r < 0) {
1920 r = handle_generic_user_record_error(argv[1], secret, &error, r, false);
1921 if (r < 0) {
1922 if (ret == 0)
1923 ret = r;
1924
1925 break;
1926 }
1927 } else
1928 break;
1929 }
1930 }
1931
1932 return ret;
1933 }
1934
1935 static int with_home(int argc, char *argv[], void *userdata) {
1936 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1937 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1938 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1939 _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
1940 _cleanup_close_ int acquired_fd = -1;
1941 _cleanup_strv_free_ char **cmdline = NULL;
1942 const char *home;
1943 int r, ret;
1944 pid_t pid;
1945
1946 r = acquire_bus(&bus);
1947 if (r < 0)
1948 return r;
1949
1950 if (argc < 3) {
1951 _cleanup_free_ char *shell = NULL;
1952
1953 /* If no command is specified, spawn a shell */
1954 r = get_shell(&shell);
1955 if (r < 0)
1956 return log_error_errno(r, "Failed to acquire shell: %m");
1957
1958 cmdline = strv_new(shell);
1959 } else
1960 cmdline = strv_copy(argv + 2);
1961 if (!cmdline)
1962 return log_oom();
1963
1964 r = acquire_passed_secrets(argv[1], &secret);
1965 if (r < 0)
1966 return r;
1967
1968 for (;;) {
1969 r = bus_message_new_method_call(bus, &m, bus_mgr, "AcquireHome");
1970 if (r < 0)
1971 return bus_log_create_error(r);
1972
1973 r = sd_bus_message_append(m, "s", argv[1]);
1974 if (r < 0)
1975 return bus_log_create_error(r);
1976
1977 r = bus_message_append_secret(m, secret);
1978 if (r < 0)
1979 return bus_log_create_error(r);
1980
1981 r = sd_bus_message_append(m, "b", /* please_suspend = */ getenv_bool("SYSTEMD_PLEASE_SUSPEND_HOME") > 0);
1982 if (r < 0)
1983 return bus_log_create_error(r);
1984
1985 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, &reply);
1986 m = sd_bus_message_unref(m);
1987 if (r < 0) {
1988 r = handle_generic_user_record_error(argv[1], secret, &error, r, false);
1989 if (r < 0)
1990 return r;
1991
1992 sd_bus_error_free(&error);
1993 } else {
1994 int fd;
1995
1996 r = sd_bus_message_read(reply, "h", &fd);
1997 if (r < 0)
1998 return bus_log_parse_error(r);
1999
2000 acquired_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2001 if (acquired_fd < 0)
2002 return log_error_errno(errno, "Failed to duplicate acquired fd: %m");
2003
2004 reply = sd_bus_message_unref(reply);
2005 break;
2006 }
2007 }
2008
2009 r = bus_call_method(bus, bus_mgr, "GetHomeByName", &error, &reply, "s", argv[1]);
2010 if (r < 0)
2011 return log_error_errno(r, "Failed to inspect home: %s", bus_error_message(&error, r));
2012
2013 r = sd_bus_message_read(reply, "usussso", NULL, NULL, NULL, NULL, &home, NULL, NULL);
2014 if (r < 0)
2015 return bus_log_parse_error(r);
2016
2017 r = safe_fork("(with)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE|FORK_REOPEN_LOG, &pid);
2018 if (r < 0)
2019 return r;
2020 if (r == 0) {
2021 if (chdir(home) < 0) {
2022 log_error_errno(errno, "Failed to change to directory %s: %m", home);
2023 _exit(255);
2024 }
2025
2026 execvp(cmdline[0], cmdline);
2027 log_error_errno(errno, "Failed to execute %s: %m", cmdline[0]);
2028 _exit(255);
2029 }
2030
2031 ret = wait_for_terminate_and_check(cmdline[0], pid, WAIT_LOG_ABNORMAL);
2032
2033 /* Close the fd that pings the home now. */
2034 acquired_fd = safe_close(acquired_fd);
2035
2036 r = bus_message_new_method_call(bus, &m, bus_mgr, "ReleaseHome");
2037 if (r < 0)
2038 return bus_log_create_error(r);
2039
2040 r = sd_bus_message_append(m, "s", argv[1]);
2041 if (r < 0)
2042 return bus_log_create_error(r);
2043
2044 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
2045 if (r < 0) {
2046 if (sd_bus_error_has_name(&error, BUS_ERROR_HOME_BUSY))
2047 log_notice("Not deactivating home directory of %s, as it is still used.", argv[1]);
2048 else
2049 return log_error_errno(r, "Failed to release user home: %s", bus_error_message(&error, r));
2050 }
2051
2052 return ret;
2053 }
2054
2055 static int lock_all_homes(int argc, char *argv[], void *userdata) {
2056 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2057 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2058 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2059 int r;
2060
2061 r = acquire_bus(&bus);
2062 if (r < 0)
2063 return r;
2064
2065 r = bus_message_new_method_call(bus, &m, bus_mgr, "LockAllHomes");
2066 if (r < 0)
2067 return bus_log_create_error(r);
2068
2069 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
2070 if (r < 0)
2071 return log_error_errno(r, "Failed to lock all homes: %s", bus_error_message(&error, r));
2072
2073 return 0;
2074 }
2075
2076 static int deactivate_all_homes(int argc, char *argv[], void *userdata) {
2077 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2078 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2079 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2080 int r;
2081
2082 r = acquire_bus(&bus);
2083 if (r < 0)
2084 return r;
2085
2086 r = bus_message_new_method_call(bus, &m, bus_mgr, "DeactivateAllHomes");
2087 if (r < 0)
2088 return bus_log_create_error(r);
2089
2090 r = sd_bus_call(bus, m, HOME_SLOW_BUS_CALL_TIMEOUT_USEC, &error, NULL);
2091 if (r < 0)
2092 return log_error_errno(r, "Failed to deactivate all homes: %s", bus_error_message(&error, r));
2093
2094 return 0;
2095 }
2096
2097 static int drop_from_identity(const char *field) {
2098 int r;
2099
2100 assert(field);
2101
2102 /* If we are called to update an identity record and drop some field, let's keep track of what to
2103 * remove from the old record */
2104 r = strv_extend(&arg_identity_filter, field);
2105 if (r < 0)
2106 return log_oom();
2107
2108 /* Let's also drop the field if it was previously set to a new value on the same command line */
2109 r = json_variant_filter(&arg_identity_extra, STRV_MAKE(field));
2110 if (r < 0)
2111 return log_error_errno(r, "Failed to filter JSON identity data: %m");
2112
2113 r = json_variant_filter(&arg_identity_extra_this_machine, STRV_MAKE(field));
2114 if (r < 0)
2115 return log_error_errno(r, "Failed to filter JSON identity data: %m");
2116
2117 r = json_variant_filter(&arg_identity_extra_privileged, STRV_MAKE(field));
2118 if (r < 0)
2119 return log_error_errno(r, "Failed to filter JSON identity data: %m");
2120
2121 return 0;
2122 }
2123
2124 static int help(int argc, char *argv[], void *userdata) {
2125 _cleanup_free_ char *link = NULL;
2126 int r;
2127
2128 pager_open(arg_pager_flags);
2129
2130 r = terminal_urlify_man("homectl", "1", &link);
2131 if (r < 0)
2132 return log_oom();
2133
2134 printf("%1$s [OPTIONS...] COMMAND ...\n\n"
2135 "%2$sCreate, manipulate or inspect home directories.%3$s\n"
2136 "\n%4$sCommands:%5$s\n"
2137 " list List home areas\n"
2138 " activate USER… Activate a home area\n"
2139 " deactivate USER… Deactivate a home area\n"
2140 " inspect USER… Inspect a home area\n"
2141 " authenticate USER… Authenticate a home area\n"
2142 " create USER Create a home area\n"
2143 " remove USER… Remove a home area\n"
2144 " update USER Update a home area\n"
2145 " passwd USER Change password of a home area\n"
2146 " resize USER SIZE Resize a home area\n"
2147 " lock USER… Temporarily lock an active home area\n"
2148 " unlock USER… Unlock a temporarily locked home area\n"
2149 " lock-all Lock all suitable home areas\n"
2150 " deactivate-all Deactivate all active home areas\n"
2151 " with USER [COMMAND…] Run shell or command with access to a home area\n"
2152 "\n%4$sOptions:%5$s\n"
2153 " -h --help Show this help\n"
2154 " --version Show package version\n"
2155 " --no-pager Do not pipe output into a pager\n"
2156 " --no-legend Do not show the headers and footers\n"
2157 " --no-ask-password Do not ask for system passwords\n"
2158 " -H --host=[USER@]HOST Operate on remote host\n"
2159 " -M --machine=CONTAINER Operate on local container\n"
2160 " --identity=PATH Read JSON identity from file\n"
2161 " --json=FORMAT Output inspection data in JSON (takes one of\n"
2162 " pretty, short, off)\n"
2163 " -j Equivalent to --json=pretty (on TTY) or\n"
2164 " --json=short (otherwise)\n"
2165 " --export-format= Strip JSON inspection data (full, stripped,\n"
2166 " minimal)\n"
2167 " -E When specified once equals -j --export-format=\n"
2168 " stripped, when specified twice equals\n"
2169 " -j --export-format=minimal\n"
2170 "\n%4$sGeneral User Record Properties:%5$s\n"
2171 " -c --real-name=REALNAME Real name for user\n"
2172 " --realm=REALM Realm to create user in\n"
2173 " --email-address=EMAIL Email address for user\n"
2174 " --location=LOCATION Set location of user on earth\n"
2175 " --icon-name=NAME Icon name for user\n"
2176 " -d --home-dir=PATH Home directory\n"
2177 " -u --uid=UID Numeric UID for user\n"
2178 " -G --member-of=GROUP Add user to group\n"
2179 " --skel=PATH Skeleton directory to use\n"
2180 " --shell=PATH Shell for account\n"
2181 " --setenv=VARIABLE[=VALUE] Set an environment variable at log-in\n"
2182 " --timezone=TIMEZONE Set a time-zone\n"
2183 " --language=LOCALE Set preferred language\n"
2184 " --ssh-authorized-keys=KEYS\n"
2185 " Specify SSH public keys\n"
2186 " --pkcs11-token-uri=URI URI to PKCS#11 security token containing\n"
2187 " private key and matching X.509 certificate\n"
2188 " --fido2-device=PATH Path to FIDO2 hidraw device with hmac-secret\n"
2189 " extension\n"
2190 " --fido2-with-client-pin=BOOL\n"
2191 " Whether to require entering a PIN to unlock the\n"
2192 " account\n"
2193 " --fido2-with-user-presence=BOOL\n"
2194 " Whether to require user presence to unlock the\n"
2195 " account\n"
2196 " --fido2-with-user-verification=BOOL\n"
2197 " Whether to require user verification to unlock\n"
2198 " the account\n"
2199 " --recovery-key=BOOL Add a recovery key\n"
2200 "\n%4$sAccount Management User Record Properties:%5$s\n"
2201 " --locked=BOOL Set locked account state\n"
2202 " --not-before=TIMESTAMP Do not allow logins before\n"
2203 " --not-after=TIMESTAMP Do not allow logins after\n"
2204 " --rate-limit-interval=SECS\n"
2205 " Login rate-limit interval in seconds\n"
2206 " --rate-limit-burst=NUMBER\n"
2207 " Login rate-limit attempts per interval\n"
2208 "\n%4$sPassword Policy User Record Properties:%5$s\n"
2209 " --password-hint=HINT Set Password hint\n"
2210 " --enforce-password-policy=BOOL\n"
2211 " Control whether to enforce system's password\n"
2212 " policy for this user\n"
2213 " -P Same as --enforce-password-password=no\n"
2214 " --password-change-now=BOOL\n"
2215 " Require the password to be changed on next login\n"
2216 " --password-change-min=TIME\n"
2217 " Require minimum time between password changes\n"
2218 " --password-change-max=TIME\n"
2219 " Require maximum time between password changes\n"
2220 " --password-change-warn=TIME\n"
2221 " How much time to warn before password expiry\n"
2222 " --password-change-inactive=TIME\n"
2223 " How much time to block password after expiry\n"
2224 "\n%4$sResource Management User Record Properties:%5$s\n"
2225 " --disk-size=BYTES Size to assign the user on disk\n"
2226 " --access-mode=MODE User home directory access mode\n"
2227 " --umask=MODE Umask for user when logging in\n"
2228 " --nice=NICE Nice level for user\n"
2229 " --rlimit=LIMIT=VALUE[:VALUE]\n"
2230 " Set resource limits\n"
2231 " --tasks-max=MAX Set maximum number of per-user tasks\n"
2232 " --memory-high=BYTES Set high memory threshold in bytes\n"
2233 " --memory-max=BYTES Set maximum memory limit\n"
2234 " --cpu-weight=WEIGHT Set CPU weight\n"
2235 " --io-weight=WEIGHT Set IO weight\n"
2236 "\n%4$sStorage User Record Properties:%5$s\n"
2237 " --storage=STORAGE Storage type to use (luks, fscrypt, directory,\n"
2238 " subvolume, cifs)\n"
2239 " --image-path=PATH Path to image file/directory\n"
2240 " --drop-caches=BOOL Whether to automatically drop caches on logout\n"
2241 "\n%4$sLUKS Storage User Record Properties:%5$s\n"
2242 " --fs-type=TYPE File system type to use in case of luks\n"
2243 " storage (btrfs, ext4, xfs)\n"
2244 " --luks-discard=BOOL Whether to use 'discard' feature of file system\n"
2245 " when activated (mounted)\n"
2246 " --luks-offline-discard=BOOL\n"
2247 " Whether to trim file on logout\n"
2248 " --luks-cipher=CIPHER Cipher to use for LUKS encryption\n"
2249 " --luks-cipher-mode=MODE Cipher mode to use for LUKS encryption\n"
2250 " --luks-volume-key-size=BITS\n"
2251 " Volume key size to use for LUKS encryption\n"
2252 " --luks-pbkdf-type=TYPE Password-based Key Derivation Function to use\n"
2253 " --luks-pbkdf-hash-algorithm=ALGORITHM\n"
2254 " PBKDF hash algorithm to use\n"
2255 " --luks-pbkdf-time-cost=SECS\n"
2256 " Time cost for PBKDF in seconds\n"
2257 " --luks-pbkdf-memory-cost=BYTES\n"
2258 " Memory cost for PBKDF in bytes\n"
2259 " --luks-pbkdf-parallel-threads=NUMBER\n"
2260 " Number of parallel threads for PKBDF\n"
2261 " --luks-extra-mount-options=OPTIONS\n"
2262 " LUKS extra mount options\n"
2263 " --auto-resize-mode=MODE Automatically grow/shrink home on login/logout\n"
2264 "\n%4$sMounting User Record Properties:%5$s\n"
2265 " --nosuid=BOOL Control the 'nosuid' flag of the home mount\n"
2266 " --nodev=BOOL Control the 'nodev' flag of the home mount\n"
2267 " --noexec=BOOL Control the 'noexec' flag of the home mount\n"
2268 "\n%4$sCIFS User Record Properties:%5$s\n"
2269 " --cifs-domain=DOMAIN CIFS (Windows) domain\n"
2270 " --cifs-user-name=USER CIFS (Windows) user name\n"
2271 " --cifs-service=SERVICE CIFS (Windows) service to mount as home area\n"
2272 " --cifs-extra-mount-options=OPTIONS\n"
2273 " CIFS (Windows) extra mount options\n"
2274 "\n%4$sLogin Behaviour User Record Properties:%5$s\n"
2275 " --stop-delay=SECS How long to leave user services running after\n"
2276 " logout\n"
2277 " --kill-processes=BOOL Whether to kill user processes when sessions\n"
2278 " terminate\n"
2279 " --auto-login=BOOL Try to log this user in automatically\n"
2280 "\nSee the %6$s for details.\n",
2281 program_invocation_short_name,
2282 ansi_highlight(),
2283 ansi_normal(),
2284 ansi_underline(),
2285 ansi_normal(),
2286 link);
2287
2288 return 0;
2289 }
2290
2291 static int parse_argv(int argc, char *argv[]) {
2292
2293 enum {
2294 ARG_VERSION = 0x100,
2295 ARG_NO_PAGER,
2296 ARG_NO_LEGEND,
2297 ARG_NO_ASK_PASSWORD,
2298 ARG_REALM,
2299 ARG_EMAIL_ADDRESS,
2300 ARG_DISK_SIZE,
2301 ARG_ACCESS_MODE,
2302 ARG_STORAGE,
2303 ARG_FS_TYPE,
2304 ARG_IMAGE_PATH,
2305 ARG_UMASK,
2306 ARG_LUKS_DISCARD,
2307 ARG_LUKS_OFFLINE_DISCARD,
2308 ARG_JSON,
2309 ARG_SETENV,
2310 ARG_TIMEZONE,
2311 ARG_LANGUAGE,
2312 ARG_LOCKED,
2313 ARG_SSH_AUTHORIZED_KEYS,
2314 ARG_LOCATION,
2315 ARG_ICON_NAME,
2316 ARG_PASSWORD_HINT,
2317 ARG_NICE,
2318 ARG_RLIMIT,
2319 ARG_NOT_BEFORE,
2320 ARG_NOT_AFTER,
2321 ARG_LUKS_CIPHER,
2322 ARG_LUKS_CIPHER_MODE,
2323 ARG_LUKS_VOLUME_KEY_SIZE,
2324 ARG_NOSUID,
2325 ARG_NODEV,
2326 ARG_NOEXEC,
2327 ARG_CIFS_DOMAIN,
2328 ARG_CIFS_USER_NAME,
2329 ARG_CIFS_SERVICE,
2330 ARG_CIFS_EXTRA_MOUNT_OPTIONS,
2331 ARG_TASKS_MAX,
2332 ARG_MEMORY_HIGH,
2333 ARG_MEMORY_MAX,
2334 ARG_CPU_WEIGHT,
2335 ARG_IO_WEIGHT,
2336 ARG_LUKS_PBKDF_TYPE,
2337 ARG_LUKS_PBKDF_HASH_ALGORITHM,
2338 ARG_LUKS_PBKDF_TIME_COST,
2339 ARG_LUKS_PBKDF_MEMORY_COST,
2340 ARG_LUKS_PBKDF_PARALLEL_THREADS,
2341 ARG_RATE_LIMIT_INTERVAL,
2342 ARG_RATE_LIMIT_BURST,
2343 ARG_STOP_DELAY,
2344 ARG_KILL_PROCESSES,
2345 ARG_ENFORCE_PASSWORD_POLICY,
2346 ARG_PASSWORD_CHANGE_NOW,
2347 ARG_PASSWORD_CHANGE_MIN,
2348 ARG_PASSWORD_CHANGE_MAX,
2349 ARG_PASSWORD_CHANGE_WARN,
2350 ARG_PASSWORD_CHANGE_INACTIVE,
2351 ARG_EXPORT_FORMAT,
2352 ARG_AUTO_LOGIN,
2353 ARG_PKCS11_TOKEN_URI,
2354 ARG_FIDO2_DEVICE,
2355 ARG_FIDO2_WITH_PIN,
2356 ARG_FIDO2_WITH_UP,
2357 ARG_FIDO2_WITH_UV,
2358 ARG_RECOVERY_KEY,
2359 ARG_AND_RESIZE,
2360 ARG_AND_CHANGE_PASSWORD,
2361 ARG_DROP_CACHES,
2362 ARG_LUKS_EXTRA_MOUNT_OPTIONS,
2363 ARG_AUTO_RESIZE_MODE,
2364 };
2365
2366 static const struct option options[] = {
2367 { "help", no_argument, NULL, 'h' },
2368 { "version", no_argument, NULL, ARG_VERSION },
2369 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2370 { "no-legend", no_argument, NULL, ARG_NO_LEGEND },
2371 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
2372 { "host", required_argument, NULL, 'H' },
2373 { "machine", required_argument, NULL, 'M' },
2374 { "identity", required_argument, NULL, 'I' },
2375 { "real-name", required_argument, NULL, 'c' },
2376 { "comment", required_argument, NULL, 'c' }, /* Compat alias to keep thing in sync with useradd(8) */
2377 { "realm", required_argument, NULL, ARG_REALM },
2378 { "email-address", required_argument, NULL, ARG_EMAIL_ADDRESS },
2379 { "location", required_argument, NULL, ARG_LOCATION },
2380 { "password-hint", required_argument, NULL, ARG_PASSWORD_HINT },
2381 { "icon-name", required_argument, NULL, ARG_ICON_NAME },
2382 { "home-dir", required_argument, NULL, 'd' }, /* Compatible with useradd(8) */
2383 { "uid", required_argument, NULL, 'u' }, /* Compatible with useradd(8) */
2384 { "member-of", required_argument, NULL, 'G' },
2385 { "groups", required_argument, NULL, 'G' }, /* Compat alias to keep thing in sync with useradd(8) */
2386 { "skel", required_argument, NULL, 'k' }, /* Compatible with useradd(8) */
2387 { "shell", required_argument, NULL, 's' }, /* Compatible with useradd(8) */
2388 { "setenv", required_argument, NULL, ARG_SETENV },
2389 { "timezone", required_argument, NULL, ARG_TIMEZONE },
2390 { "language", required_argument, NULL, ARG_LANGUAGE },
2391 { "locked", required_argument, NULL, ARG_LOCKED },
2392 { "not-before", required_argument, NULL, ARG_NOT_BEFORE },
2393 { "not-after", required_argument, NULL, ARG_NOT_AFTER },
2394 { "expiredate", required_argument, NULL, 'e' }, /* Compat alias to keep thing in sync with useradd(8) */
2395 { "ssh-authorized-keys", required_argument, NULL, ARG_SSH_AUTHORIZED_KEYS },
2396 { "disk-size", required_argument, NULL, ARG_DISK_SIZE },
2397 { "access-mode", required_argument, NULL, ARG_ACCESS_MODE },
2398 { "umask", required_argument, NULL, ARG_UMASK },
2399 { "nice", required_argument, NULL, ARG_NICE },
2400 { "rlimit", required_argument, NULL, ARG_RLIMIT },
2401 { "tasks-max", required_argument, NULL, ARG_TASKS_MAX },
2402 { "memory-high", required_argument, NULL, ARG_MEMORY_HIGH },
2403 { "memory-max", required_argument, NULL, ARG_MEMORY_MAX },
2404 { "cpu-weight", required_argument, NULL, ARG_CPU_WEIGHT },
2405 { "io-weight", required_argument, NULL, ARG_IO_WEIGHT },
2406 { "storage", required_argument, NULL, ARG_STORAGE },
2407 { "image-path", required_argument, NULL, ARG_IMAGE_PATH },
2408 { "fs-type", required_argument, NULL, ARG_FS_TYPE },
2409 { "luks-discard", required_argument, NULL, ARG_LUKS_DISCARD },
2410 { "luks-offline-discard", required_argument, NULL, ARG_LUKS_OFFLINE_DISCARD },
2411 { "luks-cipher", required_argument, NULL, ARG_LUKS_CIPHER },
2412 { "luks-cipher-mode", required_argument, NULL, ARG_LUKS_CIPHER_MODE },
2413 { "luks-volume-key-size", required_argument, NULL, ARG_LUKS_VOLUME_KEY_SIZE },
2414 { "luks-pbkdf-type", required_argument, NULL, ARG_LUKS_PBKDF_TYPE },
2415 { "luks-pbkdf-hash-algorithm", required_argument, NULL, ARG_LUKS_PBKDF_HASH_ALGORITHM },
2416 { "luks-pbkdf-time-cost", required_argument, NULL, ARG_LUKS_PBKDF_TIME_COST },
2417 { "luks-pbkdf-memory-cost", required_argument, NULL, ARG_LUKS_PBKDF_MEMORY_COST },
2418 { "luks-pbkdf-parallel-threads", required_argument, NULL, ARG_LUKS_PBKDF_PARALLEL_THREADS },
2419 { "nosuid", required_argument, NULL, ARG_NOSUID },
2420 { "nodev", required_argument, NULL, ARG_NODEV },
2421 { "noexec", required_argument, NULL, ARG_NOEXEC },
2422 { "cifs-user-name", required_argument, NULL, ARG_CIFS_USER_NAME },
2423 { "cifs-domain", required_argument, NULL, ARG_CIFS_DOMAIN },
2424 { "cifs-service", required_argument, NULL, ARG_CIFS_SERVICE },
2425 { "cifs-extra-mount-options", required_argument, NULL, ARG_CIFS_EXTRA_MOUNT_OPTIONS },
2426 { "rate-limit-interval", required_argument, NULL, ARG_RATE_LIMIT_INTERVAL },
2427 { "rate-limit-burst", required_argument, NULL, ARG_RATE_LIMIT_BURST },
2428 { "stop-delay", required_argument, NULL, ARG_STOP_DELAY },
2429 { "kill-processes", required_argument, NULL, ARG_KILL_PROCESSES },
2430 { "enforce-password-policy", required_argument, NULL, ARG_ENFORCE_PASSWORD_POLICY },
2431 { "password-change-now", required_argument, NULL, ARG_PASSWORD_CHANGE_NOW },
2432 { "password-change-min", required_argument, NULL, ARG_PASSWORD_CHANGE_MIN },
2433 { "password-change-max", required_argument, NULL, ARG_PASSWORD_CHANGE_MAX },
2434 { "password-change-warn", required_argument, NULL, ARG_PASSWORD_CHANGE_WARN },
2435 { "password-change-inactive", required_argument, NULL, ARG_PASSWORD_CHANGE_INACTIVE },
2436 { "auto-login", required_argument, NULL, ARG_AUTO_LOGIN },
2437 { "json", required_argument, NULL, ARG_JSON },
2438 { "export-format", required_argument, NULL, ARG_EXPORT_FORMAT },
2439 { "pkcs11-token-uri", required_argument, NULL, ARG_PKCS11_TOKEN_URI },
2440 { "fido2-device", required_argument, NULL, ARG_FIDO2_DEVICE },
2441 { "fido2-with-client-pin", required_argument, NULL, ARG_FIDO2_WITH_PIN },
2442 { "fido2-with-user-presence", required_argument, NULL, ARG_FIDO2_WITH_UP },
2443 { "fido2-with-user-verification",required_argument, NULL, ARG_FIDO2_WITH_UV },
2444 { "recovery-key", required_argument, NULL, ARG_RECOVERY_KEY },
2445 { "and-resize", required_argument, NULL, ARG_AND_RESIZE },
2446 { "and-change-password", required_argument, NULL, ARG_AND_CHANGE_PASSWORD },
2447 { "drop-caches", required_argument, NULL, ARG_DROP_CACHES },
2448 { "luks-extra-mount-options", required_argument, NULL, ARG_LUKS_EXTRA_MOUNT_OPTIONS },
2449 { "auto-resize-mode", required_argument, NULL, ARG_AUTO_RESIZE_MODE },
2450 {}
2451 };
2452
2453 int r;
2454
2455 assert(argc >= 0);
2456 assert(argv);
2457
2458 for (;;) {
2459 int c;
2460
2461 c = getopt_long(argc, argv, "hH:M:I:c:d:u:k:s:e:G:jPE", options, NULL);
2462 if (c < 0)
2463 break;
2464
2465 switch (c) {
2466
2467 case 'h':
2468 return help(0, NULL, NULL);
2469
2470 case ARG_VERSION:
2471 return version();
2472
2473 case ARG_NO_PAGER:
2474 arg_pager_flags |= PAGER_DISABLE;
2475 break;
2476
2477 case ARG_NO_LEGEND:
2478 arg_legend = false;
2479 break;
2480
2481 case ARG_NO_ASK_PASSWORD:
2482 arg_ask_password = false;
2483 break;
2484
2485 case 'H':
2486 arg_transport = BUS_TRANSPORT_REMOTE;
2487 arg_host = optarg;
2488 break;
2489
2490 case 'M':
2491 arg_transport = BUS_TRANSPORT_MACHINE;
2492 arg_host = optarg;
2493 break;
2494
2495 case 'I':
2496 arg_identity = optarg;
2497 break;
2498
2499 case 'c':
2500 if (isempty(optarg)) {
2501 r = drop_from_identity("realName");
2502 if (r < 0)
2503 return r;
2504
2505 break;
2506 }
2507
2508 if (!valid_gecos(optarg))
2509 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Real name '%s' not a valid GECOS field.", optarg);
2510
2511 r = json_variant_set_field_string(&arg_identity_extra, "realName", optarg);
2512 if (r < 0)
2513 return log_error_errno(r, "Failed to set realName field: %m");
2514
2515 break;
2516
2517 case 'd': {
2518 _cleanup_free_ char *hd = NULL;
2519
2520 if (isempty(optarg)) {
2521 r = drop_from_identity("homeDirectory");
2522 if (r < 0)
2523 return r;
2524
2525 break;
2526 }
2527
2528 r = parse_path_argument(optarg, false, &hd);
2529 if (r < 0)
2530 return r;
2531
2532 if (!valid_home(hd))
2533 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Home directory '%s' not valid.", hd);
2534
2535 r = json_variant_set_field_string(&arg_identity_extra, "homeDirectory", hd);
2536 if (r < 0)
2537 return log_error_errno(r, "Failed to set homeDirectory field: %m");
2538
2539 break;
2540 }
2541
2542 case ARG_REALM:
2543 if (isempty(optarg)) {
2544 r = drop_from_identity("realm");
2545 if (r < 0)
2546 return r;
2547
2548 break;
2549 }
2550
2551 r = dns_name_is_valid(optarg);
2552 if (r < 0)
2553 return log_error_errno(r, "Failed to determine whether realm '%s' is a valid DNS domain: %m", optarg);
2554 if (r == 0)
2555 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Realm '%s' is not a valid DNS domain: %m", optarg);
2556
2557 r = json_variant_set_field_string(&arg_identity_extra, "realm", optarg);
2558 if (r < 0)
2559 return log_error_errno(r, "Failed to set realm field: %m");
2560 break;
2561
2562 case ARG_EMAIL_ADDRESS:
2563 case ARG_LOCATION:
2564 case ARG_ICON_NAME:
2565 case ARG_CIFS_USER_NAME:
2566 case ARG_CIFS_DOMAIN:
2567 case ARG_CIFS_EXTRA_MOUNT_OPTIONS:
2568 case ARG_LUKS_EXTRA_MOUNT_OPTIONS: {
2569
2570 const char *field =
2571 c == ARG_EMAIL_ADDRESS ? "emailAddress" :
2572 c == ARG_LOCATION ? "location" :
2573 c == ARG_ICON_NAME ? "iconName" :
2574 c == ARG_CIFS_USER_NAME ? "cifsUserName" :
2575 c == ARG_CIFS_DOMAIN ? "cifsDomain" :
2576 c == ARG_CIFS_EXTRA_MOUNT_OPTIONS ? "cifsExtraMountOptions" :
2577 c == ARG_LUKS_EXTRA_MOUNT_OPTIONS ? "luksExtraMountOptions" :
2578 NULL;
2579
2580 assert(field);
2581
2582 if (isempty(optarg)) {
2583 r = drop_from_identity(field);
2584 if (r < 0)
2585 return r;
2586
2587 break;
2588 }
2589
2590 r = json_variant_set_field_string(&arg_identity_extra, field, optarg);
2591 if (r < 0)
2592 return log_error_errno(r, "Failed to set %s field: %m", field);
2593
2594 break;
2595 }
2596
2597 case ARG_CIFS_SERVICE:
2598 if (isempty(optarg)) {
2599 r = drop_from_identity("cifsService");
2600 if (r < 0)
2601 return r;
2602
2603 break;
2604 }
2605
2606 r = parse_cifs_service(optarg, NULL, NULL, NULL);
2607 if (r < 0)
2608 return log_error_errno(r, "Failed to validate CIFS service name: %s", optarg);
2609
2610 r = json_variant_set_field_string(&arg_identity_extra, "cifsService", optarg);
2611 if (r < 0)
2612 return log_error_errno(r, "Failed to set cifsService field: %m");
2613
2614 break;
2615
2616 case ARG_PASSWORD_HINT:
2617 if (isempty(optarg)) {
2618 r = drop_from_identity("passwordHint");
2619 if (r < 0)
2620 return r;
2621
2622 break;
2623 }
2624
2625 r = json_variant_set_field_string(&arg_identity_extra_privileged, "passwordHint", optarg);
2626 if (r < 0)
2627 return log_error_errno(r, "Failed to set passwordHint field: %m");
2628
2629 string_erase(optarg);
2630 break;
2631
2632 case ARG_NICE: {
2633 int nc;
2634
2635 if (isempty(optarg)) {
2636 r = drop_from_identity("niceLevel");
2637 if (r < 0)
2638 return r;
2639 break;
2640 }
2641
2642 r = parse_nice(optarg, &nc);
2643 if (r < 0)
2644 return log_error_errno(r, "Failed to parse nice level: %s", optarg);
2645
2646 r = json_variant_set_field_integer(&arg_identity_extra, "niceLevel", nc);
2647 if (r < 0)
2648 return log_error_errno(r, "Failed to set niceLevel field: %m");
2649
2650 break;
2651 }
2652
2653 case ARG_RLIMIT: {
2654 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL, *jcur = NULL, *jmax = NULL;
2655 _cleanup_free_ char *field = NULL, *t = NULL;
2656 const char *eq;
2657 struct rlimit rl;
2658 int l;
2659
2660 if (isempty(optarg)) {
2661 /* Remove all resource limits */
2662
2663 r = drop_from_identity("resourceLimits");
2664 if (r < 0)
2665 return r;
2666
2667 arg_identity_filter_rlimits = strv_free(arg_identity_filter_rlimits);
2668 arg_identity_extra_rlimits = json_variant_unref(arg_identity_extra_rlimits);
2669 break;
2670 }
2671
2672 eq = strchr(optarg, '=');
2673 if (!eq)
2674 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Can't parse resource limit assignment: %s", optarg);
2675
2676 field = strndup(optarg, eq - optarg);
2677 if (!field)
2678 return log_oom();
2679
2680 l = rlimit_from_string_harder(field);
2681 if (l < 0)
2682 return log_error_errno(l, "Unknown resource limit type: %s", field);
2683
2684 if (isempty(eq + 1)) {
2685 /* Remove only the specific rlimit */
2686
2687 r = strv_extend(&arg_identity_filter_rlimits, rlimit_to_string(l));
2688 if (r < 0)
2689 return r;
2690
2691 r = json_variant_filter(&arg_identity_extra_rlimits, STRV_MAKE(field));
2692 if (r < 0)
2693 return log_error_errno(r, "Failed to filter JSON identity data: %m");
2694
2695 break;
2696 }
2697
2698 r = rlimit_parse(l, eq + 1, &rl);
2699 if (r < 0)
2700 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse resource limit value: %s", eq + 1);
2701
2702 r = rl.rlim_cur == RLIM_INFINITY ? json_variant_new_null(&jcur) : json_variant_new_unsigned(&jcur, rl.rlim_cur);
2703 if (r < 0)
2704 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to allocate current integer: %m");
2705
2706 r = rl.rlim_max == RLIM_INFINITY ? json_variant_new_null(&jmax) : json_variant_new_unsigned(&jmax, rl.rlim_max);
2707 if (r < 0)
2708 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to allocate maximum integer: %m");
2709
2710 r = json_build(&v,
2711 JSON_BUILD_OBJECT(
2712 JSON_BUILD_PAIR("cur", JSON_BUILD_VARIANT(jcur)),
2713 JSON_BUILD_PAIR("max", JSON_BUILD_VARIANT(jmax))));
2714 if (r < 0)
2715 return log_error_errno(r, "Failed to build resource limit: %m");
2716
2717 t = strjoin("RLIMIT_", rlimit_to_string(l));
2718 if (!t)
2719 return log_oom();
2720
2721 r = json_variant_set_field(&arg_identity_extra_rlimits, t, v);
2722 if (r < 0)
2723 return log_error_errno(r, "Failed to set %s field: %m", rlimit_to_string(l));
2724
2725 break;
2726 }
2727
2728 case 'u': {
2729 uid_t uid;
2730
2731 if (isempty(optarg)) {
2732 r = drop_from_identity("uid");
2733 if (r < 0)
2734 return r;
2735
2736 break;
2737 }
2738
2739 r = parse_uid(optarg, &uid);
2740 if (r < 0)
2741 return log_error_errno(r, "Failed to parse UID '%s'.", optarg);
2742
2743 if (uid_is_system(uid))
2744 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "UID " UID_FMT " is in system range, refusing.", uid);
2745 if (uid_is_dynamic(uid))
2746 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "UID " UID_FMT " is in dynamic range, refusing.", uid);
2747 if (uid == UID_NOBODY)
2748 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "UID " UID_FMT " is nobody UID, refusing.", uid);
2749
2750 r = json_variant_set_field_unsigned(&arg_identity_extra, "uid", uid);
2751 if (r < 0)
2752 return log_error_errno(r, "Failed to set realm field: %m");
2753
2754 break;
2755 }
2756
2757 case 'k':
2758 case ARG_IMAGE_PATH: {
2759 const char *field = c == 'k' ? "skeletonDirectory" : "imagePath";
2760 _cleanup_free_ char *v = NULL;
2761
2762 if (isempty(optarg)) {
2763 r = drop_from_identity(field);
2764 if (r < 0)
2765 return r;
2766
2767 break;
2768 }
2769
2770 r = parse_path_argument(optarg, false, &v);
2771 if (r < 0)
2772 return r;
2773
2774 r = json_variant_set_field_string(&arg_identity_extra_this_machine, field, v);
2775 if (r < 0)
2776 return log_error_errno(r, "Failed to set %s field: %m", v);
2777
2778 break;
2779 }
2780
2781 case 's':
2782 if (isempty(optarg)) {
2783 r = drop_from_identity("shell");
2784 if (r < 0)
2785 return r;
2786
2787 break;
2788 }
2789
2790 if (!valid_shell(optarg))
2791 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Shell '%s' not valid.", optarg);
2792
2793 r = json_variant_set_field_string(&arg_identity_extra, "shell", optarg);
2794 if (r < 0)
2795 return log_error_errno(r, "Failed to set shell field: %m");
2796
2797 break;
2798
2799 case ARG_SETENV: {
2800 _cleanup_free_ char **l = NULL;
2801 _cleanup_(json_variant_unrefp) JsonVariant *ne = NULL;
2802 JsonVariant *e;
2803
2804 if (isempty(optarg)) {
2805 r = drop_from_identity("environment");
2806 if (r < 0)
2807 return r;
2808
2809 break;
2810 }
2811
2812 e = json_variant_by_key(arg_identity_extra, "environment");
2813 if (e) {
2814 r = json_variant_strv(e, &l);
2815 if (r < 0)
2816 return log_error_errno(r, "Failed to parse JSON environment field: %m");
2817 }
2818
2819 r = strv_env_replace_strdup_passthrough(&l, optarg);
2820 if (r < 0)
2821 return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
2822
2823 strv_sort(l);
2824
2825 r = json_variant_new_array_strv(&ne, l);
2826 if (r < 0)
2827 return log_error_errno(r, "Failed to allocate environment list JSON: %m");
2828
2829 r = json_variant_set_field(&arg_identity_extra, "environment", ne);
2830 if (r < 0)
2831 return log_error_errno(r, "Failed to set environment list: %m");
2832
2833 break;
2834 }
2835
2836 case ARG_TIMEZONE:
2837
2838 if (isempty(optarg)) {
2839 r = drop_from_identity("timeZone");
2840 if (r < 0)
2841 return r;
2842
2843 break;
2844 }
2845
2846 if (!timezone_is_valid(optarg, LOG_DEBUG))
2847 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Timezone '%s' is not valid.", optarg);
2848
2849 r = json_variant_set_field_string(&arg_identity_extra, "timeZone", optarg);
2850 if (r < 0)
2851 return log_error_errno(r, "Failed to set timezone field: %m");
2852
2853 break;
2854
2855 case ARG_LANGUAGE:
2856 if (isempty(optarg)) {
2857 r = drop_from_identity("language");
2858 if (r < 0)
2859 return r;
2860
2861 break;
2862 }
2863
2864 if (!locale_is_valid(optarg))
2865 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Locale '%s' is not valid.", optarg);
2866
2867 if (locale_is_installed(optarg) <= 0)
2868 log_warning("Locale '%s' is not installed, accepting anyway.", optarg);
2869
2870 r = json_variant_set_field_string(&arg_identity_extra, "preferredLanguage", optarg);
2871 if (r < 0)
2872 return log_error_errno(r, "Failed to set preferredLanguage field: %m");
2873
2874 break;
2875
2876 case ARG_NOSUID:
2877 case ARG_NODEV:
2878 case ARG_NOEXEC:
2879 case ARG_LOCKED:
2880 case ARG_KILL_PROCESSES:
2881 case ARG_ENFORCE_PASSWORD_POLICY:
2882 case ARG_AUTO_LOGIN:
2883 case ARG_PASSWORD_CHANGE_NOW: {
2884 const char *field =
2885 c == ARG_LOCKED ? "locked" :
2886 c == ARG_NOSUID ? "mountNoSuid" :
2887 c == ARG_NODEV ? "mountNoDevices" :
2888 c == ARG_NOEXEC ? "mountNoExecute" :
2889 c == ARG_KILL_PROCESSES ? "killProcesses" :
2890 c == ARG_ENFORCE_PASSWORD_POLICY ? "enforcePasswordPolicy" :
2891 c == ARG_AUTO_LOGIN ? "autoLogin" :
2892 c == ARG_PASSWORD_CHANGE_NOW ? "passwordChangeNow" :
2893 NULL;
2894
2895 assert(field);
2896
2897 if (isempty(optarg)) {
2898 r = drop_from_identity(field);
2899 if (r < 0)
2900 return r;
2901
2902 break;
2903 }
2904
2905 r = parse_boolean(optarg);
2906 if (r < 0)
2907 return log_error_errno(r, "Failed to parse %s boolean: %m", field);
2908
2909 r = json_variant_set_field_boolean(&arg_identity_extra, field, r > 0);
2910 if (r < 0)
2911 return log_error_errno(r, "Failed to set %s field: %m", field);
2912
2913 break;
2914 }
2915
2916 case 'P':
2917 r = json_variant_set_field_boolean(&arg_identity_extra, "enforcePasswordPolicy", false);
2918 if (r < 0)
2919 return log_error_errno(r, "Failed to set enforcePasswordPolicy field: %m");
2920
2921 break;
2922
2923 case ARG_DISK_SIZE:
2924 if (isempty(optarg)) {
2925 r = drop_from_identity("diskSize");
2926 if (r < 0)
2927 return r;
2928
2929 r = drop_from_identity("diskSizeRelative");
2930 if (r < 0)
2931 return r;
2932
2933 arg_disk_size = arg_disk_size_relative = UINT64_MAX;
2934 break;
2935 }
2936
2937 r = parse_permyriad(optarg);
2938 if (r < 0) {
2939 r = parse_disk_size(optarg, &arg_disk_size);
2940 if (r < 0)
2941 return r;
2942
2943 r = drop_from_identity("diskSizeRelative");
2944 if (r < 0)
2945 return r;
2946
2947 r = json_variant_set_field_unsigned(&arg_identity_extra_this_machine, "diskSize", arg_disk_size);
2948 if (r < 0)
2949 return log_error_errno(r, "Failed to set diskSize field: %m");
2950
2951 arg_disk_size_relative = UINT64_MAX;
2952 } else {
2953 /* Normalize to UINT32_MAX == 100% */
2954 arg_disk_size_relative = UINT32_SCALE_FROM_PERMYRIAD(r);
2955
2956 r = drop_from_identity("diskSize");
2957 if (r < 0)
2958 return r;
2959
2960 r = json_variant_set_field_unsigned(&arg_identity_extra_this_machine, "diskSizeRelative", arg_disk_size_relative);
2961 if (r < 0)
2962 return log_error_errno(r, "Failed to set diskSizeRelative field: %m");
2963
2964 arg_disk_size = UINT64_MAX;
2965 }
2966
2967 break;
2968
2969 case ARG_ACCESS_MODE: {
2970 mode_t mode;
2971
2972 if (isempty(optarg)) {
2973 r = drop_from_identity("accessMode");
2974 if (r < 0)
2975 return r;
2976
2977 break;
2978 }
2979
2980 r = parse_mode(optarg, &mode);
2981 if (r < 0)
2982 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Access mode '%s' not valid.", optarg);
2983
2984 r = json_variant_set_field_unsigned(&arg_identity_extra, "accessMode", mode);
2985 if (r < 0)
2986 return log_error_errno(r, "Failed to set access mode field: %m");
2987
2988 break;
2989 }
2990
2991 case ARG_LUKS_DISCARD:
2992 if (isempty(optarg)) {
2993 r = drop_from_identity("luksDiscard");
2994 if (r < 0)
2995 return r;
2996
2997 break;
2998 }
2999
3000 r = parse_boolean(optarg);
3001 if (r < 0)
3002 return log_error_errno(r, "Failed to parse --luks-discard= parameter: %s", optarg);
3003
3004 r = json_variant_set_field_boolean(&arg_identity_extra, "luksDiscard", r);
3005 if (r < 0)
3006 return log_error_errno(r, "Failed to set discard field: %m");
3007
3008 break;
3009
3010 case ARG_LUKS_OFFLINE_DISCARD:
3011 if (isempty(optarg)) {
3012 r = drop_from_identity("luksOfflineDiscard");
3013 if (r < 0)
3014 return r;
3015
3016 break;
3017 }
3018
3019 r = parse_boolean(optarg);
3020 if (r < 0)
3021 return log_error_errno(r, "Failed to parse --luks-offline-discard= parameter: %s", optarg);
3022
3023 r = json_variant_set_field_boolean(&arg_identity_extra, "luksOfflineDiscard", r);
3024 if (r < 0)
3025 return log_error_errno(r, "Failed to set offline discard field: %m");
3026
3027 break;
3028
3029 case ARG_LUKS_VOLUME_KEY_SIZE:
3030 case ARG_LUKS_PBKDF_PARALLEL_THREADS:
3031 case ARG_RATE_LIMIT_BURST: {
3032 const char *field =
3033 c == ARG_LUKS_VOLUME_KEY_SIZE ? "luksVolumeKeySize" :
3034 c == ARG_LUKS_PBKDF_PARALLEL_THREADS ? "luksPbkdfParallelThreads" :
3035 c == ARG_RATE_LIMIT_BURST ? "rateLimitBurst" : NULL;
3036 unsigned n;
3037
3038 assert(field);
3039
3040 if (isempty(optarg)) {
3041 r = drop_from_identity(field);
3042 if (r < 0)
3043 return r;
3044 }
3045
3046 r = safe_atou(optarg, &n);
3047 if (r < 0)
3048 return log_error_errno(r, "Failed to parse %s parameter: %s", field, optarg);
3049
3050 r = json_variant_set_field_unsigned(&arg_identity_extra, field, n);
3051 if (r < 0)
3052 return log_error_errno(r, "Failed to set %s field: %m", field);
3053
3054 break;
3055 }
3056
3057 case ARG_UMASK: {
3058 mode_t m;
3059
3060 if (isempty(optarg)) {
3061 r = drop_from_identity("umask");
3062 if (r < 0)
3063 return r;
3064
3065 break;
3066 }
3067
3068 r = parse_mode(optarg, &m);
3069 if (r < 0)
3070 return log_error_errno(r, "Failed to parse umask: %m");
3071
3072 r = json_variant_set_field_integer(&arg_identity_extra, "umask", m);
3073 if (r < 0)
3074 return log_error_errno(r, "Failed to set umask field: %m");
3075
3076 break;
3077 }
3078
3079 case ARG_SSH_AUTHORIZED_KEYS: {
3080 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
3081 _cleanup_(strv_freep) char **l = NULL, **add = NULL;
3082
3083 if (isempty(optarg)) {
3084 r = drop_from_identity("sshAuthorizedKeys");
3085 if (r < 0)
3086 return r;
3087
3088 break;
3089 }
3090
3091 if (optarg[0] == '@') {
3092 _cleanup_fclose_ FILE *f = NULL;
3093
3094 /* If prefixed with '@' read from a file */
3095
3096 f = fopen(optarg+1, "re");
3097 if (!f)
3098 return log_error_errno(errno, "Failed to open '%s': %m", optarg+1);
3099
3100 for (;;) {
3101 _cleanup_free_ char *line = NULL;
3102
3103 r = read_line(f, LONG_LINE_MAX, &line);
3104 if (r < 0)
3105 return log_error_errno(r, "Failed to read from '%s': %m", optarg+1);
3106 if (r == 0)
3107 break;
3108
3109 if (isempty(line))
3110 continue;
3111
3112 if (line[0] == '#')
3113 continue;
3114
3115 r = strv_consume(&add, TAKE_PTR(line));
3116 if (r < 0)
3117 return log_oom();
3118 }
3119 } else {
3120 /* Otherwise, assume it's a literal key. Let's do some superficial checks
3121 * before accept it though. */
3122
3123 if (string_has_cc(optarg, NULL))
3124 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Authorized key contains control characters, refusing.");
3125 if (optarg[0] == '#')
3126 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified key is a comment?");
3127
3128 add = strv_new(optarg);
3129 if (!add)
3130 return log_oom();
3131 }
3132
3133 v = json_variant_ref(json_variant_by_key(arg_identity_extra_privileged, "sshAuthorizedKeys"));
3134 if (v) {
3135 r = json_variant_strv(v, &l);
3136 if (r < 0)
3137 return log_error_errno(r, "Failed to parse SSH authorized keys list: %m");
3138 }
3139
3140 r = strv_extend_strv(&l, add, true);
3141 if (r < 0)
3142 return log_oom();
3143
3144 v = json_variant_unref(v);
3145
3146 r = json_variant_new_array_strv(&v, l);
3147 if (r < 0)
3148 return log_oom();
3149
3150 r = json_variant_set_field(&arg_identity_extra_privileged, "sshAuthorizedKeys", v);
3151 if (r < 0)
3152 return log_error_errno(r, "Failed to set authorized keys: %m");
3153
3154 break;
3155 }
3156
3157 case ARG_NOT_BEFORE:
3158 case ARG_NOT_AFTER:
3159 case 'e': {
3160 const char *field;
3161 usec_t n;
3162
3163 field = c == ARG_NOT_BEFORE ? "notBeforeUSec" :
3164 IN_SET(c, ARG_NOT_AFTER, 'e') ? "notAfterUSec" : NULL;
3165
3166 assert(field);
3167
3168 if (isempty(optarg)) {
3169 r = drop_from_identity(field);
3170 if (r < 0)
3171 return r;
3172
3173 break;
3174 }
3175
3176 /* Note the minor discrepancy regarding -e parsing here: we support that for compat
3177 * reasons, and in the original useradd(8) implementation it accepts dates in the
3178 * format YYYY-MM-DD. Coincidentally, we accept dates formatted like that too, but
3179 * with greater precision. */
3180 r = parse_timestamp(optarg, &n);
3181 if (r < 0)
3182 return log_error_errno(r, "Failed to parse %s parameter: %m", field);
3183
3184 r = json_variant_set_field_unsigned(&arg_identity_extra, field, n);
3185 if (r < 0)
3186 return log_error_errno(r, "Failed to set %s field: %m", field);
3187 break;
3188 }
3189
3190 case ARG_PASSWORD_CHANGE_MIN:
3191 case ARG_PASSWORD_CHANGE_MAX:
3192 case ARG_PASSWORD_CHANGE_WARN:
3193 case ARG_PASSWORD_CHANGE_INACTIVE: {
3194 const char *field;
3195 usec_t n;
3196
3197 field = c == ARG_PASSWORD_CHANGE_MIN ? "passwordChangeMinUSec" :
3198 c == ARG_PASSWORD_CHANGE_MAX ? "passwordChangeMaxUSec" :
3199 c == ARG_PASSWORD_CHANGE_WARN ? "passwordChangeWarnUSec" :
3200 c == ARG_PASSWORD_CHANGE_INACTIVE ? "passwordChangeInactiveUSec" :
3201 NULL;
3202
3203 assert(field);
3204
3205 if (isempty(optarg)) {
3206 r = drop_from_identity(field);
3207 if (r < 0)
3208 return r;
3209
3210 break;
3211 }
3212
3213 r = parse_sec(optarg, &n);
3214 if (r < 0)
3215 return log_error_errno(r, "Failed to parse %s parameter: %m", field);
3216
3217 r = json_variant_set_field_unsigned(&arg_identity_extra, field, n);
3218 if (r < 0)
3219 return log_error_errno(r, "Failed to set %s field: %m", field);
3220 break;
3221 }
3222
3223 case ARG_STORAGE:
3224 case ARG_FS_TYPE:
3225 case ARG_LUKS_CIPHER:
3226 case ARG_LUKS_CIPHER_MODE:
3227 case ARG_LUKS_PBKDF_TYPE:
3228 case ARG_LUKS_PBKDF_HASH_ALGORITHM: {
3229
3230 const char *field =
3231 c == ARG_STORAGE ? "storage" :
3232 c == ARG_FS_TYPE ? "fileSystemType" :
3233 c == ARG_LUKS_CIPHER ? "luksCipher" :
3234 c == ARG_LUKS_CIPHER_MODE ? "luksCipherMode" :
3235 c == ARG_LUKS_PBKDF_TYPE ? "luksPbkdfType" :
3236 c == ARG_LUKS_PBKDF_HASH_ALGORITHM ? "luksPbkdfHashAlgorithm" : NULL;
3237
3238 assert(field);
3239
3240 if (isempty(optarg)) {
3241 r = drop_from_identity(field);
3242 if (r < 0)
3243 return r;
3244
3245 break;
3246 }
3247
3248 if (!string_is_safe(optarg))
3249 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Parameter for %s field not valid: %s", field, optarg);
3250
3251 r = json_variant_set_field_string(
3252 IN_SET(c, ARG_STORAGE, ARG_FS_TYPE) ?
3253 &arg_identity_extra_this_machine :
3254 &arg_identity_extra, field, optarg);
3255 if (r < 0)
3256 return log_error_errno(r, "Failed to set %s field: %m", field);
3257
3258 break;
3259 }
3260
3261 case ARG_LUKS_PBKDF_TIME_COST:
3262 case ARG_RATE_LIMIT_INTERVAL:
3263 case ARG_STOP_DELAY: {
3264 const char *field =
3265 c == ARG_LUKS_PBKDF_TIME_COST ? "luksPbkdfTimeCostUSec" :
3266 c == ARG_RATE_LIMIT_INTERVAL ? "rateLimitIntervalUSec" :
3267 c == ARG_STOP_DELAY ? "stopDelayUSec" :
3268 NULL;
3269 usec_t t;
3270
3271 assert(field);
3272
3273 if (isempty(optarg)) {
3274 r = drop_from_identity(field);
3275 if (r < 0)
3276 return r;
3277
3278 break;
3279 }
3280
3281 r = parse_sec(optarg, &t);
3282 if (r < 0)
3283 return log_error_errno(r, "Failed to parse %s field: %s", field, optarg);
3284
3285 r = json_variant_set_field_unsigned(&arg_identity_extra, field, t);
3286 if (r < 0)
3287 return log_error_errno(r, "Failed to set %s field: %m", field);
3288
3289 break;
3290 }
3291
3292 case 'G': {
3293 const char *p = optarg;
3294
3295 if (isempty(p)) {
3296 r = drop_from_identity("memberOf");
3297 if (r < 0)
3298 return r;
3299
3300 break;
3301 }
3302
3303 for (;;) {
3304 _cleanup_(json_variant_unrefp) JsonVariant *mo = NULL;
3305 _cleanup_strv_free_ char **list = NULL;
3306 _cleanup_free_ char *word = NULL;
3307
3308 r = extract_first_word(&p, &word, ",", 0);
3309 if (r < 0)
3310 return log_error_errno(r, "Failed to parse group list: %m");
3311 if (r == 0)
3312 break;
3313
3314 if (!valid_user_group_name(word, 0))
3315 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid group name %s.", word);
3316
3317 mo = json_variant_ref(json_variant_by_key(arg_identity_extra, "memberOf"));
3318
3319 r = json_variant_strv(mo, &list);
3320 if (r < 0)
3321 return log_error_errno(r, "Failed to parse group list: %m");
3322
3323 r = strv_extend(&list, word);
3324 if (r < 0)
3325 return log_oom();
3326
3327 strv_sort(list);
3328 strv_uniq(list);
3329
3330 mo = json_variant_unref(mo);
3331 r = json_variant_new_array_strv(&mo, list);
3332 if (r < 0)
3333 return log_error_errno(r, "Failed to create group list JSON: %m");
3334
3335 r = json_variant_set_field(&arg_identity_extra, "memberOf", mo);
3336 if (r < 0)
3337 return log_error_errno(r, "Failed to update group list: %m");
3338 }
3339
3340 break;
3341 }
3342
3343 case ARG_TASKS_MAX: {
3344 uint64_t u;
3345
3346 if (isempty(optarg)) {
3347 r = drop_from_identity("tasksMax");
3348 if (r < 0)
3349 return r;
3350 break;
3351 }
3352
3353 r = safe_atou64(optarg, &u);
3354 if (r < 0)
3355 return log_error_errno(r, "Failed to parse --tasks-max= parameter: %s", optarg);
3356
3357 r = json_variant_set_field_unsigned(&arg_identity_extra, "tasksMax", u);
3358 if (r < 0)
3359 return log_error_errno(r, "Failed to set tasksMax field: %m");
3360
3361 break;
3362 }
3363
3364 case ARG_MEMORY_MAX:
3365 case ARG_MEMORY_HIGH:
3366 case ARG_LUKS_PBKDF_MEMORY_COST: {
3367 const char *field =
3368 c == ARG_MEMORY_MAX ? "memoryMax" :
3369 c == ARG_MEMORY_HIGH ? "memoryHigh" :
3370 c == ARG_LUKS_PBKDF_MEMORY_COST ? "luksPbkdfMemoryCost" : NULL;
3371
3372 uint64_t u;
3373
3374 assert(field);
3375
3376 if (isempty(optarg)) {
3377 r = drop_from_identity(field);
3378 if (r < 0)
3379 return r;
3380 break;
3381 }
3382
3383 r = parse_size(optarg, 1024, &u);
3384 if (r < 0)
3385 return log_error_errno(r, "Failed to parse %s parameter: %s", field, optarg);
3386
3387 r = json_variant_set_field_unsigned(&arg_identity_extra_this_machine, field, u);
3388 if (r < 0)
3389 return log_error_errno(r, "Failed to set %s field: %m", field);
3390
3391 break;
3392 }
3393
3394 case ARG_CPU_WEIGHT:
3395 case ARG_IO_WEIGHT: {
3396 const char *field = c == ARG_CPU_WEIGHT ? "cpuWeight" :
3397 c == ARG_IO_WEIGHT ? "ioWeight" : NULL;
3398 uint64_t u;
3399
3400 assert(field);
3401
3402 if (isempty(optarg)) {
3403 r = drop_from_identity(field);
3404 if (r < 0)
3405 return r;
3406 break;
3407 }
3408
3409 r = safe_atou64(optarg, &u);
3410 if (r < 0)
3411 return log_error_errno(r, "Failed to parse --cpu-weight=/--io-weight= parameter: %s", optarg);
3412
3413 if (!CGROUP_WEIGHT_IS_OK(u))
3414 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Weight %" PRIu64 " is out of valid weight range.", u);
3415
3416 r = json_variant_set_field_unsigned(&arg_identity_extra, field, u);
3417 if (r < 0)
3418 return log_error_errno(r, "Failed to set %s field: %m", field);
3419
3420 break;
3421 }
3422
3423 case ARG_PKCS11_TOKEN_URI: {
3424 const char *p;
3425
3426 if (streq(optarg, "list"))
3427 return pkcs11_list_tokens();
3428
3429 /* If --pkcs11-token-uri= is specified we always drop everything old */
3430 FOREACH_STRING(p, "pkcs11TokenUri", "pkcs11EncryptedKey") {
3431 r = drop_from_identity(p);
3432 if (r < 0)
3433 return r;
3434 }
3435
3436 if (isempty(optarg)) {
3437 arg_pkcs11_token_uri = strv_free(arg_pkcs11_token_uri);
3438 break;
3439 }
3440
3441 if (streq(optarg, "auto")) {
3442 _cleanup_free_ char *found = NULL;
3443
3444 r = pkcs11_find_token_auto(&found);
3445 if (r < 0)
3446 return r;
3447 r = strv_consume(&arg_pkcs11_token_uri, TAKE_PTR(found));
3448 } else {
3449 if (!pkcs11_uri_valid(optarg))
3450 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Not a valid PKCS#11 URI: %s", optarg);
3451
3452 r = strv_extend(&arg_pkcs11_token_uri, optarg);
3453 }
3454 if (r < 0)
3455 return r;
3456
3457 strv_uniq(arg_pkcs11_token_uri);
3458 break;
3459 }
3460
3461 case ARG_FIDO2_DEVICE: {
3462 const char *p;
3463
3464 if (streq(optarg, "list"))
3465 return fido2_list_devices();
3466
3467 FOREACH_STRING(p, "fido2HmacCredential", "fido2HmacSalt") {
3468 r = drop_from_identity(p);
3469 if (r < 0)
3470 return r;
3471 }
3472
3473 if (isempty(optarg)) {
3474 arg_fido2_device = strv_free(arg_fido2_device);
3475 break;
3476 }
3477
3478 if (streq(optarg, "auto")) {
3479 _cleanup_free_ char *found = NULL;
3480
3481 r = fido2_find_device_auto(&found);
3482 if (r < 0)
3483 return r;
3484
3485 r = strv_consume(&arg_fido2_device, TAKE_PTR(found));
3486 } else
3487 r = strv_extend(&arg_fido2_device, optarg);
3488 if (r < 0)
3489 return r;
3490
3491 strv_uniq(arg_fido2_device);
3492 break;
3493 }
3494
3495 case ARG_FIDO2_WITH_PIN: {
3496 bool lock_with_pin;
3497
3498 r = parse_boolean_argument("--fido2-with-client-pin=", optarg, &lock_with_pin);
3499 if (r < 0)
3500 return r;
3501
3502 SET_FLAG(arg_fido2_lock_with, FIDO2ENROLL_PIN, lock_with_pin);
3503 break;
3504 }
3505
3506 case ARG_FIDO2_WITH_UP: {
3507 bool lock_with_up;
3508
3509 r = parse_boolean_argument("--fido2-with-user-presence=", optarg, &lock_with_up);
3510 if (r < 0)
3511 return r;
3512
3513 SET_FLAG(arg_fido2_lock_with, FIDO2ENROLL_UP, lock_with_up);
3514 break;
3515 }
3516
3517 case ARG_FIDO2_WITH_UV: {
3518 bool lock_with_uv;
3519
3520 r = parse_boolean_argument("--fido2-with-user-verification=", optarg, &lock_with_uv);
3521 if (r < 0)
3522 return r;
3523
3524 SET_FLAG(arg_fido2_lock_with, FIDO2ENROLL_UV, lock_with_uv);
3525 break;
3526 }
3527
3528 case ARG_RECOVERY_KEY: {
3529 const char *p;
3530
3531 r = parse_boolean(optarg);
3532 if (r < 0)
3533 return log_error_errno(r, "Failed to parse --recovery-key= argument: %s", optarg);
3534
3535 arg_recovery_key = r;
3536
3537 FOREACH_STRING(p, "recoveryKey", "recoveryKeyType") {
3538 r = drop_from_identity(p);
3539 if (r < 0)
3540 return r;
3541 }
3542
3543 break;
3544 }
3545
3546 case ARG_AUTO_RESIZE_MODE:
3547 if (isempty(optarg)) {
3548 r = drop_from_identity("autoResizeMode");
3549 if (r < 0)
3550 return r;
3551
3552 break;
3553 }
3554
3555 r = auto_resize_mode_from_string(optarg);
3556 if (r < 0)
3557 return log_error_errno(r, "Failed to parse --auto-resize-mode= argument: %s", optarg);
3558
3559 r = json_variant_set_field_string(&arg_identity_extra, "autoResizeMode", auto_resize_mode_to_string(r));
3560 if (r < 0)
3561 return log_error_errno(r, "Failed to set autoResizeMode field: %m");
3562
3563 break;
3564
3565 case 'j':
3566 arg_json_format_flags = JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO;
3567 break;
3568
3569 case ARG_JSON:
3570 r = parse_json_argument(optarg, &arg_json_format_flags);
3571 if (r <= 0)
3572 return r;
3573
3574 break;
3575
3576 case 'E':
3577 if (arg_export_format == EXPORT_FORMAT_FULL)
3578 arg_export_format = EXPORT_FORMAT_STRIPPED;
3579 else if (arg_export_format == EXPORT_FORMAT_STRIPPED)
3580 arg_export_format = EXPORT_FORMAT_MINIMAL;
3581 else
3582 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specifying -E more than twice is not supported.");
3583
3584 arg_json_format_flags &= ~JSON_FORMAT_OFF;
3585 if (arg_json_format_flags == 0)
3586 arg_json_format_flags = JSON_FORMAT_PRETTY_AUTO|JSON_FORMAT_COLOR_AUTO;
3587 break;
3588
3589 case ARG_EXPORT_FORMAT:
3590 if (streq(optarg, "full"))
3591 arg_export_format = EXPORT_FORMAT_FULL;
3592 else if (streq(optarg, "stripped"))
3593 arg_export_format = EXPORT_FORMAT_STRIPPED;
3594 else if (streq(optarg, "minimal"))
3595 arg_export_format = EXPORT_FORMAT_MINIMAL;
3596 else if (streq(optarg, "help")) {
3597 puts("full\n"
3598 "stripped\n"
3599 "minimal");
3600 return 0;
3601 }
3602
3603 break;
3604
3605 case ARG_AND_RESIZE:
3606 arg_and_resize = true;
3607 break;
3608
3609 case ARG_AND_CHANGE_PASSWORD:
3610 arg_and_change_password = true;
3611 break;
3612
3613 case ARG_DROP_CACHES: {
3614 bool drop_caches;
3615
3616 if (isempty(optarg)) {
3617 r = drop_from_identity("dropCaches");
3618 if (r < 0)
3619 return r;
3620 }
3621
3622 r = parse_boolean_argument("--drop-caches=", optarg, &drop_caches);
3623 if (r < 0)
3624 return r;
3625
3626 r = json_variant_set_field_boolean(&arg_identity_extra, "dropCaches", r);
3627 if (r < 0)
3628 return log_error_errno(r, "Failed to set drop caches field: %m");
3629
3630 break;
3631 }
3632
3633 case '?':
3634 return -EINVAL;
3635
3636 default:
3637 assert_not_reached();
3638 }
3639 }
3640
3641 if (!strv_isempty(arg_pkcs11_token_uri) || !strv_isempty(arg_fido2_device))
3642 arg_and_change_password = true;
3643
3644 if (arg_disk_size != UINT64_MAX || arg_disk_size_relative != UINT64_MAX)
3645 arg_and_resize = true;
3646
3647 return 1;
3648 }
3649
3650 static int redirect_bus_mgr(void) {
3651 const char *suffix;
3652
3653 /* Talk to a different service if that's requested. (The same env var is also understood by homed, so
3654 * that it is relatively easily possible to invoke a second instance of homed for debug purposes and
3655 * have homectl talk to it, without colliding with the host version. This is handy when operating
3656 * from a homed-managed account.) */
3657
3658 suffix = getenv("SYSTEMD_HOME_DEBUG_SUFFIX");
3659 if (suffix) {
3660 static BusLocator locator = {
3661 .path = "/org/freedesktop/home1",
3662 .interface = "org.freedesktop.home1.Manager",
3663 };
3664
3665 /* Yes, we leak this memory, but there's little point to collect this, given that we only do
3666 * this in a debug environment, do it only once, and the string shall live for out entire
3667 * process runtime. */
3668
3669 locator.destination = strjoin("org.freedesktop.home1.", suffix);
3670 if (!locator.destination)
3671 return log_oom();
3672
3673 bus_mgr = &locator;
3674 } else
3675 bus_mgr = bus_home_mgr;
3676
3677 return 0;
3678 }
3679
3680 static int run(int argc, char *argv[]) {
3681 static const Verb verbs[] = {
3682 { "help", VERB_ANY, VERB_ANY, 0, help },
3683 { "list", VERB_ANY, 1, VERB_DEFAULT, list_homes },
3684 { "activate", 2, VERB_ANY, 0, activate_home },
3685 { "deactivate", 2, VERB_ANY, 0, deactivate_home },
3686 { "inspect", VERB_ANY, VERB_ANY, 0, inspect_home },
3687 { "authenticate", VERB_ANY, VERB_ANY, 0, authenticate_home },
3688 { "create", VERB_ANY, 2, 0, create_home },
3689 { "remove", 2, VERB_ANY, 0, remove_home },
3690 { "update", VERB_ANY, 2, 0, update_home },
3691 { "passwd", VERB_ANY, 2, 0, passwd_home },
3692 { "resize", 2, 3, 0, resize_home },
3693 { "lock", 2, VERB_ANY, 0, lock_home },
3694 { "unlock", 2, VERB_ANY, 0, unlock_home },
3695 { "with", 2, VERB_ANY, 0, with_home },
3696 { "lock-all", VERB_ANY, 1, 0, lock_all_homes },
3697 { "deactivate-all", VERB_ANY, 1, 0, deactivate_all_homes },
3698 {}
3699 };
3700
3701 int r;
3702
3703 log_setup();
3704
3705 r = redirect_bus_mgr();
3706 if (r < 0)
3707 return r;
3708
3709 r = parse_argv(argc, argv);
3710 if (r <= 0)
3711 return r;
3712
3713 return dispatch_verb(argc, argv, verbs, NULL);
3714 }
3715
3716 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);