1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #include "alloc-util.h"
7 #include "conf-files.h"
11 #include "fileio-label.h"
12 #include "format-util.h"
16 #include "path-util.h"
17 #include "pretty-print.h"
18 #include "selinux-util.h"
19 #include "smack-util.h"
20 #include "specifier.h"
21 #include "string-util.h"
23 #include "uid-range.h"
24 #include "user-util.h"
28 typedef enum ItemType
{
50 /* When set the group with the specified gid must exist
51 * and the check if a uid clashes with the gid is skipped.
61 static char *arg_root
= NULL
;
62 static bool arg_cat_config
= false;
63 static const char *arg_replace
= NULL
;
64 static bool arg_inline
= false;
65 static PagerFlags arg_pager_flags
= 0;
67 static OrderedHashmap
*users
= NULL
, *groups
= NULL
;
68 static OrderedHashmap
*todo_uids
= NULL
, *todo_gids
= NULL
;
69 static OrderedHashmap
*members
= NULL
;
71 static Hashmap
*database_uid
= NULL
, *database_user
= NULL
;
72 static Hashmap
*database_gid
= NULL
, *database_group
= NULL
;
74 static uid_t search_uid
= UID_INVALID
;
75 static UidRange
*uid_range
= NULL
;
76 static unsigned n_uid_range
= 0;
78 static int load_user_database(void) {
79 _cleanup_fclose_
FILE *f
= NULL
;
80 const char *passwd_path
;
84 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
85 f
= fopen(passwd_path
, "re");
87 return errno
== ENOENT
? 0 : -errno
;
89 r
= hashmap_ensure_allocated(&database_user
, &string_hash_ops
);
93 r
= hashmap_ensure_allocated(&database_uid
, NULL
);
97 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
101 n
= strdup(pw
->pw_name
);
105 k
= hashmap_put(database_user
, n
, UID_TO_PTR(pw
->pw_uid
));
106 if (k
< 0 && k
!= -EEXIST
) {
111 q
= hashmap_put(database_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
112 if (q
< 0 && q
!= -EEXIST
) {
118 if (k
<= 0 && q
<= 0)
124 static int load_group_database(void) {
125 _cleanup_fclose_
FILE *f
= NULL
;
126 const char *group_path
;
130 group_path
= prefix_roota(arg_root
, "/etc/group");
131 f
= fopen(group_path
, "re");
133 return errno
== ENOENT
? 0 : -errno
;
135 r
= hashmap_ensure_allocated(&database_group
, &string_hash_ops
);
139 r
= hashmap_ensure_allocated(&database_gid
, NULL
);
143 while ((r
= fgetgrent_sane(f
, &gr
)) > 0) {
147 n
= strdup(gr
->gr_name
);
151 k
= hashmap_put(database_group
, n
, GID_TO_PTR(gr
->gr_gid
));
152 if (k
< 0 && k
!= -EEXIST
) {
157 q
= hashmap_put(database_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
158 if (q
< 0 && q
!= -EEXIST
) {
164 if (k
<= 0 && q
<= 0)
170 static int make_backup(const char *target
, const char *x
) {
171 _cleanup_close_
int src
= -1;
172 _cleanup_fclose_
FILE *dst
= NULL
;
173 _cleanup_free_
char *temp
= NULL
;
175 struct timespec ts
[2];
179 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
181 if (errno
== ENOENT
) /* No backup necessary... */
187 if (fstat(src
, &st
) < 0)
190 r
= fopen_temporary_label(target
, x
, &dst
, &temp
);
194 r
= copy_bytes(src
, fileno(dst
), (uint64_t) -1, COPY_REFLINK
);
198 /* Don't fail on chmod() or chown(). If it stays owned by us
199 * and/or unreadable by others, then it isn't too bad... */
201 backup
= strjoina(x
, "-");
203 /* Copy over the access mask */
204 r
= fchmod_and_chown(fileno(dst
), st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
206 log_warning_errno(r
, "Failed to change access mode or ownership of %s: %m", backup
);
210 if (futimens(fileno(dst
), ts
) < 0)
211 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
213 r
= fflush_sync_and_check(dst
);
217 if (rename(temp
, backup
) < 0) {
229 static int putgrent_with_members(const struct group
*gr
, FILE *group
) {
235 a
= ordered_hashmap_get(members
, gr
->gr_name
);
237 _cleanup_strv_free_
char **l
= NULL
;
241 l
= strv_copy(gr
->gr_mem
);
246 if (strv_find(l
, *i
))
249 if (strv_extend(&l
, *i
) < 0)
265 r
= putgrent_sane(&t
, group
);
266 return r
< 0 ? r
: 1;
270 return putgrent_sane(gr
, group
);
274 static int putsgent_with_members(const struct sgrp
*sg
, FILE *gshadow
) {
280 a
= ordered_hashmap_get(members
, sg
->sg_namp
);
282 _cleanup_strv_free_
char **l
= NULL
;
286 l
= strv_copy(sg
->sg_mem
);
291 if (strv_find(l
, *i
))
294 if (strv_extend(&l
, *i
) < 0)
310 r
= putsgent_sane(&t
, gshadow
);
311 return r
< 0 ? r
: 1;
315 return putsgent_sane(sg
, gshadow
);
319 static int sync_rights(FILE *from
, FILE *to
) {
322 if (fstat(fileno(from
), &st
) < 0)
325 return fchmod_and_chown(fileno(to
), st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
328 static int rename_and_apply_smack(const char *temp_path
, const char *dest_path
) {
330 if (rename(temp_path
, dest_path
) < 0)
333 #ifdef SMACK_RUN_LABEL
334 r
= mac_smack_apply(dest_path
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);
341 static const char* default_shell(uid_t uid
) {
342 return uid
== 0 ? "/bin/sh" : "/sbin/nologin";
345 static int write_temporary_passwd(const char *passwd_path
, FILE **tmpfile
, char **tmpfile_path
) {
346 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
347 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
348 struct passwd
*pw
= NULL
;
353 if (ordered_hashmap_size(todo_uids
) == 0)
356 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
360 original
= fopen(passwd_path
, "re");
363 r
= sync_rights(original
, passwd
);
367 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
369 i
= ordered_hashmap_get(users
, pw
->pw_name
);
370 if (i
&& i
->todo_user
) {
371 log_error("%s: User \"%s\" already exists.", passwd_path
, pw
->pw_name
);
375 if (ordered_hashmap_contains(todo_uids
, UID_TO_PTR(pw
->pw_uid
))) {
376 log_error("%s: Detected collision for UID " UID_FMT
".", passwd_path
, pw
->pw_uid
);
380 /* Make sure we keep the NIS entries (if any) at the end. */
381 if (IN_SET(pw
->pw_name
[0], '+', '-'))
384 r
= putpwent_sane(pw
, passwd
);
394 if (fchmod(fileno(passwd
), 0644) < 0)
398 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
403 .pw_gecos
= i
->description
,
405 /* "x" means the password is stored in the shadow file */
406 .pw_passwd
= (char*) "x",
408 /* We default to the root directory as home */
409 .pw_dir
= i
->home
? i
->home
: (char*) "/",
411 /* Initialize the shell to nologin, with one exception:
412 * for root we patch in something special */
413 .pw_shell
= i
->shell
?: (char*) default_shell(i
->uid
),
416 r
= putpwent_sane(&n
, passwd
);
421 /* Append the remaining NIS entries if any */
423 r
= putpwent_sane(pw
, passwd
);
427 r
= fgetpwent_sane(original
, &pw
);
434 r
= fflush_and_check(passwd
);
438 *tmpfile
= TAKE_PTR(passwd
);
439 *tmpfile_path
= TAKE_PTR(passwd_tmp
);
444 static int write_temporary_shadow(const char *shadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
445 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
446 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
447 struct spwd
*sp
= NULL
;
453 if (ordered_hashmap_size(todo_uids
) == 0)
456 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
460 lstchg
= (long) (now(CLOCK_REALTIME
) / USEC_PER_DAY
);
462 original
= fopen(shadow_path
, "re");
465 r
= sync_rights(original
, shadow
);
469 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
471 i
= ordered_hashmap_get(users
, sp
->sp_namp
);
472 if (i
&& i
->todo_user
) {
473 /* we will update the existing entry */
474 sp
->sp_lstchg
= lstchg
;
476 /* only the /etc/shadow stage is left, so we can
477 * safely remove the item from the todo set */
478 i
->todo_user
= false;
479 ordered_hashmap_remove(todo_uids
, UID_TO_PTR(i
->uid
));
482 /* Make sure we keep the NIS entries (if any) at the end. */
483 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
486 r
= putspent_sane(sp
, shadow
);
496 if (fchmod(fileno(shadow
), 0000) < 0)
500 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
503 .sp_pwdp
= (char*) "!!",
510 .sp_flag
= (unsigned long) -1, /* this appears to be what everybody does ... */
513 r
= putspent_sane(&n
, shadow
);
518 /* Append the remaining NIS entries if any */
520 r
= putspent_sane(sp
, shadow
);
524 r
= fgetspent_sane(original
, &sp
);
530 if (!IN_SET(errno
, 0, ENOENT
))
533 r
= fflush_sync_and_check(shadow
);
537 *tmpfile
= TAKE_PTR(shadow
);
538 *tmpfile_path
= TAKE_PTR(shadow_tmp
);
543 static int write_temporary_group(const char *group_path
, FILE **tmpfile
, char **tmpfile_path
) {
544 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
545 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
546 bool group_changed
= false;
547 struct group
*gr
= NULL
;
552 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
555 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
559 original
= fopen(group_path
, "re");
562 r
= sync_rights(original
, group
);
566 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
567 /* Safety checks against name and GID collisions. Normally,
568 * this should be unnecessary, but given that we look at the
569 * entries anyway here, let's make an extra verification
570 * step that we don't generate duplicate entries. */
572 i
= ordered_hashmap_get(groups
, gr
->gr_name
);
573 if (i
&& i
->todo_group
) {
574 log_error("%s: Group \"%s\" already exists.", group_path
, gr
->gr_name
);
578 if (ordered_hashmap_contains(todo_gids
, GID_TO_PTR(gr
->gr_gid
))) {
579 log_error("%s: Detected collision for GID " GID_FMT
".", group_path
, gr
->gr_gid
);
583 /* Make sure we keep the NIS entries (if any) at the end. */
584 if (IN_SET(gr
->gr_name
[0], '+', '-'))
587 r
= putgrent_with_members(gr
, group
);
591 group_changed
= true;
599 if (fchmod(fileno(group
), 0644) < 0)
603 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
607 .gr_passwd
= (char*) "x",
610 r
= putgrent_with_members(&n
, group
);
614 group_changed
= true;
617 /* Append the remaining NIS entries if any */
619 r
= putgrent_sane(gr
, group
);
623 r
= fgetgrent_sane(original
, &gr
);
630 r
= fflush_sync_and_check(group
);
635 *tmpfile
= TAKE_PTR(group
);
636 *tmpfile_path
= TAKE_PTR(group_tmp
);
641 static int write_temporary_gshadow(const char * gshadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
643 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
644 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
645 bool group_changed
= false;
650 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
653 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
657 original
= fopen(gshadow_path
, "re");
661 r
= sync_rights(original
, gshadow
);
665 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
667 i
= ordered_hashmap_get(groups
, sg
->sg_namp
);
668 if (i
&& i
->todo_group
) {
669 log_error("%s: Group \"%s\" already exists.", gshadow_path
, sg
->sg_namp
);
673 r
= putsgent_with_members(sg
, gshadow
);
677 group_changed
= true;
685 if (fchmod(fileno(gshadow
), 0000) < 0)
689 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
692 .sg_passwd
= (char*) "!!",
695 r
= putsgent_with_members(&n
, gshadow
);
699 group_changed
= true;
702 r
= fflush_sync_and_check(gshadow
);
707 *tmpfile
= TAKE_PTR(gshadow
);
708 *tmpfile_path
= TAKE_PTR(gshadow_tmp
);
716 static int write_files(void) {
717 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
718 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
719 const char *passwd_path
= NULL
, *group_path
= NULL
, *shadow_path
= NULL
, *gshadow_path
= NULL
;
722 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
723 shadow_path
= prefix_roota(arg_root
, "/etc/shadow");
724 group_path
= prefix_roota(arg_root
, "/etc/group");
725 gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
727 r
= write_temporary_group(group_path
, &group
, &group_tmp
);
731 r
= write_temporary_gshadow(gshadow_path
, &gshadow
, &gshadow_tmp
);
735 r
= write_temporary_passwd(passwd_path
, &passwd
, &passwd_tmp
);
739 r
= write_temporary_shadow(shadow_path
, &shadow
, &shadow_tmp
);
743 /* Make a backup of the old files */
745 r
= make_backup("/etc/group", group_path
);
750 r
= make_backup("/etc/gshadow", gshadow_path
);
756 r
= make_backup("/etc/passwd", passwd_path
);
761 r
= make_backup("/etc/shadow", shadow_path
);
766 /* And make the new files count */
768 r
= rename_and_apply_smack(group_tmp
, group_path
);
772 group_tmp
= mfree(group_tmp
);
775 r
= rename_and_apply_smack(gshadow_tmp
, gshadow_path
);
779 gshadow_tmp
= mfree(gshadow_tmp
);
783 r
= rename_and_apply_smack(passwd_tmp
, passwd_path
);
787 passwd_tmp
= mfree(passwd_tmp
);
790 r
= rename_and_apply_smack(shadow_tmp
, shadow_path
);
794 shadow_tmp
= mfree(shadow_tmp
);
800 static int uid_is_ok(uid_t uid
, const char *name
, bool check_with_gid
) {
806 /* Let's see if we already have assigned the UID a second time */
807 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(uid
)))
810 /* Try to avoid using uids that are already used by a group
811 * that doesn't have the same name as our new user. */
812 if (check_with_gid
) {
813 i
= ordered_hashmap_get(todo_gids
, GID_TO_PTR(uid
));
814 if (i
&& !streq(i
->name
, name
))
818 /* Let's check the files directly */
819 if (hashmap_contains(database_uid
, UID_TO_PTR(uid
)))
822 if (check_with_gid
) {
823 n
= hashmap_get(database_gid
, GID_TO_PTR(uid
));
824 if (n
&& !streq(n
, name
))
828 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
834 if (!IN_SET(errno
, 0, ENOENT
))
837 if (check_with_gid
) {
839 g
= getgrgid((gid_t
) uid
);
841 if (!streq(g
->gr_name
, name
))
843 } else if (!IN_SET(errno
, 0, ENOENT
))
851 static int root_stat(const char *p
, struct stat
*st
) {
854 fix
= prefix_roota(arg_root
, p
);
855 if (stat(fix
, st
) < 0)
861 static int read_id_from_file(Item
*i
, uid_t
*_uid
, gid_t
*_gid
) {
863 bool found_uid
= false, found_gid
= false;
869 /* First, try to get the gid directly */
870 if (_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
875 /* Then, try to get the uid directly */
876 if ((_uid
|| (_gid
&& !found_gid
))
878 && root_stat(i
->uid_path
, &st
) >= 0) {
883 /* If we need the gid, but had no success yet, also derive it from the uid path */
884 if (_gid
&& !found_gid
) {
890 /* If that didn't work yet, then let's reuse the gid as uid */
891 if (_uid
&& !found_uid
&& i
->gid_path
) {
896 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
897 uid
= (uid_t
) st
.st_gid
;
919 static int add_user(Item
*i
) {
925 /* Check the database directly */
926 z
= hashmap_get(database_user
, i
->name
);
928 log_debug("User %s already exists.", i
->name
);
929 i
->uid
= PTR_TO_UID(z
);
939 p
= getpwnam(i
->name
);
941 log_debug("User %s already exists.", i
->name
);
945 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
951 if (!IN_SET(errno
, 0, ENOENT
))
952 return log_error_errno(errno
, "Failed to check if user %s already exists: %m", i
->name
);
955 /* Try to use the suggested numeric uid */
957 r
= uid_is_ok(i
->uid
, i
->name
, !i
->id_set_strict
);
959 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
961 log_debug("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
966 /* If that didn't work, try to read it from the specified path */
970 if (read_id_from_file(i
, &c
, NULL
) > 0) {
972 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
973 log_debug("User ID " UID_FMT
" of file not suitable for %s.", c
, i
->name
);
975 r
= uid_is_ok(c
, i
->name
, true);
977 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
982 log_debug("User ID " UID_FMT
" of file for %s is already used.", c
, i
->name
);
987 /* Otherwise, try to reuse the group ID */
988 if (!i
->uid_set
&& i
->gid_set
) {
989 r
= uid_is_ok((uid_t
) i
->gid
, i
->name
, true);
991 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
993 i
->uid
= (uid_t
) i
->gid
;
998 /* And if that didn't work either, let's try to find a free one */
1001 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1003 log_error("No free user ID available for %s.", i
->name
);
1007 r
= uid_is_ok(search_uid
, i
->name
, true);
1009 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1015 i
->uid
= search_uid
;
1018 r
= ordered_hashmap_ensure_allocated(&todo_uids
, NULL
);
1022 r
= ordered_hashmap_put(todo_uids
, UID_TO_PTR(i
->uid
), i
);
1026 i
->todo_user
= true;
1027 log_info("Creating user %s (%s) with uid " UID_FMT
" and gid " GID_FMT
".", i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1032 static int gid_is_ok(gid_t gid
) {
1036 if (ordered_hashmap_get(todo_gids
, GID_TO_PTR(gid
)))
1039 /* Avoid reusing gids that are already used by a different user */
1040 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(gid
)))
1043 if (hashmap_contains(database_gid
, GID_TO_PTR(gid
)))
1046 if (hashmap_contains(database_uid
, UID_TO_PTR(gid
)))
1054 if (!IN_SET(errno
, 0, ENOENT
))
1058 p
= getpwuid((uid_t
) gid
);
1061 if (!IN_SET(errno
, 0, ENOENT
))
1068 static int add_group(Item
*i
) {
1074 /* Check the database directly */
1075 z
= hashmap_get(database_group
, i
->name
);
1077 log_debug("Group %s already exists.", i
->name
);
1078 i
->gid
= PTR_TO_GID(z
);
1083 /* Also check NSS */
1088 g
= getgrnam(i
->name
);
1090 log_debug("Group %s already exists.", i
->name
);
1095 if (!IN_SET(errno
, 0, ENOENT
))
1096 return log_error_errno(errno
, "Failed to check if group %s already exists: %m", i
->name
);
1099 /* Try to use the suggested numeric gid */
1101 r
= gid_is_ok(i
->gid
);
1103 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1104 if (i
->id_set_strict
) {
1105 /* If we require the gid to already exist we can return here:
1106 * r > 0: means the gid does not exist -> fail
1107 * r == 0: means the gid exists -> nothing more to do.
1110 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1111 "Failed to create %s: please create GID %d",
1117 log_debug("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1122 /* Try to reuse the numeric uid, if there's one */
1123 if (!i
->gid_set
&& i
->uid_set
) {
1124 r
= gid_is_ok((gid_t
) i
->uid
);
1126 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1128 i
->gid
= (gid_t
) i
->uid
;
1133 /* If that didn't work, try to read it from the specified path */
1137 if (read_id_from_file(i
, NULL
, &c
) > 0) {
1139 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
1140 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", c
, i
->name
);
1144 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1149 log_debug("Group ID " GID_FMT
" of file for %s already used.", c
, i
->name
);
1154 /* And if that didn't work either, let's try to find a free one */
1157 /* We look for new GIDs in the UID pool! */
1158 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1160 log_error("No free group ID available for %s.", i
->name
);
1164 r
= gid_is_ok(search_uid
);
1166 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1172 i
->gid
= search_uid
;
1175 r
= ordered_hashmap_ensure_allocated(&todo_gids
, NULL
);
1179 r
= ordered_hashmap_put(todo_gids
, GID_TO_PTR(i
->gid
), i
);
1183 i
->todo_group
= true;
1184 log_info("Creating group %s with gid " GID_FMT
".", i
->name
, i
->gid
);
1189 static int process_item(Item
*i
) {
1199 j
= ordered_hashmap_get(groups
, i
->name
);
1200 if (j
&& j
->todo_group
) {
1201 /* When the group with the same name is already in queue,
1202 * use the information about the group and do not create
1203 * duplicated group entry. */
1204 i
->gid_set
= j
->gid_set
;
1206 i
->id_set_strict
= true;
1217 return add_group(i
);
1220 assert_not_reached("Unknown item type");
1224 static void item_free(Item
*i
) {
1232 free(i
->description
);
1238 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1240 static int add_implicit(void) {
1245 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1246 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, members
, iterator
) {
1250 if (!ordered_hashmap_get(users
, *m
)) {
1251 _cleanup_(item_freep
) Item
*j
= NULL
;
1253 r
= ordered_hashmap_ensure_allocated(&users
, &string_hash_ops
);
1262 j
->name
= strdup(*m
);
1266 r
= ordered_hashmap_put(users
, j
->name
, j
);
1270 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1274 if (!(ordered_hashmap_get(users
, g
) ||
1275 ordered_hashmap_get(groups
, g
))) {
1276 _cleanup_(item_freep
) Item
*j
= NULL
;
1278 r
= ordered_hashmap_ensure_allocated(&groups
, &string_hash_ops
);
1286 j
->type
= ADD_GROUP
;
1287 j
->name
= strdup(g
);
1291 r
= ordered_hashmap_put(groups
, j
->name
, j
);
1295 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1303 static bool item_equal(Item
*a
, Item
*b
) {
1307 if (a
->type
!= b
->type
)
1310 if (!streq_ptr(a
->name
, b
->name
))
1313 if (!streq_ptr(a
->uid_path
, b
->uid_path
))
1316 if (!streq_ptr(a
->gid_path
, b
->gid_path
))
1319 if (!streq_ptr(a
->description
, b
->description
))
1322 if (a
->uid_set
!= b
->uid_set
)
1325 if (a
->uid_set
&& a
->uid
!= b
->uid
)
1328 if (a
->gid_set
!= b
->gid_set
)
1331 if (a
->gid_set
&& a
->gid
!= b
->gid
)
1334 if (!streq_ptr(a
->home
, b
->home
))
1337 if (!streq_ptr(a
->shell
, b
->shell
))
1343 static int parse_line(const char *fname
, unsigned line
, const char *buffer
) {
1345 static const Specifier specifier_table
[] = {
1346 { 'm', specifier_machine_id
, NULL
},
1347 { 'b', specifier_boot_id
, NULL
},
1348 { 'H', specifier_host_name
, NULL
},
1349 { 'v', specifier_kernel_release
, NULL
},
1350 { 'T', specifier_tmp_dir
, NULL
},
1351 { 'V', specifier_var_tmp_dir
, NULL
},
1355 _cleanup_free_
char *action
= NULL
,
1356 *name
= NULL
, *resolved_name
= NULL
,
1357 *id
= NULL
, *resolved_id
= NULL
,
1358 *description
= NULL
, *resolved_description
= NULL
,
1359 *home
= NULL
, *resolved_home
= NULL
,
1360 *shell
, *resolved_shell
= NULL
;
1361 _cleanup_(item_freep
) Item
*i
= NULL
;
1373 r
= extract_many_words(&p
, NULL
, EXTRACT_QUOTES
,
1374 &action
, &name
, &id
, &description
, &home
, &shell
, NULL
);
1376 log_error("[%s:%u] Syntax error.", fname
, line
);
1380 log_error("[%s:%u] Missing action and name columns.", fname
, line
);
1384 log_error("[%s:%u] Trailing garbage.", fname
, line
);
1389 if (strlen(action
) != 1) {
1390 log_error("[%s:%u] Unknown modifier '%s'", fname
, line
, action
);
1394 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
)) {
1395 log_error("[%s:%u] Unknown command type '%c'.", fname
, line
, action
[0]);
1400 if (isempty(name
) || streq(name
, "-"))
1404 r
= specifier_printf(name
, specifier_table
, NULL
, &resolved_name
);
1406 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1410 if (!valid_user_group_name(resolved_name
)) {
1411 log_error("[%s:%u] '%s' is not a valid user or group name.", fname
, line
, resolved_name
);
1417 if (isempty(id
) || streq(id
, "-"))
1421 r
= specifier_printf(id
, specifier_table
, NULL
, &resolved_id
);
1423 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1428 /* Verify description */
1429 if (isempty(description
) || streq(description
, "-"))
1430 description
= mfree(description
);
1433 r
= specifier_printf(description
, specifier_table
, NULL
, &resolved_description
);
1435 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, description
);
1439 if (!valid_gecos(resolved_description
)) {
1440 log_error("[%s:%u] '%s' is not a valid GECOS field.", fname
, line
, resolved_description
);
1446 if (isempty(home
) || streq(home
, "-"))
1450 r
= specifier_printf(home
, specifier_table
, NULL
, &resolved_home
);
1452 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, home
);
1456 if (!valid_home(resolved_home
)) {
1457 log_error("[%s:%u] '%s' is not a valid home directory field.", fname
, line
, resolved_home
);
1463 if (isempty(shell
) || streq(shell
, "-"))
1464 shell
= mfree(shell
);
1467 r
= specifier_printf(shell
, specifier_table
, NULL
, &resolved_shell
);
1469 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, shell
);
1473 if (!valid_shell(resolved_shell
)) {
1474 log_error("[%s:%u] '%s' is not a valid login shell field.", fname
, line
, resolved_shell
);
1479 switch (action
[0]) {
1482 if (resolved_name
) {
1483 log_error("[%s:%u] Lines of type 'r' don't take a name field.", fname
, line
);
1488 log_error("[%s:%u] Lines of type 'r' require a ID range in the third field.", fname
, line
);
1492 if (description
|| home
|| shell
) {
1493 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1494 fname
, line
, action
[0],
1495 description
? "GECOS" : home
? "home directory" : "login shell");
1499 r
= uid_range_add_str(&uid_range
, &n_uid_range
, resolved_id
);
1501 log_error("[%s:%u] Invalid UID range %s.", fname
, line
, resolved_id
);
1510 /* Try to extend an existing member or group item */
1512 log_error("[%s:%u] Lines of type 'm' require a user name in the second field.", fname
, line
);
1517 log_error("[%s:%u] Lines of type 'm' require a group name in the third field.", fname
, line
);
1521 if (!valid_user_group_name(resolved_id
)) {
1522 log_error("[%s:%u] '%s' is not a valid user or group name.", fname
, line
, resolved_id
);
1526 if (description
|| home
|| shell
) {
1527 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1528 fname
, line
, action
[0],
1529 description
? "GECOS" : home
? "home directory" : "login shell");
1533 r
= ordered_hashmap_ensure_allocated(&members
, &string_hash_ops
);
1537 l
= ordered_hashmap_get(members
, resolved_id
);
1539 /* A list for this group name already exists, let's append to it */
1540 r
= strv_push(&l
, resolved_name
);
1544 resolved_name
= NULL
;
1546 assert_se(ordered_hashmap_update(members
, resolved_id
, l
) >= 0);
1548 /* No list for this group name exists yet, create one */
1550 l
= new0(char *, 2);
1554 l
[0] = resolved_name
;
1557 r
= ordered_hashmap_put(members
, resolved_id
, l
);
1563 resolved_id
= resolved_name
= NULL
;
1571 log_error("[%s:%u] Lines of type 'u' require a user name in the second field.", fname
, line
);
1575 r
= ordered_hashmap_ensure_allocated(&users
, &string_hash_ops
);
1584 if (path_is_absolute(resolved_id
)) {
1585 i
->uid_path
= TAKE_PTR(resolved_id
);
1586 path_simplify(i
->uid_path
, false);
1588 _cleanup_free_
char *uid
= NULL
, *gid
= NULL
;
1589 if (split_pair(resolved_id
, ":", &uid
, &gid
) == 0) {
1590 r
= parse_gid(gid
, &i
->gid
);
1592 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1594 i
->id_set_strict
= true;
1595 free_and_replace(resolved_id
, uid
);
1597 if (!streq(resolved_id
, "-")) {
1598 r
= parse_uid(resolved_id
, &i
->uid
);
1600 return log_error_errno(r
, "Failed to parse UID: '%s': %m", id
);
1606 i
->description
= TAKE_PTR(resolved_description
);
1607 i
->home
= TAKE_PTR(resolved_home
);
1608 i
->shell
= TAKE_PTR(resolved_shell
);
1615 log_error("[%s:%u] Lines of type 'g' require a user name in the second field.", fname
, line
);
1619 if (description
|| home
|| shell
) {
1620 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1621 fname
, line
, action
[0],
1622 description
? "GECOS" : home
? "home directory" : "login shell");
1626 r
= ordered_hashmap_ensure_allocated(&groups
, &string_hash_ops
);
1635 if (path_is_absolute(resolved_id
)) {
1636 i
->gid_path
= TAKE_PTR(resolved_id
);
1637 path_simplify(i
->gid_path
, false);
1639 r
= parse_gid(resolved_id
, &i
->gid
);
1641 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1654 i
->type
= action
[0];
1655 i
->name
= TAKE_PTR(resolved_name
);
1657 existing
= ordered_hashmap_get(h
, i
->name
);
1660 /* Two identical items are fine */
1661 if (!item_equal(existing
, i
))
1662 log_warning("Two or more conflicting lines for %s configured, ignoring.", i
->name
);
1667 r
= ordered_hashmap_put(h
, i
->name
, i
);
1675 static int read_config_file(const char *fn
, bool ignore_enoent
) {
1676 _cleanup_fclose_
FILE *rf
= NULL
;
1686 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf
);
1688 if (ignore_enoent
&& r
== -ENOENT
)
1691 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
1698 _cleanup_free_
char *line
= NULL
;
1702 k
= read_line(f
, LONG_LINE_MAX
, &line
);
1704 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
1711 if (IN_SET(*l
, 0, '#'))
1714 k
= parse_line(fn
, v
, l
);
1715 if (k
< 0 && r
== 0)
1720 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
1728 static void free_database(Hashmap
*by_name
, Hashmap
*by_id
) {
1732 name
= hashmap_first(by_id
);
1736 hashmap_remove(by_name
, name
);
1738 hashmap_steal_first_key(by_id
);
1742 while ((name
= hashmap_steal_first_key(by_name
)))
1745 hashmap_free(by_name
);
1746 hashmap_free(by_id
);
1749 static int cat_config(void) {
1750 _cleanup_strv_free_
char **files
= NULL
;
1753 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
1757 (void) pager_open(arg_pager_flags
);
1759 return cat_files(NULL
, files
, 0);
1762 static int help(void) {
1763 _cleanup_free_
char *link
= NULL
;
1766 r
= terminal_urlify_man("systemd-sysusers.service", "8", &link
);
1770 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1771 "Creates system user accounts.\n\n"
1772 " -h --help Show this help\n"
1773 " --version Show package version\n"
1774 " --cat-config Show configuration files\n"
1775 " --root=PATH Operate on an alternate filesystem root\n"
1776 " --replace=PATH Treat arguments as replacement for PATH\n"
1777 " --inline Treat arguments as configuration lines\n"
1778 " --no-pager Do not pipe output into a pager\n"
1779 "\nSee the %s for details.\n"
1780 , program_invocation_short_name
1787 static int parse_argv(int argc
, char *argv
[]) {
1790 ARG_VERSION
= 0x100,
1798 static const struct option options
[] = {
1799 { "help", no_argument
, NULL
, 'h' },
1800 { "version", no_argument
, NULL
, ARG_VERSION
},
1801 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
1802 { "root", required_argument
, NULL
, ARG_ROOT
},
1803 { "replace", required_argument
, NULL
, ARG_REPLACE
},
1804 { "inline", no_argument
, NULL
, ARG_INLINE
},
1805 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
1814 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
1824 case ARG_CAT_CONFIG
:
1825 arg_cat_config
= true;
1829 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
1835 if (!path_is_absolute(optarg
) ||
1836 !endswith(optarg
, ".conf"))
1837 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1838 "The argument to --replace= must an absolute path to a config file");
1840 arg_replace
= optarg
;
1848 arg_pager_flags
|= PAGER_DISABLE
;
1855 assert_not_reached("Unhandled option");
1858 if (arg_replace
&& arg_cat_config
)
1859 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1860 "Option --replace= is not supported with --cat-config");
1862 if (arg_replace
&& optind
>= argc
)
1863 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1864 "When --replace= is given, some configuration items must be specified");
1869 static int parse_arguments(char **args
) {
1874 STRV_FOREACH(arg
, args
) {
1876 /* Use (argument):n, where n==1 for the first positional arg */
1877 r
= parse_line("(argument)", pos
, *arg
);
1879 r
= read_config_file(*arg
, false);
1889 static int read_config_files(char **args
) {
1890 _cleanup_strv_free_
char **files
= NULL
;
1891 _cleanup_free_
char *p
= NULL
;
1895 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
1899 STRV_FOREACH(f
, files
)
1900 if (p
&& path_equal(*f
, p
)) {
1901 log_debug("Parsing arguments at position \"%s\"…", *f
);
1903 r
= parse_arguments(args
);
1907 log_debug("Reading config file \"%s\"…", *f
);
1909 /* Just warn, ignore result otherwise */
1910 (void) read_config_file(*f
, true);
1916 int main(int argc
, char *argv
[]) {
1917 _cleanup_close_
int lock
= -1;
1923 r
= parse_argv(argc
, argv
);
1927 log_setup_service();
1929 if (arg_cat_config
) {
1936 r
= mac_selinux_init();
1938 log_error_errno(r
, "SELinux setup failed: %m");
1942 /* If command line arguments are specified along with --replace, read all
1943 * configuration files and insert the positional arguments at the specified
1944 * place. Otherwise, if command line arguments are specified, execute just
1945 * them, and finally, without --replace= or any positional arguments, just
1946 * read configuration and execute it.
1948 if (arg_replace
|| optind
>= argc
)
1949 r
= read_config_files(argv
+ optind
);
1951 r
= parse_arguments(argv
+ optind
);
1955 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our detection
1956 * whether the names or UID/GID area already used otherwise doesn't get confused. After all, even though
1957 * nss-systemd synthesizes these users/groups, they should still appear in /etc/passwd and /etc/group, as the
1958 * synthesizing logic is merely supposed to be fallback for cases where we run with a completely unpopulated
1960 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0) {
1961 r
= log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
1966 /* Default to default range of 1..SYSTEM_UID_MAX */
1967 r
= uid_range_add(&uid_range
, &n_uid_range
, 1, SYSTEM_UID_MAX
);
1978 lock
= take_etc_passwd_lock(arg_root
);
1980 log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
1984 r
= load_user_database();
1986 log_error_errno(r
, "Failed to load user database: %m");
1990 r
= load_group_database();
1992 log_error_errno(r
, "Failed to read group database: %m");
1996 ORDERED_HASHMAP_FOREACH(i
, groups
, iterator
)
1997 (void) process_item(i
);
1999 ORDERED_HASHMAP_FOREACH(i
, users
, iterator
)
2000 (void) process_item(i
);
2004 log_error_errno(r
, "Failed to write files: %m");
2009 ordered_hashmap_free_with_destructor(groups
, item_free
);
2010 ordered_hashmap_free_with_destructor(users
, item_free
);
2012 while ((v
= ordered_hashmap_steal_first_key_and_value(members
, (void **) &n
))) {
2016 ordered_hashmap_free(members
);
2018 ordered_hashmap_free(todo_uids
);
2019 ordered_hashmap_free(todo_gids
);
2021 free_database(database_user
, database_uid
);
2022 free_database(database_group
, database_gid
);
2028 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;