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"
17 #include "fileio-label.h"
18 #include "format-util.h"
20 #include "path-util.h"
21 #include "selinux-util.h"
22 #include "smack-util.h"
23 #include "specifier.h"
24 #include "string-util.h"
26 #include "terminal-util.h"
27 #include "uid-range.h"
28 #include "user-util.h"
32 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;
69 static char **config_dirs
= CONF_PATHS_STRV("sysusers.d");
71 static OrderedHashmap
*users
= NULL
, *groups
= NULL
;
72 static OrderedHashmap
*todo_uids
= NULL
, *todo_gids
= NULL
;
73 static OrderedHashmap
*members
= NULL
;
75 static Hashmap
*database_uid
= NULL
, *database_user
= NULL
;
76 static Hashmap
*database_gid
= NULL
, *database_group
= NULL
;
78 static uid_t search_uid
= UID_INVALID
;
79 static UidRange
*uid_range
= NULL
;
80 static unsigned n_uid_range
= 0;
82 static int load_user_database(void) {
83 _cleanup_fclose_
FILE *f
= NULL
;
84 const char *passwd_path
;
88 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
89 f
= fopen(passwd_path
, "re");
91 return errno
== ENOENT
? 0 : -errno
;
93 r
= hashmap_ensure_allocated(&database_user
, &string_hash_ops
);
97 r
= hashmap_ensure_allocated(&database_uid
, NULL
);
101 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
105 n
= strdup(pw
->pw_name
);
109 k
= hashmap_put(database_user
, n
, UID_TO_PTR(pw
->pw_uid
));
110 if (k
< 0 && k
!= -EEXIST
) {
115 q
= hashmap_put(database_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
116 if (q
< 0 && q
!= -EEXIST
) {
122 if (k
<= 0 && q
<= 0)
128 static int load_group_database(void) {
129 _cleanup_fclose_
FILE *f
= NULL
;
130 const char *group_path
;
134 group_path
= prefix_roota(arg_root
, "/etc/group");
135 f
= fopen(group_path
, "re");
137 return errno
== ENOENT
? 0 : -errno
;
139 r
= hashmap_ensure_allocated(&database_group
, &string_hash_ops
);
143 r
= hashmap_ensure_allocated(&database_gid
, NULL
);
148 while ((gr
= fgetgrent(f
))) {
152 n
= strdup(gr
->gr_name
);
156 k
= hashmap_put(database_group
, n
, GID_TO_PTR(gr
->gr_gid
));
157 if (k
< 0 && k
!= -EEXIST
) {
162 q
= hashmap_put(database_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
163 if (q
< 0 && q
!= -EEXIST
) {
169 if (k
<= 0 && q
<= 0)
174 if (!IN_SET(errno
, 0, ENOENT
))
180 static int make_backup(const char *target
, const char *x
) {
181 _cleanup_close_
int src
= -1;
182 _cleanup_fclose_
FILE *dst
= NULL
;
183 _cleanup_free_
char *temp
= NULL
;
185 struct timespec ts
[2];
189 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
191 if (errno
== ENOENT
) /* No backup necessary... */
197 if (fstat(src
, &st
) < 0)
200 r
= fopen_temporary_label(target
, x
, &dst
, &temp
);
204 r
= copy_bytes(src
, fileno(dst
), (uint64_t) -1, COPY_REFLINK
);
208 /* Don't fail on chmod() or chown(). If it stays owned by us
209 * and/or unreadable by others, then it isn't too bad... */
211 backup
= strjoina(x
, "-");
213 /* Copy over the access mask */
214 if (fchmod(fileno(dst
), st
.st_mode
& 07777) < 0)
215 log_warning_errno(errno
, "Failed to change mode on %s: %m", backup
);
217 if (fchown(fileno(dst
), st
.st_uid
, st
.st_gid
)< 0)
218 log_warning_errno(errno
, "Failed to change ownership of %s: %m", backup
);
222 if (futimens(fileno(dst
), ts
) < 0)
223 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
225 r
= fflush_sync_and_check(dst
);
229 if (rename(temp
, backup
) < 0) {
241 static int putgrent_with_members(const struct group
*gr
, FILE *group
) {
247 a
= ordered_hashmap_get(members
, gr
->gr_name
);
249 _cleanup_strv_free_
char **l
= NULL
;
253 l
= strv_copy(gr
->gr_mem
);
258 if (strv_find(l
, *i
))
261 if (strv_extend(&l
, *i
) < 0)
277 r
= putgrent_sane(&t
, group
);
278 return r
< 0 ? r
: 1;
282 return putgrent_sane(gr
, group
);
286 static int putsgent_with_members(const struct sgrp
*sg
, FILE *gshadow
) {
292 a
= ordered_hashmap_get(members
, sg
->sg_namp
);
294 _cleanup_strv_free_
char **l
= NULL
;
298 l
= strv_copy(sg
->sg_mem
);
303 if (strv_find(l
, *i
))
306 if (strv_extend(&l
, *i
) < 0)
322 r
= putsgent_sane(&t
, gshadow
);
323 return r
< 0 ? r
: 1;
327 return putsgent_sane(sg
, gshadow
);
331 static int sync_rights(FILE *from
, FILE *to
) {
334 if (fstat(fileno(from
), &st
) < 0)
337 if (fchmod(fileno(to
), st
.st_mode
& 07777) < 0)
340 if (fchown(fileno(to
), st
.st_uid
, st
.st_gid
) < 0)
346 static int rename_and_apply_smack(const char *temp_path
, const char *dest_path
) {
348 if (rename(temp_path
, dest_path
) < 0)
351 #ifdef SMACK_RUN_LABEL
352 r
= mac_smack_apply(dest_path
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);
359 static const char* default_shell(uid_t uid
) {
360 return uid
== 0 ? "/bin/sh" : "/sbin/nologin";
363 static int write_temporary_passwd(const char *passwd_path
, FILE **tmpfile
, char **tmpfile_path
) {
364 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
365 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
366 struct passwd
*pw
= NULL
;
371 if (ordered_hashmap_size(todo_uids
) == 0)
374 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
378 original
= fopen(passwd_path
, "re");
381 r
= sync_rights(original
, passwd
);
385 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
387 i
= ordered_hashmap_get(users
, pw
->pw_name
);
388 if (i
&& i
->todo_user
) {
389 log_error("%s: User \"%s\" already exists.", passwd_path
, pw
->pw_name
);
393 if (ordered_hashmap_contains(todo_uids
, UID_TO_PTR(pw
->pw_uid
))) {
394 log_error("%s: Detected collision for UID " UID_FMT
".", passwd_path
, pw
->pw_uid
);
398 /* Make sure we keep the NIS entries (if any) at the end. */
399 if (IN_SET(pw
->pw_name
[0], '+', '-'))
402 r
= putpwent_sane(pw
, passwd
);
412 if (fchmod(fileno(passwd
), 0644) < 0)
416 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
421 .pw_gecos
= i
->description
,
423 /* "x" means the password is stored in the shadow file */
424 .pw_passwd
= (char*) "x",
426 /* We default to the root directory as home */
427 .pw_dir
= i
->home
? i
->home
: (char*) "/",
429 /* Initialize the shell to nologin, with one exception:
430 * for root we patch in something special */
431 .pw_shell
= i
->shell
?: (char*) default_shell(i
->uid
),
434 r
= putpwent_sane(&n
, passwd
);
439 /* Append the remaining NIS entries if any */
441 r
= putpwent_sane(pw
, passwd
);
445 r
= fgetpwent_sane(original
, &pw
);
452 r
= fflush_and_check(passwd
);
456 *tmpfile
= TAKE_PTR(passwd
);
457 *tmpfile_path
= TAKE_PTR(passwd_tmp
);
462 static int write_temporary_shadow(const char *shadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
463 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
464 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
465 struct spwd
*sp
= NULL
;
471 if (ordered_hashmap_size(todo_uids
) == 0)
474 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
478 lstchg
= (long) (now(CLOCK_REALTIME
) / USEC_PER_DAY
);
480 original
= fopen(shadow_path
, "re");
483 r
= sync_rights(original
, shadow
);
487 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
489 i
= ordered_hashmap_get(users
, sp
->sp_namp
);
490 if (i
&& i
->todo_user
) {
491 /* we will update the existing entry */
492 sp
->sp_lstchg
= lstchg
;
494 /* only the /etc/shadow stage is left, so we can
495 * safely remove the item from the todo set */
496 i
->todo_user
= false;
497 ordered_hashmap_remove(todo_uids
, UID_TO_PTR(i
->uid
));
500 /* Make sure we keep the NIS entries (if any) at the end. */
501 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
504 r
= putspent_sane(sp
, shadow
);
514 if (fchmod(fileno(shadow
), 0000) < 0)
518 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
521 .sp_pwdp
= (char*) "!!",
528 .sp_flag
= (unsigned long) -1, /* this appears to be what everybody does ... */
531 r
= putspent_sane(&n
, shadow
);
536 /* Append the remaining NIS entries if any */
538 r
= putspent_sane(sp
, shadow
);
542 r
= fgetspent_sane(original
, &sp
);
548 if (!IN_SET(errno
, 0, ENOENT
))
551 r
= fflush_sync_and_check(shadow
);
555 *tmpfile
= TAKE_PTR(shadow
);
556 *tmpfile_path
= TAKE_PTR(shadow_tmp
);
561 static int write_temporary_group(const char *group_path
, FILE **tmpfile
, char **tmpfile_path
) {
562 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
563 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
564 bool group_changed
= false;
565 struct group
*gr
= NULL
;
570 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
573 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
577 original
= fopen(group_path
, "re");
580 r
= sync_rights(original
, group
);
584 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
585 /* Safety checks against name and GID collisions. Normally,
586 * this should be unnecessary, but given that we look at the
587 * entries anyway here, let's make an extra verification
588 * step that we don't generate duplicate entries. */
590 i
= ordered_hashmap_get(groups
, gr
->gr_name
);
591 if (i
&& i
->todo_group
) {
592 log_error("%s: Group \"%s\" already exists.", group_path
, gr
->gr_name
);
596 if (ordered_hashmap_contains(todo_gids
, GID_TO_PTR(gr
->gr_gid
))) {
597 log_error("%s: Detected collision for GID " GID_FMT
".", group_path
, gr
->gr_gid
);
601 /* Make sure we keep the NIS entries (if any) at the end. */
602 if (IN_SET(gr
->gr_name
[0], '+', '-'))
605 r
= putgrent_with_members(gr
, group
);
609 group_changed
= true;
617 if (fchmod(fileno(group
), 0644) < 0)
621 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
625 .gr_passwd
= (char*) "x",
628 r
= putgrent_with_members(&n
, group
);
632 group_changed
= true;
635 /* Append the remaining NIS entries if any */
637 r
= putgrent_sane(gr
, group
);
641 r
= fgetgrent_sane(original
, &gr
);
648 r
= fflush_sync_and_check(group
);
653 *tmpfile
= TAKE_PTR(group
);
654 *tmpfile_path
= TAKE_PTR(group_tmp
);
659 static int write_temporary_gshadow(const char * gshadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
661 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
662 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
663 bool group_changed
= false;
668 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
671 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
675 original
= fopen(gshadow_path
, "re");
679 r
= sync_rights(original
, gshadow
);
683 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
685 i
= ordered_hashmap_get(groups
, sg
->sg_namp
);
686 if (i
&& i
->todo_group
) {
687 log_error("%s: Group \"%s\" already exists.", gshadow_path
, sg
->sg_namp
);
691 r
= putsgent_with_members(sg
, gshadow
);
695 group_changed
= true;
703 if (fchmod(fileno(gshadow
), 0000) < 0)
707 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
710 .sg_passwd
= (char*) "!!",
713 r
= putsgent_with_members(&n
, gshadow
);
717 group_changed
= true;
720 r
= fflush_sync_and_check(gshadow
);
725 *tmpfile
= TAKE_PTR(gshadow
);
726 *tmpfile_path
= TAKE_PTR(gshadow_tmp
);
734 static int write_files(void) {
735 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
736 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
737 const char *passwd_path
= NULL
, *group_path
= NULL
, *shadow_path
= NULL
, *gshadow_path
= NULL
;
740 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
741 shadow_path
= prefix_roota(arg_root
, "/etc/shadow");
742 group_path
= prefix_roota(arg_root
, "/etc/group");
743 gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
745 r
= write_temporary_group(group_path
, &group
, &group_tmp
);
749 r
= write_temporary_gshadow(gshadow_path
, &gshadow
, &gshadow_tmp
);
753 r
= write_temporary_passwd(passwd_path
, &passwd
, &passwd_tmp
);
757 r
= write_temporary_shadow(shadow_path
, &shadow
, &shadow_tmp
);
761 /* Make a backup of the old files */
763 r
= make_backup("/etc/group", group_path
);
768 r
= make_backup("/etc/gshadow", gshadow_path
);
774 r
= make_backup("/etc/passwd", passwd_path
);
779 r
= make_backup("/etc/shadow", shadow_path
);
784 /* And make the new files count */
786 r
= rename_and_apply_smack(group_tmp
, group_path
);
790 group_tmp
= mfree(group_tmp
);
793 r
= rename_and_apply_smack(gshadow_tmp
, gshadow_path
);
797 gshadow_tmp
= mfree(gshadow_tmp
);
801 r
= rename_and_apply_smack(passwd_tmp
, passwd_path
);
805 passwd_tmp
= mfree(passwd_tmp
);
808 r
= rename_and_apply_smack(shadow_tmp
, shadow_path
);
812 shadow_tmp
= mfree(shadow_tmp
);
818 static int uid_is_ok(uid_t uid
, const char *name
, bool check_with_gid
) {
824 /* Let's see if we already have assigned the UID a second time */
825 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(uid
)))
828 /* Try to avoid using uids that are already used by a group
829 * that doesn't have the same name as our new user. */
830 if (check_with_gid
) {
831 i
= ordered_hashmap_get(todo_gids
, GID_TO_PTR(uid
));
832 if (i
&& !streq(i
->name
, name
))
836 /* Let's check the files directly */
837 if (hashmap_contains(database_uid
, UID_TO_PTR(uid
)))
840 if (check_with_gid
) {
841 n
= hashmap_get(database_gid
, GID_TO_PTR(uid
));
842 if (n
&& !streq(n
, name
))
846 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
852 if (!IN_SET(errno
, 0, ENOENT
))
855 if (check_with_gid
) {
857 g
= getgrgid((gid_t
) uid
);
859 if (!streq(g
->gr_name
, name
))
861 } else if (!IN_SET(errno
, 0, ENOENT
))
869 static int root_stat(const char *p
, struct stat
*st
) {
872 fix
= prefix_roota(arg_root
, p
);
873 if (stat(fix
, st
) < 0)
879 static int read_id_from_file(Item
*i
, uid_t
*_uid
, gid_t
*_gid
) {
881 bool found_uid
= false, found_gid
= false;
887 /* First, try to get the gid directly */
888 if (_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
893 /* Then, try to get the uid directly */
894 if ((_uid
|| (_gid
&& !found_gid
))
896 && root_stat(i
->uid_path
, &st
) >= 0) {
901 /* If we need the gid, but had no success yet, also derive it from the uid path */
902 if (_gid
&& !found_gid
) {
908 /* If that didn't work yet, then let's reuse the gid as uid */
909 if (_uid
&& !found_uid
&& i
->gid_path
) {
914 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
915 uid
= (uid_t
) st
.st_gid
;
937 static int add_user(Item
*i
) {
943 /* Check the database directly */
944 z
= hashmap_get(database_user
, i
->name
);
946 log_debug("User %s already exists.", i
->name
);
947 i
->uid
= PTR_TO_UID(z
);
957 p
= getpwnam(i
->name
);
959 log_debug("User %s already exists.", i
->name
);
963 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
969 if (!IN_SET(errno
, 0, ENOENT
))
970 return log_error_errno(errno
, "Failed to check if user %s already exists: %m", i
->name
);
973 /* Try to use the suggested numeric uid */
975 r
= uid_is_ok(i
->uid
, i
->name
, !i
->id_set_strict
);
977 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
979 log_debug("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
984 /* If that didn't work, try to read it from the specified path */
988 if (read_id_from_file(i
, &c
, NULL
) > 0) {
990 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
991 log_debug("User ID " UID_FMT
" of file not suitable for %s.", c
, i
->name
);
993 r
= uid_is_ok(c
, i
->name
, true);
995 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1000 log_debug("User ID " UID_FMT
" of file for %s is already used.", c
, i
->name
);
1005 /* Otherwise, try to reuse the group ID */
1006 if (!i
->uid_set
&& i
->gid_set
) {
1007 r
= uid_is_ok((uid_t
) i
->gid
, i
->name
, true);
1009 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1011 i
->uid
= (uid_t
) i
->gid
;
1016 /* And if that didn't work either, let's try to find a free one */
1019 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1021 log_error("No free user ID available for %s.", i
->name
);
1025 r
= uid_is_ok(search_uid
, i
->name
, true);
1027 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1033 i
->uid
= search_uid
;
1036 r
= ordered_hashmap_ensure_allocated(&todo_uids
, NULL
);
1040 r
= ordered_hashmap_put(todo_uids
, UID_TO_PTR(i
->uid
), i
);
1044 i
->todo_user
= true;
1045 log_info("Creating user %s (%s) with uid " UID_FMT
" and gid " GID_FMT
".", i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1050 static int gid_is_ok(gid_t gid
) {
1054 if (ordered_hashmap_get(todo_gids
, GID_TO_PTR(gid
)))
1057 /* Avoid reusing gids that are already used by a different user */
1058 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(gid
)))
1061 if (hashmap_contains(database_gid
, GID_TO_PTR(gid
)))
1064 if (hashmap_contains(database_uid
, UID_TO_PTR(gid
)))
1072 if (!IN_SET(errno
, 0, ENOENT
))
1076 p
= getpwuid((uid_t
) gid
);
1079 if (!IN_SET(errno
, 0, ENOENT
))
1086 static int add_group(Item
*i
) {
1092 /* Check the database directly */
1093 z
= hashmap_get(database_group
, i
->name
);
1095 log_debug("Group %s already exists.", i
->name
);
1096 i
->gid
= PTR_TO_GID(z
);
1101 /* Also check NSS */
1106 g
= getgrnam(i
->name
);
1108 log_debug("Group %s already exists.", i
->name
);
1113 if (!IN_SET(errno
, 0, ENOENT
))
1114 return log_error_errno(errno
, "Failed to check if group %s already exists: %m", i
->name
);
1117 /* Try to use the suggested numeric gid */
1119 r
= gid_is_ok(i
->gid
);
1121 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1122 if (i
->id_set_strict
) {
1123 /* If we require the gid to already exist we can return here:
1124 * r > 0: means the gid does not exist -> fail
1125 * r == 0: means the gid exists -> nothing more to do.
1128 log_error("Failed to create %s: please create GID %d", i
->name
, i
->gid
);
1135 log_debug("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1140 /* Try to reuse the numeric uid, if there's one */
1141 if (!i
->gid_set
&& i
->uid_set
) {
1142 r
= gid_is_ok((gid_t
) i
->uid
);
1144 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1146 i
->gid
= (gid_t
) i
->uid
;
1151 /* If that didn't work, try to read it from the specified path */
1155 if (read_id_from_file(i
, NULL
, &c
) > 0) {
1157 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
1158 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", c
, i
->name
);
1162 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1167 log_debug("Group ID " GID_FMT
" of file for %s already used.", c
, i
->name
);
1172 /* And if that didn't work either, let's try to find a free one */
1175 /* We look for new GIDs in the UID pool! */
1176 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1178 log_error("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 void item_free(Item
*i
) {
1250 free(i
->description
);
1256 DEFINE_TRIVIAL_CLEANUP_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
, &string_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
, &string_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 static int parse_line(const char *fname
, unsigned line
, const char *buffer
) {
1363 static const Specifier specifier_table
[] = {
1364 { 'm', specifier_machine_id
, NULL
},
1365 { 'b', specifier_boot_id
, NULL
},
1366 { 'H', specifier_host_name
, NULL
},
1367 { 'v', specifier_kernel_release
, NULL
},
1371 _cleanup_free_
char *action
= NULL
,
1372 *name
= NULL
, *resolved_name
= NULL
,
1373 *id
= NULL
, *resolved_id
= NULL
,
1374 *description
= NULL
,
1376 *shell
, *resolved_shell
= NULL
;
1377 _cleanup_(item_freep
) Item
*i
= NULL
;
1389 r
= extract_many_words(&p
, NULL
, EXTRACT_QUOTES
,
1390 &action
, &name
, &id
, &description
, &home
, &shell
, NULL
);
1392 log_error("[%s:%u] Syntax error.", fname
, line
);
1396 log_error("[%s:%u] Missing action and name columns.", fname
, line
);
1400 log_error("[%s:%u] Trailing garbage.", fname
, line
);
1405 if (strlen(action
) != 1) {
1406 log_error("[%s:%u] Unknown modifier '%s'", fname
, line
, action
);
1410 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
)) {
1411 log_error("[%s:%u] Unknown command type '%c'.", fname
, line
, action
[0]);
1416 if (isempty(name
) || streq(name
, "-"))
1420 r
= specifier_printf(name
, specifier_table
, NULL
, &resolved_name
);
1422 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1426 if (!valid_user_group_name(resolved_name
)) {
1427 log_error("[%s:%u] '%s' is not a valid user or group name.", fname
, line
, resolved_name
);
1433 if (isempty(id
) || streq(id
, "-"))
1437 r
= specifier_printf(id
, specifier_table
, NULL
, &resolved_id
);
1439 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1444 /* Verify description */
1445 if (isempty(description
) || streq(description
, "-"))
1446 description
= mfree(description
);
1449 if (!valid_gecos(description
)) {
1450 log_error("[%s:%u] '%s' is not a valid GECOS field.", fname
, line
, description
);
1456 if (isempty(home
) || streq(home
, "-"))
1460 if (!valid_home(home
)) {
1461 log_error("[%s:%u] '%s' is not a valid home directory field.", fname
, line
, home
);
1467 if (isempty(shell
) || streq(shell
, "-"))
1468 shell
= mfree(shell
);
1471 r
= specifier_printf(shell
, specifier_table
, NULL
, &resolved_shell
);
1473 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, shell
);
1477 if (!valid_shell(resolved_shell
)) {
1478 log_error("[%s:%u] '%s' is not a valid login shell field.", fname
, line
, resolved_shell
);
1483 switch (action
[0]) {
1486 if (resolved_name
) {
1487 log_error("[%s:%u] Lines of type 'r' don't take a name field.", fname
, line
);
1492 log_error("[%s:%u] Lines of type 'r' require a ID range in the third field.", fname
, line
);
1496 if (description
|| home
|| shell
) {
1497 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1498 fname
, line
, action
[0],
1499 description
? "GECOS" : home
? "home directory" : "login shell");
1503 r
= uid_range_add_str(&uid_range
, &n_uid_range
, resolved_id
);
1505 log_error("[%s:%u] Invalid UID range %s.", fname
, line
, resolved_id
);
1514 /* Try to extend an existing member or group item */
1516 log_error("[%s:%u] Lines of type 'm' require a user name in the second field.", fname
, line
);
1521 log_error("[%s:%u] Lines of type 'm' require a group name in the third field.", fname
, line
);
1525 if (!valid_user_group_name(resolved_id
)) {
1526 log_error("[%s:%u] '%s' is not a valid user or group name.", fname
, line
, resolved_id
);
1530 if (description
|| home
|| shell
) {
1531 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1532 fname
, line
, action
[0],
1533 description
? "GECOS" : home
? "home directory" : "login shell");
1537 r
= ordered_hashmap_ensure_allocated(&members
, &string_hash_ops
);
1541 l
= ordered_hashmap_get(members
, resolved_id
);
1543 /* A list for this group name already exists, let's append to it */
1544 r
= strv_push(&l
, resolved_name
);
1548 resolved_name
= NULL
;
1550 assert_se(ordered_hashmap_update(members
, resolved_id
, l
) >= 0);
1552 /* No list for this group name exists yet, create one */
1554 l
= new0(char *, 2);
1558 l
[0] = resolved_name
;
1561 r
= ordered_hashmap_put(members
, resolved_id
, l
);
1567 resolved_id
= resolved_name
= NULL
;
1575 log_error("[%s:%u] Lines of type 'u' require a user name in the second field.", fname
, line
);
1579 r
= ordered_hashmap_ensure_allocated(&users
, &string_hash_ops
);
1588 if (path_is_absolute(resolved_id
)) {
1589 i
->uid_path
= TAKE_PTR(resolved_id
);
1591 path_kill_slashes(i
->uid_path
);
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(description
);
1612 i
->home
= TAKE_PTR(home
);
1613 i
->shell
= TAKE_PTR(resolved_shell
);
1620 log_error("[%s:%u] Lines of type 'g' require a user name in the second field.", fname
, line
);
1624 if (description
|| home
|| shell
) {
1625 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1626 fname
, line
, action
[0],
1627 description
? "GECOS" : home
? "home directory" : "login shell");
1631 r
= ordered_hashmap_ensure_allocated(&groups
, &string_hash_ops
);
1640 if (path_is_absolute(resolved_id
)) {
1641 i
->gid_path
= TAKE_PTR(resolved_id
);
1643 path_kill_slashes(i
->gid_path
);
1645 r
= parse_gid(resolved_id
, &i
->gid
);
1647 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1660 i
->type
= action
[0];
1661 i
->name
= TAKE_PTR(resolved_name
);
1663 existing
= ordered_hashmap_get(h
, i
->name
);
1666 /* Two identical items are fine */
1667 if (!item_equal(existing
, i
))
1668 log_warning("Two or more conflicting lines for %s configured, ignoring.", i
->name
);
1673 r
= ordered_hashmap_put(h
, i
->name
, i
);
1681 static int read_config_file(const char *fn
, bool ignore_enoent
) {
1682 _cleanup_fclose_
FILE *rf
= NULL
;
1684 char line
[LINE_MAX
];
1693 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) config_dirs
, &rf
);
1695 if (ignore_enoent
&& r
== -ENOENT
)
1698 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
1704 FOREACH_LINE(line
, f
, break) {
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
;
1751 _cleanup_free_
char *replace_file
= NULL
;
1754 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, NULL
);
1758 return cat_files(NULL
, files
, 0);
1761 static void help(void) {
1762 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1763 "Creates system user accounts.\n\n"
1764 " -h --help Show this help\n"
1765 " --version Show package version\n"
1766 " --cat-config Show configuration files\n"
1767 " --root=PATH Operate on an alternate filesystem root\n"
1768 " --replace=PATH Treat arguments as replacement for PATH\n"
1769 " --inline Treat arguments as configuration lines\n"
1770 , program_invocation_short_name
);
1773 static int parse_argv(int argc
, char *argv
[]) {
1776 ARG_VERSION
= 0x100,
1783 static const struct option options
[] = {
1784 { "help", no_argument
, NULL
, 'h' },
1785 { "version", no_argument
, NULL
, ARG_VERSION
},
1786 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
1787 { "root", required_argument
, NULL
, ARG_ROOT
},
1788 { "replace", required_argument
, NULL
, ARG_REPLACE
},
1789 { "inline", no_argument
, NULL
, ARG_INLINE
},
1798 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
1809 case ARG_CAT_CONFIG
:
1810 arg_cat_config
= true;
1814 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
1820 if (!path_is_absolute(optarg
) ||
1821 !endswith(optarg
, ".conf")) {
1822 log_error("The argument to --replace= must an absolute path to a config file");
1826 arg_replace
= optarg
;
1837 assert_not_reached("Unhandled option");
1840 if (arg_replace
&& arg_cat_config
) {
1841 log_error("Option --replace= is not supported with --cat-config");
1845 if (arg_replace
&& optind
>= argc
) {
1846 log_error("When --replace= is given, some configuration items must be specified");
1853 static int parse_arguments(char **args
) {
1858 STRV_FOREACH(arg
, args
) {
1860 /* Use (argument):n, where n==1 for the first positional arg */
1861 r
= parse_line("(argument)", pos
, *arg
);
1863 r
= read_config_file(*arg
, false);
1873 static int read_config_files(char **args
) {
1874 _cleanup_strv_free_
char **files
= NULL
;
1875 _cleanup_free_
char *p
= NULL
;
1879 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, &p
);
1883 STRV_FOREACH(f
, files
)
1884 if (p
&& path_equal(*f
, p
)) {
1885 log_debug("Parsing arguments at position \"%s\"…", *f
);
1887 r
= parse_arguments(args
);
1891 log_debug("Reading config file \"%s\"…", *f
);
1893 /* Just warn, ignore result otherwise */
1894 (void) read_config_file(*f
, true);
1900 int main(int argc
, char *argv
[]) {
1901 _cleanup_close_
int lock
= -1;
1907 r
= parse_argv(argc
, argv
);
1911 log_set_target(LOG_TARGET_AUTO
);
1912 log_parse_environment();
1915 if (arg_cat_config
) {
1922 r
= mac_selinux_init();
1924 log_error_errno(r
, "SELinux setup failed: %m");
1928 /* If command line arguments are specified along with --replace, read all
1929 * configuration files and insert the positional arguments at the specified
1930 * place. Otherwise, if command line arguments are specified, execute just
1931 * them, and finally, without --replace= or any positional arguments, just
1932 * read configuration and execute it.
1934 if (arg_replace
|| optind
>= argc
)
1935 r
= read_config_files(argv
+ optind
);
1937 r
= parse_arguments(argv
+ optind
);
1941 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our detection
1942 * whether the names or UID/GID area already used otherwise doesn't get confused. After all, even though
1943 * nss-systemd synthesizes these users/groups, they should still appear in /etc/passwd and /etc/group, as the
1944 * synthesizing logic is merely supposed to be fallback for cases where we run with a completely unpopulated
1946 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0) {
1947 r
= log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
1952 /* Default to default range of 1..SYSTEM_UID_MAX */
1953 r
= uid_range_add(&uid_range
, &n_uid_range
, 1, SYSTEM_UID_MAX
);
1964 lock
= take_etc_passwd_lock(arg_root
);
1966 log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
1970 r
= load_user_database();
1972 log_error_errno(r
, "Failed to load user database: %m");
1976 r
= load_group_database();
1978 log_error_errno(r
, "Failed to read group database: %m");
1982 ORDERED_HASHMAP_FOREACH(i
, groups
, iterator
)
1983 (void) process_item(i
);
1985 ORDERED_HASHMAP_FOREACH(i
, users
, iterator
)
1986 (void) process_item(i
);
1990 log_error_errno(r
, "Failed to write files: %m");
1993 ordered_hashmap_free_with_destructor(groups
, item_free
);
1994 ordered_hashmap_free_with_destructor(users
, item_free
);
1996 while ((n
= ordered_hashmap_first_key(members
))) {
1997 strv_free(ordered_hashmap_steal_first(members
));
2000 ordered_hashmap_free(members
);
2002 ordered_hashmap_free(todo_uids
);
2003 ordered_hashmap_free(todo_gids
);
2005 free_database(database_user
, database_uid
);
2006 free_database(database_group
, database_gid
);
2012 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;