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