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 OrderedHashmap
*users
= NULL
, *groups
= NULL
;
70 static OrderedHashmap
*todo_uids
= NULL
, *todo_gids
= NULL
;
71 static OrderedHashmap
*members
= NULL
;
73 static Hashmap
*database_uid
= NULL
, *database_user
= NULL
;
74 static Hashmap
*database_gid
= NULL
, *database_group
= NULL
;
76 static uid_t search_uid
= UID_INVALID
;
77 static UidRange
*uid_range
= NULL
;
78 static unsigned n_uid_range
= 0;
80 static int load_user_database(void) {
81 _cleanup_fclose_
FILE *f
= NULL
;
82 const char *passwd_path
;
86 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
87 f
= fopen(passwd_path
, "re");
89 return errno
== ENOENT
? 0 : -errno
;
91 r
= hashmap_ensure_allocated(&database_user
, &string_hash_ops
);
95 r
= hashmap_ensure_allocated(&database_uid
, NULL
);
99 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
103 n
= strdup(pw
->pw_name
);
107 k
= hashmap_put(database_user
, n
, UID_TO_PTR(pw
->pw_uid
));
108 if (k
< 0 && k
!= -EEXIST
) {
113 q
= hashmap_put(database_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
114 if (q
< 0 && q
!= -EEXIST
) {
120 if (k
<= 0 && q
<= 0)
126 static int load_group_database(void) {
127 _cleanup_fclose_
FILE *f
= NULL
;
128 const char *group_path
;
132 group_path
= prefix_roota(arg_root
, "/etc/group");
133 f
= fopen(group_path
, "re");
135 return errno
== ENOENT
? 0 : -errno
;
137 r
= hashmap_ensure_allocated(&database_group
, &string_hash_ops
);
141 r
= hashmap_ensure_allocated(&database_gid
, NULL
);
146 while ((gr
= fgetgrent(f
))) {
150 n
= strdup(gr
->gr_name
);
154 k
= hashmap_put(database_group
, n
, GID_TO_PTR(gr
->gr_gid
));
155 if (k
< 0 && k
!= -EEXIST
) {
160 q
= hashmap_put(database_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
161 if (q
< 0 && q
!= -EEXIST
) {
167 if (k
<= 0 && q
<= 0)
172 if (!IN_SET(errno
, 0, ENOENT
))
178 static int make_backup(const char *target
, const char *x
) {
179 _cleanup_close_
int src
= -1;
180 _cleanup_fclose_
FILE *dst
= NULL
;
181 _cleanup_free_
char *temp
= NULL
;
183 struct timespec ts
[2];
187 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
189 if (errno
== ENOENT
) /* No backup necessary... */
195 if (fstat(src
, &st
) < 0)
198 r
= fopen_temporary_label(target
, x
, &dst
, &temp
);
202 r
= copy_bytes(src
, fileno(dst
), (uint64_t) -1, COPY_REFLINK
);
206 /* Don't fail on chmod() or chown(). If it stays owned by us
207 * and/or unreadable by others, then it isn't too bad... */
209 backup
= strjoina(x
, "-");
211 /* Copy over the access mask */
212 if (fchmod(fileno(dst
), st
.st_mode
& 07777) < 0)
213 log_warning_errno(errno
, "Failed to change mode on %s: %m", backup
);
215 if (fchown(fileno(dst
), st
.st_uid
, st
.st_gid
)< 0)
216 log_warning_errno(errno
, "Failed to change ownership of %s: %m", backup
);
220 if (futimens(fileno(dst
), ts
) < 0)
221 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
223 r
= fflush_sync_and_check(dst
);
227 if (rename(temp
, backup
) < 0) {
239 static int putgrent_with_members(const struct group
*gr
, FILE *group
) {
245 a
= ordered_hashmap_get(members
, gr
->gr_name
);
247 _cleanup_strv_free_
char **l
= NULL
;
251 l
= strv_copy(gr
->gr_mem
);
256 if (strv_find(l
, *i
))
259 if (strv_extend(&l
, *i
) < 0)
275 r
= putgrent_sane(&t
, group
);
276 return r
< 0 ? r
: 1;
280 return putgrent_sane(gr
, group
);
284 static int putsgent_with_members(const struct sgrp
*sg
, FILE *gshadow
) {
290 a
= ordered_hashmap_get(members
, sg
->sg_namp
);
292 _cleanup_strv_free_
char **l
= NULL
;
296 l
= strv_copy(sg
->sg_mem
);
301 if (strv_find(l
, *i
))
304 if (strv_extend(&l
, *i
) < 0)
320 r
= putsgent_sane(&t
, gshadow
);
321 return r
< 0 ? r
: 1;
325 return putsgent_sane(sg
, gshadow
);
329 static int sync_rights(FILE *from
, FILE *to
) {
332 if (fstat(fileno(from
), &st
) < 0)
335 if (fchmod(fileno(to
), st
.st_mode
& 07777) < 0)
338 if (fchown(fileno(to
), st
.st_uid
, st
.st_gid
) < 0)
344 static int rename_and_apply_smack(const char *temp_path
, const char *dest_path
) {
346 if (rename(temp_path
, dest_path
) < 0)
349 #ifdef SMACK_RUN_LABEL
350 r
= mac_smack_apply(dest_path
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);
357 static const char* default_shell(uid_t uid
) {
358 return uid
== 0 ? "/bin/sh" : "/sbin/nologin";
361 static int write_temporary_passwd(const char *passwd_path
, FILE **tmpfile
, char **tmpfile_path
) {
362 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
363 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
364 struct passwd
*pw
= NULL
;
369 if (ordered_hashmap_size(todo_uids
) == 0)
372 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
376 original
= fopen(passwd_path
, "re");
379 r
= sync_rights(original
, passwd
);
383 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
385 i
= ordered_hashmap_get(users
, pw
->pw_name
);
386 if (i
&& i
->todo_user
) {
387 log_error("%s: User \"%s\" already exists.", passwd_path
, pw
->pw_name
);
391 if (ordered_hashmap_contains(todo_uids
, UID_TO_PTR(pw
->pw_uid
))) {
392 log_error("%s: Detected collision for UID " UID_FMT
".", passwd_path
, pw
->pw_uid
);
396 /* Make sure we keep the NIS entries (if any) at the end. */
397 if (IN_SET(pw
->pw_name
[0], '+', '-'))
400 r
= putpwent_sane(pw
, passwd
);
410 if (fchmod(fileno(passwd
), 0644) < 0)
414 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
419 .pw_gecos
= i
->description
,
421 /* "x" means the password is stored in the shadow file */
422 .pw_passwd
= (char*) "x",
424 /* We default to the root directory as home */
425 .pw_dir
= i
->home
? i
->home
: (char*) "/",
427 /* Initialize the shell to nologin, with one exception:
428 * for root we patch in something special */
429 .pw_shell
= i
->shell
?: (char*) default_shell(i
->uid
),
432 r
= putpwent_sane(&n
, passwd
);
437 /* Append the remaining NIS entries if any */
439 r
= putpwent_sane(pw
, passwd
);
443 r
= fgetpwent_sane(original
, &pw
);
450 r
= fflush_and_check(passwd
);
454 *tmpfile
= TAKE_PTR(passwd
);
455 *tmpfile_path
= TAKE_PTR(passwd_tmp
);
460 static int write_temporary_shadow(const char *shadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
461 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
462 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
463 struct spwd
*sp
= NULL
;
469 if (ordered_hashmap_size(todo_uids
) == 0)
472 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
476 lstchg
= (long) (now(CLOCK_REALTIME
) / USEC_PER_DAY
);
478 original
= fopen(shadow_path
, "re");
481 r
= sync_rights(original
, shadow
);
485 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
487 i
= ordered_hashmap_get(users
, sp
->sp_namp
);
488 if (i
&& i
->todo_user
) {
489 /* we will update the existing entry */
490 sp
->sp_lstchg
= lstchg
;
492 /* only the /etc/shadow stage is left, so we can
493 * safely remove the item from the todo set */
494 i
->todo_user
= false;
495 ordered_hashmap_remove(todo_uids
, UID_TO_PTR(i
->uid
));
498 /* Make sure we keep the NIS entries (if any) at the end. */
499 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
502 r
= putspent_sane(sp
, shadow
);
512 if (fchmod(fileno(shadow
), 0000) < 0)
516 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
519 .sp_pwdp
= (char*) "!!",
526 .sp_flag
= (unsigned long) -1, /* this appears to be what everybody does ... */
529 r
= putspent_sane(&n
, shadow
);
534 /* Append the remaining NIS entries if any */
536 r
= putspent_sane(sp
, shadow
);
540 r
= fgetspent_sane(original
, &sp
);
546 if (!IN_SET(errno
, 0, ENOENT
))
549 r
= fflush_sync_and_check(shadow
);
553 *tmpfile
= TAKE_PTR(shadow
);
554 *tmpfile_path
= TAKE_PTR(shadow_tmp
);
559 static int write_temporary_group(const char *group_path
, FILE **tmpfile
, char **tmpfile_path
) {
560 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
561 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
562 bool group_changed
= false;
563 struct group
*gr
= NULL
;
568 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
571 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
575 original
= fopen(group_path
, "re");
578 r
= sync_rights(original
, group
);
582 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
583 /* Safety checks against name and GID collisions. Normally,
584 * this should be unnecessary, but given that we look at the
585 * entries anyway here, let's make an extra verification
586 * step that we don't generate duplicate entries. */
588 i
= ordered_hashmap_get(groups
, gr
->gr_name
);
589 if (i
&& i
->todo_group
) {
590 log_error("%s: Group \"%s\" already exists.", group_path
, gr
->gr_name
);
594 if (ordered_hashmap_contains(todo_gids
, GID_TO_PTR(gr
->gr_gid
))) {
595 log_error("%s: Detected collision for GID " GID_FMT
".", group_path
, gr
->gr_gid
);
599 /* Make sure we keep the NIS entries (if any) at the end. */
600 if (IN_SET(gr
->gr_name
[0], '+', '-'))
603 r
= putgrent_with_members(gr
, group
);
607 group_changed
= true;
615 if (fchmod(fileno(group
), 0644) < 0)
619 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
623 .gr_passwd
= (char*) "x",
626 r
= putgrent_with_members(&n
, group
);
630 group_changed
= true;
633 /* Append the remaining NIS entries if any */
635 r
= putgrent_sane(gr
, group
);
639 r
= fgetgrent_sane(original
, &gr
);
646 r
= fflush_sync_and_check(group
);
651 *tmpfile
= TAKE_PTR(group
);
652 *tmpfile_path
= TAKE_PTR(group_tmp
);
657 static int write_temporary_gshadow(const char * gshadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
659 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
660 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
661 bool group_changed
= false;
666 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
669 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
673 original
= fopen(gshadow_path
, "re");
677 r
= sync_rights(original
, gshadow
);
681 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
683 i
= ordered_hashmap_get(groups
, sg
->sg_namp
);
684 if (i
&& i
->todo_group
) {
685 log_error("%s: Group \"%s\" already exists.", gshadow_path
, sg
->sg_namp
);
689 r
= putsgent_with_members(sg
, gshadow
);
693 group_changed
= true;
701 if (fchmod(fileno(gshadow
), 0000) < 0)
705 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
708 .sg_passwd
= (char*) "!!",
711 r
= putsgent_with_members(&n
, gshadow
);
715 group_changed
= true;
718 r
= fflush_sync_and_check(gshadow
);
723 *tmpfile
= TAKE_PTR(gshadow
);
724 *tmpfile_path
= TAKE_PTR(gshadow_tmp
);
732 static int write_files(void) {
733 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
734 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
735 const char *passwd_path
= NULL
, *group_path
= NULL
, *shadow_path
= NULL
, *gshadow_path
= NULL
;
738 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
739 shadow_path
= prefix_roota(arg_root
, "/etc/shadow");
740 group_path
= prefix_roota(arg_root
, "/etc/group");
741 gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
743 r
= write_temporary_group(group_path
, &group
, &group_tmp
);
747 r
= write_temporary_gshadow(gshadow_path
, &gshadow
, &gshadow_tmp
);
751 r
= write_temporary_passwd(passwd_path
, &passwd
, &passwd_tmp
);
755 r
= write_temporary_shadow(shadow_path
, &shadow
, &shadow_tmp
);
759 /* Make a backup of the old files */
761 r
= make_backup("/etc/group", group_path
);
766 r
= make_backup("/etc/gshadow", gshadow_path
);
772 r
= make_backup("/etc/passwd", passwd_path
);
777 r
= make_backup("/etc/shadow", shadow_path
);
782 /* And make the new files count */
784 r
= rename_and_apply_smack(group_tmp
, group_path
);
788 group_tmp
= mfree(group_tmp
);
791 r
= rename_and_apply_smack(gshadow_tmp
, gshadow_path
);
795 gshadow_tmp
= mfree(gshadow_tmp
);
799 r
= rename_and_apply_smack(passwd_tmp
, passwd_path
);
803 passwd_tmp
= mfree(passwd_tmp
);
806 r
= rename_and_apply_smack(shadow_tmp
, shadow_path
);
810 shadow_tmp
= mfree(shadow_tmp
);
816 static int uid_is_ok(uid_t uid
, const char *name
, bool check_with_gid
) {
822 /* Let's see if we already have assigned the UID a second time */
823 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(uid
)))
826 /* Try to avoid using uids that are already used by a group
827 * that doesn't have the same name as our new user. */
828 if (check_with_gid
) {
829 i
= ordered_hashmap_get(todo_gids
, GID_TO_PTR(uid
));
830 if (i
&& !streq(i
->name
, name
))
834 /* Let's check the files directly */
835 if (hashmap_contains(database_uid
, UID_TO_PTR(uid
)))
838 if (check_with_gid
) {
839 n
= hashmap_get(database_gid
, GID_TO_PTR(uid
));
840 if (n
&& !streq(n
, name
))
844 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
850 if (!IN_SET(errno
, 0, ENOENT
))
853 if (check_with_gid
) {
855 g
= getgrgid((gid_t
) uid
);
857 if (!streq(g
->gr_name
, name
))
859 } else if (!IN_SET(errno
, 0, ENOENT
))
867 static int root_stat(const char *p
, struct stat
*st
) {
870 fix
= prefix_roota(arg_root
, p
);
871 if (stat(fix
, st
) < 0)
877 static int read_id_from_file(Item
*i
, uid_t
*_uid
, gid_t
*_gid
) {
879 bool found_uid
= false, found_gid
= false;
885 /* First, try to get the gid directly */
886 if (_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
891 /* Then, try to get the uid directly */
892 if ((_uid
|| (_gid
&& !found_gid
))
894 && root_stat(i
->uid_path
, &st
) >= 0) {
899 /* If we need the gid, but had no success yet, also derive it from the uid path */
900 if (_gid
&& !found_gid
) {
906 /* If that didn't work yet, then let's reuse the gid as uid */
907 if (_uid
&& !found_uid
&& i
->gid_path
) {
912 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
913 uid
= (uid_t
) st
.st_gid
;
935 static int add_user(Item
*i
) {
941 /* Check the database directly */
942 z
= hashmap_get(database_user
, i
->name
);
944 log_debug("User %s already exists.", i
->name
);
945 i
->uid
= PTR_TO_UID(z
);
955 p
= getpwnam(i
->name
);
957 log_debug("User %s already exists.", i
->name
);
961 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
967 if (!IN_SET(errno
, 0, ENOENT
))
968 return log_error_errno(errno
, "Failed to check if user %s already exists: %m", i
->name
);
971 /* Try to use the suggested numeric uid */
973 r
= uid_is_ok(i
->uid
, i
->name
, !i
->id_set_strict
);
975 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
977 log_debug("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
982 /* If that didn't work, try to read it from the specified path */
986 if (read_id_from_file(i
, &c
, NULL
) > 0) {
988 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
989 log_debug("User ID " UID_FMT
" of file not suitable for %s.", c
, i
->name
);
991 r
= uid_is_ok(c
, i
->name
, true);
993 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
998 log_debug("User ID " UID_FMT
" of file for %s is already used.", c
, i
->name
);
1003 /* Otherwise, try to reuse the group ID */
1004 if (!i
->uid_set
&& i
->gid_set
) {
1005 r
= uid_is_ok((uid_t
) i
->gid
, i
->name
, true);
1007 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1009 i
->uid
= (uid_t
) i
->gid
;
1014 /* And if that didn't work either, let's try to find a free one */
1017 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1019 log_error("No free user ID available for %s.", i
->name
);
1023 r
= uid_is_ok(search_uid
, i
->name
, true);
1025 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1031 i
->uid
= search_uid
;
1034 r
= ordered_hashmap_ensure_allocated(&todo_uids
, NULL
);
1038 r
= ordered_hashmap_put(todo_uids
, UID_TO_PTR(i
->uid
), i
);
1042 i
->todo_user
= true;
1043 log_info("Creating user %s (%s) with uid " UID_FMT
" and gid " GID_FMT
".", i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1048 static int gid_is_ok(gid_t gid
) {
1052 if (ordered_hashmap_get(todo_gids
, GID_TO_PTR(gid
)))
1055 /* Avoid reusing gids that are already used by a different user */
1056 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(gid
)))
1059 if (hashmap_contains(database_gid
, GID_TO_PTR(gid
)))
1062 if (hashmap_contains(database_uid
, UID_TO_PTR(gid
)))
1070 if (!IN_SET(errno
, 0, ENOENT
))
1074 p
= getpwuid((uid_t
) gid
);
1077 if (!IN_SET(errno
, 0, ENOENT
))
1084 static int add_group(Item
*i
) {
1090 /* Check the database directly */
1091 z
= hashmap_get(database_group
, i
->name
);
1093 log_debug("Group %s already exists.", i
->name
);
1094 i
->gid
= PTR_TO_GID(z
);
1099 /* Also check NSS */
1104 g
= getgrnam(i
->name
);
1106 log_debug("Group %s already exists.", i
->name
);
1111 if (!IN_SET(errno
, 0, ENOENT
))
1112 return log_error_errno(errno
, "Failed to check if group %s already exists: %m", i
->name
);
1115 /* Try to use the suggested numeric gid */
1117 r
= gid_is_ok(i
->gid
);
1119 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1120 if (i
->id_set_strict
) {
1121 /* If we require the gid to already exist we can return here:
1122 * r > 0: means the gid does not exist -> fail
1123 * r == 0: means the gid exists -> nothing more to do.
1126 log_error("Failed to create %s: please create GID %d", i
->name
, i
->gid
);
1133 log_debug("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1138 /* Try to reuse the numeric uid, if there's one */
1139 if (!i
->gid_set
&& i
->uid_set
) {
1140 r
= gid_is_ok((gid_t
) i
->uid
);
1142 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1144 i
->gid
= (gid_t
) i
->uid
;
1149 /* If that didn't work, try to read it from the specified path */
1153 if (read_id_from_file(i
, NULL
, &c
) > 0) {
1155 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
1156 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", c
, i
->name
);
1160 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1165 log_debug("Group ID " GID_FMT
" of file for %s already used.", c
, i
->name
);
1170 /* And if that didn't work either, let's try to find a free one */
1173 /* We look for new GIDs in the UID pool! */
1174 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1176 log_error("No free group ID available for %s.", i
->name
);
1180 r
= gid_is_ok(search_uid
);
1182 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1188 i
->gid
= search_uid
;
1191 r
= ordered_hashmap_ensure_allocated(&todo_gids
, NULL
);
1195 r
= ordered_hashmap_put(todo_gids
, GID_TO_PTR(i
->gid
), i
);
1199 i
->todo_group
= true;
1200 log_info("Creating group %s with gid " GID_FMT
".", i
->name
, i
->gid
);
1205 static int process_item(Item
*i
) {
1215 j
= ordered_hashmap_get(groups
, i
->name
);
1216 if (j
&& j
->todo_group
) {
1217 /* When the group with the same name is already in queue,
1218 * use the information about the group and do not create
1219 * duplicated group entry. */
1220 i
->gid_set
= j
->gid_set
;
1222 i
->id_set_strict
= true;
1233 return add_group(i
);
1236 assert_not_reached("Unknown item type");
1240 static void item_free(Item
*i
) {
1248 free(i
->description
);
1254 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1256 static int add_implicit(void) {
1261 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1262 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, members
, iterator
) {
1266 if (!ordered_hashmap_get(users
, *m
)) {
1267 _cleanup_(item_freep
) Item
*j
= NULL
;
1269 r
= ordered_hashmap_ensure_allocated(&users
, &string_hash_ops
);
1278 j
->name
= strdup(*m
);
1282 r
= ordered_hashmap_put(users
, j
->name
, j
);
1286 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1290 if (!(ordered_hashmap_get(users
, g
) ||
1291 ordered_hashmap_get(groups
, g
))) {
1292 _cleanup_(item_freep
) Item
*j
= NULL
;
1294 r
= ordered_hashmap_ensure_allocated(&groups
, &string_hash_ops
);
1302 j
->type
= ADD_GROUP
;
1303 j
->name
= strdup(g
);
1307 r
= ordered_hashmap_put(groups
, j
->name
, j
);
1311 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1319 static bool item_equal(Item
*a
, Item
*b
) {
1323 if (a
->type
!= b
->type
)
1326 if (!streq_ptr(a
->name
, b
->name
))
1329 if (!streq_ptr(a
->uid_path
, b
->uid_path
))
1332 if (!streq_ptr(a
->gid_path
, b
->gid_path
))
1335 if (!streq_ptr(a
->description
, b
->description
))
1338 if (a
->uid_set
!= b
->uid_set
)
1341 if (a
->uid_set
&& a
->uid
!= b
->uid
)
1344 if (a
->gid_set
!= b
->gid_set
)
1347 if (a
->gid_set
&& a
->gid
!= b
->gid
)
1350 if (!streq_ptr(a
->home
, b
->home
))
1353 if (!streq_ptr(a
->shell
, b
->shell
))
1359 static int parse_line(const char *fname
, unsigned line
, const char *buffer
) {
1361 static const Specifier specifier_table
[] = {
1362 { 'm', specifier_machine_id
, NULL
},
1363 { 'b', specifier_boot_id
, NULL
},
1364 { 'H', specifier_host_name
, NULL
},
1365 { 'v', specifier_kernel_release
, NULL
},
1366 { 'T', specifier_tmp_dir
, NULL
},
1367 { 'V', specifier_var_tmp_dir
, NULL
},
1371 _cleanup_free_
char *action
= NULL
,
1372 *name
= NULL
, *resolved_name
= NULL
,
1373 *id
= NULL
, *resolved_id
= NULL
,
1374 *description
= NULL
, *resolved_description
= NULL
,
1375 *home
= NULL
, *resolved_home
= 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 r
= specifier_printf(description
, specifier_table
, NULL
, &resolved_description
);
1451 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, description
);
1455 if (!valid_gecos(resolved_description
)) {
1456 log_error("[%s:%u] '%s' is not a valid GECOS field.", fname
, line
, resolved_description
);
1462 if (isempty(home
) || streq(home
, "-"))
1466 r
= specifier_printf(home
, specifier_table
, NULL
, &resolved_home
);
1468 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, home
);
1472 if (!valid_home(resolved_home
)) {
1473 log_error("[%s:%u] '%s' is not a valid home directory field.", fname
, line
, resolved_home
);
1479 if (isempty(shell
) || streq(shell
, "-"))
1480 shell
= mfree(shell
);
1483 r
= specifier_printf(shell
, specifier_table
, NULL
, &resolved_shell
);
1485 log_error("[%s:%u] Failed to replace specifiers: %s", fname
, line
, shell
);
1489 if (!valid_shell(resolved_shell
)) {
1490 log_error("[%s:%u] '%s' is not a valid login shell field.", fname
, line
, resolved_shell
);
1495 switch (action
[0]) {
1498 if (resolved_name
) {
1499 log_error("[%s:%u] Lines of type 'r' don't take a name field.", fname
, line
);
1504 log_error("[%s:%u] Lines of type 'r' require a ID range in the third field.", fname
, line
);
1508 if (description
|| home
|| shell
) {
1509 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1510 fname
, line
, action
[0],
1511 description
? "GECOS" : home
? "home directory" : "login shell");
1515 r
= uid_range_add_str(&uid_range
, &n_uid_range
, resolved_id
);
1517 log_error("[%s:%u] Invalid UID range %s.", fname
, line
, resolved_id
);
1526 /* Try to extend an existing member or group item */
1528 log_error("[%s:%u] Lines of type 'm' require a user name in the second field.", fname
, line
);
1533 log_error("[%s:%u] Lines of type 'm' require a group name in the third field.", fname
, line
);
1537 if (!valid_user_group_name(resolved_id
)) {
1538 log_error("[%s:%u] '%s' is not a valid user or group name.", fname
, line
, resolved_id
);
1542 if (description
|| home
|| shell
) {
1543 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1544 fname
, line
, action
[0],
1545 description
? "GECOS" : home
? "home directory" : "login shell");
1549 r
= ordered_hashmap_ensure_allocated(&members
, &string_hash_ops
);
1553 l
= ordered_hashmap_get(members
, resolved_id
);
1555 /* A list for this group name already exists, let's append to it */
1556 r
= strv_push(&l
, resolved_name
);
1560 resolved_name
= NULL
;
1562 assert_se(ordered_hashmap_update(members
, resolved_id
, l
) >= 0);
1564 /* No list for this group name exists yet, create one */
1566 l
= new0(char *, 2);
1570 l
[0] = resolved_name
;
1573 r
= ordered_hashmap_put(members
, resolved_id
, l
);
1579 resolved_id
= resolved_name
= NULL
;
1587 log_error("[%s:%u] Lines of type 'u' require a user name in the second field.", fname
, line
);
1591 r
= ordered_hashmap_ensure_allocated(&users
, &string_hash_ops
);
1600 if (path_is_absolute(resolved_id
)) {
1601 i
->uid_path
= TAKE_PTR(resolved_id
);
1602 path_simplify(i
->uid_path
, false);
1604 _cleanup_free_
char *uid
= NULL
, *gid
= NULL
;
1605 if (split_pair(resolved_id
, ":", &uid
, &gid
) == 0) {
1606 r
= parse_gid(gid
, &i
->gid
);
1608 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1610 i
->id_set_strict
= true;
1611 free_and_replace(resolved_id
, uid
);
1613 if (!streq(resolved_id
, "-")) {
1614 r
= parse_uid(resolved_id
, &i
->uid
);
1616 return log_error_errno(r
, "Failed to parse UID: '%s': %m", id
);
1622 i
->description
= TAKE_PTR(resolved_description
);
1623 i
->home
= TAKE_PTR(resolved_home
);
1624 i
->shell
= TAKE_PTR(resolved_shell
);
1631 log_error("[%s:%u] Lines of type 'g' require a user name in the second field.", fname
, line
);
1635 if (description
|| home
|| shell
) {
1636 log_error("[%s:%u] Lines of type '%c' don't take a %s field.",
1637 fname
, line
, action
[0],
1638 description
? "GECOS" : home
? "home directory" : "login shell");
1642 r
= ordered_hashmap_ensure_allocated(&groups
, &string_hash_ops
);
1651 if (path_is_absolute(resolved_id
)) {
1652 i
->gid_path
= TAKE_PTR(resolved_id
);
1653 path_simplify(i
->gid_path
, false);
1655 r
= parse_gid(resolved_id
, &i
->gid
);
1657 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1670 i
->type
= action
[0];
1671 i
->name
= TAKE_PTR(resolved_name
);
1673 existing
= ordered_hashmap_get(h
, i
->name
);
1676 /* Two identical items are fine */
1677 if (!item_equal(existing
, i
))
1678 log_warning("Two or more conflicting lines for %s configured, ignoring.", i
->name
);
1683 r
= ordered_hashmap_put(h
, i
->name
, i
);
1691 static int read_config_file(const char *fn
, bool ignore_enoent
) {
1692 _cleanup_fclose_
FILE *rf
= NULL
;
1694 char line
[LINE_MAX
];
1703 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf
);
1705 if (ignore_enoent
&& r
== -ENOENT
)
1708 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
1714 FOREACH_LINE(line
, f
, break) {
1721 if (IN_SET(*l
, 0, '#'))
1724 k
= parse_line(fn
, v
, l
);
1725 if (k
< 0 && r
== 0)
1730 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
1738 static void free_database(Hashmap
*by_name
, Hashmap
*by_id
) {
1742 name
= hashmap_first(by_id
);
1746 hashmap_remove(by_name
, name
);
1748 hashmap_steal_first_key(by_id
);
1752 while ((name
= hashmap_steal_first_key(by_name
)))
1755 hashmap_free(by_name
);
1756 hashmap_free(by_id
);
1759 static int cat_config(void) {
1760 _cleanup_strv_free_
char **files
= NULL
;
1763 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
1767 return cat_files(NULL
, files
, 0);
1770 static void help(void) {
1771 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1772 "Creates system user accounts.\n\n"
1773 " -h --help Show this help\n"
1774 " --version Show package version\n"
1775 " --cat-config Show configuration files\n"
1776 " --root=PATH Operate on an alternate filesystem root\n"
1777 " --replace=PATH Treat arguments as replacement for PATH\n"
1778 " --inline Treat arguments as configuration lines\n"
1779 , program_invocation_short_name
);
1782 static int parse_argv(int argc
, char *argv
[]) {
1785 ARG_VERSION
= 0x100,
1792 static const struct option options
[] = {
1793 { "help", no_argument
, NULL
, 'h' },
1794 { "version", no_argument
, NULL
, ARG_VERSION
},
1795 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
1796 { "root", required_argument
, NULL
, ARG_ROOT
},
1797 { "replace", required_argument
, NULL
, ARG_REPLACE
},
1798 { "inline", no_argument
, NULL
, ARG_INLINE
},
1807 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
1818 case ARG_CAT_CONFIG
:
1819 arg_cat_config
= true;
1823 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
1829 if (!path_is_absolute(optarg
) ||
1830 !endswith(optarg
, ".conf")) {
1831 log_error("The argument to --replace= must an absolute path to a config file");
1835 arg_replace
= optarg
;
1846 assert_not_reached("Unhandled option");
1849 if (arg_replace
&& arg_cat_config
) {
1850 log_error("Option --replace= is not supported with --cat-config");
1854 if (arg_replace
&& optind
>= argc
) {
1855 log_error("When --replace= is given, some configuration items must be specified");
1862 static int parse_arguments(char **args
) {
1867 STRV_FOREACH(arg
, args
) {
1869 /* Use (argument):n, where n==1 for the first positional arg */
1870 r
= parse_line("(argument)", pos
, *arg
);
1872 r
= read_config_file(*arg
, false);
1882 static int read_config_files(char **args
) {
1883 _cleanup_strv_free_
char **files
= NULL
;
1884 _cleanup_free_
char *p
= NULL
;
1888 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
1892 STRV_FOREACH(f
, files
)
1893 if (p
&& path_equal(*f
, p
)) {
1894 log_debug("Parsing arguments at position \"%s\"…", *f
);
1896 r
= parse_arguments(args
);
1900 log_debug("Reading config file \"%s\"…", *f
);
1902 /* Just warn, ignore result otherwise */
1903 (void) read_config_file(*f
, true);
1909 int main(int argc
, char *argv
[]) {
1910 _cleanup_close_
int lock
= -1;
1916 r
= parse_argv(argc
, argv
);
1920 log_set_target(LOG_TARGET_AUTO
);
1921 log_parse_environment();
1924 if (arg_cat_config
) {
1931 r
= mac_selinux_init();
1933 log_error_errno(r
, "SELinux setup failed: %m");
1937 /* If command line arguments are specified along with --replace, read all
1938 * configuration files and insert the positional arguments at the specified
1939 * place. Otherwise, if command line arguments are specified, execute just
1940 * them, and finally, without --replace= or any positional arguments, just
1941 * read configuration and execute it.
1943 if (arg_replace
|| optind
>= argc
)
1944 r
= read_config_files(argv
+ optind
);
1946 r
= parse_arguments(argv
+ optind
);
1950 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our detection
1951 * whether the names or UID/GID area already used otherwise doesn't get confused. After all, even though
1952 * nss-systemd synthesizes these users/groups, they should still appear in /etc/passwd and /etc/group, as the
1953 * synthesizing logic is merely supposed to be fallback for cases where we run with a completely unpopulated
1955 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0) {
1956 r
= log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
1961 /* Default to default range of 1..SYSTEM_UID_MAX */
1962 r
= uid_range_add(&uid_range
, &n_uid_range
, 1, SYSTEM_UID_MAX
);
1973 lock
= take_etc_passwd_lock(arg_root
);
1975 log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
1979 r
= load_user_database();
1981 log_error_errno(r
, "Failed to load user database: %m");
1985 r
= load_group_database();
1987 log_error_errno(r
, "Failed to read group database: %m");
1991 ORDERED_HASHMAP_FOREACH(i
, groups
, iterator
)
1992 (void) process_item(i
);
1994 ORDERED_HASHMAP_FOREACH(i
, users
, iterator
)
1995 (void) process_item(i
);
1999 log_error_errno(r
, "Failed to write files: %m");
2002 ordered_hashmap_free_with_destructor(groups
, item_free
);
2003 ordered_hashmap_free_with_destructor(users
, item_free
);
2005 while ((n
= ordered_hashmap_first_key(members
))) {
2006 strv_free(ordered_hashmap_steal_first(members
));
2009 ordered_hashmap_free(members
);
2011 ordered_hashmap_free(todo_uids
);
2012 ordered_hashmap_free(todo_gids
);
2014 free_database(database_user
, database_uid
);
2015 free_database(database_group
, database_gid
);
2021 return r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;