1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #include "alloc-util.h"
7 #include "conf-files.h"
12 #include "format-util.h"
15 #include "main-func.h"
17 #include "path-util.h"
18 #include "pretty-print.h"
20 #include "selinux-util.h"
21 #include "smack-util.h"
22 #include "specifier.h"
23 #include "string-util.h"
25 #include "tmpfile-util-label.h"
26 #include "uid-range.h"
27 #include "user-util.h"
31 typedef enum ItemType
{
54 /* When set the group with the specified gid must exist
55 * and the check if a uid clashes with the gid is skipped.
65 static char *arg_root
= NULL
;
66 static bool arg_cat_config
= false;
67 static const char *arg_replace
= NULL
;
68 static bool arg_inline
= false;
69 static PagerFlags arg_pager_flags
= 0;
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_by_uid
= NULL
, *database_by_username
= NULL
;
76 static Hashmap
*database_by_gid
= NULL
, *database_by_groupname
= NULL
;
77 static Set
*database_users
= NULL
, *database_groups
= NULL
;
79 static uid_t search_uid
= UID_INVALID
;
80 static UidRange
*uid_range
= NULL
;
81 static unsigned n_uid_range
= 0;
83 STATIC_DESTRUCTOR_REGISTER(groups
, ordered_hashmap_freep
);
84 STATIC_DESTRUCTOR_REGISTER(users
, ordered_hashmap_freep
);
85 STATIC_DESTRUCTOR_REGISTER(members
, ordered_hashmap_freep
);
86 STATIC_DESTRUCTOR_REGISTER(todo_uids
, ordered_hashmap_freep
);
87 STATIC_DESTRUCTOR_REGISTER(todo_gids
, ordered_hashmap_freep
);
88 STATIC_DESTRUCTOR_REGISTER(database_by_uid
, hashmap_freep
);
89 STATIC_DESTRUCTOR_REGISTER(database_by_username
, hashmap_freep
);
90 STATIC_DESTRUCTOR_REGISTER(database_users
, set_free_freep
);
91 STATIC_DESTRUCTOR_REGISTER(database_by_gid
, hashmap_freep
);
92 STATIC_DESTRUCTOR_REGISTER(database_by_groupname
, hashmap_freep
);
93 STATIC_DESTRUCTOR_REGISTER(database_groups
, set_free_freep
);
94 STATIC_DESTRUCTOR_REGISTER(uid_range
, freep
);
95 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
97 static int errno_is_not_exists(int code
) {
98 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
100 return IN_SET(code
, 0, ENOENT
, ESRCH
, EBADF
, EPERM
);
103 static int load_user_database(void) {
104 _cleanup_fclose_
FILE *f
= NULL
;
105 const char *passwd_path
;
109 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
110 f
= fopen(passwd_path
, "re");
112 return errno
== ENOENT
? 0 : -errno
;
114 r
= hashmap_ensure_allocated(&database_by_username
, &string_hash_ops
);
118 r
= hashmap_ensure_allocated(&database_by_uid
, NULL
);
122 r
= set_ensure_allocated(&database_users
, NULL
);
126 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
130 n
= strdup(pw
->pw_name
);
134 k
= set_put(database_users
, n
);
140 k
= hashmap_put(database_by_username
, n
, UID_TO_PTR(pw
->pw_uid
));
141 if (k
< 0 && k
!= -EEXIST
)
144 q
= hashmap_put(database_by_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
145 if (q
< 0 && q
!= -EEXIST
)
151 static int load_group_database(void) {
152 _cleanup_fclose_
FILE *f
= NULL
;
153 const char *group_path
;
157 group_path
= prefix_roota(arg_root
, "/etc/group");
158 f
= fopen(group_path
, "re");
160 return errno
== ENOENT
? 0 : -errno
;
162 r
= hashmap_ensure_allocated(&database_by_groupname
, &string_hash_ops
);
166 r
= hashmap_ensure_allocated(&database_by_gid
, NULL
);
170 r
= set_ensure_allocated(&database_groups
, NULL
);
174 while ((r
= fgetgrent_sane(f
, &gr
)) > 0) {
178 n
= strdup(gr
->gr_name
);
182 k
= set_put(database_groups
, n
);
188 k
= hashmap_put(database_by_groupname
, n
, GID_TO_PTR(gr
->gr_gid
));
189 if (k
< 0 && k
!= -EEXIST
)
192 q
= hashmap_put(database_by_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
193 if (q
< 0 && q
!= -EEXIST
)
199 static int make_backup(const char *target
, const char *x
) {
200 _cleanup_close_
int src
= -1;
201 _cleanup_fclose_
FILE *dst
= NULL
;
202 _cleanup_free_
char *dst_tmp
= NULL
;
204 struct timespec ts
[2];
208 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
210 if (errno
== ENOENT
) /* No backup necessary... */
216 if (fstat(src
, &st
) < 0)
219 r
= fopen_temporary_label(target
, x
, &dst
, &dst_tmp
);
223 r
= copy_bytes(src
, fileno(dst
), (uint64_t) -1, COPY_REFLINK
);
227 /* Don't fail on chmod() or chown(). If it stays owned by us
228 * and/or unreadable by others, then it isn't too bad... */
230 backup
= strjoina(x
, "-");
232 /* Copy over the access mask */
233 r
= chmod_and_chown_unsafe(dst_tmp
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
235 log_warning_errno(r
, "Failed to change access mode or ownership of %s: %m", backup
);
239 if (futimens(fileno(dst
), ts
) < 0)
240 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
242 r
= fflush_sync_and_check(dst
);
246 if (rename(dst_tmp
, backup
) < 0) {
254 (void) unlink(dst_tmp
);
258 static int putgrent_with_members(const struct group
*gr
, FILE *group
) {
264 a
= ordered_hashmap_get(members
, gr
->gr_name
);
266 _cleanup_strv_free_
char **l
= NULL
;
270 l
= strv_copy(gr
->gr_mem
);
275 if (strv_find(l
, *i
))
278 if (strv_extend(&l
, *i
) < 0)
294 r
= putgrent_sane(&t
, group
);
295 return r
< 0 ? r
: 1;
299 return putgrent_sane(gr
, group
);
303 static int putsgent_with_members(const struct sgrp
*sg
, FILE *gshadow
) {
309 a
= ordered_hashmap_get(members
, sg
->sg_namp
);
311 _cleanup_strv_free_
char **l
= NULL
;
315 l
= strv_copy(sg
->sg_mem
);
320 if (strv_find(l
, *i
))
323 if (strv_extend(&l
, *i
) < 0)
339 r
= putsgent_sane(&t
, gshadow
);
340 return r
< 0 ? r
: 1;
344 return putsgent_sane(sg
, gshadow
);
348 static int sync_rights(FILE *from
, const char *to
) {
351 if (fstat(fileno(from
), &st
) < 0)
354 return chmod_and_chown_unsafe(to
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
357 static int rename_and_apply_smack(const char *temp_path
, const char *dest_path
) {
359 if (rename(temp_path
, dest_path
) < 0)
362 #ifdef SMACK_RUN_LABEL
363 r
= mac_smack_apply(dest_path
, SMACK_ATTR_ACCESS
, SMACK_FLOOR_LABEL
);
370 static const char* default_shell(uid_t uid
) {
371 return uid
== 0 ? "/bin/sh" : NOLOGIN
;
374 static int write_temporary_passwd(const char *passwd_path
, FILE **tmpfile
, char **tmpfile_path
) {
375 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
376 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
377 struct passwd
*pw
= NULL
;
382 if (ordered_hashmap_size(todo_uids
) == 0)
385 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
389 original
= fopen(passwd_path
, "re");
392 r
= sync_rights(original
, passwd_tmp
);
396 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
398 i
= ordered_hashmap_get(users
, pw
->pw_name
);
399 if (i
&& i
->todo_user
)
400 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
401 "%s: User \"%s\" already exists.",
402 passwd_path
, pw
->pw_name
);
404 if (ordered_hashmap_contains(todo_uids
, UID_TO_PTR(pw
->pw_uid
)))
405 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
406 "%s: Detected collision for UID " UID_FMT
".",
407 passwd_path
, pw
->pw_uid
);
409 /* Make sure we keep the NIS entries (if any) at the end. */
410 if (IN_SET(pw
->pw_name
[0], '+', '-'))
413 r
= putpwent_sane(pw
, passwd
);
423 if (fchmod(fileno(passwd
), 0644) < 0)
427 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
432 .pw_gecos
= i
->description
,
434 /* "x" means the password is stored in the shadow file */
435 .pw_passwd
= (char*) "x",
437 /* We default to the root directory as home */
438 .pw_dir
= i
->home
?: (char*) "/",
440 /* Initialize the shell to nologin, with one exception:
441 * for root we patch in something special */
442 .pw_shell
= i
->shell
?: (char*) default_shell(i
->uid
),
445 r
= putpwent_sane(&n
, passwd
);
450 /* Append the remaining NIS entries if any */
452 r
= putpwent_sane(pw
, passwd
);
456 r
= fgetpwent_sane(original
, &pw
);
463 r
= fflush_and_check(passwd
);
467 *tmpfile
= TAKE_PTR(passwd
);
468 *tmpfile_path
= TAKE_PTR(passwd_tmp
);
473 static int write_temporary_shadow(const char *shadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
474 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
475 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
476 struct spwd
*sp
= NULL
;
482 if (ordered_hashmap_size(todo_uids
) == 0)
485 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
489 lstchg
= (long) (now(CLOCK_REALTIME
) / USEC_PER_DAY
);
491 original
= fopen(shadow_path
, "re");
494 r
= sync_rights(original
, shadow_tmp
);
498 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
500 i
= ordered_hashmap_get(users
, sp
->sp_namp
);
501 if (i
&& i
->todo_user
) {
502 /* we will update the existing entry */
503 sp
->sp_lstchg
= lstchg
;
505 /* only the /etc/shadow stage is left, so we can
506 * safely remove the item from the todo set */
507 i
->todo_user
= false;
508 ordered_hashmap_remove(todo_uids
, UID_TO_PTR(i
->uid
));
511 /* Make sure we keep the NIS entries (if any) at the end. */
512 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
515 r
= putspent_sane(sp
, shadow
);
525 if (fchmod(fileno(shadow
), 0000) < 0)
529 ORDERED_HASHMAP_FOREACH(i
, todo_uids
, iterator
) {
532 .sp_pwdp
= (char*) "!!", /* lock this password, and make it invalid */
539 .sp_flag
= (unsigned long) -1, /* this appears to be what everybody does ... */
542 r
= putspent_sane(&n
, shadow
);
547 /* Append the remaining NIS entries if any */
549 r
= putspent_sane(sp
, shadow
);
553 r
= fgetspent_sane(original
, &sp
);
559 if (!IN_SET(errno
, 0, ENOENT
))
562 r
= fflush_sync_and_check(shadow
);
566 *tmpfile
= TAKE_PTR(shadow
);
567 *tmpfile_path
= TAKE_PTR(shadow_tmp
);
572 static int write_temporary_group(const char *group_path
, FILE **tmpfile
, char **tmpfile_path
) {
573 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
574 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
575 bool group_changed
= false;
576 struct group
*gr
= NULL
;
581 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
584 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
588 original
= fopen(group_path
, "re");
591 r
= sync_rights(original
, group_tmp
);
595 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
596 /* Safety checks against name and GID collisions. Normally,
597 * this should be unnecessary, but given that we look at the
598 * entries anyway here, let's make an extra verification
599 * step that we don't generate duplicate entries. */
601 i
= ordered_hashmap_get(groups
, gr
->gr_name
);
602 if (i
&& i
->todo_group
)
603 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
604 "%s: Group \"%s\" already exists.",
605 group_path
, gr
->gr_name
);
607 if (ordered_hashmap_contains(todo_gids
, GID_TO_PTR(gr
->gr_gid
)))
608 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
609 "%s: Detected collision for GID " GID_FMT
".",
610 group_path
, gr
->gr_gid
);
612 /* Make sure we keep the NIS entries (if any) at the end. */
613 if (IN_SET(gr
->gr_name
[0], '+', '-'))
616 r
= putgrent_with_members(gr
, group
);
620 group_changed
= true;
628 if (fchmod(fileno(group
), 0644) < 0)
632 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
636 .gr_passwd
= (char*) "x",
639 r
= putgrent_with_members(&n
, group
);
643 group_changed
= true;
646 /* Append the remaining NIS entries if any */
648 r
= putgrent_sane(gr
, group
);
652 r
= fgetgrent_sane(original
, &gr
);
659 r
= fflush_sync_and_check(group
);
664 *tmpfile
= TAKE_PTR(group
);
665 *tmpfile_path
= TAKE_PTR(group_tmp
);
670 static int write_temporary_gshadow(const char * gshadow_path
, FILE **tmpfile
, char **tmpfile_path
) {
672 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
673 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
674 bool group_changed
= false;
679 if (ordered_hashmap_size(todo_gids
) == 0 && ordered_hashmap_size(members
) == 0)
682 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
686 original
= fopen(gshadow_path
, "re");
690 r
= sync_rights(original
, gshadow_tmp
);
694 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
696 i
= ordered_hashmap_get(groups
, sg
->sg_namp
);
697 if (i
&& i
->todo_group
)
698 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
699 "%s: Group \"%s\" already exists.",
700 gshadow_path
, sg
->sg_namp
);
702 r
= putsgent_with_members(sg
, gshadow
);
706 group_changed
= true;
714 if (fchmod(fileno(gshadow
), 0000) < 0)
718 ORDERED_HASHMAP_FOREACH(i
, todo_gids
, iterator
) {
721 .sg_passwd
= (char*) "!!",
724 r
= putsgent_with_members(&n
, gshadow
);
728 group_changed
= true;
731 r
= fflush_sync_and_check(gshadow
);
736 *tmpfile
= TAKE_PTR(gshadow
);
737 *tmpfile_path
= TAKE_PTR(gshadow_tmp
);
745 static int write_files(void) {
746 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
747 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
748 const char *passwd_path
= NULL
, *group_path
= NULL
, *shadow_path
= NULL
, *gshadow_path
= NULL
;
751 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
752 shadow_path
= prefix_roota(arg_root
, "/etc/shadow");
753 group_path
= prefix_roota(arg_root
, "/etc/group");
754 gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
756 r
= write_temporary_group(group_path
, &group
, &group_tmp
);
760 r
= write_temporary_gshadow(gshadow_path
, &gshadow
, &gshadow_tmp
);
764 r
= write_temporary_passwd(passwd_path
, &passwd
, &passwd_tmp
);
768 r
= write_temporary_shadow(shadow_path
, &shadow
, &shadow_tmp
);
772 /* Make a backup of the old files */
774 r
= make_backup("/etc/group", group_path
);
779 r
= make_backup("/etc/gshadow", gshadow_path
);
785 r
= make_backup("/etc/passwd", passwd_path
);
790 r
= make_backup("/etc/shadow", shadow_path
);
795 /* And make the new files count */
797 r
= rename_and_apply_smack(group_tmp
, group_path
);
801 group_tmp
= mfree(group_tmp
);
804 r
= rename_and_apply_smack(gshadow_tmp
, gshadow_path
);
808 gshadow_tmp
= mfree(gshadow_tmp
);
812 r
= rename_and_apply_smack(passwd_tmp
, passwd_path
);
816 passwd_tmp
= mfree(passwd_tmp
);
819 r
= rename_and_apply_smack(shadow_tmp
, shadow_path
);
823 shadow_tmp
= mfree(shadow_tmp
);
829 static int uid_is_ok(uid_t uid
, const char *name
, bool check_with_gid
) {
835 /* Let's see if we already have assigned the UID a second time */
836 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(uid
)))
839 /* Try to avoid using uids that are already used by a group
840 * that doesn't have the same name as our new user. */
841 if (check_with_gid
) {
842 i
= ordered_hashmap_get(todo_gids
, GID_TO_PTR(uid
));
843 if (i
&& !streq(i
->name
, name
))
847 /* Let's check the files directly */
848 if (hashmap_contains(database_by_uid
, UID_TO_PTR(uid
)))
851 if (check_with_gid
) {
852 n
= hashmap_get(database_by_gid
, GID_TO_PTR(uid
));
853 if (n
&& !streq(n
, name
))
857 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
863 if (!IN_SET(errno
, 0, ENOENT
))
866 if (check_with_gid
) {
868 g
= getgrgid((gid_t
) uid
);
870 if (!streq(g
->gr_name
, name
))
872 } else if (!IN_SET(errno
, 0, ENOENT
))
880 static int root_stat(const char *p
, struct stat
*st
) {
883 fix
= prefix_roota(arg_root
, p
);
884 if (stat(fix
, st
) < 0)
890 static int read_id_from_file(Item
*i
, uid_t
*_uid
, gid_t
*_gid
) {
892 bool found_uid
= false, found_gid
= false;
898 /* First, try to get the gid directly */
899 if (_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
904 /* Then, try to get the uid directly */
905 if ((_uid
|| (_gid
&& !found_gid
))
907 && root_stat(i
->uid_path
, &st
) >= 0) {
912 /* If we need the gid, but had no success yet, also derive it from the uid path */
913 if (_gid
&& !found_gid
) {
919 /* If that didn't work yet, then let's reuse the gid as uid */
920 if (_uid
&& !found_uid
&& i
->gid_path
) {
925 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
926 uid
= (uid_t
) st
.st_gid
;
948 static int add_user(Item
*i
) {
954 /* Check the database directly */
955 z
= hashmap_get(database_by_username
, i
->name
);
957 log_debug("User %s already exists.", i
->name
);
958 i
->uid
= PTR_TO_UID(z
);
968 p
= getpwnam(i
->name
);
970 log_debug("User %s already exists.", i
->name
);
974 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
980 if (!errno_is_not_exists(errno
))
981 return log_error_errno(errno
, "Failed to check if user %s already exists: %m", i
->name
);
984 /* Try to use the suggested numeric uid */
986 r
= uid_is_ok(i
->uid
, i
->name
, !i
->id_set_strict
);
988 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
990 log_debug("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
995 /* If that didn't work, try to read it from the specified path */
999 if (read_id_from_file(i
, &c
, NULL
) > 0) {
1001 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
1002 log_debug("User ID " UID_FMT
" of file not suitable for %s.", c
, i
->name
);
1004 r
= uid_is_ok(c
, i
->name
, true);
1006 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1011 log_debug("User ID " UID_FMT
" of file for %s is already used.", c
, i
->name
);
1016 /* Otherwise, try to reuse the group ID */
1017 if (!i
->uid_set
&& i
->gid_set
) {
1018 r
= uid_is_ok((uid_t
) i
->gid
, i
->name
, true);
1020 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1022 i
->uid
= (uid_t
) i
->gid
;
1027 /* And if that didn't work either, let's try to find a free one */
1030 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1032 return log_error_errno(r
, "No free user ID available for %s.", i
->name
);
1034 r
= uid_is_ok(search_uid
, i
->name
, true);
1036 return log_error_errno(r
, "Failed to verify uid " UID_FMT
": %m", i
->uid
);
1042 i
->uid
= search_uid
;
1045 r
= ordered_hashmap_ensure_allocated(&todo_uids
, NULL
);
1049 r
= ordered_hashmap_put(todo_uids
, UID_TO_PTR(i
->uid
), i
);
1053 i
->todo_user
= true;
1054 log_info("Creating user %s (%s) with uid " UID_FMT
" and gid " GID_FMT
".", i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1059 static int gid_is_ok(gid_t gid
) {
1063 if (ordered_hashmap_get(todo_gids
, GID_TO_PTR(gid
)))
1066 /* Avoid reusing gids that are already used by a different user */
1067 if (ordered_hashmap_get(todo_uids
, UID_TO_PTR(gid
)))
1070 if (hashmap_contains(database_by_gid
, GID_TO_PTR(gid
)))
1073 if (hashmap_contains(database_by_uid
, UID_TO_PTR(gid
)))
1081 if (!IN_SET(errno
, 0, ENOENT
))
1085 p
= getpwuid((uid_t
) gid
);
1088 if (!IN_SET(errno
, 0, ENOENT
))
1095 static int get_gid_by_name(const char *name
, gid_t
*gid
) {
1100 /* Check the database directly */
1101 z
= hashmap_get(database_by_groupname
, name
);
1103 *gid
= PTR_TO_GID(z
);
1107 /* Also check NSS */
1117 if (!errno_is_not_exists(errno
))
1118 return log_error_errno(errno
, "Failed to check if group %s already exists: %m", name
);
1124 static int add_group(Item
*i
) {
1129 r
= get_gid_by_name(i
->name
, &i
->gid
);
1133 log_debug("Group %s already exists.", i
->name
);
1138 /* Try to use the suggested numeric gid */
1140 r
= gid_is_ok(i
->gid
);
1142 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1143 if (i
->id_set_strict
) {
1144 /* If we require the gid to already exist we can return here:
1145 * r > 0: means the gid does not exist -> fail
1146 * r == 0: means the gid exists -> nothing more to do.
1149 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1150 "Failed to create %s: please create GID %d",
1156 log_debug("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1161 /* Try to reuse the numeric uid, if there's one */
1162 if (!i
->gid_set
&& i
->uid_set
) {
1163 r
= gid_is_ok((gid_t
) i
->uid
);
1165 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1167 i
->gid
= (gid_t
) i
->uid
;
1172 /* If that didn't work, try to read it from the specified path */
1176 if (read_id_from_file(i
, NULL
, &c
) > 0) {
1178 if (c
<= 0 || !uid_range_contains(uid_range
, n_uid_range
, c
))
1179 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", c
, i
->name
);
1183 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1188 log_debug("Group ID " GID_FMT
" of file for %s already used.", c
, i
->name
);
1193 /* And if that didn't work either, let's try to find a free one */
1196 /* We look for new GIDs in the UID pool! */
1197 r
= uid_range_next_lower(uid_range
, n_uid_range
, &search_uid
);
1199 return log_error_errno(r
, "No free group ID available for %s.", i
->name
);
1201 r
= gid_is_ok(search_uid
);
1203 return log_error_errno(r
, "Failed to verify gid " GID_FMT
": %m", i
->gid
);
1209 i
->gid
= search_uid
;
1212 r
= ordered_hashmap_ensure_allocated(&todo_gids
, NULL
);
1216 r
= ordered_hashmap_put(todo_gids
, GID_TO_PTR(i
->gid
), i
);
1220 i
->todo_group
= true;
1221 log_info("Creating group %s with gid " GID_FMT
".", i
->name
, i
->gid
);
1226 static int process_item(Item
*i
) {
1236 j
= ordered_hashmap_get(groups
, i
->group_name
?: i
->name
);
1237 if (j
&& j
->todo_group
) {
1238 /* When a group with the target name is already in queue,
1239 * use the information about the group and do not create
1240 * duplicated group entry. */
1241 i
->gid_set
= j
->gid_set
;
1243 i
->id_set_strict
= true;
1244 } else if (i
->group_name
) {
1245 /* When a group name was given instead of a GID and it's
1246 * not in queue, then it must already exist. */
1247 r
= get_gid_by_name(i
->group_name
, &i
->gid
);
1249 return log_error_errno(r
, "Group %s not found.", i
->group_name
);
1251 i
->id_set_strict
= true;
1262 return add_group(i
);
1265 assert_not_reached("Unknown item type");
1269 static Item
* item_free(Item
*i
) {
1274 free(i
->group_name
);
1277 free(i
->description
);
1283 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1284 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops
, char, string_hash_func
, string_compare_func
, Item
, item_free
);
1286 static int add_implicit(void) {
1291 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1292 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, members
, iterator
) {
1296 if (!ordered_hashmap_get(users
, *m
)) {
1297 _cleanup_(item_freep
) Item
*j
= NULL
;
1299 r
= ordered_hashmap_ensure_allocated(&users
, &item_hash_ops
);
1308 j
->name
= strdup(*m
);
1312 r
= ordered_hashmap_put(users
, j
->name
, j
);
1316 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1320 if (!(ordered_hashmap_get(users
, g
) ||
1321 ordered_hashmap_get(groups
, g
))) {
1322 _cleanup_(item_freep
) Item
*j
= NULL
;
1324 r
= ordered_hashmap_ensure_allocated(&groups
, &item_hash_ops
);
1332 j
->type
= ADD_GROUP
;
1333 j
->name
= strdup(g
);
1337 r
= ordered_hashmap_put(groups
, j
->name
, j
);
1341 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1349 static bool item_equal(Item
*a
, Item
*b
) {
1353 if (a
->type
!= b
->type
)
1356 if (!streq_ptr(a
->name
, b
->name
))
1359 if (!streq_ptr(a
->uid_path
, b
->uid_path
))
1362 if (!streq_ptr(a
->gid_path
, b
->gid_path
))
1365 if (!streq_ptr(a
->description
, b
->description
))
1368 if (a
->uid_set
!= b
->uid_set
)
1371 if (a
->uid_set
&& a
->uid
!= b
->uid
)
1374 if (a
->gid_set
!= b
->gid_set
)
1377 if (a
->gid_set
&& a
->gid
!= b
->gid
)
1380 if (!streq_ptr(a
->home
, b
->home
))
1383 if (!streq_ptr(a
->shell
, b
->shell
))
1389 static int parse_line(const char *fname
, unsigned line
, const char *buffer
) {
1391 static const Specifier specifier_table
[] = {
1392 { 'm', specifier_machine_id
, NULL
},
1393 { 'b', specifier_boot_id
, NULL
},
1394 { 'H', specifier_host_name
, NULL
},
1395 { 'v', specifier_kernel_release
, NULL
},
1396 { 'T', specifier_tmp_dir
, NULL
},
1397 { 'V', specifier_var_tmp_dir
, NULL
},
1401 _cleanup_free_
char *action
= NULL
,
1402 *name
= NULL
, *resolved_name
= NULL
,
1403 *id
= NULL
, *resolved_id
= NULL
,
1404 *description
= NULL
, *resolved_description
= NULL
,
1405 *home
= NULL
, *resolved_home
= NULL
,
1406 *shell
= NULL
, *resolved_shell
= NULL
;
1407 _cleanup_(item_freep
) Item
*i
= NULL
;
1419 r
= extract_many_words(&p
, NULL
, EXTRACT_UNQUOTE
,
1420 &action
, &name
, &id
, &description
, &home
, &shell
, NULL
);
1422 return log_error_errno(r
, "[%s:%u] Syntax error.", fname
, line
);
1424 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1425 "[%s:%u] Missing action and name columns.", fname
, line
);
1427 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1428 "[%s:%u] Trailing garbage.", fname
, line
);
1431 if (strlen(action
) != 1)
1432 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1433 "[%s:%u] Unknown modifier '%s'", fname
, line
, action
);
1435 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
))
1436 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG
),
1437 "[%s:%u] Unknown command type '%c'.", fname
, line
, action
[0]);
1440 if (empty_or_dash(name
))
1444 r
= specifier_printf(name
, specifier_table
, NULL
, &resolved_name
);
1446 log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s", fname
, line
, name
);
1448 if (!valid_user_group_name(resolved_name
))
1449 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1450 "[%s:%u] '%s' is not a valid user or group name.",
1451 fname
, line
, resolved_name
);
1455 if (empty_or_dash(id
))
1459 r
= specifier_printf(id
, specifier_table
, NULL
, &resolved_id
);
1461 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1465 /* Verify description */
1466 if (empty_or_dash(description
))
1467 description
= mfree(description
);
1470 r
= specifier_printf(description
, specifier_table
, NULL
, &resolved_description
);
1472 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1473 fname
, line
, description
);
1475 if (!valid_gecos(resolved_description
))
1476 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1477 "[%s:%u] '%s' is not a valid GECOS field.",
1478 fname
, line
, resolved_description
);
1482 if (empty_or_dash(home
))
1486 r
= specifier_printf(home
, specifier_table
, NULL
, &resolved_home
);
1488 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1491 if (!valid_home(resolved_home
))
1492 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1493 "[%s:%u] '%s' is not a valid home directory field.",
1494 fname
, line
, resolved_home
);
1498 if (empty_or_dash(shell
))
1499 shell
= mfree(shell
);
1502 r
= specifier_printf(shell
, specifier_table
, NULL
, &resolved_shell
);
1504 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s",
1505 fname
, line
, shell
);
1507 if (!valid_shell(resolved_shell
))
1508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1509 "[%s:%u] '%s' is not a valid login shell field.",
1510 fname
, line
, resolved_shell
);
1513 switch (action
[0]) {
1517 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1518 "[%s:%u] Lines of type 'r' don't take a name field.",
1522 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1523 "[%s:%u] Lines of type 'r' require a ID range in the third field.",
1526 if (description
|| home
|| shell
)
1527 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1528 "[%s:%u] Lines of type '%c' don't take a %s field.",
1529 fname
, line
, action
[0],
1530 description
? "GECOS" : home
? "home directory" : "login shell");
1532 r
= uid_range_add_str(&uid_range
, &n_uid_range
, resolved_id
);
1534 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1535 "[%s:%u] Invalid UID range %s.", fname
, line
, resolved_id
);
1540 /* Try to extend an existing member or group item */
1542 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1543 "[%s:%u] Lines of type 'm' require a user name in the second field.",
1547 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1548 "[%s:%u] Lines of type 'm' require a group name in the third field.",
1551 if (!valid_user_group_name(resolved_id
))
1552 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1553 "[%s:%u] '%s' is not a valid user or group name.",
1554 fname
, line
, resolved_id
);
1556 if (description
|| home
|| shell
)
1557 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1558 "[%s:%u] Lines of type '%c' don't take a %s field.",
1559 fname
, line
, action
[0],
1560 description
? "GECOS" : home
? "home directory" : "login shell");
1562 r
= string_strv_ordered_hashmap_put(&members
, resolved_id
, resolved_name
);
1564 return log_error_errno(r
, "Failed to store mapping for %s: %m", resolved_id
);
1571 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1572 "[%s:%u] Lines of type 'u' require a user name in the second field.",
1575 r
= ordered_hashmap_ensure_allocated(&users
, &item_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 if (valid_user_group_name(gid
))
1593 i
->group_name
= TAKE_PTR(gid
);
1595 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1598 i
->id_set_strict
= true;
1600 free_and_replace(resolved_id
, uid
);
1602 if (!streq(resolved_id
, "-")) {
1603 r
= parse_uid(resolved_id
, &i
->uid
);
1605 return log_error_errno(r
, "Failed to parse UID: '%s': %m", id
);
1611 i
->description
= TAKE_PTR(resolved_description
);
1612 i
->home
= TAKE_PTR(resolved_home
);
1613 i
->shell
= TAKE_PTR(resolved_shell
);
1620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1621 "[%s:%u] Lines of type 'g' require a user name in the second field.",
1624 if (description
|| home
|| shell
)
1625 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1626 "[%s:%u] Lines of type '%c' don't take a %s field.",
1627 fname
, line
, action
[0],
1628 description
? "GECOS" : home
? "home directory" : "login shell");
1630 r
= ordered_hashmap_ensure_allocated(&groups
, &item_hash_ops
);
1639 if (path_is_absolute(resolved_id
)) {
1640 i
->gid_path
= TAKE_PTR(resolved_id
);
1641 path_simplify(i
->gid_path
, false);
1643 r
= parse_gid(resolved_id
, &i
->gid
);
1645 return log_error_errno(r
, "Failed to parse GID: '%s': %m", id
);
1658 i
->type
= action
[0];
1659 i
->name
= TAKE_PTR(resolved_name
);
1661 existing
= ordered_hashmap_get(h
, i
->name
);
1663 /* Two identical items are fine */
1664 if (!item_equal(existing
, i
))
1665 log_warning("Two or more conflicting lines for %s configured, ignoring.", i
->name
);
1670 r
= ordered_hashmap_put(h
, i
->name
, i
);
1678 static int read_config_file(const char *fn
, bool ignore_enoent
) {
1679 _cleanup_fclose_
FILE *rf
= NULL
;
1689 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf
);
1691 if (ignore_enoent
&& r
== -ENOENT
)
1694 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
1701 _cleanup_free_
char *line
= NULL
;
1705 k
= read_line(f
, LONG_LINE_MAX
, &line
);
1707 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
1714 if (IN_SET(*l
, 0, '#'))
1717 k
= parse_line(fn
, v
, l
);
1718 if (k
< 0 && r
== 0)
1723 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
1731 static int cat_config(void) {
1732 _cleanup_strv_free_
char **files
= NULL
;
1735 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
1739 (void) pager_open(arg_pager_flags
);
1741 return cat_files(NULL
, files
, 0);
1744 static int help(void) {
1745 _cleanup_free_
char *link
= NULL
;
1748 r
= terminal_urlify_man("systemd-sysusers.service", "8", &link
);
1752 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1753 "Creates system user accounts.\n\n"
1754 " -h --help Show this help\n"
1755 " --version Show package version\n"
1756 " --cat-config Show configuration files\n"
1757 " --root=PATH Operate on an alternate filesystem root\n"
1758 " --replace=PATH Treat arguments as replacement for PATH\n"
1759 " --inline Treat arguments as configuration lines\n"
1760 " --no-pager Do not pipe output into a pager\n"
1761 "\nSee the %s for details.\n"
1762 , program_invocation_short_name
1769 static int parse_argv(int argc
, char *argv
[]) {
1772 ARG_VERSION
= 0x100,
1780 static const struct option options
[] = {
1781 { "help", no_argument
, NULL
, 'h' },
1782 { "version", no_argument
, NULL
, ARG_VERSION
},
1783 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
1784 { "root", required_argument
, NULL
, ARG_ROOT
},
1785 { "replace", required_argument
, NULL
, ARG_REPLACE
},
1786 { "inline", no_argument
, NULL
, ARG_INLINE
},
1787 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
1796 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
1806 case ARG_CAT_CONFIG
:
1807 arg_cat_config
= true;
1811 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
1817 if (!path_is_absolute(optarg
) ||
1818 !endswith(optarg
, ".conf"))
1819 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1820 "The argument to --replace= must an absolute path to a config file");
1822 arg_replace
= optarg
;
1830 arg_pager_flags
|= PAGER_DISABLE
;
1837 assert_not_reached("Unhandled option");
1840 if (arg_replace
&& arg_cat_config
)
1841 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1842 "Option --replace= is not supported with --cat-config");
1844 if (arg_replace
&& optind
>= argc
)
1845 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1846 "When --replace= is given, some configuration items must be specified");
1851 static int parse_arguments(char **args
) {
1856 STRV_FOREACH(arg
, args
) {
1858 /* Use (argument):n, where n==1 for the first positional arg */
1859 r
= parse_line("(argument)", pos
, *arg
);
1861 r
= read_config_file(*arg
, false);
1871 static int read_config_files(char **args
) {
1872 _cleanup_strv_free_
char **files
= NULL
;
1873 _cleanup_free_
char *p
= NULL
;
1877 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
1881 STRV_FOREACH(f
, files
)
1882 if (p
&& path_equal(*f
, p
)) {
1883 log_debug("Parsing arguments at position \"%s\"…", *f
);
1885 r
= parse_arguments(args
);
1889 log_debug("Reading config file \"%s\"…", *f
);
1891 /* Just warn, ignore result otherwise */
1892 (void) read_config_file(*f
, true);
1898 static int run(int argc
, char *argv
[]) {
1899 _cleanup_close_
int lock
= -1;
1904 r
= parse_argv(argc
, argv
);
1908 log_setup_service();
1911 return cat_config();
1915 r
= mac_selinux_init();
1917 return log_error_errno(r
, "SELinux setup failed: %m");
1919 /* If command line arguments are specified along with --replace, read all
1920 * configuration files and insert the positional arguments at the specified
1921 * place. Otherwise, if command line arguments are specified, execute just
1922 * them, and finally, without --replace= or any positional arguments, just
1923 * read configuration and execute it.
1925 if (arg_replace
|| optind
>= argc
)
1926 r
= read_config_files(argv
+ optind
);
1928 r
= parse_arguments(argv
+ optind
);
1932 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our detection
1933 * whether the names or UID/GID area already used otherwise doesn't get confused. After all, even though
1934 * nss-systemd synthesizes these users/groups, they should still appear in /etc/passwd and /etc/group, as the
1935 * synthesizing logic is merely supposed to be fallback for cases where we run with a completely unpopulated
1937 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
1938 return log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
1941 /* Default to default range of 1..SYSTEM_UID_MAX */
1942 r
= uid_range_add(&uid_range
, &n_uid_range
, 1, SYSTEM_UID_MAX
);
1951 lock
= take_etc_passwd_lock(arg_root
);
1953 return log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
1955 r
= load_user_database();
1957 return log_error_errno(r
, "Failed to load user database: %m");
1959 r
= load_group_database();
1961 return log_error_errno(r
, "Failed to read group database: %m");
1963 ORDERED_HASHMAP_FOREACH(i
, groups
, iterator
)
1964 (void) process_item(i
);
1966 ORDERED_HASHMAP_FOREACH(i
, users
, iterator
)
1967 (void) process_item(i
);
1971 return log_error_errno(r
, "Failed to write files: %m");
1976 DEFINE_MAIN_FUNCTION(run
);