]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/sysusers/sysusers.c
Finalize for v256~rc2
[thirdparty/systemd.git] / src / sysusers / sysusers.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <getopt.h>
4 #include <utmp.h>
5
6 #include "alloc-util.h"
7 #include "build.h"
8 #include "chase.h"
9 #include "conf-files.h"
10 #include "constants.h"
11 #include "copy.h"
12 #include "creds-util.h"
13 #include "dissect-image.h"
14 #include "env-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "format-util.h"
18 #include "fs-util.h"
19 #include "hashmap.h"
20 #include "libcrypt-util.h"
21 #include "main-func.h"
22 #include "memory-util.h"
23 #include "mount-util.h"
24 #include "nscd-flush.h"
25 #include "pager.h"
26 #include "parse-argument.h"
27 #include "path-util.h"
28 #include "pretty-print.h"
29 #include "selinux-util.h"
30 #include "set.h"
31 #include "smack-util.h"
32 #include "specifier.h"
33 #include "stat-util.h"
34 #include "string-util.h"
35 #include "strv.h"
36 #include "sync-util.h"
37 #include "tmpfile-util-label.h"
38 #include "uid-classification.h"
39 #include "uid-range.h"
40 #include "user-util.h"
41 #include "utf8.h"
42
43 typedef enum ItemType {
44 ADD_USER = 'u',
45 ADD_GROUP = 'g',
46 ADD_MEMBER = 'm',
47 ADD_RANGE = 'r',
48 } ItemType;
49
50 static const char* item_type_to_string(ItemType t) {
51 switch (t) {
52 case ADD_USER:
53 return "user";
54 case ADD_GROUP:
55 return "group";
56 case ADD_MEMBER:
57 return "member";
58 case ADD_RANGE:
59 return "range";
60 default:
61 assert_not_reached();
62 }
63 }
64
65 typedef struct Item {
66 ItemType type;
67
68 char *name;
69 char *group_name;
70 char *uid_path;
71 char *gid_path;
72 char *description;
73 char *home;
74 char *shell;
75
76 gid_t gid;
77 uid_t uid;
78
79 char *filename;
80 unsigned line;
81
82 bool gid_set;
83
84 /* When set the group with the specified GID must exist
85 * and the check if a UID clashes with the GID is skipped.
86 */
87 bool id_set_strict;
88
89 bool uid_set;
90
91 bool todo_user;
92 bool todo_group;
93 } Item;
94
95 static char *arg_root = NULL;
96 static char *arg_image = NULL;
97 static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
98 static const char *arg_replace = NULL;
99 static bool arg_dry_run = false;
100 static bool arg_inline = false;
101 static PagerFlags arg_pager_flags = 0;
102 static ImagePolicy *arg_image_policy = NULL;
103
104 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
105 STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
106 STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
107
108 typedef struct Context {
109 OrderedHashmap *users, *groups;
110 OrderedHashmap *todo_uids, *todo_gids;
111 OrderedHashmap *members;
112
113 Hashmap *database_by_uid, *database_by_username;
114 Hashmap *database_by_gid, *database_by_groupname;
115
116 /* A helper set to hold names that are used by database_by_{uid,gid,username,groupname} above. */
117 Set *names;
118
119 uid_t search_uid;
120 UIDRange *uid_range;
121
122 UGIDAllocationRange login_defs;
123 bool login_defs_need_warning;
124 } Context;
125
126 static void context_done(Context *c) {
127 assert(c);
128
129 ordered_hashmap_free(c->groups);
130 ordered_hashmap_free(c->users);
131 ordered_hashmap_free(c->members);
132 ordered_hashmap_free(c->todo_uids);
133 ordered_hashmap_free(c->todo_gids);
134
135 hashmap_free(c->database_by_uid);
136 hashmap_free(c->database_by_username);
137 hashmap_free(c->database_by_gid);
138 hashmap_free(c->database_by_groupname);
139
140 set_free_free(c->names);
141 uid_range_free(c->uid_range);
142 }
143
144 static void maybe_emit_login_defs_warning(Context *c) {
145 assert(c);
146
147 if (!c->login_defs_need_warning)
148 return;
149
150 if (c->login_defs.system_alloc_uid_min != SYSTEM_ALLOC_UID_MIN ||
151 c->login_defs.system_uid_max != SYSTEM_UID_MAX)
152 log_warning("login.defs specifies UID allocation range "UID_FMT"–"UID_FMT
153 " that is different than the built-in defaults ("UID_FMT"–"UID_FMT")",
154 c->login_defs.system_alloc_uid_min, c->login_defs.system_uid_max,
155 (uid_t) SYSTEM_ALLOC_UID_MIN, (uid_t) SYSTEM_UID_MAX);
156 if (c->login_defs.system_alloc_gid_min != SYSTEM_ALLOC_GID_MIN ||
157 c->login_defs.system_gid_max != SYSTEM_GID_MAX)
158 log_warning("login.defs specifies GID allocation range "GID_FMT"–"GID_FMT
159 " that is different than the built-in defaults ("GID_FMT"–"GID_FMT")",
160 c->login_defs.system_alloc_gid_min, c->login_defs.system_gid_max,
161 (gid_t) SYSTEM_ALLOC_GID_MIN, (gid_t) SYSTEM_GID_MAX);
162
163 c->login_defs_need_warning = false;
164 }
165
166 static int load_user_database(Context *c) {
167 _cleanup_fclose_ FILE *f = NULL;
168 const char *passwd_path;
169 struct passwd *pw;
170 int r;
171
172 assert(c);
173
174 passwd_path = prefix_roota(arg_root, "/etc/passwd");
175 f = fopen(passwd_path, "re");
176 if (!f)
177 return errno == ENOENT ? 0 : -errno;
178
179 r = hashmap_ensure_allocated(&c->database_by_username, &string_hash_ops);
180 if (r < 0)
181 return r;
182
183 r = hashmap_ensure_allocated(&c->database_by_uid, NULL);
184 if (r < 0)
185 return r;
186
187 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
188 r = set_ensure_allocated(&c->names, NULL);
189 if (r < 0)
190 return r;
191
192 while ((r = fgetpwent_sane(f, &pw)) > 0) {
193
194 char *n = strdup(pw->pw_name);
195 if (!n)
196 return -ENOMEM;
197
198 r = set_consume(c->names, n);
199 if (r < 0)
200 return r;
201 assert(r > 0); /* The set uses pointer comparisons, so n must not be in the set. */
202
203 r = hashmap_put(c->database_by_username, n, UID_TO_PTR(pw->pw_uid));
204 if (r == -EEXIST)
205 log_debug_errno(r, "%s: user '%s' is listed twice, ignoring duplicate uid.",
206 passwd_path, n);
207 else if (r < 0)
208 return r;
209
210 r = hashmap_put(c->database_by_uid, UID_TO_PTR(pw->pw_uid), n);
211 if (r == -EEXIST)
212 log_debug_errno(r, "%s: uid "UID_FMT" is listed twice, ignoring duplicate name.",
213 passwd_path, pw->pw_uid);
214 else if (r < 0)
215 return r;
216 }
217 return r;
218 }
219
220 static int load_group_database(Context *c) {
221 _cleanup_fclose_ FILE *f = NULL;
222 const char *group_path;
223 struct group *gr;
224 int r;
225
226 assert(c);
227
228 group_path = prefix_roota(arg_root, "/etc/group");
229 f = fopen(group_path, "re");
230 if (!f)
231 return errno == ENOENT ? 0 : -errno;
232
233 r = hashmap_ensure_allocated(&c->database_by_groupname, &string_hash_ops);
234 if (r < 0)
235 return r;
236
237 r = hashmap_ensure_allocated(&c->database_by_gid, NULL);
238 if (r < 0)
239 return r;
240
241 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
242 r = set_ensure_allocated(&c->names, NULL);
243 if (r < 0)
244 return r;
245
246 while ((r = fgetgrent_sane(f, &gr)) > 0) {
247
248 char *n = strdup(gr->gr_name);
249 if (!n)
250 return -ENOMEM;
251
252 r = set_consume(c->names, n);
253 if (r < 0)
254 return r;
255 assert(r > 0); /* The set uses pointer comparisons, so n must not be in the set. */
256
257 r = hashmap_put(c->database_by_groupname, n, GID_TO_PTR(gr->gr_gid));
258 if (r == -EEXIST)
259 log_debug_errno(r, "%s: group '%s' is listed twice, ignoring duplicate gid.",
260 group_path, n);
261 else if (r < 0)
262 return r;
263
264 r = hashmap_put(c->database_by_gid, GID_TO_PTR(gr->gr_gid), n);
265 if (r == -EEXIST)
266 log_debug_errno(r, "%s: gid "GID_FMT" is listed twice, ignoring duplicate name.",
267 group_path, gr->gr_gid);
268 else if (r < 0)
269 return r;
270 }
271 return r;
272 }
273
274 static int make_backup(const char *target, const char *x) {
275 _cleanup_(unlink_and_freep) char *dst_tmp = NULL;
276 _cleanup_fclose_ FILE *dst = NULL;
277 _cleanup_close_ int src = -EBADF;
278 const char *backup;
279 struct stat st;
280 int r;
281
282 assert(target);
283 assert(x);
284
285 src = open(x, O_RDONLY|O_CLOEXEC|O_NOCTTY);
286 if (src < 0) {
287 if (errno == ENOENT) /* No backup necessary... */
288 return 0;
289
290 return -errno;
291 }
292
293 if (fstat(src, &st) < 0)
294 return -errno;
295
296 r = fopen_temporary_label(
297 target, /* The path for which to the look up the label */
298 x, /* Where we want the file actually to end up */
299 &dst, /* The temporary file we write to */
300 &dst_tmp);
301 if (r < 0)
302 return r;
303
304 r = copy_bytes(src, fileno(dst), UINT64_MAX, COPY_REFLINK);
305 if (r < 0)
306 return r;
307
308 backup = strjoina(x, "-");
309
310 /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
311 * unreadable by others, then it isn't too bad... */
312 r = fchmod_and_chown_with_fallback(fileno(dst), dst_tmp, st.st_mode & 07777, st.st_uid, st.st_gid);
313 if (r < 0)
314 log_warning_errno(r, "Failed to change access mode or ownership of %s: %m", backup);
315
316 if (futimens(fileno(dst), (const struct timespec[2]) { st.st_atim, st.st_mtim }) < 0)
317 log_warning_errno(errno, "Failed to fix access and modification time of %s: %m", backup);
318
319 r = fsync_full(fileno(dst));
320 if (r < 0)
321 return r;
322
323 if (rename(dst_tmp, backup) < 0)
324 return errno;
325
326 dst_tmp = mfree(dst_tmp); /* disable the unlink_and_freep() hook now that the file has been renamed */
327 return 0;
328 }
329
330 static int putgrent_with_members(
331 Context *c,
332 const struct group *gr,
333 FILE *group) {
334
335 char **a;
336 int r;
337
338 assert(c);
339 assert(gr);
340 assert(group);
341
342 a = ordered_hashmap_get(c->members, gr->gr_name);
343 if (a) {
344 _cleanup_strv_free_ char **l = NULL;
345 bool added = false;
346
347 l = strv_copy(gr->gr_mem);
348 if (!l)
349 return -ENOMEM;
350
351 STRV_FOREACH(i, a) {
352 if (strv_contains(l, *i))
353 continue;
354
355 r = strv_extend(&l, *i);
356 if (r < 0)
357 return r;
358
359 added = true;
360 }
361
362 if (added) {
363 struct group t;
364
365 strv_uniq(l);
366 strv_sort(l);
367
368 t = *gr;
369 t.gr_mem = l;
370
371 r = putgrent_sane(&t, group);
372 return r < 0 ? r : 1;
373 }
374 }
375
376 return putgrent_sane(gr, group);
377 }
378
379 #if ENABLE_GSHADOW
380 static int putsgent_with_members(
381 Context *c,
382 const struct sgrp *sg,
383 FILE *gshadow) {
384
385 char **a;
386 int r;
387
388 assert(sg);
389 assert(gshadow);
390
391 a = ordered_hashmap_get(c->members, sg->sg_namp);
392 if (a) {
393 _cleanup_strv_free_ char **l = NULL;
394 bool added = false;
395
396 l = strv_copy(sg->sg_mem);
397 if (!l)
398 return -ENOMEM;
399
400 STRV_FOREACH(i, a) {
401 if (strv_contains(l, *i))
402 continue;
403
404 r = strv_extend(&l, *i);
405 if (r < 0)
406 return r;
407
408 added = true;
409 }
410
411 if (added) {
412 struct sgrp t;
413
414 strv_uniq(l);
415 strv_sort(l);
416
417 t = *sg;
418 t.sg_mem = l;
419
420 r = putsgent_sane(&t, gshadow);
421 return r < 0 ? r : 1;
422 }
423 }
424
425 return putsgent_sane(sg, gshadow);
426 }
427 #endif
428
429 static const char* pick_shell(const Item *i) {
430 if (i->type != ADD_USER)
431 return NULL;
432 if (i->shell)
433 return i->shell;
434 if (i->uid_set && i->uid == 0)
435 return default_root_shell(arg_root);
436 return NOLOGIN;
437 }
438
439 static int write_temporary_passwd(
440 Context *c,
441 const char *passwd_path,
442 FILE **ret_tmpfile,
443 char **ret_tmpfile_path) {
444
445 _cleanup_fclose_ FILE *original = NULL, *passwd = NULL;
446 _cleanup_(unlink_and_freep) char *passwd_tmp = NULL;
447 struct passwd *pw = NULL;
448 Item *i;
449 int r;
450
451 assert(c);
452
453 if (ordered_hashmap_isempty(c->todo_uids))
454 return 0;
455
456 if (arg_dry_run) {
457 log_info("Would write /etc/passwd%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
458 return 0;
459 }
460
461 r = fopen_temporary_label("/etc/passwd", passwd_path, &passwd, &passwd_tmp);
462 if (r < 0)
463 return log_debug_errno(r, "Failed to open temporary copy of %s: %m", passwd_path);
464
465 original = fopen(passwd_path, "re");
466 if (original) {
467
468 /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
469 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
470 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
471 * it easier to depend on sysusers in packaging scripts and suchlike. */
472 r = copy_rights_with_fallback(fileno(original), fileno(passwd), passwd_tmp);
473 if (r < 0)
474 return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
475 passwd_path, passwd_tmp);
476
477 while ((r = fgetpwent_sane(original, &pw)) > 0) {
478 i = ordered_hashmap_get(c->users, pw->pw_name);
479 if (i && i->todo_user)
480 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
481 "%s: User \"%s\" already exists.",
482 passwd_path, pw->pw_name);
483
484 if (ordered_hashmap_contains(c->todo_uids, UID_TO_PTR(pw->pw_uid)))
485 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
486 "%s: Detected collision for UID " UID_FMT ".",
487 passwd_path, pw->pw_uid);
488
489 /* Make sure we keep the NIS entries (if any) at the end. */
490 if (IN_SET(pw->pw_name[0], '+', '-'))
491 break;
492
493 r = putpwent_sane(pw, passwd);
494 if (r < 0)
495 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
496 pw->pw_name);
497 }
498 if (r < 0)
499 return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
500
501 } else {
502 if (errno != ENOENT)
503 return log_debug_errno(errno, "Failed to open %s: %m", passwd_path);
504 if (fchmod(fileno(passwd), 0644) < 0)
505 return log_debug_errno(errno, "Failed to fchmod %s: %m", passwd_tmp);
506 }
507
508 ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
509 _cleanup_free_ char *creds_shell = NULL, *cn = NULL;
510
511 struct passwd n = {
512 .pw_name = i->name,
513 .pw_uid = i->uid,
514 .pw_gid = i->gid,
515 .pw_gecos = (char*) strempty(i->description),
516
517 /* "x" means the password is stored in the shadow file */
518 .pw_passwd = (char*) PASSWORD_SEE_SHADOW,
519
520 /* We default to the root directory as home */
521 .pw_dir = i->home ?: (char*) "/",
522
523 /* Initialize the shell to nologin, with one exception:
524 * for root we patch in something special */
525 .pw_shell = (char*) pick_shell(i),
526 };
527
528 /* Try to pick up the shell for this account via the credentials logic */
529 cn = strjoin("passwd.shell.", i->name);
530 if (!cn)
531 return -ENOMEM;
532
533 r = read_credential(cn, (void**) &creds_shell, NULL);
534 if (r < 0)
535 log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
536 else
537 n.pw_shell = creds_shell;
538
539 r = putpwent_sane(&n, passwd);
540 if (r < 0)
541 return log_debug_errno(r, "Failed to add new user \"%s\" to temporary passwd file: %m",
542 i->name);
543 }
544
545 /* Append the remaining NIS entries if any */
546 while (pw) {
547 r = putpwent_sane(pw, passwd);
548 if (r < 0)
549 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
550 pw->pw_name);
551
552 r = fgetpwent_sane(original, &pw);
553 if (r < 0)
554 return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
555 if (r == 0)
556 break;
557 }
558
559 r = fflush_sync_and_check(passwd);
560 if (r < 0)
561 return log_debug_errno(r, "Failed to flush %s: %m", passwd_tmp);
562
563 *ret_tmpfile = TAKE_PTR(passwd);
564 *ret_tmpfile_path = TAKE_PTR(passwd_tmp);
565
566 return 0;
567 }
568
569 static usec_t epoch_or_now(void) {
570 uint64_t epoch;
571
572 if (secure_getenv_uint64("SOURCE_DATE_EPOCH", &epoch) >= 0) {
573 if (epoch > UINT64_MAX/USEC_PER_SEC) /* Overflow check */
574 return USEC_INFINITY;
575 return (usec_t) epoch * USEC_PER_SEC;
576 }
577
578 return now(CLOCK_REALTIME);
579 }
580
581 static int write_temporary_shadow(
582 Context *c,
583 const char *shadow_path,
584 FILE **ret_tmpfile,
585 char **ret_tmpfile_path) {
586
587 _cleanup_fclose_ FILE *original = NULL, *shadow = NULL;
588 _cleanup_(unlink_and_freep) char *shadow_tmp = NULL;
589 struct spwd *sp = NULL;
590 long lstchg;
591 Item *i;
592 int r;
593
594 assert(c);
595
596 if (ordered_hashmap_isempty(c->todo_uids))
597 return 0;
598
599 if (arg_dry_run) {
600 log_info("Would write /etc/shadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
601 return 0;
602 }
603
604 r = fopen_temporary_label("/etc/shadow", shadow_path, &shadow, &shadow_tmp);
605 if (r < 0)
606 return log_debug_errno(r, "Failed to open temporary copy of %s: %m", shadow_path);
607
608 lstchg = (long) (epoch_or_now() / USEC_PER_DAY);
609
610 original = fopen(shadow_path, "re");
611 if (original) {
612
613 r = copy_rights_with_fallback(fileno(original), fileno(shadow), shadow_tmp);
614 if (r < 0)
615 return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
616 shadow_path, shadow_tmp);
617
618 while ((r = fgetspent_sane(original, &sp)) > 0) {
619 i = ordered_hashmap_get(c->users, sp->sp_namp);
620 if (i && i->todo_user) {
621 /* we will update the existing entry */
622 sp->sp_lstchg = lstchg;
623
624 /* only the /etc/shadow stage is left, so we can
625 * safely remove the item from the todo set */
626 i->todo_user = false;
627 ordered_hashmap_remove(c->todo_uids, UID_TO_PTR(i->uid));
628 }
629
630 /* Make sure we keep the NIS entries (if any) at the end. */
631 if (IN_SET(sp->sp_namp[0], '+', '-'))
632 break;
633
634 r = putspent_sane(sp, shadow);
635 if (r < 0)
636 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
637 sp->sp_namp);
638
639 }
640 if (r < 0)
641 return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
642
643 } else {
644 if (errno != ENOENT)
645 return log_debug_errno(errno, "Failed to open %s: %m", shadow_path);
646 if (fchmod(fileno(shadow), 0000) < 0)
647 return log_debug_errno(errno, "Failed to fchmod %s: %m", shadow_tmp);
648 }
649
650 ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
651 _cleanup_(erase_and_freep) char *creds_password = NULL;
652 bool is_hashed;
653
654 struct spwd n = {
655 .sp_namp = i->name,
656 .sp_lstchg = lstchg,
657 .sp_min = -1,
658 .sp_max = -1,
659 .sp_warn = -1,
660 .sp_inact = -1,
661 .sp_expire = -1,
662 .sp_flag = ULONG_MAX, /* this appears to be what everybody does ... */
663 };
664
665 r = get_credential_user_password(i->name, &creds_password, &is_hashed);
666 if (r < 0)
667 log_debug_errno(r, "Couldn't read password credential for user '%s', ignoring: %m", i->name);
668
669 if (creds_password && !is_hashed) {
670 _cleanup_(erase_and_freep) char* plaintext_password = TAKE_PTR(creds_password);
671 r = hash_password(plaintext_password, &creds_password);
672 if (r < 0)
673 return log_debug_errno(r, "Failed to hash password: %m");
674 }
675
676 if (creds_password)
677 n.sp_pwdp = creds_password;
678 else if (streq(i->name, "root"))
679 /* Let firstboot set the password later */
680 n.sp_pwdp = (char*) PASSWORD_UNPROVISIONED;
681 else
682 n.sp_pwdp = (char*) PASSWORD_LOCKED_AND_INVALID;
683
684 r = putspent_sane(&n, shadow);
685 if (r < 0)
686 return log_debug_errno(r, "Failed to add new user \"%s\" to temporary shadow file: %m",
687 i->name);
688 }
689
690 /* Append the remaining NIS entries if any */
691 while (sp) {
692 r = putspent_sane(sp, shadow);
693 if (r < 0)
694 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
695 sp->sp_namp);
696
697 r = fgetspent_sane(original, &sp);
698 if (r < 0)
699 return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
700 if (r == 0)
701 break;
702 }
703 if (!IN_SET(errno, 0, ENOENT))
704 return -errno;
705
706 r = fflush_sync_and_check(shadow);
707 if (r < 0)
708 return log_debug_errno(r, "Failed to flush %s: %m", shadow_tmp);
709
710 *ret_tmpfile = TAKE_PTR(shadow);
711 *ret_tmpfile_path = TAKE_PTR(shadow_tmp);
712
713 return 0;
714 }
715
716 static int write_temporary_group(
717 Context *c,
718 const char *group_path,
719 FILE **ret_tmpfile,
720 char **ret_tmpfile_path) {
721
722 _cleanup_fclose_ FILE *original = NULL, *group = NULL;
723 _cleanup_(unlink_and_freep) char *group_tmp = NULL;
724 bool group_changed = false;
725 struct group *gr = NULL;
726 Item *i;
727 int r;
728
729 assert(c);
730
731 if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
732 return 0;
733
734 if (arg_dry_run) {
735 log_info("Would write /etc/group%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
736 return 0;
737 }
738
739 r = fopen_temporary_label("/etc/group", group_path, &group, &group_tmp);
740 if (r < 0)
741 return log_error_errno(r, "Failed to open temporary copy of %s: %m", group_path);
742
743 original = fopen(group_path, "re");
744 if (original) {
745
746 r = copy_rights_with_fallback(fileno(original), fileno(group), group_tmp);
747 if (r < 0)
748 return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
749 group_path, group_tmp);
750
751 while ((r = fgetgrent_sane(original, &gr)) > 0) {
752 /* Safety checks against name and GID collisions. Normally,
753 * this should be unnecessary, but given that we look at the
754 * entries anyway here, let's make an extra verification
755 * step that we don't generate duplicate entries. */
756
757 i = ordered_hashmap_get(c->groups, gr->gr_name);
758 if (i && i->todo_group)
759 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
760 "%s: Group \"%s\" already exists.",
761 group_path, gr->gr_name);
762
763 if (ordered_hashmap_contains(c->todo_gids, GID_TO_PTR(gr->gr_gid)))
764 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
765 "%s: Detected collision for GID " GID_FMT ".",
766 group_path, gr->gr_gid);
767
768 /* Make sure we keep the NIS entries (if any) at the end. */
769 if (IN_SET(gr->gr_name[0], '+', '-'))
770 break;
771
772 r = putgrent_with_members(c, gr, group);
773 if (r < 0)
774 return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
775 gr->gr_name);
776 if (r > 0)
777 group_changed = true;
778 }
779 if (r < 0)
780 return log_error_errno(r, "Failed to read %s: %m", group_path);
781
782 } else {
783 if (errno != ENOENT)
784 return log_error_errno(errno, "Failed to open %s: %m", group_path);
785 if (fchmod(fileno(group), 0644) < 0)
786 return log_error_errno(errno, "Failed to fchmod %s: %m", group_tmp);
787 }
788
789 ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
790 struct group n = {
791 .gr_name = i->name,
792 .gr_gid = i->gid,
793 .gr_passwd = (char*) PASSWORD_SEE_SHADOW,
794 };
795
796 r = putgrent_with_members(c, &n, group);
797 if (r < 0)
798 return log_error_errno(r, "Failed to add new group \"%s\" to temporary group file: %m",
799 gr->gr_name);
800
801 group_changed = true;
802 }
803
804 /* Append the remaining NIS entries if any */
805 while (gr) {
806 r = putgrent_sane(gr, group);
807 if (r < 0)
808 return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
809 gr->gr_name);
810
811 r = fgetgrent_sane(original, &gr);
812 if (r < 0)
813 return log_error_errno(r, "Failed to read %s: %m", group_path);
814 if (r == 0)
815 break;
816 }
817
818 r = fflush_sync_and_check(group);
819 if (r < 0)
820 return log_error_errno(r, "Failed to flush %s: %m", group_tmp);
821
822 if (group_changed) {
823 *ret_tmpfile = TAKE_PTR(group);
824 *ret_tmpfile_path = TAKE_PTR(group_tmp);
825 }
826 return 0;
827 }
828
829 static int write_temporary_gshadow(
830 Context *c,
831 const char * gshadow_path,
832 FILE **ret_tmpfile,
833 char **ret_tmpfile_path) {
834
835 #if ENABLE_GSHADOW
836 _cleanup_fclose_ FILE *original = NULL, *gshadow = NULL;
837 _cleanup_(unlink_and_freep) char *gshadow_tmp = NULL;
838 bool group_changed = false;
839 Item *i;
840 int r;
841
842 assert(c);
843
844 if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
845 return 0;
846
847 if (arg_dry_run) {
848 log_info("Would write /etc/gshadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
849 return 0;
850 }
851
852 r = fopen_temporary_label("/etc/gshadow", gshadow_path, &gshadow, &gshadow_tmp);
853 if (r < 0)
854 return log_error_errno(r, "Failed to open temporary copy of %s: %m", gshadow_path);
855
856 original = fopen(gshadow_path, "re");
857 if (original) {
858 struct sgrp *sg;
859
860 r = copy_rights_with_fallback(fileno(original), fileno(gshadow), gshadow_tmp);
861 if (r < 0)
862 return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
863 gshadow_path, gshadow_tmp);
864
865 while ((r = fgetsgent_sane(original, &sg)) > 0) {
866
867 i = ordered_hashmap_get(c->groups, sg->sg_namp);
868 if (i && i->todo_group)
869 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
870 "%s: Group \"%s\" already exists.",
871 gshadow_path, sg->sg_namp);
872
873 r = putsgent_with_members(c, sg, gshadow);
874 if (r < 0)
875 return log_error_errno(r, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
876 sg->sg_namp);
877 if (r > 0)
878 group_changed = true;
879 }
880 if (r < 0)
881 return r;
882
883 } else {
884 if (errno != ENOENT)
885 return log_error_errno(errno, "Failed to open %s: %m", gshadow_path);
886 if (fchmod(fileno(gshadow), 0000) < 0)
887 return log_error_errno(errno, "Failed to fchmod %s: %m", gshadow_tmp);
888 }
889
890 ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
891 struct sgrp n = {
892 .sg_namp = i->name,
893 .sg_passwd = (char*) PASSWORD_LOCKED_AND_INVALID,
894 };
895
896 r = putsgent_with_members(c, &n, gshadow);
897 if (r < 0)
898 return log_error_errno(r, "Failed to add new group \"%s\" to temporary gshadow file: %m",
899 n.sg_namp);
900
901 group_changed = true;
902 }
903
904 r = fflush_sync_and_check(gshadow);
905 if (r < 0)
906 return log_error_errno(r, "Failed to flush %s: %m", gshadow_tmp);
907
908 if (group_changed) {
909 *ret_tmpfile = TAKE_PTR(gshadow);
910 *ret_tmpfile_path = TAKE_PTR(gshadow_tmp);
911 }
912 #endif
913 return 0;
914 }
915
916 static int write_files(Context *c) {
917 _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;
918 _cleanup_(unlink_and_freep) char *passwd_tmp = NULL, *group_tmp = NULL, *shadow_tmp = NULL, *gshadow_tmp = NULL;
919 int r;
920
921 const char
922 *passwd_path = prefix_roota(arg_root, "/etc/passwd"),
923 *shadow_path = prefix_roota(arg_root, "/etc/shadow"),
924 *group_path = prefix_roota(arg_root, "/etc/group"),
925 *gshadow_path = prefix_roota(arg_root, "/etc/gshadow");
926
927 assert(c);
928
929 r = write_temporary_group(c, group_path, &group, &group_tmp);
930 if (r < 0)
931 return r;
932
933 r = write_temporary_gshadow(c, gshadow_path, &gshadow, &gshadow_tmp);
934 if (r < 0)
935 return r;
936
937 r = write_temporary_passwd(c, passwd_path, &passwd, &passwd_tmp);
938 if (r < 0)
939 return r;
940
941 r = write_temporary_shadow(c, shadow_path, &shadow, &shadow_tmp);
942 if (r < 0)
943 return r;
944
945 /* Make a backup of the old files */
946 if (group) {
947 r = make_backup("/etc/group", group_path);
948 if (r < 0)
949 return log_error_errno(r, "Failed to backup %s: %m", group_path);
950 }
951 if (gshadow) {
952 r = make_backup("/etc/gshadow", gshadow_path);
953 if (r < 0)
954 return log_error_errno(r, "Failed to backup %s: %m", gshadow_path);
955 }
956
957 if (passwd) {
958 r = make_backup("/etc/passwd", passwd_path);
959 if (r < 0)
960 return log_error_errno(r, "Failed to backup %s: %m", passwd_path);
961 }
962 if (shadow) {
963 r = make_backup("/etc/shadow", shadow_path);
964 if (r < 0)
965 return log_error_errno(r, "Failed to backup %s: %m", shadow_path);
966 }
967
968 /* And make the new files count */
969 if (group) {
970 r = rename_and_apply_smack_floor_label(group_tmp, group_path);
971 if (r < 0)
972 return log_error_errno(r, "Failed to rename %s to %s: %m",
973 group_tmp, group_path);
974 group_tmp = mfree(group_tmp);
975
976 if (!arg_root && !arg_image)
977 (void) nscd_flush_cache(STRV_MAKE("group"));
978 }
979 if (gshadow) {
980 r = rename_and_apply_smack_floor_label(gshadow_tmp, gshadow_path);
981 if (r < 0)
982 return log_error_errno(r, "Failed to rename %s to %s: %m",
983 gshadow_tmp, gshadow_path);
984
985 gshadow_tmp = mfree(gshadow_tmp);
986 }
987
988 if (passwd) {
989 r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
990 if (r < 0)
991 return log_error_errno(r, "Failed to rename %s to %s: %m",
992 passwd_tmp, passwd_path);
993
994 passwd_tmp = mfree(passwd_tmp);
995
996 if (!arg_root && !arg_image)
997 (void) nscd_flush_cache(STRV_MAKE("passwd"));
998 }
999 if (shadow) {
1000 r = rename_and_apply_smack_floor_label(shadow_tmp, shadow_path);
1001 if (r < 0)
1002 return log_error_errno(r, "Failed to rename %s to %s: %m",
1003 shadow_tmp, shadow_path);
1004
1005 shadow_tmp = mfree(shadow_tmp);
1006 }
1007
1008 return 0;
1009 }
1010
1011 static int uid_is_ok(
1012 Context *c,
1013 uid_t uid,
1014 const char *name,
1015 bool check_with_gid) {
1016
1017 int r;
1018 assert(c);
1019
1020 /* Let's see if we already have assigned the UID a second time */
1021 if (ordered_hashmap_get(c->todo_uids, UID_TO_PTR(uid)))
1022 return 0;
1023
1024 /* Try to avoid using uids that are already used by a group
1025 * that doesn't have the same name as our new user. */
1026 if (check_with_gid) {
1027 Item *i;
1028
1029 i = ordered_hashmap_get(c->todo_gids, GID_TO_PTR(uid));
1030 if (i && !streq(i->name, name))
1031 return 0;
1032 }
1033
1034 /* Let's check the files directly */
1035 if (hashmap_contains(c->database_by_uid, UID_TO_PTR(uid)))
1036 return 0;
1037
1038 if (check_with_gid) {
1039 const char *n;
1040
1041 n = hashmap_get(c->database_by_gid, GID_TO_PTR(uid));
1042 if (n && !streq(n, name))
1043 return 0;
1044 }
1045
1046 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
1047 if (!arg_root) {
1048 _cleanup_free_ struct group *g = NULL;
1049
1050 r = getpwuid_malloc(uid, /* ret= */ NULL);
1051 if (r >= 0)
1052 return 0;
1053 if (r != -ESRCH)
1054 return r;
1055
1056 if (check_with_gid) {
1057 r = getgrgid_malloc((gid_t) uid, &g);
1058 if (r >= 0) {
1059 if (!streq(g->gr_name, name))
1060 return 0;
1061 } else if (r != -ESRCH)
1062 return r;
1063 }
1064 }
1065
1066 return 1;
1067 }
1068
1069 static int root_stat(const char *p, struct stat *st) {
1070 const char *fix;
1071
1072 fix = prefix_roota(arg_root, p);
1073 return RET_NERRNO(stat(fix, st));
1074 }
1075
1076 static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
1077 struct stat st;
1078 bool found_uid = false, found_gid = false;
1079 uid_t uid = 0;
1080 gid_t gid = 0;
1081
1082 assert(i);
1083
1084 /* First, try to get the GID directly */
1085 if (ret_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
1086 gid = st.st_gid;
1087 found_gid = true;
1088 }
1089
1090 /* Then, try to get the UID directly */
1091 if ((ret_uid || (ret_gid && !found_gid))
1092 && i->uid_path
1093 && root_stat(i->uid_path, &st) >= 0) {
1094
1095 uid = st.st_uid;
1096 found_uid = true;
1097
1098 /* If we need the gid, but had no success yet, also derive it from the UID path */
1099 if (ret_gid && !found_gid) {
1100 gid = st.st_gid;
1101 found_gid = true;
1102 }
1103 }
1104
1105 /* If that didn't work yet, then let's reuse the GID as UID */
1106 if (ret_uid && !found_uid && i->gid_path) {
1107
1108 if (found_gid) {
1109 uid = (uid_t) gid;
1110 found_uid = true;
1111 } else if (root_stat(i->gid_path, &st) >= 0) {
1112 uid = (uid_t) st.st_gid;
1113 found_uid = true;
1114 }
1115 }
1116
1117 if (ret_uid) {
1118 if (!found_uid)
1119 return 0;
1120
1121 *ret_uid = uid;
1122 }
1123
1124 if (ret_gid) {
1125 if (!found_gid)
1126 return 0;
1127
1128 *ret_gid = gid;
1129 }
1130
1131 return 1;
1132 }
1133
1134 static int add_user(Context *c, Item *i) {
1135 void *z;
1136 int r;
1137
1138 assert(c);
1139 assert(i);
1140
1141 /* Check the database directly */
1142 z = hashmap_get(c->database_by_username, i->name);
1143 if (z) {
1144 log_debug("User %s already exists.", i->name);
1145 i->uid = PTR_TO_UID(z);
1146 i->uid_set = true;
1147 return 0;
1148 }
1149
1150 if (!arg_root) {
1151 _cleanup_free_ struct passwd *p = NULL;
1152
1153 /* Also check NSS */
1154 r = getpwnam_malloc(i->name, &p);
1155 if (r >= 0) {
1156 log_debug("User %s already exists.", i->name);
1157 i->uid = p->pw_uid;
1158 i->uid_set = true;
1159
1160 r = free_and_strdup(&i->description, p->pw_gecos);
1161 if (r < 0)
1162 return log_oom();
1163
1164 return 0;
1165 }
1166 if (r != -ESRCH)
1167 return log_error_errno(r, "Failed to check if user %s already exists: %m", i->name);
1168 }
1169
1170 /* Try to use the suggested numeric UID */
1171 if (i->uid_set) {
1172 r = uid_is_ok(c, i->uid, i->name, !i->id_set_strict);
1173 if (r < 0)
1174 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
1175 if (r == 0) {
1176 log_info("Suggested user ID " UID_FMT " for %s already used.", i->uid, i->name);
1177 i->uid_set = false;
1178 }
1179 }
1180
1181 /* If that didn't work, try to read it from the specified path */
1182 if (!i->uid_set) {
1183 uid_t candidate;
1184
1185 if (read_id_from_file(i, &candidate, NULL) > 0) {
1186
1187 if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
1188 log_debug("User ID " UID_FMT " of file not suitable for %s.", candidate, i->name);
1189 else {
1190 r = uid_is_ok(c, candidate, i->name, true);
1191 if (r < 0)
1192 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
1193 else if (r > 0) {
1194 i->uid = candidate;
1195 i->uid_set = true;
1196 } else
1197 log_debug("User ID " UID_FMT " of file for %s is already used.", candidate, i->name);
1198 }
1199 }
1200 }
1201
1202 /* Otherwise, try to reuse the group ID */
1203 if (!i->uid_set && i->gid_set) {
1204 r = uid_is_ok(c, (uid_t) i->gid, i->name, true);
1205 if (r < 0)
1206 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
1207 if (r > 0) {
1208 i->uid = (uid_t) i->gid;
1209 i->uid_set = true;
1210 }
1211 }
1212
1213 /* And if that didn't work either, let's try to find a free one */
1214 if (!i->uid_set) {
1215 maybe_emit_login_defs_warning(c);
1216
1217 for (;;) {
1218 r = uid_range_next_lower(c->uid_range, &c->search_uid);
1219 if (r < 0)
1220 return log_error_errno(r, "No free user ID available for %s.", i->name);
1221
1222 r = uid_is_ok(c, c->search_uid, i->name, true);
1223 if (r < 0)
1224 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
1225 else if (r > 0)
1226 break;
1227 }
1228
1229 i->uid_set = true;
1230 i->uid = c->search_uid;
1231 }
1232
1233 r = ordered_hashmap_ensure_put(&c->todo_uids, NULL, UID_TO_PTR(i->uid), i);
1234 if (r == -EEXIST)
1235 return log_error_errno(r, "Requested user %s with UID " UID_FMT " and gid" GID_FMT " to be created is duplicated "
1236 "or conflicts with another user.", i->name, i->uid, i->gid);
1237 if (r == -ENOMEM)
1238 return log_oom();
1239 if (r < 0)
1240 return log_error_errno(r, "Failed to store user %s with UID " UID_FMT " and GID " GID_FMT " to be created: %m",
1241 i->name, i->uid, i->gid);
1242
1243 i->todo_user = true;
1244 log_info("Creating user '%s' (%s) with UID " UID_FMT " and GID " GID_FMT ".",
1245 i->name, strna(i->description), i->uid, i->gid);
1246
1247 return 0;
1248 }
1249
1250 static int gid_is_ok(
1251 Context *c,
1252 gid_t gid,
1253 const char *groupname,
1254 bool check_with_uid) {
1255
1256 Item *user;
1257 char *username;
1258 int r;
1259
1260 assert(c);
1261 assert(groupname);
1262
1263 if (ordered_hashmap_get(c->todo_gids, GID_TO_PTR(gid)))
1264 return 0;
1265
1266 /* Avoid reusing gids that are already used by a different user */
1267 if (check_with_uid) {
1268 user = ordered_hashmap_get(c->todo_uids, UID_TO_PTR(gid));
1269 if (user && !streq(user->name, groupname))
1270 return 0;
1271 }
1272
1273 if (hashmap_contains(c->database_by_gid, GID_TO_PTR(gid)))
1274 return 0;
1275
1276 if (check_with_uid) {
1277 username = hashmap_get(c->database_by_uid, UID_TO_PTR(gid));
1278 if (username && !streq(username, groupname))
1279 return 0;
1280 }
1281
1282 if (!arg_root) {
1283 r = getgrgid_malloc(gid, /* ret= */ NULL);
1284 if (r >= 0)
1285 return 0;
1286 if (r != -ESRCH)
1287 return r;
1288
1289 if (check_with_uid) {
1290 r = getpwuid_malloc(gid, /* ret= */ NULL);
1291 if (r >= 0)
1292 return 0;
1293 if (r != -ESRCH)
1294 return r;
1295 }
1296 }
1297
1298 return 1;
1299 }
1300
1301 static int get_gid_by_name(
1302 Context *c,
1303 const char *name,
1304 gid_t *ret_gid) {
1305
1306 void *z;
1307 int r;
1308
1309 assert(c);
1310 assert(ret_gid);
1311
1312 /* Check the database directly */
1313 z = hashmap_get(c->database_by_groupname, name);
1314 if (z) {
1315 *ret_gid = PTR_TO_GID(z);
1316 return 0;
1317 }
1318
1319 /* Also check NSS */
1320 if (!arg_root) {
1321 _cleanup_free_ struct group *g = NULL;
1322
1323 r = getgrnam_malloc(name, &g);
1324 if (r >= 0) {
1325 *ret_gid = g->gr_gid;
1326 return 0;
1327 }
1328 if (r != -ESRCH)
1329 return log_error_errno(r, "Failed to check if group %s already exists: %m", name);
1330 }
1331
1332 return -ENOENT;
1333 }
1334
1335 static int add_group(Context *c, Item *i) {
1336 int r;
1337
1338 assert(c);
1339 assert(i);
1340
1341 r = get_gid_by_name(c, i->name, &i->gid);
1342 if (r != -ENOENT) {
1343 if (r < 0)
1344 return r;
1345 log_debug("Group %s already exists.", i->name);
1346 i->gid_set = true;
1347 return 0;
1348 }
1349
1350 /* Try to use the suggested numeric GID */
1351 if (i->gid_set) {
1352 r = gid_is_ok(c, i->gid, i->name, false);
1353 if (r < 0)
1354 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
1355 if (i->id_set_strict) {
1356 /* If we require the GID to already exist we can return here:
1357 * r > 0: means the GID does not exist -> fail
1358 * r == 0: means the GID exists -> nothing more to do.
1359 */
1360 if (r > 0)
1361 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1362 "Failed to create %s: please create GID " GID_FMT,
1363 i->name, i->gid);
1364 if (r == 0)
1365 return 0;
1366 }
1367 if (r == 0) {
1368 log_info("Suggested group ID " GID_FMT " for %s already used.", i->gid, i->name);
1369 i->gid_set = false;
1370 }
1371 }
1372
1373 /* Try to reuse the numeric uid, if there's one */
1374 if (!i->gid_set && i->uid_set) {
1375 r = gid_is_ok(c, (gid_t) i->uid, i->name, true);
1376 if (r < 0)
1377 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
1378 if (r > 0) {
1379 i->gid = (gid_t) i->uid;
1380 i->gid_set = true;
1381 }
1382 }
1383
1384 /* If that didn't work, try to read it from the specified path */
1385 if (!i->gid_set) {
1386 gid_t candidate;
1387
1388 if (read_id_from_file(i, NULL, &candidate) > 0) {
1389
1390 if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
1391 log_debug("Group ID " GID_FMT " of file not suitable for %s.", candidate, i->name);
1392 else {
1393 r = gid_is_ok(c, candidate, i->name, true);
1394 if (r < 0)
1395 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
1396 else if (r > 0) {
1397 i->gid = candidate;
1398 i->gid_set = true;
1399 } else
1400 log_debug("Group ID " GID_FMT " of file for %s already used.", candidate, i->name);
1401 }
1402 }
1403 }
1404
1405 /* And if that didn't work either, let's try to find a free one */
1406 if (!i->gid_set) {
1407 maybe_emit_login_defs_warning(c);
1408
1409 for (;;) {
1410 /* We look for new GIDs in the UID pool! */
1411 r = uid_range_next_lower(c->uid_range, &c->search_uid);
1412 if (r < 0)
1413 return log_error_errno(r, "No free group ID available for %s.", i->name);
1414
1415 r = gid_is_ok(c, c->search_uid, i->name, true);
1416 if (r < 0)
1417 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
1418 else if (r > 0)
1419 break;
1420 }
1421
1422 i->gid_set = true;
1423 i->gid = c->search_uid;
1424 }
1425
1426 r = ordered_hashmap_ensure_put(&c->todo_gids, NULL, GID_TO_PTR(i->gid), i);
1427 if (r == -EEXIST)
1428 return log_error_errno(r, "Requested group %s with GID "GID_FMT " to be created is duplicated or conflicts with another user.", i->name, i->gid);
1429 if (r == -ENOMEM)
1430 return log_oom();
1431 if (r < 0)
1432 return log_error_errno(r, "Failed to store group %s with GID " GID_FMT " to be created: %m", i->name, i->gid);
1433
1434 i->todo_group = true;
1435 log_info("Creating group '%s' with GID " GID_FMT ".", i->name, i->gid);
1436
1437 return 0;
1438 }
1439
1440 static int process_item(Context *c, Item *i) {
1441 int r;
1442
1443 assert(c);
1444 assert(i);
1445
1446 switch (i->type) {
1447
1448 case ADD_USER: {
1449 Item *j = NULL;
1450
1451 if (!i->gid_set)
1452 j = ordered_hashmap_get(c->groups, i->group_name ?: i->name);
1453
1454 if (j && j->todo_group) {
1455 /* When a group with the target name is already in queue,
1456 * use the information about the group and do not create
1457 * duplicated group entry. */
1458 i->gid_set = j->gid_set;
1459 i->gid = j->gid;
1460 i->id_set_strict = true;
1461 } else if (i->group_name) {
1462 /* When a group name was given instead of a GID and it's
1463 * not in queue, then it must already exist. */
1464 r = get_gid_by_name(c, i->group_name, &i->gid);
1465 if (r < 0)
1466 return log_error_errno(r, "Group %s not found.", i->group_name);
1467 i->gid_set = true;
1468 i->id_set_strict = true;
1469 } else {
1470 r = add_group(c, i);
1471 if (r < 0)
1472 return r;
1473 }
1474
1475 return add_user(c, i);
1476 }
1477
1478 case ADD_GROUP:
1479 return add_group(c, i);
1480
1481 default:
1482 assert_not_reached();
1483 }
1484 }
1485
1486 static Item* item_free(Item *i) {
1487 if (!i)
1488 return NULL;
1489
1490 free(i->name);
1491 free(i->group_name);
1492 free(i->uid_path);
1493 free(i->gid_path);
1494 free(i->description);
1495 free(i->home);
1496 free(i->shell);
1497 free(i->filename);
1498 return mfree(i);
1499 }
1500
1501 DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1502 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
1503
1504 static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
1505 assert(name);
1506 assert(!!filename == (line > 0));
1507
1508 _cleanup_(item_freep) Item *new = new(Item, 1);
1509 if (!new)
1510 return NULL;
1511
1512 *new = (Item) {
1513 .type = type,
1514 .line = line,
1515 };
1516
1517 if (free_and_strdup(&new->name, name) < 0 ||
1518 free_and_strdup(&new->filename, filename) < 0)
1519 return NULL;
1520
1521 return TAKE_PTR(new);
1522 }
1523
1524 static int add_implicit(Context *c) {
1525 char *g, **l;
1526 int r;
1527
1528 assert(c);
1529
1530 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1531 ORDERED_HASHMAP_FOREACH_KEY(l, g, c->members) {
1532 STRV_FOREACH(m, l)
1533 if (!ordered_hashmap_get(c->users, *m)) {
1534 _cleanup_(item_freep) Item *j =
1535 item_new(ADD_USER, *m, /* filename= */ NULL, /* line= */ 0);
1536 if (!j)
1537 return log_oom();
1538
1539 r = ordered_hashmap_ensure_put(&c->users, &item_hash_ops, j->name, j);
1540 if (r == -ENOMEM)
1541 return log_oom();
1542 if (r < 0)
1543 return log_error_errno(r, "Failed to add implicit user '%s': %m", j->name);
1544
1545 log_debug("Adding implicit user '%s' due to m line", j->name);
1546 TAKE_PTR(j);
1547 }
1548
1549 if (!(ordered_hashmap_get(c->users, g) ||
1550 ordered_hashmap_get(c->groups, g))) {
1551 _cleanup_(item_freep) Item *j =
1552 item_new(ADD_GROUP, g, /* filename= */ NULL, /* line= */ 0);
1553 if (!j)
1554 return log_oom();
1555
1556 r = ordered_hashmap_ensure_put(&c->groups, &item_hash_ops, j->name, j);
1557 if (r == -ENOMEM)
1558 return log_oom();
1559 if (r < 0)
1560 return log_error_errno(r, "Failed to add implicit group '%s': %m", j->name);
1561
1562 log_debug("Adding implicit group '%s' due to m line", j->name);
1563 TAKE_PTR(j);
1564 }
1565 }
1566
1567 return 0;
1568 }
1569
1570 static int item_equivalent(Item *a, Item *b) {
1571 int r;
1572
1573 assert(a);
1574 assert(b);
1575
1576 if (a->type != b->type) {
1577 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1578 "Item not equivalent because types differ");
1579 return false;
1580 }
1581
1582 if (!streq_ptr(a->name, b->name)) {
1583 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1584 "Item not equivalent because names differ ('%s' vs. '%s')",
1585 a->name, b->name);
1586 return false;
1587 }
1588
1589 /* Paths were simplified previously, so we can use streq. */
1590 if (!streq_ptr(a->uid_path, b->uid_path)) {
1591 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1592 "Item not equivalent because UID paths differ (%s vs. %s)",
1593 a->uid_path ?: "(unset)", b->uid_path ?: "(unset)");
1594 return false;
1595 }
1596
1597 if (!streq_ptr(a->gid_path, b->gid_path)) {
1598 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1599 "Item not equivalent because GID paths differ (%s vs. %s)",
1600 a->gid_path ?: "(unset)", b->gid_path ?: "(unset)");
1601 return false;
1602 }
1603
1604 if (!streq_ptr(a->description, b->description)) {
1605 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1606 "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1607 strempty(a->description), strempty(b->description));
1608 return false;
1609 }
1610
1611 if ((a->uid_set != b->uid_set) ||
1612 (a->uid_set && a->uid != b->uid)) {
1613 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1614 "Item not equivalent because UIDs differ (%s vs. %s)",
1615 a->uid_set ? FORMAT_UID(a->uid) : "(unset)",
1616 b->uid_set ? FORMAT_UID(b->uid) : "(unset)");
1617 return false;
1618 }
1619
1620 if ((a->gid_set != b->gid_set) ||
1621 (a->gid_set && a->gid != b->gid)) {
1622 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1623 "Item not equivalent because GIDs differ (%s vs. %s)",
1624 a->gid_set ? FORMAT_GID(a->gid) : "(unset)",
1625 b->gid_set ? FORMAT_GID(b->gid) : "(unset)");
1626 return false;
1627 }
1628
1629 if (!streq_ptr(a->home, b->home)) {
1630 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1631 "Item not equivalent because home directories differ ('%s' vs. '%s')",
1632 strempty(a->description), strempty(b->description));
1633 return false;
1634 }
1635
1636 /* Check if the two paths refer to the same file.
1637 * If the paths are equal (after normalization), it's obviously the same file.
1638 * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1639 * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1640 * /usr/sbin/nologin).
1641 * If we can't resolve something, treat different paths as different. */
1642
1643 const char *a_shell = pick_shell(a),
1644 *b_shell = pick_shell(b);
1645 if (!path_equal(a_shell, b_shell) &&
1646 !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
1647 _cleanup_free_ char *pa = NULL, *pb = NULL;
1648
1649 r = chase(a_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pa, NULL);
1650 if (r < 0) {
1651 log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
1652 r, "Failed to look up path '%s%s%s': %m",
1653 strempty(arg_root), arg_root ? "/" : "", a_shell);
1654 return ERRNO_IS_RESOURCE(r) ? r : false;
1655 }
1656
1657 r = chase(b_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pb, NULL);
1658 if (r < 0) {
1659 log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
1660 r, "Failed to look up path '%s%s%s': %m",
1661 strempty(arg_root), arg_root ? "/" : "", b_shell);
1662 return ERRNO_IS_RESOURCE(r) ? r : false;
1663 }
1664
1665 if (!path_equal(pa, pb)) {
1666 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1667 "Item not equivalent because shells differ ('%s' vs. '%s')",
1668 pa, pb);
1669 return false;
1670 }
1671 }
1672
1673 return true;
1674 }
1675
1676 static int parse_line(
1677 const char *fname,
1678 unsigned line,
1679 const char *buffer,
1680 bool *invalid_config,
1681 void *context) {
1682
1683 Context *c = ASSERT_PTR(context);
1684 _cleanup_free_ char *action = NULL,
1685 *name = NULL, *resolved_name = NULL,
1686 *id = NULL, *resolved_id = NULL,
1687 *description = NULL, *resolved_description = NULL,
1688 *home = NULL, *resolved_home = NULL,
1689 *shell = NULL, *resolved_shell = NULL;
1690 _cleanup_(item_freep) Item *i = NULL;
1691 Item *existing;
1692 OrderedHashmap *h;
1693 int r;
1694 const char *p;
1695
1696 assert(fname);
1697 assert(line >= 1);
1698 assert(buffer);
1699 assert(!invalid_config); /* We don't support invalid_config yet. */
1700
1701 /* Parse columns */
1702 p = buffer;
1703 r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
1704 &action, &name, &id, &description, &home, &shell);
1705 if (r < 0)
1706 return log_syntax(NULL, LOG_ERR, fname, line, r, "Syntax error.");
1707 if (r < 2)
1708 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1709 "Missing action and name columns.");
1710 if (!isempty(p))
1711 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1712 "Trailing garbage.");
1713
1714 /* Verify action */
1715 if (strlen(action) != 1)
1716 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1717 "Unknown modifier '%s'.", action);
1718
1719 if (!IN_SET(action[0], ADD_USER, ADD_GROUP, ADD_MEMBER, ADD_RANGE))
1720 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
1721 "Unknown command type '%c'.", action[0]);
1722
1723 /* Verify name */
1724 if (empty_or_dash(name))
1725 name = mfree(name);
1726
1727 if (name) {
1728 r = specifier_printf(name, NAME_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_name);
1729 if (r < 0)
1730 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", name);
1731
1732 if (!valid_user_group_name(resolved_name, 0))
1733 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1734 "'%s' is not a valid user or group name.", resolved_name);
1735 }
1736
1737 /* Verify id */
1738 if (empty_or_dash(id))
1739 id = mfree(id);
1740
1741 if (id) {
1742 r = specifier_printf(id, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_id);
1743 if (r < 0)
1744 return log_syntax(NULL, LOG_ERR, fname, line, r,
1745 "Failed to replace specifiers in '%s': %m", name);
1746 }
1747
1748 /* Verify description */
1749 if (empty_or_dash(description))
1750 description = mfree(description);
1751
1752 if (description) {
1753 r = specifier_printf(description, LONG_LINE_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_description);
1754 if (r < 0)
1755 return log_syntax(NULL, LOG_ERR, fname, line, r,
1756 "Failed to replace specifiers in '%s': %m", description);
1757
1758 if (!valid_gecos(resolved_description))
1759 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1760 "'%s' is not a valid GECOS field.", resolved_description);
1761 }
1762
1763 /* Verify home */
1764 if (empty_or_dash(home))
1765 home = mfree(home);
1766
1767 if (home) {
1768 r = specifier_printf(home, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_home);
1769 if (r < 0)
1770 return log_syntax(NULL, LOG_ERR, fname, line, r,
1771 "Failed to replace specifiers in '%s': %m", home);
1772
1773 path_simplify(resolved_home);
1774
1775 if (!valid_home(resolved_home))
1776 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1777 "'%s' is not a valid home directory field.", resolved_home);
1778 }
1779
1780 /* Verify shell */
1781 if (empty_or_dash(shell))
1782 shell = mfree(shell);
1783
1784 if (shell) {
1785 r = specifier_printf(shell, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_shell);
1786 if (r < 0)
1787 return log_syntax(NULL, LOG_ERR, fname, line, r,
1788 "Failed to replace specifiers in '%s': %m", shell);
1789
1790 path_simplify(resolved_shell);
1791
1792 if (!valid_shell(resolved_shell))
1793 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1794 "'%s' is not a valid login shell field.", resolved_shell);
1795 }
1796
1797 switch (action[0]) {
1798
1799 case ADD_RANGE:
1800 if (resolved_name)
1801 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1802 "Lines of type 'r' don't take a name field.");
1803
1804 if (!resolved_id)
1805 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1806 "Lines of type 'r' require an ID range in the third field.");
1807
1808 if (description || home || shell)
1809 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1810 "Lines of type '%c' don't take a %s field.",
1811 action[0],
1812 description ? "GECOS" : home ? "home directory" : "login shell");
1813
1814 r = uid_range_add_str(&c->uid_range, resolved_id);
1815 if (r < 0)
1816 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1817 "Invalid UID range %s.", resolved_id);
1818
1819 return 0;
1820
1821 case ADD_MEMBER: {
1822 /* Try to extend an existing member or group item */
1823 if (!name)
1824 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1825 "Lines of type 'm' require a user name in the second field.");
1826
1827 if (!resolved_id)
1828 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1829 "Lines of type 'm' require a group name in the third field.");
1830
1831 if (!valid_user_group_name(resolved_id, 0))
1832 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1833 "'%s' is not a valid user or group name.", resolved_id);
1834
1835 if (description || home || shell)
1836 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1837 "Lines of type '%c' don't take a %s field.",
1838 action[0],
1839 description ? "GECOS" : home ? "home directory" : "login shell");
1840
1841 r = string_strv_ordered_hashmap_put(&c->members, resolved_id, resolved_name);
1842 if (r < 0)
1843 return log_error_errno(r, "Failed to store mapping for %s: %m", resolved_id);
1844
1845 return 0;
1846 }
1847
1848 case ADD_USER:
1849 if (!name)
1850 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1851 "Lines of type 'u' require a user name in the second field.");
1852
1853 r = ordered_hashmap_ensure_allocated(&c->users, &item_hash_ops);
1854 if (r < 0)
1855 return log_oom();
1856
1857 i = item_new(ADD_USER, resolved_name, fname, line);
1858 if (!i)
1859 return log_oom();
1860
1861 if (resolved_id) {
1862 if (path_is_absolute(resolved_id))
1863 i->uid_path = path_simplify(TAKE_PTR(resolved_id));
1864 else {
1865 _cleanup_free_ char *uid = NULL, *gid = NULL;
1866 if (split_pair(resolved_id, ":", &uid, &gid) == 0) {
1867 r = parse_gid(gid, &i->gid);
1868 if (r < 0) {
1869 if (valid_user_group_name(gid, 0))
1870 i->group_name = TAKE_PTR(gid);
1871 else
1872 return log_syntax(NULL, LOG_ERR, fname, line, r,
1873 "Failed to parse GID: '%s': %m", id);
1874 } else {
1875 i->gid_set = true;
1876 i->id_set_strict = true;
1877 }
1878 free_and_replace(resolved_id, uid);
1879 }
1880 if (!streq(resolved_id, "-")) {
1881 r = parse_uid(resolved_id, &i->uid);
1882 if (r < 0)
1883 return log_syntax(NULL, LOG_ERR, fname, line, r,
1884 "Failed to parse UID: '%s': %m", id);
1885 i->uid_set = true;
1886 }
1887 }
1888 }
1889
1890 i->description = TAKE_PTR(resolved_description);
1891 i->home = TAKE_PTR(resolved_home);
1892 i->shell = TAKE_PTR(resolved_shell);
1893
1894 h = c->users;
1895 break;
1896
1897 case ADD_GROUP:
1898 if (!name)
1899 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1900 "Lines of type 'g' require a user name in the second field.");
1901
1902 if (description || home || shell)
1903 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1904 "Lines of type '%c' don't take a %s field.",
1905 action[0],
1906 description ? "GECOS" : home ? "home directory" : "login shell");
1907
1908 r = ordered_hashmap_ensure_allocated(&c->groups, &item_hash_ops);
1909 if (r < 0)
1910 return log_oom();
1911
1912 i = item_new(ADD_GROUP, resolved_name, fname, line);
1913 if (!i)
1914 return log_oom();
1915
1916 if (resolved_id) {
1917 if (path_is_absolute(resolved_id))
1918 i->gid_path = path_simplify(TAKE_PTR(resolved_id));
1919 else {
1920 r = parse_gid(resolved_id, &i->gid);
1921 if (r < 0)
1922 return log_syntax(NULL, LOG_ERR, fname, line, r,
1923 "Failed to parse GID: '%s': %m", id);
1924
1925 i->gid_set = true;
1926 }
1927 }
1928
1929 h = c->groups;
1930 break;
1931
1932 default:
1933 assert_not_reached();
1934 }
1935
1936 existing = ordered_hashmap_get(h, i->name);
1937 if (existing) {
1938 /* Two functionally-equivalent items are fine */
1939 r = item_equivalent(i, existing);
1940 if (r < 0)
1941 return r;
1942 if (r == 0) {
1943 if (existing->filename)
1944 log_syntax(NULL, LOG_WARNING, fname, line, 0,
1945 "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
1946 item_type_to_string(i->type),
1947 i->name,
1948 existing->filename, existing->line);
1949 else
1950 log_syntax(NULL, LOG_WARNING, fname, line, 0,
1951 "Conflict with earlier configuration for %s '%s', ignoring line.",
1952 item_type_to_string(i->type),
1953 i->name);
1954 }
1955
1956 return 0;
1957 }
1958
1959 r = ordered_hashmap_put(h, i->name, i);
1960 if (r < 0)
1961 return log_oom();
1962
1963 i = NULL;
1964 return 0;
1965 }
1966
1967 static int read_config_file(Context *c, const char *fn, bool ignore_enoent) {
1968 return conf_file_read(
1969 arg_root,
1970 (const char**) CONF_PATHS_STRV("sysusers.d"),
1971 ASSERT_PTR(fn),
1972 parse_line,
1973 ASSERT_PTR(c),
1974 ignore_enoent,
1975 /* invalid_config= */ NULL);
1976 }
1977
1978 static int cat_config(void) {
1979 _cleanup_strv_free_ char **files = NULL;
1980 int r;
1981
1982 r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
1983 if (r < 0)
1984 return r;
1985
1986 pager_open(arg_pager_flags);
1987
1988 return cat_files(NULL, files, arg_cat_flags);
1989 }
1990
1991 static int help(void) {
1992 _cleanup_free_ char *link = NULL;
1993 int r;
1994
1995 r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
1996 if (r < 0)
1997 return log_oom();
1998
1999 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
2000 "Creates system user accounts.\n\n"
2001 " -h --help Show this help\n"
2002 " --version Show package version\n"
2003 " --cat-config Show configuration files\n"
2004 " --tldr Show non-comment parts of configuration\n"
2005 " --root=PATH Operate on an alternate filesystem root\n"
2006 " --image=PATH Operate on disk image as filesystem root\n"
2007 " --image-policy=POLICY Specify disk image dissection policy\n"
2008 " --replace=PATH Treat arguments as replacement for PATH\n"
2009 " --dry-run Just print what would be done\n"
2010 " --inline Treat arguments as configuration lines\n"
2011 " --no-pager Do not pipe output into a pager\n"
2012 "\nSee the %s for details.\n",
2013 program_invocation_short_name,
2014 link);
2015
2016 return 0;
2017 }
2018
2019 static int parse_argv(int argc, char *argv[]) {
2020
2021 enum {
2022 ARG_VERSION = 0x100,
2023 ARG_CAT_CONFIG,
2024 ARG_TLDR,
2025 ARG_ROOT,
2026 ARG_IMAGE,
2027 ARG_IMAGE_POLICY,
2028 ARG_REPLACE,
2029 ARG_DRY_RUN,
2030 ARG_INLINE,
2031 ARG_NO_PAGER,
2032 };
2033
2034 static const struct option options[] = {
2035 { "help", no_argument, NULL, 'h' },
2036 { "version", no_argument, NULL, ARG_VERSION },
2037 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
2038 { "tldr", no_argument, NULL, ARG_TLDR },
2039 { "root", required_argument, NULL, ARG_ROOT },
2040 { "image", required_argument, NULL, ARG_IMAGE },
2041 { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
2042 { "replace", required_argument, NULL, ARG_REPLACE },
2043 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
2044 { "inline", no_argument, NULL, ARG_INLINE },
2045 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2046 {}
2047 };
2048
2049 int c, r;
2050
2051 assert(argc >= 0);
2052 assert(argv);
2053
2054 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
2055
2056 switch (c) {
2057
2058 case 'h':
2059 return help();
2060
2061 case ARG_VERSION:
2062 return version();
2063
2064 case ARG_CAT_CONFIG:
2065 arg_cat_flags = CAT_CONFIG_ON;
2066 break;
2067
2068 case ARG_TLDR:
2069 arg_cat_flags = CAT_TLDR;
2070 break;
2071
2072 case ARG_ROOT:
2073 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
2074 if (r < 0)
2075 return r;
2076 break;
2077
2078 case ARG_IMAGE:
2079 #ifdef STANDALONE
2080 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2081 "This systemd-sysusers version is compiled without support for --image=.");
2082 #else
2083 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
2084 if (r < 0)
2085 return r;
2086 break;
2087 #endif
2088
2089 case ARG_IMAGE_POLICY:
2090 r = parse_image_policy_argument(optarg, &arg_image_policy);
2091 if (r < 0)
2092 return r;
2093 break;
2094
2095 case ARG_REPLACE:
2096 if (!path_is_absolute(optarg))
2097 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2098 "The argument to --replace= must be an absolute path.");
2099 if (!endswith(optarg, ".conf"))
2100 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2101 "The argument to --replace= must have the extension '.conf'.");
2102
2103 arg_replace = optarg;
2104 break;
2105
2106 case ARG_DRY_RUN:
2107 arg_dry_run = true;
2108 break;
2109
2110 case ARG_INLINE:
2111 arg_inline = true;
2112 break;
2113
2114 case ARG_NO_PAGER:
2115 arg_pager_flags |= PAGER_DISABLE;
2116 break;
2117
2118 case '?':
2119 return -EINVAL;
2120
2121 default:
2122 assert_not_reached();
2123 }
2124
2125 if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
2126 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2127 "Option --replace= is not supported with --cat-config/--tldr.");
2128
2129 if (arg_replace && optind >= argc)
2130 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2131 "When --replace= is given, some configuration items must be specified.");
2132
2133 if (arg_image && arg_root)
2134 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2135 "Use either --root= or --image=, the combination of both is not supported.");
2136
2137 return 1;
2138 }
2139
2140 static int parse_arguments(Context *c, char **args) {
2141 unsigned pos = 1;
2142 int r;
2143
2144 assert(c);
2145
2146 STRV_FOREACH(arg, args) {
2147 if (arg_inline)
2148 /* Use (argument):n, where n==1 for the first positional arg */
2149 r = parse_line("(argument)", pos, *arg, /* invalid_config= */ NULL, c);
2150 else
2151 r = read_config_file(c, *arg, /* ignore_enoent= */ false);
2152 if (r < 0)
2153 return r;
2154
2155 pos++;
2156 }
2157
2158 return 0;
2159 }
2160
2161 static int read_config_files(Context *c, char **args) {
2162 _cleanup_strv_free_ char **files = NULL;
2163 _cleanup_free_ char *p = NULL;
2164 int r;
2165
2166 assert(c);
2167
2168 r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
2169 if (r < 0)
2170 return r;
2171
2172 STRV_FOREACH(f, files)
2173 if (p && path_equal(*f, p)) {
2174 log_debug("Parsing arguments at position \"%s\"%s", *f, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
2175
2176 r = parse_arguments(c, args);
2177 if (r < 0)
2178 return r;
2179 } else {
2180 log_debug("Reading config file \"%s\"%s", *f, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
2181
2182 /* Just warn, ignore result otherwise */
2183 (void) read_config_file(c, *f, /* ignore_enoent= */ true);
2184 }
2185
2186 return 0;
2187 }
2188
2189 static int read_credential_lines(Context *c) {
2190 _cleanup_free_ char *j = NULL;
2191 const char *d;
2192 int r;
2193
2194 assert(c);
2195
2196 r = get_credentials_dir(&d);
2197 if (r == -ENXIO)
2198 return 0;
2199 if (r < 0)
2200 return log_error_errno(r, "Failed to get credentials directory: %m");
2201
2202 j = path_join(d, "sysusers.extra");
2203 if (!j)
2204 return log_oom();
2205
2206 (void) read_config_file(c, j, /* ignore_enoent= */ true);
2207 return 0;
2208 }
2209
2210 static int run(int argc, char *argv[]) {
2211 #ifndef STANDALONE
2212 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
2213 _cleanup_(umount_and_freep) char *mounted_dir = NULL;
2214 #endif
2215 _cleanup_close_ int lock = -EBADF;
2216 _cleanup_(context_done) Context c = {
2217 .search_uid = UID_INVALID,
2218 };
2219
2220 Item *i;
2221 int r;
2222
2223 r = parse_argv(argc, argv);
2224 if (r <= 0)
2225 return r;
2226
2227 log_setup();
2228
2229 if (arg_cat_flags != CAT_CONFIG_OFF)
2230 return cat_config();
2231
2232 umask(0022);
2233
2234 r = mac_init();
2235 if (r < 0)
2236 return r;
2237
2238 #ifndef STANDALONE
2239 if (arg_image) {
2240 assert(!arg_root);
2241
2242 r = mount_image_privately_interactively(
2243 arg_image,
2244 arg_image_policy,
2245 DISSECT_IMAGE_GENERIC_ROOT |
2246 DISSECT_IMAGE_REQUIRE_ROOT |
2247 DISSECT_IMAGE_VALIDATE_OS |
2248 DISSECT_IMAGE_RELAX_VAR_CHECK |
2249 DISSECT_IMAGE_FSCK |
2250 DISSECT_IMAGE_GROWFS |
2251 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
2252 &mounted_dir,
2253 /* ret_dir_fd= */ NULL,
2254 &loop_device);
2255 if (r < 0)
2256 return r;
2257
2258 arg_root = strdup(mounted_dir);
2259 if (!arg_root)
2260 return log_oom();
2261 }
2262 #else
2263 assert(!arg_image);
2264 #endif
2265
2266 /* If command line arguments are specified along with --replace, read all configuration files and
2267 * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2268 * specified, execute just them, and finally, without --replace= or any positional arguments, just
2269 * read configuration and execute it. */
2270 if (arg_replace || optind >= argc)
2271 r = read_config_files(&c, argv + optind);
2272 else
2273 r = parse_arguments(&c, argv + optind);
2274 if (r < 0)
2275 return r;
2276
2277 r = read_credential_lines(&c);
2278 if (r < 0)
2279 return r;
2280
2281 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our
2282 * detection whether the names or UID/GID area already used otherwise doesn't get confused. After
2283 * all, even though nss-systemd synthesizes these users/groups, they should still appear in
2284 * /etc/passwd and /etc/group, as the synthesizing logic is merely supposed to be fallback for cases
2285 * where we run with a completely unpopulated /etc. */
2286 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
2287 return log_error_errno(errno, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
2288
2289 if (!c.uid_range) {
2290 /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2291 r = read_login_defs(&c.login_defs, NULL, arg_root);
2292 if (r < 0)
2293 return log_error_errno(r, "Failed to read %s%s: %m",
2294 strempty(arg_root), "/etc/login.defs");
2295
2296 c.login_defs_need_warning = true;
2297
2298 /* We pick a range that very conservative: we look at compiled-in maximum and the value in
2299 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
2300 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2301 * it's only used during allocation, so we use the configured value directly). */
2302 uid_t begin = c.login_defs.system_alloc_uid_min,
2303 end = MIN3((uid_t) SYSTEM_UID_MAX, c.login_defs.system_uid_max, c.login_defs.system_gid_max);
2304 if (begin < end) {
2305 r = uid_range_add(&c.uid_range, begin, end - begin + 1);
2306 if (r < 0)
2307 return log_oom();
2308 }
2309 }
2310
2311 r = add_implicit(&c);
2312 if (r < 0)
2313 return r;
2314
2315 if (!arg_dry_run) {
2316 lock = take_etc_passwd_lock(arg_root);
2317 if (lock < 0)
2318 return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
2319 }
2320
2321 r = load_user_database(&c);
2322 if (r < 0)
2323 return log_error_errno(r, "Failed to load user database: %m");
2324
2325 r = load_group_database(&c);
2326 if (r < 0)
2327 return log_error_errno(r, "Failed to read group database: %m");
2328
2329 ORDERED_HASHMAP_FOREACH(i, c.groups)
2330 (void) process_item(&c, i);
2331
2332 ORDERED_HASHMAP_FOREACH(i, c.users)
2333 (void) process_item(&c, i);
2334
2335 return write_files(&c);
2336 }
2337
2338 DEFINE_MAIN_FUNCTION(run);