1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2014 Lennart Poettering
11 #include "alloc-util.h"
12 #include "conf-files.h"
16 #include "fileio-label.h"
17 #include "format-util.h"
21 #include "path-util.h"
22 #include "selinux-util.h"
23 #include "smack-util.h"
24 #include "specifier.h"
25 #include "string-util.h"
27 #include "terminal-util.h"
28 #include "uid-range.h"
29 #include "user-util.h"
33 typedef enum ItemType
{
55 /* When set the group with the specified gid must exist
56 * and the check if a uid clashes with the gid is skipped.
66 static char *arg_root
= NULL
;
67 static bool arg_cat_config
= false;
68 static const char *arg_replace
= NULL
;
69 static bool arg_inline
= false;
70 static bool arg_no_pager
= false;
72 static OrderedHashmap
*users
= NULL
, *groups
= NULL
;
73 static OrderedHashmap
*todo_uids
= NULL
, *todo_gids
= NULL
;
74 static OrderedHashmap
*members
= NULL
;
76 static Hashmap
*database_uid
= NULL
, *database_user
= NULL
;
77 static Hashmap
*database_gid
= NULL
, *database_group
= NULL
;
79 static uid_t search_uid
= UID_INVALID
;
80 static UidRange
*uid_range
= NULL
;
81 static unsigned n_uid_range
= 0;
83 static int load_user_database(void) {
84 _cleanup_fclose_
FILE *f
= NULL
;
85 const char *passwd_path
;
89 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
90 f
= fopen(passwd_path
, "re");
92 return errno
== ENOENT
? 0 : -errno
;
94 r
= hashmap_ensure_allocated(&database_user
, &string_hash_ops
);
98 r
= hashmap_ensure_allocated(&database_uid
, NULL
);
102 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
106 n
= strdup(pw
->pw_name
);
110 k
= hashmap_put(database_user
, n
, UID_TO_PTR(pw
->pw_uid
));
111 if (k
< 0 && k
!= -EEXIST
) {
116 q
= hashmap_put(database_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
117 if (q
< 0 && q
!= -EEXIST
) {
123 if (k
<= 0 && q
<= 0)
129 static int load_group_database(void) {
130 _cleanup_fclose_
FILE *f
= NULL
;
131 const char *group_path
;
135 group_path
= prefix_roota(arg_root
, "/etc/group");
136 f
= fopen(group_path
, "re");
138 return errno
== ENOENT
? 0 : -errno
;
140 r
= hashmap_ensure_allocated(&database_group
, &string_hash_ops
);
144 r
= hashmap_ensure_allocated(&database_gid
, NULL
);
149 while ((gr
= fgetgrent(f
))) {
153 n
= strdup(gr
->gr_name
);
157 k
= hashmap_put(database_group
, n
, GID_TO_PTR(gr
->gr_gid
));
158 if (k
< 0 && k
!= -EEXIST
) {
163 q
= hashmap_put(database_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
164 if (q
< 0 && q
!= -EEXIST
) {
170 if (k
<= 0 && q
<= 0)
175 if (!IN_SET(errno
, 0, ENOENT
))
181 static int make_backup(const char *target
, const char *x
) {
182 _cleanup_close_
int src
= -1;
183 _cleanup_fclose_
FILE *dst
= NULL
;
184 _cleanup_free_
char *temp
= NULL
;
186 struct timespec ts
[2];
190 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
192 if (errno
== ENOENT
) /* No backup necessary... */
198 if (fstat(src
, &st
) < 0)
201 r
= fopen_temporary_label(target
, x
, &dst
, &temp
);
205 r
= copy_bytes(src
, fileno(dst
), (uint64_t) -1, COPY_REFLINK
);
209 /* Don't fail on chmod() or chown(). If it stays owned by us
210 * and/or unreadable by others, then it isn't too bad... */
212 backup
= strjoina(x
, "-");
214 /* Copy over the access mask */
215 r
= fchmod_and_chown(fileno(dst
), st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
217 log_warning_errno(r
, "Failed to change access mode or ownership of %s: %m", backup
);
221 if (futimens(fileno(dst
), ts
) < 0)
222 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
224 r
= fflush_sync_and_check(dst
);
228 if (rename(temp
, backup
) < 0) {
240 static int putgrent_with_members(const struct group
*gr
, FILE *group
) {
246 a
= ordered_hashmap_get(members
, gr
->gr_name
);
248 _cleanup_strv_free_
char **l
= NULL
;
252 l
= strv_copy(gr
->gr_mem
);
257 if (strv_find(l
, *i
))
260 if (strv_extend(&l
, *i
) < 0)
276 r
= putgrent_sane(&t
, group
);
277 return r
< 0 ? r
: 1;
281 return putgrent_sane(gr
, group
);
285 static int putsgent_with_members(const struct sgrp
*sg
, FILE *gshadow
) {
291 a
= ordered_hashmap_get(members
, sg
->sg_namp
);
293 _cleanup_strv_free_
char **l
= NULL
;
297 l
= strv_copy(sg
->sg_mem
);
302 if (strv_find(l
, *i
))
305 if (strv_extend(&l
, *i
) < 0)
321 r
= putsgent_sane(&t
, gshadow
);
322 return r
< 0 ? r
: 1;
326 return putsgent_sane(sg
, gshadow
);
330 static int sync_rights(FILE *from
, FILE *to
) {
333 if (fstat(fileno(from
), &st
) < 0)
336 return fchmod_and_chown(fileno(to
), st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
339 static int rename_and_apply_smack(const char *temp_path
, const char *dest_path
) {
341 if (rename(temp_path
, dest_path
) < 0)
344 #ifdef SMACK_RUN_LABEL
345 r
= mac_smack_apply(dest_path
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);
352 static const char* default_shell(uid_t uid
) {
353 return uid
== 0 ? "/bin/sh" : "/sbin/nologin";
356 static int write_temporary_passwd(const char *passwd_path
, FILE **tmpfile
, char **tmpfile_path
) {
357 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
358 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
359 struct passwd
*pw
= NULL
;
364 if (ordered_hashmap_size(todo_uids
) == 0)
367 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
371 original
= fopen(passwd_path
, "re");
374 r
= sync_rights(original
, passwd
);
378 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
380 i
= ordered_hashmap_get(users
, pw
->pw_name
);
381 if (i
&& i
->todo_user
) {
382 log_error("%s: User \"%s\" already exists.", passwd_path
, pw
->pw_name
);
386 if (ordered_hashmap_contains(todo_uids
, UID_TO_PTR(pw
->pw_uid
))) {
387 log_error("%s: Detected collision for UID " UID_FMT
".", passwd_path
, pw
->pw_uid
);
391 /* Make sure we keep the NIS entries (if any) at the end. */
392 if (IN_SET(pw
->pw_name
[0], '+', '-'))
395 r
= putpwent_sane(pw
, passwd
);
405 if (fchmod(fileno(passwd
), 0644) < 0)
409 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
414 .pw_gecos
= i
->description
,
416 /* "x" means the password is stored in the shadow file */
417 .pw_passwd
= (char*) "x",
419 /* We default to the root directory as home */
420 .pw_dir
= i
->home
? i
->home
: (char*) "/",
422 /* Initialize the shell to nologin, with one exception:
423 * for root we patch in something special */
424 .pw_shell
= i
->shell
?: (char*) default_shell(i
->uid
),
427 r
= putpwent_sane(&n
, passwd
);
432 /* Append the remaining NIS entries if any */
434 r
= putpwent_sane(pw
, passwd
);
438 r
= fgetpwent_sane(original
, &pw
);
445 r
= fflush_and_check(passwd
);
449 *tmpfile
= TAKE_PTR(passwd
);
450 *tmpfile_path
= TAKE_PTR(passwd_tmp
);
455 static int write_temporary_shadow(const char *shadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
456 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
457 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
458 struct spwd
*sp
= NULL
;
464 if (ordered_hashmap_size(todo_uids
) == 0)
467 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
471 lstchg
= (long) (now(CLOCK_REALTIME
) / USEC_PER_DAY
);
473 original
= fopen(shadow_path
, "re");
476 r
= sync_rights(original
, shadow
);
480 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
482 i
= ordered_hashmap_get(users
, sp
->sp_namp
);
483 if (i
&& i
->todo_user
) {
484 /* we will update the existing entry */
485 sp
->sp_lstchg
= lstchg
;
487 /* only the /etc/shadow stage is left, so we can
488 * safely remove the item from the todo set */
489 i
->todo_user
= false;
490 ordered_hashmap_remove(todo_uids
, UID_TO_PTR(i
->uid
));
493 /* Make sure we keep the NIS entries (if any) at the end. */
494 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
497 r
= putspent_sane(sp
, shadow
);
507 if (fchmod(fileno(shadow
), 0000) < 0)
511 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
514 .sp_pwdp
= (char*) "!!",
521 .sp_flag
= (unsigned long) -1, /* this appears to be what everybody does ... */
524 r
= putspent_sane(&n
, shadow
);
529 /* Append the remaining NIS entries if any */
531 r
= putspent_sane(sp
, shadow
);
535 r
= fgetspent_sane(original
, &sp
);
541 if (!IN_SET(errno
, 0, ENOENT
))
544 r
= fflush_sync_and_check(shadow
);
548 *tmpfile
= TAKE_PTR(shadow
);
549 *tmpfile_path
= TAKE_PTR(shadow_tmp
);
554 static int write_temporary_group(const char *group_path
, FILE **tmpfile
, char **tmpfile_path
) {
555 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
556 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
557 bool group_changed
= false;
558 struct group
*gr
= NULL
;
563 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
566 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
570 original
= fopen(group_path
, "re");
573 r
= sync_rights(original
, group
);
577 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
578 /* Safety checks against name and GID collisions. Normally,
579 * this should be unnecessary, but given that we look at the
580 * entries anyway here, let's make an extra verification
581 * step that we don't generate duplicate entries. */
583 i
= ordered_hashmap_get(groups
, gr
->gr_name
);
584 if (i
&& i
->todo_group
) {
585 log_error("%s: Group \"%s\" already exists.", group_path
, gr
->gr_name
);
589 if (ordered_hashmap_contains(todo_gids
, GID_TO_PTR(gr
->gr_gid
))) {
590 log_error("%s: Detected collision for GID " GID_FMT
".", group_path
, gr
->gr_gid
);
594 /* Make sure we keep the NIS entries (if any) at the end. */
595 if (IN_SET(gr
->gr_name
[0], '+', '-'))
598 r
= putgrent_with_members(gr
, group
);
602 group_changed
= true;
610 if (fchmod(fileno(group
), 0644) < 0)
614 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
618 .gr_passwd
= (char*) "x",
621 r
= putgrent_with_members(&n
, group
);
625 group_changed
= true;
628 /* Append the remaining NIS entries if any */
630 r
= putgrent_sane(gr
, group
);
634 r
= fgetgrent_sane(original
, &gr
);
641 r
= fflush_sync_and_check(group
);
646 *tmpfile
= TAKE_PTR(group
);
647 *tmpfile_path
= TAKE_PTR(group_tmp
);
652 static int write_temporary_gshadow(const char * gshadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
654 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
655 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
656 bool group_changed
= false;
661 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
664 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
668 original
= fopen(gshadow_path
, "re");
672 r
= sync_rights(original
, gshadow
);
676 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
678 i
= ordered_hashmap_get(groups
, sg
->sg_namp
);
679 if (i
&& i
->todo_group
) {
680 log_error("%s: Group \"%s\" already exists.", gshadow_path
, sg
->sg_namp
);
684 r
= putsgent_with_members(sg
, gshadow
);
688 group_changed
= true;
696 if (fchmod(fileno(gshadow
), 0000) < 0)
700 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
703 .sg_passwd
= (char*) "!!",
706 r
= putsgent_with_members(&n
, gshadow
);
710 group_changed
= true;
713 r
= fflush_sync_and_check(gshadow
);
718 *tmpfile
= TAKE_PTR(gshadow
);
719 *tmpfile_path
= TAKE_PTR(gshadow_tmp
);
727 static int write_files(void) {
728 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
729 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
730 const char *passwd_path
= NULL
, *group_path
= NULL
, *shadow_path
= NULL
, *gshadow_path
= NULL
;
733 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
734 shadow_path
= prefix_roota(arg_root
, "/etc/shadow");
735 group_path
= prefix_roota(arg_root
, "/etc/group");
736 gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
738 r
= write_temporary_group(group_path
, &group
, &group_tmp
);
742 r
= write_temporary_gshadow(gshadow_path
, &gshadow
, &gshadow_tmp
);
746 r
= write_temporary_passwd(passwd_path
, &passwd
, &passwd_tmp
);
750 r
= write_temporary_shadow(shadow_path
, &shadow
, &shadow_tmp
);
754 /* Make a backup of the old files */
756 r
= make_backup("/etc/group", group_path
);
761 r
= make_backup("/etc/gshadow", gshadow_path
);
767 r
= make_backup("/etc/passwd", passwd_path
);
772 r
= make_backup("/etc/shadow", shadow_path
);
777 /* And make the new files count */
779 r
= rename_and_apply_smack(group_tmp
, group_path
);
783 group_tmp
= mfree(group_tmp
);
786 r
= rename_and_apply_smack(gshadow_tmp
, gshadow_path
);
790 gshadow_tmp
= mfree(gshadow_tmp
);
794 r
= rename_and_apply_smack(passwd_tmp
, passwd_path
);
798 passwd_tmp
= mfree(passwd_tmp
);
801 r
= rename_and_apply_smack(shadow_tmp
, shadow_path
);
805 shadow_tmp
= mfree(shadow_tmp
);
811 static int uid_is_ok(uid_t uid
, const char *name
, bool check_with_gid
) {
817 /* Let's see if we already have assigned the UID a second time */
818 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(uid
)))
821 /* Try to avoid using uids that are already used by a group
822 * that doesn't have the same name as our new user. */
823 if (check_with_gid
) {
824 i
= ordered_hashmap_get(todo_gids
, GID_TO_PTR(uid
));
825 if (i
&& !streq(i
->name
, name
))
829 /* Let's check the files directly */
830 if (hashmap_contains(database_uid
, UID_TO_PTR(uid
)))
833 if (check_with_gid
) {
834 n
= hashmap_get(database_gid
, GID_TO_PTR(uid
));
835 if (n
&& !streq(n
, name
))
839 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
845 if (!IN_SET(errno
, 0, ENOENT
))
848 if (check_with_gid
) {
850 g
= getgrgid((gid_t
) uid
);
852 if (!streq(g
->gr_name
, name
))
854 } else if (!IN_SET(errno
, 0, ENOENT
))
862 static int root_stat(const char *p
, struct stat
*st
) {
865 fix
= prefix_roota(arg_root
, p
);
866 if (stat(fix
, st
) < 0)
872 static int read_id_from_file(Item
*i
, uid_t
*_uid
, gid_t
*_gid
) {
874 bool found_uid
= false, found_gid
= false;
880 /* First, try to get the gid directly */
881 if (_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
886 /* Then, try to get the uid directly */
887 if ((_uid
|| (_gid
&& !found_gid
))
889 && root_stat(i
->uid_path
, &st
) >= 0) {
894 /* If we need the gid, but had no success yet, also derive it from the uid path */
895 if (_gid
&& !found_gid
) {
901 /* If that didn't work yet, then let's reuse the gid as uid */
902 if (_uid
&& !found_uid
&& i
->gid_path
) {
907 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
908 uid
= (uid_t
) st
.st_gid
;
930 static int add_user(Item
*i
) {
936 /* Check the database directly */
937 z
= hashmap_get(database_user
, i
->name
);
939 log_debug("User %s already exists.", i
->name
);
940 i
->uid
= PTR_TO_UID(z
);
950 p
= getpwnam(i
->name
);
952 log_debug("User %s already exists.", i
->name
);
956 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
962 if (!IN_SET(errno
, 0, ENOENT
))
963 return log_error_errno(errno
, "Failed to check if user %s already exists: %m", i
->name
);
966 /* Try to use the suggested numeric uid */
968 r
= uid_is_ok(i
->uid
, i
->name
, !i
->id_set_strict
);
970 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
972 log_debug("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
977 /* If that didn't work, try to read it from the specified path */
981 if (read_id_from_file(i
, &c
, NULL
) > 0) {
983 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
984 log_debug("User ID " UID_FMT
" of file not suitable for %s.", c
, i
->name
);
986 r
= uid_is_ok(c
, i
->name
, true);
988 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
993 log_debug("User ID " UID_FMT
" of file for %s is already used.", c
, i
->name
);
998 /* Otherwise, try to reuse the group ID */
999 if (!i
->uid_set
&& i
->gid_set
) {
1000 r
= uid_is_ok((uid_t
) i
->gid
, i
->name
, true);
1002 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1004 i
->uid
= (uid_t
) i
->gid
;
1009 /* And if that didn't work either, let's try to find a free one */
1012 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1014 log_error("No free user ID available for %s.", i
->name
);
1018 r
= uid_is_ok(search_uid
, i
->name
, true);
1020 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1026 i
->uid
= search_uid
;
1029 r
= ordered_hashmap_ensure_allocated(&todo_uids
, NULL
);
1033 r
= ordered_hashmap_put(todo_uids
, UID_TO_PTR(i
->uid
), i
);
1037 i
->todo_user
= true;
1038 log_info("Creating user %s (%s) with uid " UID_FMT
" and gid " GID_FMT
".", i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1043 static int gid_is_ok(gid_t gid
) {
1047 if (ordered_hashmap_get(todo_gids
, GID_TO_PTR(gid
)))
1050 /* Avoid reusing gids that are already used by a different user */
1051 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(gid
)))
1054 if (hashmap_contains(database_gid
, GID_TO_PTR(gid
)))
1057 if (hashmap_contains(database_uid
, UID_TO_PTR(gid
)))
1065 if (!IN_SET(errno
, 0, ENOENT
))
1069 p
= getpwuid((uid_t
) gid
);
1072 if (!IN_SET(errno
, 0, ENOENT
))
1079 static int add_group(Item
*i
) {
1085 /* Check the database directly */
1086 z
= hashmap_get(database_group
, i
->name
);
1088 log_debug("Group %s already exists.", i
->name
);
1089 i
->gid
= PTR_TO_GID(z
);
1094 /* Also check NSS */
1099 g
= getgrnam(i
->name
);
1101 log_debug("Group %s already exists.", i
->name
);
1106 if (!IN_SET(errno
, 0, ENOENT
))
1107 return log_error_errno(errno
, "Failed to check if group %s already exists: %m", i
->name
);
1110 /* Try to use the suggested numeric gid */
1112 r
= gid_is_ok(i
->gid
);
1114 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1115 if (i
->id_set_strict
) {
1116 /* If we require the gid to already exist we can return here:
1117 * r > 0: means the gid does not exist -> fail
1118 * r == 0: means the gid exists -> nothing more to do.
1121 log_error("Failed to create %s: please create GID %d", i
->name
, i
->gid
);
1128 log_debug("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1133 /* Try to reuse the numeric uid, if there's one */
1134 if (!i
->gid_set
&& i
->uid_set
) {
1135 r
= gid_is_ok((gid_t
) i
->uid
);
1137 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1139 i
->gid
= (gid_t
) i
->uid
;
1144 /* If that didn't work, try to read it from the specified path */
1148 if (read_id_from_file(i
, NULL
, &c
) > 0) {
1150 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
1151 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", c
, i
->name
);
1155 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1160 log_debug("Group ID " GID_FMT
" of file for %s already used.", c
, i
->name
);
1165 /* And if that didn't work either, let's try to find a free one */
1168 /* We look for new GIDs in the UID pool! */
1169 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1171 log_error("No free group ID available for %s.", i
->name
);
1175 r
= gid_is_ok(search_uid
);
1177 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1183 i
->gid
= search_uid
;
1186 r
= ordered_hashmap_ensure_allocated(&todo_gids
, NULL
);
1190 r
= ordered_hashmap_put(todo_gids
, GID_TO_PTR(i
->gid
), i
);
1194 i
->todo_group
= true;
1195 log_info("Creating group %s with gid " GID_FMT
".", i
->name
, i
->gid
);
1200 static int process_item(Item
*i
) {
1210 j
= ordered_hashmap_get(groups
, i
->name
);
1211 if (j
&& j
->todo_group
) {
1212 /* When the group with the same name is already in queue,
1213 * use the information about the group and do not create
1214 * duplicated group entry. */
1215 i
->gid_set
= j
->gid_set
;
1217 i
->id_set_strict
= true;
1228 return add_group(i
);
1231 assert_not_reached("Unknown item type");
1235 static void item_free(Item
*i
) {
1243 free(i
->description
);
1249 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1251 static int add_implicit(void) {
1256 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1257 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, members
, iterator
) {
1261 if (!ordered_hashmap_get(users
, *m
)) {
1262 _cleanup_(item_freep
) Item
*j
= NULL
;
1264 r
= ordered_hashmap_ensure_allocated(&users
, &string_hash_ops
);
1273 j
->name
= strdup(*m
);
1277 r
= ordered_hashmap_put(users
, j
->name
, j
);
1281 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1285 if (!(ordered_hashmap_get(users
, g
) ||
1286 ordered_hashmap_get(groups
, g
))) {
1287 _cleanup_(item_freep
) Item
*j
= NULL
;
1289 r
= ordered_hashmap_ensure_allocated(&groups
, &string_hash_ops
);
1297 j
->type
= ADD_GROUP
;
1298 j
->name
= strdup(g
);
1302 r
= ordered_hashmap_put(groups
, j
->name
, j
);
1306 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1314 static bool item_equal(Item
*a
, Item
*b
) {
1318 if (a
->type
!= b
->type
)
1321 if (!streq_ptr(a
->name
, b
->name
))
1324 if (!streq_ptr(a
->uid_path
, b
->uid_path
))
1327 if (!streq_ptr(a
->gid_path
, b
->gid_path
))
1330 if (!streq_ptr(a
->description
, b
->description
))
1333 if (a
->uid_set
!= b
->uid_set
)
1336 if (a
->uid_set
&& a
->uid
!= b
->uid
)
1339 if (a
->gid_set
!= b
->gid_set
)
1342 if (a
->gid_set
&& a
->gid
!= b
->gid
)
1345 if (!streq_ptr(a
->home
, b
->home
))
1348 if (!streq_ptr(a
->shell
, b
->shell
))
1354 static int parse_line(const char *fname
, unsigned line
, const char *buffer
) {
1356 static const Specifier specifier_table
[] = {
1357 { 'm', specifier_machine_id
, NULL
},
1358 { 'b', specifier_boot_id
, NULL
},
1359 { 'H', specifier_host_name
, NULL
},
1360 { 'v', specifier_kernel_release
, NULL
},
1361 { 'T', specifier_tmp_dir
, NULL
},
1362 { 'V', specifier_var_tmp_dir
, NULL
},
1366 _cleanup_free_
char *action
= NULL
,
1367 *name
= NULL
, *resolved_name
= NULL
,
1368 *id
= NULL
, *resolved_id
= NULL
,
1369 *description
= NULL
, *resolved_description
= NULL
,
1370 *home
= NULL
, *resolved_home
= NULL
,
1371 *shell
, *resolved_shell
= NULL
;
1372 _cleanup_(item_freep
) Item
*i
= NULL
;
1384 r
= extract_many_words(&p
, NULL
, EXTRACT_QUOTES
,
1385 &action
, &name
, &id
, &description
, &home
, &shell
, NULL
);
1387 log_error("[%s:%u] Syntax error.", fname
, line
);
1391 log_error("[%s:%u] Missing action and name columns.", fname
, line
);
1395 log_error("[%s:%u] Trailing garbage.", fname
, line
);
1400 if (strlen(action
) != 1) {
1401 log_error("[%s:%u] Unknown modifier '%s'", fname
, line
, action
);
1405 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
)) {
1406 log_error("[%s:%u] Unknown command type '%c'.", fname
, line
, action
[0]);
1411 if (isempty(name
) || streq(name
, "-"))
1415 r
= specifier_printf(name
, specifier_table
, NULL
, &resolved_name
);
1417 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1421 if (!valid_user_group_name(resolved_name
)) {
1422 log_error("[%s:%u] '%s' is not a valid user or group name.", fname
, line
, resolved_name
);
1428 if (isempty(id
) || streq(id
, "-"))
1432 r
= specifier_printf(id
, specifier_table
, NULL
, &resolved_id
);
1434 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1439 /* Verify description */
1440 if (isempty(description
) || streq(description
, "-"))
1441 description
= mfree(description
);
1444 r
= specifier_printf(description
, specifier_table
, NULL
, &resolved_description
);
1446 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, description
);
1450 if (!valid_gecos(resolved_description
)) {
1451 log_error("[%s:%u] '%s' is not a valid GECOS field.", fname
, line
, resolved_description
);
1457 if (isempty(home
) || streq(home
, "-"))
1461 r
= specifier_printf(home
, specifier_table
, NULL
, &resolved_home
);
1463 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, home
);
1467 if (!valid_home(resolved_home
)) {
1468 log_error("[%s:%u] '%s' is not a valid home directory field.", fname
, line
, resolved_home
);
1474 if (isempty(shell
) || streq(shell
, "-"))
1475 shell
= mfree(shell
);
1478 r
= specifier_printf(shell
, specifier_table
, NULL
, &resolved_shell
);
1480 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, shell
);
1484 if (!valid_shell(resolved_shell
)) {
1485 log_error("[%s:%u] '%s' is not a valid login shell field.", fname
, line
, resolved_shell
);
1490 switch (action
[0]) {
1493 if (resolved_name
) {
1494 log_error("[%s:%u] Lines of type 'r' don't take a name field.", fname
, line
);
1499 log_error("[%s:%u] Lines of type 'r' require a ID range in the third field.", fname
, line
);
1503 if (description
|| home
|| shell
) {
1504 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1505 fname
, line
, action
[0],
1506 description
? "GECOS" : home
? "home directory" : "login shell");
1510 r
= uid_range_add_str(&uid_range
, &n_uid_range
, resolved_id
);
1512 log_error("[%s:%u] Invalid UID range %s.", fname
, line
, resolved_id
);
1521 /* Try to extend an existing member or group item */
1523 log_error("[%s:%u] Lines of type 'm' require a user name in the second field.", fname
, line
);
1528 log_error("[%s:%u] Lines of type 'm' require a group name in the third field.", fname
, line
);
1532 if (!valid_user_group_name(resolved_id
)) {
1533 log_error("[%s:%u] '%s' is not a valid user or group name.", fname
, line
, resolved_id
);
1537 if (description
|| home
|| shell
) {
1538 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1539 fname
, line
, action
[0],
1540 description
? "GECOS" : home
? "home directory" : "login shell");
1544 r
= ordered_hashmap_ensure_allocated(&members
, &string_hash_ops
);
1548 l
= ordered_hashmap_get(members
, resolved_id
);
1550 /* A list for this group name already exists, let's append to it */
1551 r
= strv_push(&l
, resolved_name
);
1555 resolved_name
= NULL
;
1557 assert_se(ordered_hashmap_update(members
, resolved_id
, l
) >= 0);
1559 /* No list for this group name exists yet, create one */
1561 l
= new0(char *, 2);
1565 l
[0] = resolved_name
;
1568 r
= ordered_hashmap_put(members
, resolved_id
, l
);
1574 resolved_id
= resolved_name
= NULL
;
1582 log_error("[%s:%u] Lines of type 'u' require a user name in the second field.", fname
, line
);
1586 r
= ordered_hashmap_ensure_allocated(&users
, &string_hash_ops
);
1595 if (path_is_absolute(resolved_id
)) {
1596 i
->uid_path
= TAKE_PTR(resolved_id
);
1597 path_simplify(i
->uid_path
, false);
1599 _cleanup_free_
char *uid
= NULL
, *gid
= NULL
;
1600 if (split_pair(resolved_id
, ":", &uid
, &gid
) == 0) {
1601 r
= parse_gid(gid
, &i
->gid
);
1603 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1605 i
->id_set_strict
= true;
1606 free_and_replace(resolved_id
, uid
);
1608 if (!streq(resolved_id
, "-")) {
1609 r
= parse_uid(resolved_id
, &i
->uid
);
1611 return log_error_errno(r
, "Failed to parse UID: '%s': %m", id
);
1617 i
->description
= TAKE_PTR(resolved_description
);
1618 i
->home
= TAKE_PTR(resolved_home
);
1619 i
->shell
= TAKE_PTR(resolved_shell
);
1626 log_error("[%s:%u] Lines of type 'g' require a user name in the second field.", fname
, line
);
1630 if (description
|| home
|| shell
) {
1631 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1632 fname
, line
, action
[0],
1633 description
? "GECOS" : home
? "home directory" : "login shell");
1637 r
= ordered_hashmap_ensure_allocated(&groups
, &string_hash_ops
);
1646 if (path_is_absolute(resolved_id
)) {
1647 i
->gid_path
= TAKE_PTR(resolved_id
);
1648 path_simplify(i
->gid_path
, false);
1650 r
= parse_gid(resolved_id
, &i
->gid
);
1652 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1665 i
->type
= action
[0];
1666 i
->name
= TAKE_PTR(resolved_name
);
1668 existing
= ordered_hashmap_get(h
, i
->name
);
1671 /* Two identical items are fine */
1672 if (!item_equal(existing
, i
))
1673 log_warning("Two or more conflicting lines for %s configured, ignoring.", i
->name
);
1678 r
= ordered_hashmap_put(h
, i
->name
, i
);
1686 static int read_config_file(const char *fn
, bool ignore_enoent
) {
1687 _cleanup_fclose_
FILE *rf
= NULL
;
1689 char line
[LINE_MAX
];
1698 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf
);
1700 if (ignore_enoent
&& r
== -ENOENT
)
1703 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
1709 FOREACH_LINE(line
, f
, break) {
1716 if (IN_SET(*l
, 0, '#'))
1719 k
= parse_line(fn
, v
, l
);
1720 if (k
< 0 && r
== 0)
1725 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
1733 static void free_database(Hashmap
*by_name
, Hashmap
*by_id
) {
1737 name
= hashmap_first(by_id
);
1741 hashmap_remove(by_name
, name
);
1743 hashmap_steal_first_key(by_id
);
1747 while ((name
= hashmap_steal_first_key(by_name
)))
1750 hashmap_free(by_name
);
1751 hashmap_free(by_id
);
1754 static int cat_config(void) {
1755 _cleanup_strv_free_
char **files
= NULL
;
1758 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
1762 (void) pager_open(arg_no_pager
, false);
1764 return cat_files(NULL
, files
, 0);
1767 static void help(void) {
1768 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1769 "Creates system user accounts.\n\n"
1770 " -h --help Show this help\n"
1771 " --version Show package version\n"
1772 " --cat-config Show configuration files\n"
1773 " --root=PATH Operate on an alternate filesystem root\n"
1774 " --replace=PATH Treat arguments as replacement for PATH\n"
1775 " --inline Treat arguments as configuration lines\n"
1776 " --no-pager Do not pipe output into a pager\n"
1777 , program_invocation_short_name
);
1780 static int parse_argv(int argc
, char *argv
[]) {
1783 ARG_VERSION
= 0x100,
1791 static const struct option options
[] = {
1792 { "help", no_argument
, NULL
, 'h' },
1793 { "version", no_argument
, NULL
, ARG_VERSION
},
1794 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
1795 { "root", required_argument
, NULL
, ARG_ROOT
},
1796 { "replace", required_argument
, NULL
, ARG_REPLACE
},
1797 { "inline", no_argument
, NULL
, ARG_INLINE
},
1798 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
1807 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
1818 case ARG_CAT_CONFIG
:
1819 arg_cat_config
= true;
1823 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
1829 if (!path_is_absolute(optarg
) ||
1830 !endswith(optarg
, ".conf")) {
1831 log_error("The argument to --replace= must an absolute path to a config file");
1835 arg_replace
= optarg
;
1843 arg_no_pager
= true;
1850 assert_not_reached("Unhandled option");
1853 if (arg_replace
&& arg_cat_config
) {
1854 log_error("Option --replace= is not supported with --cat-config");
1858 if (arg_replace
&& optind
>= argc
) {
1859 log_error("When --replace= is given, some configuration items must be specified");
1866 static int parse_arguments(char **args
) {
1871 STRV_FOREACH(arg
, args
) {
1873 /* Use (argument):n, where n==1 for the first positional arg */
1874 r
= parse_line("(argument)", pos
, *arg
);
1876 r
= read_config_file(*arg
, false);
1886 static int read_config_files(char **args
) {
1887 _cleanup_strv_free_
char **files
= NULL
;
1888 _cleanup_free_
char *p
= NULL
;
1892 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
1896 STRV_FOREACH(f
, files
)
1897 if (p
&& path_equal(*f
, p
)) {
1898 log_debug("Parsing arguments at position \"%s\"…", *f
);
1900 r
= parse_arguments(args
);
1904 log_debug("Reading config file \"%s\"…", *f
);
1906 /* Just warn, ignore result otherwise */
1907 (void) read_config_file(*f
, true);
1913 int main(int argc
, char *argv
[]) {
1914 _cleanup_close_
int lock
= -1;
1920 r
= parse_argv(argc
, argv
);
1924 log_set_target(LOG_TARGET_AUTO
);
1925 log_parse_environment();
1928 if (arg_cat_config
) {
1935 r
= mac_selinux_init();
1937 log_error_errno(r
, "SELinux setup failed: %m");
1941 /* If command line arguments are specified along with --replace, read all
1942 * configuration files and insert the positional arguments at the specified
1943 * place. Otherwise, if command line arguments are specified, execute just
1944 * them, and finally, without --replace= or any positional arguments, just
1945 * read configuration and execute it.
1947 if (arg_replace
|| optind
>= argc
)
1948 r
= read_config_files(argv
+ optind
);
1950 r
= parse_arguments(argv
+ optind
);
1954 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our detection
1955 * whether the names or UID/GID area already used otherwise doesn't get confused. After all, even though
1956 * nss-systemd synthesizes these users/groups, they should still appear in /etc/passwd and /etc/group, as the
1957 * synthesizing logic is merely supposed to be fallback for cases where we run with a completely unpopulated
1959 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0) {
1960 r
= log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
1965 /* Default to default range of 1..SYSTEM_UID_MAX */
1966 r
= uid_range_add(&uid_range
, &n_uid_range
, 1, SYSTEM_UID_MAX
);
1977 lock
= take_etc_passwd_lock(arg_root
);
1979 log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
1983 r
= load_user_database();
1985 log_error_errno(r
, "Failed to load user database: %m");
1989 r
= load_group_database();
1991 log_error_errno(r
, "Failed to read group database: %m");
1995 ORDERED_HASHMAP_FOREACH(i
, groups
, iterator
)
1996 (void) process_item(i
);
1998 ORDERED_HASHMAP_FOREACH(i
, users
, iterator
)
1999 (void) process_item(i
);
2003 log_error_errno(r
, "Failed to write files: %m");
2008 ordered_hashmap_free_with_destructor(groups
, item_free
);
2009 ordered_hashmap_free_with_destructor(users
, item_free
);
2011 while ((n
= ordered_hashmap_first_key(members
))) {
2012 strv_free(ordered_hashmap_steal_first(members
));
2015 ordered_hashmap_free(members
);
2017 ordered_hashmap_free(todo_uids
);
2018 ordered_hashmap_free(todo_gids
);
2020 free_database(database_user
, database_uid
);
2021 free_database(database_group
, database_gid
);
2027 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;