1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #include "alloc-util.h"
7 #include "conf-files.h"
12 #include "format-util.h"
15 #include "main-func.h"
17 #include "path-util.h"
18 #include "pretty-print.h"
20 #include "selinux-util.h"
21 #include "smack-util.h"
22 #include "specifier.h"
23 #include "string-util.h"
25 #include "tmpfile-util-label.h"
26 #include "uid-range.h"
27 #include "user-util.h"
31 typedef enum ItemType
{
53 /* When set the group with the specified gid must exist
54 * and the check if a uid clashes with the gid is skipped.
64 static char *arg_root
= NULL
;
65 static bool arg_cat_config
= false;
66 static const char *arg_replace
= NULL
;
67 static bool arg_inline
= false;
68 static PagerFlags arg_pager_flags
= 0;
70 static OrderedHashmap
*users
= NULL
, *groups
= NULL
;
71 static OrderedHashmap
*todo_uids
= NULL
, *todo_gids
= NULL
;
72 static OrderedHashmap
*members
= NULL
;
74 static Hashmap
*database_by_uid
= NULL
, *database_by_username
= NULL
;
75 static Hashmap
*database_by_gid
= NULL
, *database_by_groupname
= NULL
;
76 static Set
*database_users
= NULL
, *database_groups
= NULL
;
78 static uid_t search_uid
= UID_INVALID
;
79 static UidRange
*uid_range
= NULL
;
80 static unsigned n_uid_range
= 0;
82 STATIC_DESTRUCTOR_REGISTER(groups
, ordered_hashmap_freep
);
83 STATIC_DESTRUCTOR_REGISTER(users
, ordered_hashmap_freep
);
84 STATIC_DESTRUCTOR_REGISTER(members
, ordered_hashmap_freep
);
85 STATIC_DESTRUCTOR_REGISTER(todo_uids
, ordered_hashmap_freep
);
86 STATIC_DESTRUCTOR_REGISTER(todo_gids
, ordered_hashmap_freep
);
87 STATIC_DESTRUCTOR_REGISTER(database_by_uid
, hashmap_freep
);
88 STATIC_DESTRUCTOR_REGISTER(database_by_username
, hashmap_freep
);
89 STATIC_DESTRUCTOR_REGISTER(database_users
, set_free_freep
);
90 STATIC_DESTRUCTOR_REGISTER(database_by_gid
, hashmap_freep
);
91 STATIC_DESTRUCTOR_REGISTER(database_by_groupname
, hashmap_freep
);
92 STATIC_DESTRUCTOR_REGISTER(database_groups
, set_free_freep
);
93 STATIC_DESTRUCTOR_REGISTER(uid_range
, freep
);
94 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
96 static int load_user_database(void) {
97 _cleanup_fclose_
FILE *f
= NULL
;
98 const char *passwd_path
;
102 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
103 f
= fopen(passwd_path
, "re");
105 return errno
== ENOENT
? 0 : -errno
;
107 r
= hashmap_ensure_allocated(&database_by_username
, &string_hash_ops
);
111 r
= hashmap_ensure_allocated(&database_by_uid
, NULL
);
115 r
= set_ensure_allocated(&database_users
, NULL
);
119 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
123 n
= strdup(pw
->pw_name
);
127 k
= set_put(database_users
, n
);
133 k
= hashmap_put(database_by_username
, n
, UID_TO_PTR(pw
->pw_uid
));
134 if (k
< 0 && k
!= -EEXIST
)
137 q
= hashmap_put(database_by_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
138 if (q
< 0 && q
!= -EEXIST
)
144 static int load_group_database(void) {
145 _cleanup_fclose_
FILE *f
= NULL
;
146 const char *group_path
;
150 group_path
= prefix_roota(arg_root
, "/etc/group");
151 f
= fopen(group_path
, "re");
153 return errno
== ENOENT
? 0 : -errno
;
155 r
= hashmap_ensure_allocated(&database_by_groupname
, &string_hash_ops
);
159 r
= hashmap_ensure_allocated(&database_by_gid
, NULL
);
163 r
= set_ensure_allocated(&database_groups
, NULL
);
167 while ((r
= fgetgrent_sane(f
, &gr
)) > 0) {
171 n
= strdup(gr
->gr_name
);
175 k
= set_put(database_groups
, n
);
181 k
= hashmap_put(database_by_groupname
, n
, GID_TO_PTR(gr
->gr_gid
));
182 if (k
< 0 && k
!= -EEXIST
)
185 q
= hashmap_put(database_by_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
186 if (q
< 0 && q
!= -EEXIST
)
192 static int make_backup(const char *target
, const char *x
) {
193 _cleanup_close_
int src
= -1;
194 _cleanup_fclose_
FILE *dst
= NULL
;
195 _cleanup_free_
char *temp
= NULL
;
197 struct timespec ts
[2];
201 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
203 if (errno
== ENOENT
) /* No backup necessary... */
209 if (fstat(src
, &st
) < 0)
212 r
= fopen_temporary_label(target
, x
, &dst
, &temp
);
216 r
= copy_bytes(src
, fileno(dst
), (uint64_t) -1, COPY_REFLINK
);
220 /* Don't fail on chmod() or chown(). If it stays owned by us
221 * and/or unreadable by others, then it isn't too bad... */
223 backup
= strjoina(x
, "-");
225 /* Copy over the access mask */
226 r
= fchmod_and_chown(fileno(dst
), st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
228 log_warning_errno(r
, "Failed to change access mode or ownership of %s: %m", backup
);
232 if (futimens(fileno(dst
), ts
) < 0)
233 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
235 r
= fflush_sync_and_check(dst
);
239 if (rename(temp
, backup
) < 0) {
251 static int putgrent_with_members(const struct group
*gr
, FILE *group
) {
257 a
= ordered_hashmap_get(members
, gr
->gr_name
);
259 _cleanup_strv_free_
char **l
= NULL
;
263 l
= strv_copy(gr
->gr_mem
);
268 if (strv_find(l
, *i
))
271 if (strv_extend(&l
, *i
) < 0)
287 r
= putgrent_sane(&t
, group
);
288 return r
< 0 ? r
: 1;
292 return putgrent_sane(gr
, group
);
296 static int putsgent_with_members(const struct sgrp
*sg
, FILE *gshadow
) {
302 a
= ordered_hashmap_get(members
, sg
->sg_namp
);
304 _cleanup_strv_free_
char **l
= NULL
;
308 l
= strv_copy(sg
->sg_mem
);
313 if (strv_find(l
, *i
))
316 if (strv_extend(&l
, *i
) < 0)
332 r
= putsgent_sane(&t
, gshadow
);
333 return r
< 0 ? r
: 1;
337 return putsgent_sane(sg
, gshadow
);
341 static int sync_rights(FILE *from
, FILE *to
) {
344 if (fstat(fileno(from
), &st
) < 0)
347 return fchmod_and_chown(fileno(to
), st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
350 static int rename_and_apply_smack(const char *temp_path
, const char *dest_path
) {
352 if (rename(temp_path
, dest_path
) < 0)
355 #ifdef SMACK_RUN_LABEL
356 r
= mac_smack_apply(dest_path
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);
363 static const char* default_shell(uid_t uid
) {
364 return uid
== 0 ? "/bin/sh" : NOLOGIN
;
367 static int write_temporary_passwd(const char *passwd_path
, FILE **tmpfile
, char **tmpfile_path
) {
368 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
369 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
370 struct passwd
*pw
= NULL
;
375 if (ordered_hashmap_size(todo_uids
) == 0)
378 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
382 original
= fopen(passwd_path
, "re");
385 r
= sync_rights(original
, passwd
);
389 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
391 i
= ordered_hashmap_get(users
, pw
->pw_name
);
392 if (i
&& i
->todo_user
)
393 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
394 "%s: User \"%s\" already exists.",
395 passwd_path
, pw
->pw_name
);
397 if (ordered_hashmap_contains(todo_uids
, UID_TO_PTR(pw
->pw_uid
)))
398 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
399 "%s: Detected collision for UID " UID_FMT
".",
400 passwd_path
, pw
->pw_uid
);
402 /* Make sure we keep the NIS entries (if any) at the end. */
403 if (IN_SET(pw
->pw_name
[0], '+', '-'))
406 r
= putpwent_sane(pw
, passwd
);
416 if (fchmod(fileno(passwd
), 0644) < 0)
420 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
425 .pw_gecos
= i
->description
,
427 /* "x" means the password is stored in the shadow file */
428 .pw_passwd
= (char*) "x",
430 /* We default to the root directory as home */
431 .pw_dir
= i
->home
? i
->home
: (char*) "/",
433 /* Initialize the shell to nologin, with one exception:
434 * for root we patch in something special */
435 .pw_shell
= i
->shell
?: (char*) default_shell(i
->uid
),
438 r
= putpwent_sane(&n
, passwd
);
443 /* Append the remaining NIS entries if any */
445 r
= putpwent_sane(pw
, passwd
);
449 r
= fgetpwent_sane(original
, &pw
);
456 r
= fflush_and_check(passwd
);
460 *tmpfile
= TAKE_PTR(passwd
);
461 *tmpfile_path
= TAKE_PTR(passwd_tmp
);
466 static int write_temporary_shadow(const char *shadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
467 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
468 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
469 struct spwd
*sp
= NULL
;
475 if (ordered_hashmap_size(todo_uids
) == 0)
478 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
482 lstchg
= (long) (now(CLOCK_REALTIME
) / USEC_PER_DAY
);
484 original
= fopen(shadow_path
, "re");
487 r
= sync_rights(original
, shadow
);
491 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
493 i
= ordered_hashmap_get(users
, sp
->sp_namp
);
494 if (i
&& i
->todo_user
) {
495 /* we will update the existing entry */
496 sp
->sp_lstchg
= lstchg
;
498 /* only the /etc/shadow stage is left, so we can
499 * safely remove the item from the todo set */
500 i
->todo_user
= false;
501 ordered_hashmap_remove(todo_uids
, UID_TO_PTR(i
->uid
));
504 /* Make sure we keep the NIS entries (if any) at the end. */
505 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
508 r
= putspent_sane(sp
, shadow
);
518 if (fchmod(fileno(shadow
), 0000) < 0)
522 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
525 .sp_pwdp
= (char*) "!!",
532 .sp_flag
= (unsigned long) -1, /* this appears to be what everybody does ... */
535 r
= putspent_sane(&n
, shadow
);
540 /* Append the remaining NIS entries if any */
542 r
= putspent_sane(sp
, shadow
);
546 r
= fgetspent_sane(original
, &sp
);
552 if (!IN_SET(errno
, 0, ENOENT
))
555 r
= fflush_sync_and_check(shadow
);
559 *tmpfile
= TAKE_PTR(shadow
);
560 *tmpfile_path
= TAKE_PTR(shadow_tmp
);
565 static int write_temporary_group(const char *group_path
, FILE **tmpfile
, char **tmpfile_path
) {
566 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
567 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
568 bool group_changed
= false;
569 struct group
*gr
= NULL
;
574 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
577 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
581 original
= fopen(group_path
, "re");
584 r
= sync_rights(original
, group
);
588 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
589 /* Safety checks against name and GID collisions. Normally,
590 * this should be unnecessary, but given that we look at the
591 * entries anyway here, let's make an extra verification
592 * step that we don't generate duplicate entries. */
594 i
= ordered_hashmap_get(groups
, gr
->gr_name
);
595 if (i
&& i
->todo_group
)
596 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
597 "%s: Group \"%s\" already exists.",
598 group_path
, gr
->gr_name
);
600 if (ordered_hashmap_contains(todo_gids
, GID_TO_PTR(gr
->gr_gid
)))
601 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
602 "%s: Detected collision for GID " GID_FMT
".",
603 group_path
, gr
->gr_gid
);
605 /* Make sure we keep the NIS entries (if any) at the end. */
606 if (IN_SET(gr
->gr_name
[0], '+', '-'))
609 r
= putgrent_with_members(gr
, group
);
613 group_changed
= true;
621 if (fchmod(fileno(group
), 0644) < 0)
625 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
629 .gr_passwd
= (char*) "x",
632 r
= putgrent_with_members(&n
, group
);
636 group_changed
= true;
639 /* Append the remaining NIS entries if any */
641 r
= putgrent_sane(gr
, group
);
645 r
= fgetgrent_sane(original
, &gr
);
652 r
= fflush_sync_and_check(group
);
657 *tmpfile
= TAKE_PTR(group
);
658 *tmpfile_path
= TAKE_PTR(group_tmp
);
663 static int write_temporary_gshadow(const char * gshadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
665 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
666 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
667 bool group_changed
= false;
672 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
675 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
679 original
= fopen(gshadow_path
, "re");
683 r
= sync_rights(original
, gshadow
);
687 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
689 i
= ordered_hashmap_get(groups
, sg
->sg_namp
);
690 if (i
&& i
->todo_group
)
691 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
692 "%s: Group \"%s\" already exists.",
693 gshadow_path
, sg
->sg_namp
);
695 r
= putsgent_with_members(sg
, gshadow
);
699 group_changed
= true;
707 if (fchmod(fileno(gshadow
), 0000) < 0)
711 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
714 .sg_passwd
= (char*) "!!",
717 r
= putsgent_with_members(&n
, gshadow
);
721 group_changed
= true;
724 r
= fflush_sync_and_check(gshadow
);
729 *tmpfile
= TAKE_PTR(gshadow
);
730 *tmpfile_path
= TAKE_PTR(gshadow_tmp
);
738 static int write_files(void) {
739 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
740 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
741 const char *passwd_path
= NULL
, *group_path
= NULL
, *shadow_path
= NULL
, *gshadow_path
= NULL
;
744 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
745 shadow_path
= prefix_roota(arg_root
, "/etc/shadow");
746 group_path
= prefix_roota(arg_root
, "/etc/group");
747 gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
749 r
= write_temporary_group(group_path
, &group
, &group_tmp
);
753 r
= write_temporary_gshadow(gshadow_path
, &gshadow
, &gshadow_tmp
);
757 r
= write_temporary_passwd(passwd_path
, &passwd
, &passwd_tmp
);
761 r
= write_temporary_shadow(shadow_path
, &shadow
, &shadow_tmp
);
765 /* Make a backup of the old files */
767 r
= make_backup("/etc/group", group_path
);
772 r
= make_backup("/etc/gshadow", gshadow_path
);
778 r
= make_backup("/etc/passwd", passwd_path
);
783 r
= make_backup("/etc/shadow", shadow_path
);
788 /* And make the new files count */
790 r
= rename_and_apply_smack(group_tmp
, group_path
);
794 group_tmp
= mfree(group_tmp
);
797 r
= rename_and_apply_smack(gshadow_tmp
, gshadow_path
);
801 gshadow_tmp
= mfree(gshadow_tmp
);
805 r
= rename_and_apply_smack(passwd_tmp
, passwd_path
);
809 passwd_tmp
= mfree(passwd_tmp
);
812 r
= rename_and_apply_smack(shadow_tmp
, shadow_path
);
816 shadow_tmp
= mfree(shadow_tmp
);
822 static int uid_is_ok(uid_t uid
, const char *name
, bool check_with_gid
) {
828 /* Let's see if we already have assigned the UID a second time */
829 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(uid
)))
832 /* Try to avoid using uids that are already used by a group
833 * that doesn't have the same name as our new user. */
834 if (check_with_gid
) {
835 i
= ordered_hashmap_get(todo_gids
, GID_TO_PTR(uid
));
836 if (i
&& !streq(i
->name
, name
))
840 /* Let's check the files directly */
841 if (hashmap_contains(database_by_uid
, UID_TO_PTR(uid
)))
844 if (check_with_gid
) {
845 n
= hashmap_get(database_by_gid
, GID_TO_PTR(uid
));
846 if (n
&& !streq(n
, name
))
850 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
856 if (!IN_SET(errno
, 0, ENOENT
))
859 if (check_with_gid
) {
861 g
= getgrgid((gid_t
) uid
);
863 if (!streq(g
->gr_name
, name
))
865 } else if (!IN_SET(errno
, 0, ENOENT
))
873 static int root_stat(const char *p
, struct stat
*st
) {
876 fix
= prefix_roota(arg_root
, p
);
877 if (stat(fix
, st
) < 0)
883 static int read_id_from_file(Item
*i
, uid_t
*_uid
, gid_t
*_gid
) {
885 bool found_uid
= false, found_gid
= false;
891 /* First, try to get the gid directly */
892 if (_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
897 /* Then, try to get the uid directly */
898 if ((_uid
|| (_gid
&& !found_gid
))
900 && root_stat(i
->uid_path
, &st
) >= 0) {
905 /* If we need the gid, but had no success yet, also derive it from the uid path */
906 if (_gid
&& !found_gid
) {
912 /* If that didn't work yet, then let's reuse the gid as uid */
913 if (_uid
&& !found_uid
&& i
->gid_path
) {
918 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
919 uid
= (uid_t
) st
.st_gid
;
941 static int add_user(Item
*i
) {
947 /* Check the database directly */
948 z
= hashmap_get(database_by_username
, i
->name
);
950 log_debug("User %s already exists.", i
->name
);
951 i
->uid
= PTR_TO_UID(z
);
961 p
= getpwnam(i
->name
);
963 log_debug("User %s already exists.", i
->name
);
967 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
973 if (!IN_SET(errno
, 0, ENOENT
))
974 return log_error_errno(errno
, "Failed to check if user %s already exists: %m", i
->name
);
977 /* Try to use the suggested numeric uid */
979 r
= uid_is_ok(i
->uid
, i
->name
, !i
->id_set_strict
);
981 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
983 log_debug("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
988 /* If that didn't work, try to read it from the specified path */
992 if (read_id_from_file(i
, &c
, NULL
) > 0) {
994 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
995 log_debug("User ID " UID_FMT
" of file not suitable for %s.", c
, i
->name
);
997 r
= uid_is_ok(c
, i
->name
, true);
999 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1004 log_debug("User ID " UID_FMT
" of file for %s is already used.", c
, i
->name
);
1009 /* Otherwise, try to reuse the group ID */
1010 if (!i
->uid_set
&& i
->gid_set
) {
1011 r
= uid_is_ok((uid_t
) i
->gid
, i
->name
, true);
1013 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1015 i
->uid
= (uid_t
) i
->gid
;
1020 /* And if that didn't work either, let's try to find a free one */
1023 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1025 return log_error_errno(r
, "No free user ID available for %s.", i
->name
);
1027 r
= uid_is_ok(search_uid
, i
->name
, true);
1029 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1035 i
->uid
= search_uid
;
1038 r
= ordered_hashmap_ensure_allocated(&todo_uids
, NULL
);
1042 r
= ordered_hashmap_put(todo_uids
, UID_TO_PTR(i
->uid
), i
);
1046 i
->todo_user
= true;
1047 log_info("Creating user %s (%s) with uid " UID_FMT
" and gid " GID_FMT
".", i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1052 static int gid_is_ok(gid_t gid
) {
1056 if (ordered_hashmap_get(todo_gids
, GID_TO_PTR(gid
)))
1059 /* Avoid reusing gids that are already used by a different user */
1060 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(gid
)))
1063 if (hashmap_contains(database_by_gid
, GID_TO_PTR(gid
)))
1066 if (hashmap_contains(database_by_uid
, UID_TO_PTR(gid
)))
1074 if (!IN_SET(errno
, 0, ENOENT
))
1078 p
= getpwuid((uid_t
) gid
);
1081 if (!IN_SET(errno
, 0, ENOENT
))
1088 static int add_group(Item
*i
) {
1094 /* Check the database directly */
1095 z
= hashmap_get(database_by_groupname
, i
->name
);
1097 log_debug("Group %s already exists.", i
->name
);
1098 i
->gid
= PTR_TO_GID(z
);
1103 /* Also check NSS */
1108 g
= getgrnam(i
->name
);
1110 log_debug("Group %s already exists.", i
->name
);
1115 if (!IN_SET(errno
, 0, ENOENT
))
1116 return log_error_errno(errno
, "Failed to check if group %s already exists: %m", i
->name
);
1119 /* Try to use the suggested numeric gid */
1121 r
= gid_is_ok(i
->gid
);
1123 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1124 if (i
->id_set_strict
) {
1125 /* If we require the gid to already exist we can return here:
1126 * r > 0: means the gid does not exist -> fail
1127 * r == 0: means the gid exists -> nothing more to do.
1130 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1131 "Failed to create %s: please create GID %d",
1137 log_debug("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1142 /* Try to reuse the numeric uid, if there's one */
1143 if (!i
->gid_set
&& i
->uid_set
) {
1144 r
= gid_is_ok((gid_t
) i
->uid
);
1146 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1148 i
->gid
= (gid_t
) i
->uid
;
1153 /* If that didn't work, try to read it from the specified path */
1157 if (read_id_from_file(i
, NULL
, &c
) > 0) {
1159 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
1160 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", c
, i
->name
);
1164 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1169 log_debug("Group ID " GID_FMT
" of file for %s already used.", c
, i
->name
);
1174 /* And if that didn't work either, let's try to find a free one */
1177 /* We look for new GIDs in the UID pool! */
1178 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1180 return log_error_errno(r
, "No free group ID available for %s.", i
->name
);
1182 r
= gid_is_ok(search_uid
);
1184 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1190 i
->gid
= search_uid
;
1193 r
= ordered_hashmap_ensure_allocated(&todo_gids
, NULL
);
1197 r
= ordered_hashmap_put(todo_gids
, GID_TO_PTR(i
->gid
), i
);
1201 i
->todo_group
= true;
1202 log_info("Creating group %s with gid " GID_FMT
".", i
->name
, i
->gid
);
1207 static int process_item(Item
*i
) {
1217 j
= ordered_hashmap_get(groups
, i
->name
);
1218 if (j
&& j
->todo_group
) {
1219 /* When the group with the same name is already in queue,
1220 * use the information about the group and do not create
1221 * duplicated group entry. */
1222 i
->gid_set
= j
->gid_set
;
1224 i
->id_set_strict
= true;
1235 return add_group(i
);
1238 assert_not_reached("Unknown item type");
1242 static Item
* item_free(Item
*i
) {
1249 free(i
->description
);
1255 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1256 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops
, char, string_hash_func
, string_compare_func
, Item
, item_free
);
1258 static int add_implicit(void) {
1263 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1264 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, members
, iterator
) {
1268 if (!ordered_hashmap_get(users
, *m
)) {
1269 _cleanup_(item_freep
) Item
*j
= NULL
;
1271 r
= ordered_hashmap_ensure_allocated(&users
, &item_hash_ops
);
1280 j
->name
= strdup(*m
);
1284 r
= ordered_hashmap_put(users
, j
->name
, j
);
1288 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1292 if (!(ordered_hashmap_get(users
, g
) ||
1293 ordered_hashmap_get(groups
, g
))) {
1294 _cleanup_(item_freep
) Item
*j
= NULL
;
1296 r
= ordered_hashmap_ensure_allocated(&groups
, &item_hash_ops
);
1304 j
->type
= ADD_GROUP
;
1305 j
->name
= strdup(g
);
1309 r
= ordered_hashmap_put(groups
, j
->name
, j
);
1313 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1321 static bool item_equal(Item
*a
, Item
*b
) {
1325 if (a
->type
!= b
->type
)
1328 if (!streq_ptr(a
->name
, b
->name
))
1331 if (!streq_ptr(a
->uid_path
, b
->uid_path
))
1334 if (!streq_ptr(a
->gid_path
, b
->gid_path
))
1337 if (!streq_ptr(a
->description
, b
->description
))
1340 if (a
->uid_set
!= b
->uid_set
)
1343 if (a
->uid_set
&& a
->uid
!= b
->uid
)
1346 if (a
->gid_set
!= b
->gid_set
)
1349 if (a
->gid_set
&& a
->gid
!= b
->gid
)
1352 if (!streq_ptr(a
->home
, b
->home
))
1355 if (!streq_ptr(a
->shell
, b
->shell
))
1361 DEFINE_PRIVATE_HASH_OPS_FULL(members_hash_ops
, char, string_hash_func
, string_compare_func
, free
, char*, strv_free
);
1363 static int parse_line(const char *fname
, unsigned line
, const char *buffer
) {
1365 static const Specifier specifier_table
[] = {
1366 { 'm', specifier_machine_id
, NULL
},
1367 { 'b', specifier_boot_id
, NULL
},
1368 { 'H', specifier_host_name
, NULL
},
1369 { 'v', specifier_kernel_release
, NULL
},
1370 { 'T', specifier_tmp_dir
, NULL
},
1371 { 'V', specifier_var_tmp_dir
, NULL
},
1375 _cleanup_free_
char *action
= NULL
,
1376 *name
= NULL
, *resolved_name
= NULL
,
1377 *id
= NULL
, *resolved_id
= NULL
,
1378 *description
= NULL
, *resolved_description
= NULL
,
1379 *home
= NULL
, *resolved_home
= NULL
,
1380 *shell
= NULL
, *resolved_shell
= NULL
;
1381 _cleanup_(item_freep
) Item
*i
= NULL
;
1393 r
= extract_many_words(&p
, NULL
, EXTRACT_UNQUOTE
,
1394 &action
, &name
, &id
, &description
, &home
, &shell
, NULL
);
1396 return log_error_errno(r
, "[%s:%u] Syntax error.", fname
, line
);
1398 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1399 "[%s:%u] Missing action and name columns.", fname
, line
);
1401 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1402 "[%s:%u] Trailing garbage.", fname
, line
);
1405 if (strlen(action
) != 1)
1406 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1407 "[%s:%u] Unknown modifier '%s'", fname
, line
, action
);
1409 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
))
1410 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
1411 "[%s:%u] Unknown command type '%c'.", fname
, line
, action
[0]);
1414 if (empty_or_dash(name
))
1418 r
= specifier_printf(name
, specifier_table
, NULL
, &resolved_name
);
1420 log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1422 if (!valid_user_group_name(resolved_name
))
1423 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1424 "[%s:%u] '%s' is not a valid user or group name.",
1425 fname
, line
, resolved_name
);
1429 if (empty_or_dash(id
))
1433 r
= specifier_printf(id
, specifier_table
, NULL
, &resolved_id
);
1435 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1439 /* Verify description */
1440 if (empty_or_dash(description
))
1441 description
= mfree(description
);
1444 r
= specifier_printf(description
, specifier_table
, NULL
, &resolved_description
);
1446 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1447 fname
, line
, description
);
1449 if (!valid_gecos(resolved_description
))
1450 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1451 "[%s:%u] '%s' is not a valid GECOS field.",
1452 fname
, line
, resolved_description
);
1456 if (empty_or_dash(home
))
1460 r
= specifier_printf(home
, specifier_table
, NULL
, &resolved_home
);
1462 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1465 if (!valid_home(resolved_home
))
1466 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1467 "[%s:%u] '%s' is not a valid home directory field.",
1468 fname
, line
, resolved_home
);
1472 if (empty_or_dash(shell
))
1473 shell
= mfree(shell
);
1476 r
= specifier_printf(shell
, specifier_table
, NULL
, &resolved_shell
);
1478 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1479 fname
, line
, shell
);
1481 if (!valid_shell(resolved_shell
))
1482 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1483 "[%s:%u] '%s' is not a valid login shell field.",
1484 fname
, line
, resolved_shell
);
1487 switch (action
[0]) {
1491 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1492 "[%s:%u] Lines of type 'r' don't take a name field.",
1496 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1497 "[%s:%u] Lines of type 'r' require a ID range in the third field.",
1500 if (description
|| home
|| shell
)
1501 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1502 "[%s:%u] Lines of type '%c' don't take a %s field.",
1503 fname
, line
, action
[0],
1504 description
? "GECOS" : home
? "home directory" : "login shell");
1506 r
= uid_range_add_str(&uid_range
, &n_uid_range
, resolved_id
);
1508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1509 "[%s:%u] Invalid UID range %s.", fname
, line
, resolved_id
);
1516 /* Try to extend an existing member or group item */
1518 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1519 "[%s:%u] Lines of type 'm' require a user name in the second field.",
1523 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1524 "[%s:%u] Lines of type 'm' require a group name in the third field.",
1527 if (!valid_user_group_name(resolved_id
))
1528 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1529 "[%s:%u] '%s' is not a valid user or group name.",
1530 fname
, line
, resolved_id
);
1532 if (description
|| home
|| shell
)
1533 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1534 "[%s:%u] Lines of type '%c' don't take a %s field.",
1535 fname
, line
, action
[0],
1536 description
? "GECOS" : home
? "home directory" : "login shell");
1538 r
= ordered_hashmap_ensure_allocated(&members
, &members_hash_ops
);
1542 l
= ordered_hashmap_get(members
, resolved_id
);
1544 /* A list for this group name already exists, let's append to it */
1545 r
= strv_push(&l
, resolved_name
);
1549 resolved_name
= NULL
;
1551 assert_se(ordered_hashmap_update(members
, resolved_id
, l
) >= 0);
1553 /* No list for this group name exists yet, create one */
1555 l
= new0(char *, 2);
1559 l
[0] = resolved_name
;
1562 r
= ordered_hashmap_put(members
, resolved_id
, l
);
1568 resolved_id
= resolved_name
= NULL
;
1576 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1577 "[%s:%u] Lines of type 'u' require a user name in the second field.",
1580 r
= ordered_hashmap_ensure_allocated(&users
, &item_hash_ops
);
1589 if (path_is_absolute(resolved_id
)) {
1590 i
->uid_path
= TAKE_PTR(resolved_id
);
1591 path_simplify(i
->uid_path
, false);
1593 _cleanup_free_
char *uid
= NULL
, *gid
= NULL
;
1594 if (split_pair(resolved_id
, ":", &uid
, &gid
) == 0) {
1595 r
= parse_gid(gid
, &i
->gid
);
1597 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1599 i
->id_set_strict
= true;
1600 free_and_replace(resolved_id
, uid
);
1602 if (!streq(resolved_id
, "-")) {
1603 r
= parse_uid(resolved_id
, &i
->uid
);
1605 return log_error_errno(r
, "Failed to parse UID: '%s': %m", id
);
1611 i
->description
= TAKE_PTR(resolved_description
);
1612 i
->home
= TAKE_PTR(resolved_home
);
1613 i
->shell
= TAKE_PTR(resolved_shell
);
1620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1621 "[%s:%u] Lines of type 'g' require a user name in the second field.",
1624 if (description
|| home
|| shell
)
1625 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1626 "[%s:%u] Lines of type '%c' don't take a %s field.",
1627 fname
, line
, action
[0],
1628 description
? "GECOS" : home
? "home directory" : "login shell");
1630 r
= ordered_hashmap_ensure_allocated(&groups
, &item_hash_ops
);
1639 if (path_is_absolute(resolved_id
)) {
1640 i
->gid_path
= TAKE_PTR(resolved_id
);
1641 path_simplify(i
->gid_path
, false);
1643 r
= parse_gid(resolved_id
, &i
->gid
);
1645 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1658 i
->type
= action
[0];
1659 i
->name
= TAKE_PTR(resolved_name
);
1661 existing
= ordered_hashmap_get(h
, i
->name
);
1663 /* Two identical items are fine */
1664 if (!item_equal(existing
, i
))
1665 log_warning("Two or more conflicting lines for %s configured, ignoring.", i
->name
);
1670 r
= ordered_hashmap_put(h
, i
->name
, i
);
1678 static int read_config_file(const char *fn
, bool ignore_enoent
) {
1679 _cleanup_fclose_
FILE *rf
= NULL
;
1689 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf
);
1691 if (ignore_enoent
&& r
== -ENOENT
)
1694 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
1701 _cleanup_free_
char *line
= NULL
;
1705 k
= read_line(f
, LONG_LINE_MAX
, &line
);
1707 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
1714 if (IN_SET(*l
, 0, '#'))
1717 k
= parse_line(fn
, v
, l
);
1718 if (k
< 0 && r
== 0)
1723 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
1731 static int cat_config(void) {
1732 _cleanup_strv_free_
char **files
= NULL
;
1735 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
1739 (void) pager_open(arg_pager_flags
);
1741 return cat_files(NULL
, files
, 0);
1744 static int help(void) {
1745 _cleanup_free_
char *link
= NULL
;
1748 r
= terminal_urlify_man("systemd-sysusers.service", "8", &link
);
1752 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1753 "Creates system user accounts.\n\n"
1754 " -h --help Show this help\n"
1755 " --version Show package version\n"
1756 " --cat-config Show configuration files\n"
1757 " --root=PATH Operate on an alternate filesystem root\n"
1758 " --replace=PATH Treat arguments as replacement for PATH\n"
1759 " --inline Treat arguments as configuration lines\n"
1760 " --no-pager Do not pipe output into a pager\n"
1761 "\nSee the %s for details.\n"
1762 , program_invocation_short_name
1769 static int parse_argv(int argc
, char *argv
[]) {
1772 ARG_VERSION
= 0x100,
1780 static const struct option options
[] = {
1781 { "help", no_argument
, NULL
, 'h' },
1782 { "version", no_argument
, NULL
, ARG_VERSION
},
1783 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
1784 { "root", required_argument
, NULL
, ARG_ROOT
},
1785 { "replace", required_argument
, NULL
, ARG_REPLACE
},
1786 { "inline", no_argument
, NULL
, ARG_INLINE
},
1787 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
1796 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
1806 case ARG_CAT_CONFIG
:
1807 arg_cat_config
= true;
1811 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
1817 if (!path_is_absolute(optarg
) ||
1818 !endswith(optarg
, ".conf"))
1819 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1820 "The argument to --replace= must an absolute path to a config file");
1822 arg_replace
= optarg
;
1830 arg_pager_flags
|= PAGER_DISABLE
;
1837 assert_not_reached("Unhandled option");
1840 if (arg_replace
&& arg_cat_config
)
1841 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1842 "Option --replace= is not supported with --cat-config");
1844 if (arg_replace
&& optind
>= argc
)
1845 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1846 "When --replace= is given, some configuration items must be specified");
1851 static int parse_arguments(char **args
) {
1856 STRV_FOREACH(arg
, args
) {
1858 /* Use (argument):n, where n==1 for the first positional arg */
1859 r
= parse_line("(argument)", pos
, *arg
);
1861 r
= read_config_file(*arg
, false);
1871 static int read_config_files(char **args
) {
1872 _cleanup_strv_free_
char **files
= NULL
;
1873 _cleanup_free_
char *p
= NULL
;
1877 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
1881 STRV_FOREACH(f
, files
)
1882 if (p
&& path_equal(*f
, p
)) {
1883 log_debug("Parsing arguments at position \"%s\"…", *f
);
1885 r
= parse_arguments(args
);
1889 log_debug("Reading config file \"%s\"…", *f
);
1891 /* Just warn, ignore result otherwise */
1892 (void) read_config_file(*f
, true);
1898 static int run(int argc
, char *argv
[]) {
1899 _cleanup_close_
int lock
= -1;
1904 r
= parse_argv(argc
, argv
);
1908 log_setup_service();
1911 return cat_config();
1915 r
= mac_selinux_init();
1917 return log_error_errno(r
, "SELinux setup failed: %m");
1919 /* If command line arguments are specified along with --replace, read all
1920 * configuration files and insert the positional arguments at the specified
1921 * place. Otherwise, if command line arguments are specified, execute just
1922 * them, and finally, without --replace= or any positional arguments, just
1923 * read configuration and execute it.
1925 if (arg_replace
|| optind
>= argc
)
1926 r
= read_config_files(argv
+ optind
);
1928 r
= parse_arguments(argv
+ optind
);
1932 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our detection
1933 * whether the names or UID/GID area already used otherwise doesn't get confused. After all, even though
1934 * nss-systemd synthesizes these users/groups, they should still appear in /etc/passwd and /etc/group, as the
1935 * synthesizing logic is merely supposed to be fallback for cases where we run with a completely unpopulated
1937 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
1938 return log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
1941 /* Default to default range of 1..SYSTEM_UID_MAX */
1942 r
= uid_range_add(&uid_range
, &n_uid_range
, 1, SYSTEM_UID_MAX
);
1951 lock
= take_etc_passwd_lock(arg_root
);
1953 return log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
1955 r
= load_user_database();
1957 return log_error_errno(r
, "Failed to load user database: %m");
1959 r
= load_group_database();
1961 return log_error_errno(r
, "Failed to read group database: %m");
1963 ORDERED_HASHMAP_FOREACH(i
, groups
, iterator
)
1964 (void) process_item(i
);
1966 ORDERED_HASHMAP_FOREACH(i
, users
, iterator
)
1967 (void) process_item(i
);
1971 return log_error_errno(r
, "Failed to write files: %m");
1976 DEFINE_MAIN_FUNCTION(run
);