1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "alloc-util.h"
9 #include "conf-files.h"
10 #include "constants.h"
12 #include "creds-util.h"
13 #include "dissect-image.h"
17 #include "format-util.h"
20 #include "libcrypt-util.h"
21 #include "main-func.h"
22 #include "memory-util.h"
23 #include "mount-util.h"
24 #include "nscd-flush.h"
26 #include "parse-argument.h"
27 #include "path-util.h"
28 #include "pretty-print.h"
29 #include "selinux-util.h"
31 #include "smack-util.h"
32 #include "specifier.h"
33 #include "stat-util.h"
34 #include "string-util.h"
36 #include "sync-util.h"
37 #include "tmpfile-util-label.h"
38 #include "uid-classification.h"
39 #include "uid-range.h"
40 #include "user-util.h"
43 typedef enum ItemType
{
50 static const char* item_type_to_string(ItemType t
) {
84 /* When set the group with the specified GID must exist
85 * and the check if a UID clashes with the GID is skipped.
95 static char *arg_root
= NULL
;
96 static char *arg_image
= NULL
;
97 static CatFlags arg_cat_flags
= CAT_CONFIG_OFF
;
98 static const char *arg_replace
= NULL
;
99 static bool arg_dry_run
= false;
100 static bool arg_inline
= false;
101 static PagerFlags arg_pager_flags
= 0;
102 static ImagePolicy
*arg_image_policy
= NULL
;
104 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
105 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
106 STATIC_DESTRUCTOR_REGISTER(arg_image_policy
, image_policy_freep
);
108 typedef struct Context
{
109 OrderedHashmap
*users
, *groups
;
110 OrderedHashmap
*todo_uids
, *todo_gids
;
111 OrderedHashmap
*members
;
113 Hashmap
*database_by_uid
, *database_by_username
;
114 Hashmap
*database_by_gid
, *database_by_groupname
;
116 /* A helper set to hold names that are used by database_by_{uid,gid,username,groupname} above. */
122 UGIDAllocationRange login_defs
;
123 bool login_defs_need_warning
;
126 static void context_done(Context
*c
) {
129 ordered_hashmap_free(c
->groups
);
130 ordered_hashmap_free(c
->users
);
131 ordered_hashmap_free(c
->members
);
132 ordered_hashmap_free(c
->todo_uids
);
133 ordered_hashmap_free(c
->todo_gids
);
135 hashmap_free(c
->database_by_uid
);
136 hashmap_free(c
->database_by_username
);
137 hashmap_free(c
->database_by_gid
);
138 hashmap_free(c
->database_by_groupname
);
140 set_free_free(c
->names
);
141 uid_range_free(c
->uid_range
);
144 static void maybe_emit_login_defs_warning(Context
*c
) {
147 if (!c
->login_defs_need_warning
)
150 if (c
->login_defs
.system_alloc_uid_min
!= SYSTEM_ALLOC_UID_MIN
||
151 c
->login_defs
.system_uid_max
!= SYSTEM_UID_MAX
)
152 log_warning("login.defs specifies UID allocation range "UID_FMT
"–"UID_FMT
153 " that is different than the built-in defaults ("UID_FMT
"–"UID_FMT
")",
154 c
->login_defs
.system_alloc_uid_min
, c
->login_defs
.system_uid_max
,
155 (uid_t
) SYSTEM_ALLOC_UID_MIN
, (uid_t
) SYSTEM_UID_MAX
);
156 if (c
->login_defs
.system_alloc_gid_min
!= SYSTEM_ALLOC_GID_MIN
||
157 c
->login_defs
.system_gid_max
!= SYSTEM_GID_MAX
)
158 log_warning("login.defs specifies GID allocation range "GID_FMT
"–"GID_FMT
159 " that is different than the built-in defaults ("GID_FMT
"–"GID_FMT
")",
160 c
->login_defs
.system_alloc_gid_min
, c
->login_defs
.system_gid_max
,
161 (gid_t
) SYSTEM_ALLOC_GID_MIN
, (gid_t
) SYSTEM_GID_MAX
);
163 c
->login_defs_need_warning
= false;
166 static int load_user_database(Context
*c
) {
167 _cleanup_fclose_
FILE *f
= NULL
;
168 const char *passwd_path
;
174 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
175 f
= fopen(passwd_path
, "re");
177 return errno
== ENOENT
? 0 : -errno
;
179 r
= hashmap_ensure_allocated(&c
->database_by_username
, &string_hash_ops
);
183 r
= hashmap_ensure_allocated(&c
->database_by_uid
, NULL
);
187 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
188 r
= set_ensure_allocated(&c
->names
, NULL
);
192 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
194 char *n
= strdup(pw
->pw_name
);
198 r
= set_consume(c
->names
, n
);
201 assert(r
> 0); /* The set uses pointer comparisons, so n must not be in the set. */
203 r
= hashmap_put(c
->database_by_username
, n
, UID_TO_PTR(pw
->pw_uid
));
205 log_debug_errno(r
, "%s: user '%s' is listed twice, ignoring duplicate uid.",
210 r
= hashmap_put(c
->database_by_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
212 log_debug_errno(r
, "%s: uid "UID_FMT
" is listed twice, ignoring duplicate name.",
213 passwd_path
, pw
->pw_uid
);
220 static int load_group_database(Context
*c
) {
221 _cleanup_fclose_
FILE *f
= NULL
;
222 const char *group_path
;
228 group_path
= prefix_roota(arg_root
, "/etc/group");
229 f
= fopen(group_path
, "re");
231 return errno
== ENOENT
? 0 : -errno
;
233 r
= hashmap_ensure_allocated(&c
->database_by_groupname
, &string_hash_ops
);
237 r
= hashmap_ensure_allocated(&c
->database_by_gid
, NULL
);
241 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
242 r
= set_ensure_allocated(&c
->names
, NULL
);
246 while ((r
= fgetgrent_sane(f
, &gr
)) > 0) {
248 char *n
= strdup(gr
->gr_name
);
252 r
= set_consume(c
->names
, n
);
255 assert(r
> 0); /* The set uses pointer comparisons, so n must not be in the set. */
257 r
= hashmap_put(c
->database_by_groupname
, n
, GID_TO_PTR(gr
->gr_gid
));
259 log_debug_errno(r
, "%s: group '%s' is listed twice, ignoring duplicate gid.",
264 r
= hashmap_put(c
->database_by_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
266 log_debug_errno(r
, "%s: gid "GID_FMT
" is listed twice, ignoring duplicate name.",
267 group_path
, gr
->gr_gid
);
274 static int make_backup(const char *target
, const char *x
) {
275 _cleanup_(unlink_and_freep
) char *dst_tmp
= NULL
;
276 _cleanup_fclose_
FILE *dst
= NULL
;
277 _cleanup_close_
int src
= -EBADF
;
285 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
287 if (errno
== ENOENT
) /* No backup necessary... */
293 if (fstat(src
, &st
) < 0)
296 r
= fopen_temporary_label(
297 target
, /* The path for which to the look up the label */
298 x
, /* Where we want the file actually to end up */
299 &dst
, /* The temporary file we write to */
304 r
= copy_bytes(src
, fileno(dst
), UINT64_MAX
, COPY_REFLINK
);
308 backup
= strjoina(x
, "-");
310 /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
311 * unreadable by others, then it isn't too bad... */
312 r
= fchmod_and_chown_with_fallback(fileno(dst
), dst_tmp
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
314 log_warning_errno(r
, "Failed to change access mode or ownership of %s: %m", backup
);
316 if (futimens(fileno(dst
), (const struct timespec
[2]) { st
.st_atim
, st
.st_mtim
}) < 0)
317 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
319 r
= fsync_full(fileno(dst
));
323 if (rename(dst_tmp
, backup
) < 0)
326 dst_tmp
= mfree(dst_tmp
); /* disable the unlink_and_freep() hook now that the file has been renamed */
330 static int putgrent_with_members(
332 const struct group
*gr
,
342 a
= ordered_hashmap_get(c
->members
, gr
->gr_name
);
344 _cleanup_strv_free_
char **l
= NULL
;
347 l
= strv_copy(gr
->gr_mem
);
352 if (strv_contains(l
, *i
))
355 r
= strv_extend(&l
, *i
);
371 r
= putgrent_sane(&t
, group
);
372 return r
< 0 ? r
: 1;
376 return putgrent_sane(gr
, group
);
380 static int putsgent_with_members(
382 const struct sgrp
*sg
,
391 a
= ordered_hashmap_get(c
->members
, sg
->sg_namp
);
393 _cleanup_strv_free_
char **l
= NULL
;
396 l
= strv_copy(sg
->sg_mem
);
401 if (strv_contains(l
, *i
))
404 r
= strv_extend(&l
, *i
);
420 r
= putsgent_sane(&t
, gshadow
);
421 return r
< 0 ? r
: 1;
425 return putsgent_sane(sg
, gshadow
);
429 static const char* pick_shell(const Item
*i
) {
430 if (i
->type
!= ADD_USER
)
434 if (i
->uid_set
&& i
->uid
== 0)
435 return default_root_shell(arg_root
);
439 static int write_temporary_passwd(
441 const char *passwd_path
,
443 char **ret_tmpfile_path
) {
445 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
446 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
447 struct passwd
*pw
= NULL
;
453 if (ordered_hashmap_isempty(c
->todo_uids
))
457 log_info("Would write /etc/passwd%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
461 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
463 return log_debug_errno(r
, "Failed to open temporary copy of %s: %m", passwd_path
);
465 original
= fopen(passwd_path
, "re");
468 /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
469 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
470 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
471 * it easier to depend on sysusers in packaging scripts and suchlike. */
472 r
= copy_rights_with_fallback(fileno(original
), fileno(passwd
), passwd_tmp
);
474 return log_debug_errno(r
, "Failed to copy permissions from %s to %s: %m",
475 passwd_path
, passwd_tmp
);
477 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
478 i
= ordered_hashmap_get(c
->users
, pw
->pw_name
);
479 if (i
&& i
->todo_user
)
480 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
481 "%s: User \"%s\" already exists.",
482 passwd_path
, pw
->pw_name
);
484 if (ordered_hashmap_contains(c
->todo_uids
, UID_TO_PTR(pw
->pw_uid
)))
485 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
486 "%s: Detected collision for UID " UID_FMT
".",
487 passwd_path
, pw
->pw_uid
);
489 /* Make sure we keep the NIS entries (if any) at the end. */
490 if (IN_SET(pw
->pw_name
[0], '+', '-'))
493 r
= putpwent_sane(pw
, passwd
);
495 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary passwd file: %m",
499 return log_debug_errno(r
, "Failed to read %s: %m", passwd_path
);
503 return log_debug_errno(errno
, "Failed to open %s: %m", passwd_path
);
504 if (fchmod(fileno(passwd
), 0644) < 0)
505 return log_debug_errno(errno
, "Failed to fchmod %s: %m", passwd_tmp
);
508 ORDERED_HASHMAP_FOREACH(i
, c
->todo_uids
) {
509 _cleanup_free_
char *creds_shell
= NULL
, *cn
= NULL
;
515 .pw_gecos
= (char*) strempty(i
->description
),
517 /* "x" means the password is stored in the shadow file */
518 .pw_passwd
= (char*) PASSWORD_SEE_SHADOW
,
520 /* We default to the root directory as home */
521 .pw_dir
= i
->home
?: (char*) "/",
523 /* Initialize the shell to nologin, with one exception:
524 * for root we patch in something special */
525 .pw_shell
= (char*) pick_shell(i
),
528 /* Try to pick up the shell for this account via the credentials logic */
529 cn
= strjoin("passwd.shell.", i
->name
);
533 r
= read_credential(cn
, (void**) &creds_shell
, NULL
);
535 log_debug_errno(r
, "Couldn't read credential '%s', ignoring: %m", cn
);
537 n
.pw_shell
= creds_shell
;
539 r
= putpwent_sane(&n
, passwd
);
541 return log_debug_errno(r
, "Failed to add new user \"%s\" to temporary passwd file: %m",
545 /* Append the remaining NIS entries if any */
547 r
= putpwent_sane(pw
, passwd
);
549 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary passwd file: %m",
552 r
= fgetpwent_sane(original
, &pw
);
554 return log_debug_errno(r
, "Failed to read %s: %m", passwd_path
);
559 r
= fflush_sync_and_check(passwd
);
561 return log_debug_errno(r
, "Failed to flush %s: %m", passwd_tmp
);
563 *ret_tmpfile
= TAKE_PTR(passwd
);
564 *ret_tmpfile_path
= TAKE_PTR(passwd_tmp
);
569 static usec_t
epoch_or_now(void) {
572 if (secure_getenv_uint64("SOURCE_DATE_EPOCH", &epoch
) >= 0) {
573 if (epoch
> UINT64_MAX
/USEC_PER_SEC
) /* Overflow check */
574 return USEC_INFINITY
;
575 return (usec_t
) epoch
* USEC_PER_SEC
;
578 return now(CLOCK_REALTIME
);
581 static int write_temporary_shadow(
583 const char *shadow_path
,
585 char **ret_tmpfile_path
) {
587 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
588 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
589 struct spwd
*sp
= NULL
;
596 if (ordered_hashmap_isempty(c
->todo_uids
))
600 log_info("Would write /etc/shadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
604 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
606 return log_debug_errno(r
, "Failed to open temporary copy of %s: %m", shadow_path
);
608 lstchg
= (long) (epoch_or_now() / USEC_PER_DAY
);
610 original
= fopen(shadow_path
, "re");
613 r
= copy_rights_with_fallback(fileno(original
), fileno(shadow
), shadow_tmp
);
615 return log_debug_errno(r
, "Failed to copy permissions from %s to %s: %m",
616 shadow_path
, shadow_tmp
);
618 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
619 i
= ordered_hashmap_get(c
->users
, sp
->sp_namp
);
620 if (i
&& i
->todo_user
) {
621 /* we will update the existing entry */
622 sp
->sp_lstchg
= lstchg
;
624 /* only the /etc/shadow stage is left, so we can
625 * safely remove the item from the todo set */
626 i
->todo_user
= false;
627 ordered_hashmap_remove(c
->todo_uids
, UID_TO_PTR(i
->uid
));
630 /* Make sure we keep the NIS entries (if any) at the end. */
631 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
634 r
= putspent_sane(sp
, shadow
);
636 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary shadow file: %m",
641 return log_debug_errno(r
, "Failed to read %s: %m", shadow_path
);
645 return log_debug_errno(errno
, "Failed to open %s: %m", shadow_path
);
646 if (fchmod(fileno(shadow
), 0000) < 0)
647 return log_debug_errno(errno
, "Failed to fchmod %s: %m", shadow_tmp
);
650 ORDERED_HASHMAP_FOREACH(i
, c
->todo_uids
) {
651 _cleanup_(erase_and_freep
) char *creds_password
= NULL
;
662 .sp_flag
= ULONG_MAX
, /* this appears to be what everybody does ... */
665 r
= get_credential_user_password(i
->name
, &creds_password
, &is_hashed
);
667 log_debug_errno(r
, "Couldn't read password credential for user '%s', ignoring: %m", i
->name
);
669 if (creds_password
&& !is_hashed
) {
670 _cleanup_(erase_and_freep
) char* plaintext_password
= TAKE_PTR(creds_password
);
671 r
= hash_password(plaintext_password
, &creds_password
);
673 return log_debug_errno(r
, "Failed to hash password: %m");
677 n
.sp_pwdp
= creds_password
;
678 else if (streq(i
->name
, "root"))
679 /* Let firstboot set the password later */
680 n
.sp_pwdp
= (char*) PASSWORD_UNPROVISIONED
;
682 n
.sp_pwdp
= (char*) PASSWORD_LOCKED_AND_INVALID
;
684 r
= putspent_sane(&n
, shadow
);
686 return log_debug_errno(r
, "Failed to add new user \"%s\" to temporary shadow file: %m",
690 /* Append the remaining NIS entries if any */
692 r
= putspent_sane(sp
, shadow
);
694 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary shadow file: %m",
697 r
= fgetspent_sane(original
, &sp
);
699 return log_debug_errno(r
, "Failed to read %s: %m", shadow_path
);
703 if (!IN_SET(errno
, 0, ENOENT
))
706 r
= fflush_sync_and_check(shadow
);
708 return log_debug_errno(r
, "Failed to flush %s: %m", shadow_tmp
);
710 *ret_tmpfile
= TAKE_PTR(shadow
);
711 *ret_tmpfile_path
= TAKE_PTR(shadow_tmp
);
716 static int write_temporary_group(
718 const char *group_path
,
720 char **ret_tmpfile_path
) {
722 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
723 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
724 bool group_changed
= false;
725 struct group
*gr
= NULL
;
731 if (ordered_hashmap_isempty(c
->todo_gids
) && ordered_hashmap_isempty(c
->members
))
735 log_info("Would write /etc/group%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
739 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
741 return log_error_errno(r
, "Failed to open temporary copy of %s: %m", group_path
);
743 original
= fopen(group_path
, "re");
746 r
= copy_rights_with_fallback(fileno(original
), fileno(group
), group_tmp
);
748 return log_error_errno(r
, "Failed to copy permissions from %s to %s: %m",
749 group_path
, group_tmp
);
751 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
752 /* Safety checks against name and GID collisions. Normally,
753 * this should be unnecessary, but given that we look at the
754 * entries anyway here, let's make an extra verification
755 * step that we don't generate duplicate entries. */
757 i
= ordered_hashmap_get(c
->groups
, gr
->gr_name
);
758 if (i
&& i
->todo_group
)
759 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
760 "%s: Group \"%s\" already exists.",
761 group_path
, gr
->gr_name
);
763 if (ordered_hashmap_contains(c
->todo_gids
, GID_TO_PTR(gr
->gr_gid
)))
764 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
765 "%s: Detected collision for GID " GID_FMT
".",
766 group_path
, gr
->gr_gid
);
768 /* Make sure we keep the NIS entries (if any) at the end. */
769 if (IN_SET(gr
->gr_name
[0], '+', '-'))
772 r
= putgrent_with_members(c
, gr
, group
);
774 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary group file: %m",
777 group_changed
= true;
780 return log_error_errno(r
, "Failed to read %s: %m", group_path
);
784 return log_error_errno(errno
, "Failed to open %s: %m", group_path
);
785 if (fchmod(fileno(group
), 0644) < 0)
786 return log_error_errno(errno
, "Failed to fchmod %s: %m", group_tmp
);
789 ORDERED_HASHMAP_FOREACH(i
, c
->todo_gids
) {
793 .gr_passwd
= (char*) PASSWORD_SEE_SHADOW
,
796 r
= putgrent_with_members(c
, &n
, group
);
798 return log_error_errno(r
, "Failed to add new group \"%s\" to temporary group file: %m",
801 group_changed
= true;
804 /* Append the remaining NIS entries if any */
806 r
= putgrent_sane(gr
, group
);
808 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary group file: %m",
811 r
= fgetgrent_sane(original
, &gr
);
813 return log_error_errno(r
, "Failed to read %s: %m", group_path
);
818 r
= fflush_sync_and_check(group
);
820 return log_error_errno(r
, "Failed to flush %s: %m", group_tmp
);
823 *ret_tmpfile
= TAKE_PTR(group
);
824 *ret_tmpfile_path
= TAKE_PTR(group_tmp
);
829 static int write_temporary_gshadow(
831 const char * gshadow_path
,
833 char **ret_tmpfile_path
) {
836 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
837 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
838 bool group_changed
= false;
844 if (ordered_hashmap_isempty(c
->todo_gids
) && ordered_hashmap_isempty(c
->members
))
848 log_info("Would write /etc/gshadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
852 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
854 return log_error_errno(r
, "Failed to open temporary copy of %s: %m", gshadow_path
);
856 original
= fopen(gshadow_path
, "re");
860 r
= copy_rights_with_fallback(fileno(original
), fileno(gshadow
), gshadow_tmp
);
862 return log_error_errno(r
, "Failed to copy permissions from %s to %s: %m",
863 gshadow_path
, gshadow_tmp
);
865 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
867 i
= ordered_hashmap_get(c
->groups
, sg
->sg_namp
);
868 if (i
&& i
->todo_group
)
869 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
870 "%s: Group \"%s\" already exists.",
871 gshadow_path
, sg
->sg_namp
);
873 r
= putsgent_with_members(c
, sg
, gshadow
);
875 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
878 group_changed
= true;
885 return log_error_errno(errno
, "Failed to open %s: %m", gshadow_path
);
886 if (fchmod(fileno(gshadow
), 0000) < 0)
887 return log_error_errno(errno
, "Failed to fchmod %s: %m", gshadow_tmp
);
890 ORDERED_HASHMAP_FOREACH(i
, c
->todo_gids
) {
893 .sg_passwd
= (char*) PASSWORD_LOCKED_AND_INVALID
,
896 r
= putsgent_with_members(c
, &n
, gshadow
);
898 return log_error_errno(r
, "Failed to add new group \"%s\" to temporary gshadow file: %m",
901 group_changed
= true;
904 r
= fflush_sync_and_check(gshadow
);
906 return log_error_errno(r
, "Failed to flush %s: %m", gshadow_tmp
);
909 *ret_tmpfile
= TAKE_PTR(gshadow
);
910 *ret_tmpfile_path
= TAKE_PTR(gshadow_tmp
);
916 static int write_files(Context
*c
) {
917 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
918 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
922 *passwd_path
= prefix_roota(arg_root
, "/etc/passwd"),
923 *shadow_path
= prefix_roota(arg_root
, "/etc/shadow"),
924 *group_path
= prefix_roota(arg_root
, "/etc/group"),
925 *gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
929 r
= write_temporary_group(c
, group_path
, &group
, &group_tmp
);
933 r
= write_temporary_gshadow(c
, gshadow_path
, &gshadow
, &gshadow_tmp
);
937 r
= write_temporary_passwd(c
, passwd_path
, &passwd
, &passwd_tmp
);
941 r
= write_temporary_shadow(c
, shadow_path
, &shadow
, &shadow_tmp
);
945 /* Make a backup of the old files */
947 r
= make_backup("/etc/group", group_path
);
949 return log_error_errno(r
, "Failed to backup %s: %m", group_path
);
952 r
= make_backup("/etc/gshadow", gshadow_path
);
954 return log_error_errno(r
, "Failed to backup %s: %m", gshadow_path
);
958 r
= make_backup("/etc/passwd", passwd_path
);
960 return log_error_errno(r
, "Failed to backup %s: %m", passwd_path
);
963 r
= make_backup("/etc/shadow", shadow_path
);
965 return log_error_errno(r
, "Failed to backup %s: %m", shadow_path
);
968 /* And make the new files count */
970 r
= rename_and_apply_smack_floor_label(group_tmp
, group_path
);
972 return log_error_errno(r
, "Failed to rename %s to %s: %m",
973 group_tmp
, group_path
);
974 group_tmp
= mfree(group_tmp
);
976 if (!arg_root
&& !arg_image
)
977 (void) nscd_flush_cache(STRV_MAKE("group"));
980 r
= rename_and_apply_smack_floor_label(gshadow_tmp
, gshadow_path
);
982 return log_error_errno(r
, "Failed to rename %s to %s: %m",
983 gshadow_tmp
, gshadow_path
);
985 gshadow_tmp
= mfree(gshadow_tmp
);
989 r
= rename_and_apply_smack_floor_label(passwd_tmp
, passwd_path
);
991 return log_error_errno(r
, "Failed to rename %s to %s: %m",
992 passwd_tmp
, passwd_path
);
994 passwd_tmp
= mfree(passwd_tmp
);
996 if (!arg_root
&& !arg_image
)
997 (void) nscd_flush_cache(STRV_MAKE("passwd"));
1000 r
= rename_and_apply_smack_floor_label(shadow_tmp
, shadow_path
);
1002 return log_error_errno(r
, "Failed to rename %s to %s: %m",
1003 shadow_tmp
, shadow_path
);
1005 shadow_tmp
= mfree(shadow_tmp
);
1011 static int uid_is_ok(
1015 bool check_with_gid
) {
1020 /* Let's see if we already have assigned the UID a second time */
1021 if (ordered_hashmap_get(c
->todo_uids
, UID_TO_PTR(uid
)))
1024 /* Try to avoid using uids that are already used by a group
1025 * that doesn't have the same name as our new user. */
1026 if (check_with_gid
) {
1029 i
= ordered_hashmap_get(c
->todo_gids
, GID_TO_PTR(uid
));
1030 if (i
&& !streq(i
->name
, name
))
1034 /* Let's check the files directly */
1035 if (hashmap_contains(c
->database_by_uid
, UID_TO_PTR(uid
)))
1038 if (check_with_gid
) {
1041 n
= hashmap_get(c
->database_by_gid
, GID_TO_PTR(uid
));
1042 if (n
&& !streq(n
, name
))
1046 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
1048 _cleanup_free_
struct group
*g
= NULL
;
1050 r
= getpwuid_malloc(uid
, /* ret= */ NULL
);
1056 if (check_with_gid
) {
1057 r
= getgrgid_malloc((gid_t
) uid
, &g
);
1059 if (!streq(g
->gr_name
, name
))
1061 } else if (r
!= -ESRCH
)
1069 static int root_stat(const char *p
, struct stat
*st
) {
1072 fix
= prefix_roota(arg_root
, p
);
1073 return RET_NERRNO(stat(fix
, st
));
1076 static int read_id_from_file(Item
*i
, uid_t
*ret_uid
, gid_t
*ret_gid
) {
1078 bool found_uid
= false, found_gid
= false;
1084 /* First, try to get the GID directly */
1085 if (ret_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
1090 /* Then, try to get the UID directly */
1091 if ((ret_uid
|| (ret_gid
&& !found_gid
))
1093 && root_stat(i
->uid_path
, &st
) >= 0) {
1098 /* If we need the gid, but had no success yet, also derive it from the UID path */
1099 if (ret_gid
&& !found_gid
) {
1105 /* If that didn't work yet, then let's reuse the GID as UID */
1106 if (ret_uid
&& !found_uid
&& i
->gid_path
) {
1111 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
1112 uid
= (uid_t
) st
.st_gid
;
1134 static int add_user(Context
*c
, Item
*i
) {
1141 /* Check the database directly */
1142 z
= hashmap_get(c
->database_by_username
, i
->name
);
1144 log_debug("User %s already exists.", i
->name
);
1145 i
->uid
= PTR_TO_UID(z
);
1151 _cleanup_free_
struct passwd
*p
= NULL
;
1153 /* Also check NSS */
1154 r
= getpwnam_malloc(i
->name
, &p
);
1156 log_debug("User %s already exists.", i
->name
);
1160 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
1167 return log_error_errno(r
, "Failed to check if user %s already exists: %m", i
->name
);
1170 /* Try to use the suggested numeric UID */
1172 r
= uid_is_ok(c
, i
->uid
, i
->name
, !i
->id_set_strict
);
1174 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1176 log_info("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
1181 /* If that didn't work, try to read it from the specified path */
1185 if (read_id_from_file(i
, &candidate
, NULL
) > 0) {
1187 if (candidate
<= 0 || !uid_range_contains(c
->uid_range
, candidate
))
1188 log_debug("User ID " UID_FMT
" of file not suitable for %s.", candidate
, i
->name
);
1190 r
= uid_is_ok(c
, candidate
, i
->name
, true);
1192 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1197 log_debug("User ID " UID_FMT
" of file for %s is already used.", candidate
, i
->name
);
1202 /* Otherwise, try to reuse the group ID */
1203 if (!i
->uid_set
&& i
->gid_set
) {
1204 r
= uid_is_ok(c
, (uid_t
) i
->gid
, i
->name
, true);
1206 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1208 i
->uid
= (uid_t
) i
->gid
;
1213 /* And if that didn't work either, let's try to find a free one */
1215 maybe_emit_login_defs_warning(c
);
1218 r
= uid_range_next_lower(c
->uid_range
, &c
->search_uid
);
1220 return log_error_errno(r
, "No free user ID available for %s.", i
->name
);
1222 r
= uid_is_ok(c
, c
->search_uid
, i
->name
, true);
1224 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1230 i
->uid
= c
->search_uid
;
1233 r
= ordered_hashmap_ensure_put(&c
->todo_uids
, NULL
, UID_TO_PTR(i
->uid
), i
);
1235 return log_error_errno(r
, "Requested user %s with UID " UID_FMT
" and gid" GID_FMT
" to be created is duplicated "
1236 "or conflicts with another user.", i
->name
, i
->uid
, i
->gid
);
1240 return log_error_errno(r
, "Failed to store user %s with UID " UID_FMT
" and GID " GID_FMT
" to be created: %m",
1241 i
->name
, i
->uid
, i
->gid
);
1243 i
->todo_user
= true;
1244 log_info("Creating user '%s' (%s) with UID " UID_FMT
" and GID " GID_FMT
".",
1245 i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1250 static int gid_is_ok(
1253 const char *groupname
,
1254 bool check_with_uid
) {
1263 if (ordered_hashmap_get(c
->todo_gids
, GID_TO_PTR(gid
)))
1266 /* Avoid reusing gids that are already used by a different user */
1267 if (check_with_uid
) {
1268 user
= ordered_hashmap_get(c
->todo_uids
, UID_TO_PTR(gid
));
1269 if (user
&& !streq(user
->name
, groupname
))
1273 if (hashmap_contains(c
->database_by_gid
, GID_TO_PTR(gid
)))
1276 if (check_with_uid
) {
1277 username
= hashmap_get(c
->database_by_uid
, UID_TO_PTR(gid
));
1278 if (username
&& !streq(username
, groupname
))
1283 r
= getgrgid_malloc(gid
, /* ret= */ NULL
);
1289 if (check_with_uid
) {
1290 r
= getpwuid_malloc(gid
, /* ret= */ NULL
);
1301 static int get_gid_by_name(
1312 /* Check the database directly */
1313 z
= hashmap_get(c
->database_by_groupname
, name
);
1315 *ret_gid
= PTR_TO_GID(z
);
1319 /* Also check NSS */
1321 _cleanup_free_
struct group
*g
= NULL
;
1323 r
= getgrnam_malloc(name
, &g
);
1325 *ret_gid
= g
->gr_gid
;
1329 return log_error_errno(r
, "Failed to check if group %s already exists: %m", name
);
1335 static int add_group(Context
*c
, Item
*i
) {
1341 r
= get_gid_by_name(c
, i
->name
, &i
->gid
);
1345 log_debug("Group %s already exists.", i
->name
);
1350 /* Try to use the suggested numeric GID */
1352 r
= gid_is_ok(c
, i
->gid
, i
->name
, false);
1354 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1355 if (i
->id_set_strict
) {
1356 /* If we require the GID to already exist we can return here:
1357 * r > 0: means the GID does not exist -> fail
1358 * r == 0: means the GID exists -> nothing more to do.
1361 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1362 "Failed to create %s: please create GID " GID_FMT
,
1368 log_info("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1373 /* Try to reuse the numeric uid, if there's one */
1374 if (!i
->gid_set
&& i
->uid_set
) {
1375 r
= gid_is_ok(c
, (gid_t
) i
->uid
, i
->name
, true);
1377 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1379 i
->gid
= (gid_t
) i
->uid
;
1384 /* If that didn't work, try to read it from the specified path */
1388 if (read_id_from_file(i
, NULL
, &candidate
) > 0) {
1390 if (candidate
<= 0 || !uid_range_contains(c
->uid_range
, candidate
))
1391 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", candidate
, i
->name
);
1393 r
= gid_is_ok(c
, candidate
, i
->name
, true);
1395 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1400 log_debug("Group ID " GID_FMT
" of file for %s already used.", candidate
, i
->name
);
1405 /* And if that didn't work either, let's try to find a free one */
1407 maybe_emit_login_defs_warning(c
);
1410 /* We look for new GIDs in the UID pool! */
1411 r
= uid_range_next_lower(c
->uid_range
, &c
->search_uid
);
1413 return log_error_errno(r
, "No free group ID available for %s.", i
->name
);
1415 r
= gid_is_ok(c
, c
->search_uid
, i
->name
, true);
1417 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1423 i
->gid
= c
->search_uid
;
1426 r
= ordered_hashmap_ensure_put(&c
->todo_gids
, NULL
, GID_TO_PTR(i
->gid
), i
);
1428 return log_error_errno(r
, "Requested group %s with GID "GID_FMT
" to be created is duplicated or conflicts with another user.", i
->name
, i
->gid
);
1432 return log_error_errno(r
, "Failed to store group %s with GID " GID_FMT
" to be created: %m", i
->name
, i
->gid
);
1434 i
->todo_group
= true;
1435 log_info("Creating group '%s' with GID " GID_FMT
".", i
->name
, i
->gid
);
1440 static int process_item(Context
*c
, Item
*i
) {
1452 j
= ordered_hashmap_get(c
->groups
, i
->group_name
?: i
->name
);
1454 if (j
&& j
->todo_group
) {
1455 /* When a group with the target name is already in queue,
1456 * use the information about the group and do not create
1457 * duplicated group entry. */
1458 i
->gid_set
= j
->gid_set
;
1460 i
->id_set_strict
= true;
1461 } else if (i
->group_name
) {
1462 /* When a group name was given instead of a GID and it's
1463 * not in queue, then it must already exist. */
1464 r
= get_gid_by_name(c
, i
->group_name
, &i
->gid
);
1466 return log_error_errno(r
, "Group %s not found.", i
->group_name
);
1468 i
->id_set_strict
= true;
1470 r
= add_group(c
, i
);
1475 return add_user(c
, i
);
1479 return add_group(c
, i
);
1482 assert_not_reached();
1486 static Item
* item_free(Item
*i
) {
1491 free(i
->group_name
);
1494 free(i
->description
);
1501 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1502 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops
, char, string_hash_func
, string_compare_func
, Item
, item_free
);
1504 static Item
* item_new(ItemType type
, const char *name
, const char *filename
, unsigned line
) {
1506 assert(!!filename
== (line
> 0));
1508 _cleanup_(item_freep
) Item
*new = new(Item
, 1);
1517 if (free_and_strdup(&new->name
, name
) < 0 ||
1518 free_and_strdup(&new->filename
, filename
) < 0)
1521 return TAKE_PTR(new);
1524 static int add_implicit(Context
*c
) {
1530 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1531 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, c
->members
) {
1533 if (!ordered_hashmap_get(c
->users
, *m
)) {
1534 _cleanup_(item_freep
) Item
*j
=
1535 item_new(ADD_USER
, *m
, /* filename= */ NULL
, /* line= */ 0);
1539 r
= ordered_hashmap_ensure_put(&c
->users
, &item_hash_ops
, j
->name
, j
);
1543 return log_error_errno(r
, "Failed to add implicit user '%s': %m", j
->name
);
1545 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1549 if (!(ordered_hashmap_get(c
->users
, g
) ||
1550 ordered_hashmap_get(c
->groups
, g
))) {
1551 _cleanup_(item_freep
) Item
*j
=
1552 item_new(ADD_GROUP
, g
, /* filename= */ NULL
, /* line= */ 0);
1556 r
= ordered_hashmap_ensure_put(&c
->groups
, &item_hash_ops
, j
->name
, j
);
1560 return log_error_errno(r
, "Failed to add implicit group '%s': %m", j
->name
);
1562 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1570 static int item_equivalent(Item
*a
, Item
*b
) {
1576 if (a
->type
!= b
->type
) {
1577 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1578 "Item not equivalent because types differ");
1582 if (!streq_ptr(a
->name
, b
->name
)) {
1583 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1584 "Item not equivalent because names differ ('%s' vs. '%s')",
1589 /* Paths were simplified previously, so we can use streq. */
1590 if (!streq_ptr(a
->uid_path
, b
->uid_path
)) {
1591 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1592 "Item not equivalent because UID paths differ (%s vs. %s)",
1593 a
->uid_path
?: "(unset)", b
->uid_path
?: "(unset)");
1597 if (!streq_ptr(a
->gid_path
, b
->gid_path
)) {
1598 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1599 "Item not equivalent because GID paths differ (%s vs. %s)",
1600 a
->gid_path
?: "(unset)", b
->gid_path
?: "(unset)");
1604 if (!streq_ptr(a
->description
, b
->description
)) {
1605 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1606 "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1607 strempty(a
->description
), strempty(b
->description
));
1611 if ((a
->uid_set
!= b
->uid_set
) ||
1612 (a
->uid_set
&& a
->uid
!= b
->uid
)) {
1613 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1614 "Item not equivalent because UIDs differ (%s vs. %s)",
1615 a
->uid_set
? FORMAT_UID(a
->uid
) : "(unset)",
1616 b
->uid_set
? FORMAT_UID(b
->uid
) : "(unset)");
1620 if ((a
->gid_set
!= b
->gid_set
) ||
1621 (a
->gid_set
&& a
->gid
!= b
->gid
)) {
1622 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1623 "Item not equivalent because GIDs differ (%s vs. %s)",
1624 a
->gid_set
? FORMAT_GID(a
->gid
) : "(unset)",
1625 b
->gid_set
? FORMAT_GID(b
->gid
) : "(unset)");
1629 if (!streq_ptr(a
->home
, b
->home
)) {
1630 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1631 "Item not equivalent because home directories differ ('%s' vs. '%s')",
1632 strempty(a
->description
), strempty(b
->description
));
1636 /* Check if the two paths refer to the same file.
1637 * If the paths are equal (after normalization), it's obviously the same file.
1638 * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1639 * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1640 * /usr/sbin/nologin).
1641 * If we can't resolve something, treat different paths as different. */
1643 const char *a_shell
= pick_shell(a
),
1644 *b_shell
= pick_shell(b
);
1645 if (!path_equal(a_shell
, b_shell
) &&
1646 !(is_nologin_shell(a_shell
) && is_nologin_shell(b_shell
))) {
1647 _cleanup_free_
char *pa
= NULL
, *pb
= NULL
;
1649 r
= chase(a_shell
, arg_root
, CHASE_PREFIX_ROOT
| CHASE_NONEXISTENT
, &pa
, NULL
);
1651 log_full_errno(ERRNO_IS_RESOURCE(r
) ? LOG_ERR
: LOG_DEBUG
,
1652 r
, "Failed to look up path '%s%s%s': %m",
1653 strempty(arg_root
), arg_root
? "/" : "", a_shell
);
1654 return ERRNO_IS_RESOURCE(r
) ? r
: false;
1657 r
= chase(b_shell
, arg_root
, CHASE_PREFIX_ROOT
| CHASE_NONEXISTENT
, &pb
, NULL
);
1659 log_full_errno(ERRNO_IS_RESOURCE(r
) ? LOG_ERR
: LOG_DEBUG
,
1660 r
, "Failed to look up path '%s%s%s': %m",
1661 strempty(arg_root
), arg_root
? "/" : "", b_shell
);
1662 return ERRNO_IS_RESOURCE(r
) ? r
: false;
1665 if (!path_equal(pa
, pb
)) {
1666 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1667 "Item not equivalent because shells differ ('%s' vs. '%s')",
1676 static int parse_line(
1680 bool *invalid_config
,
1683 Context
*c
= ASSERT_PTR(context
);
1684 _cleanup_free_
char *action
= NULL
,
1685 *name
= NULL
, *resolved_name
= NULL
,
1686 *id
= NULL
, *resolved_id
= NULL
,
1687 *description
= NULL
, *resolved_description
= NULL
,
1688 *home
= NULL
, *resolved_home
= NULL
,
1689 *shell
= NULL
, *resolved_shell
= NULL
;
1690 _cleanup_(item_freep
) Item
*i
= NULL
;
1699 assert(!invalid_config
); /* We don't support invalid_config yet. */
1703 r
= extract_many_words(&p
, NULL
, EXTRACT_UNQUOTE
,
1704 &action
, &name
, &id
, &description
, &home
, &shell
);
1706 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Syntax error.");
1708 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1709 "Missing action and name columns.");
1711 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1712 "Trailing garbage.");
1715 if (strlen(action
) != 1)
1716 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1717 "Unknown modifier '%s'.", action
);
1719 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
))
1720 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
1721 "Unknown command type '%c'.", action
[0]);
1724 if (empty_or_dash(name
))
1728 r
= specifier_printf(name
, NAME_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_name
);
1730 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to replace specifiers in '%s': %m", name
);
1732 if (!valid_user_group_name(resolved_name
, 0))
1733 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1734 "'%s' is not a valid user or group name.", resolved_name
);
1738 if (empty_or_dash(id
))
1742 r
= specifier_printf(id
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_id
);
1744 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1745 "Failed to replace specifiers in '%s': %m", name
);
1748 /* Verify description */
1749 if (empty_or_dash(description
))
1750 description
= mfree(description
);
1753 r
= specifier_printf(description
, LONG_LINE_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_description
);
1755 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1756 "Failed to replace specifiers in '%s': %m", description
);
1758 if (!valid_gecos(resolved_description
))
1759 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1760 "'%s' is not a valid GECOS field.", resolved_description
);
1764 if (empty_or_dash(home
))
1768 r
= specifier_printf(home
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_home
);
1770 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1771 "Failed to replace specifiers in '%s': %m", home
);
1773 path_simplify(resolved_home
);
1775 if (!valid_home(resolved_home
))
1776 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1777 "'%s' is not a valid home directory field.", resolved_home
);
1781 if (empty_or_dash(shell
))
1782 shell
= mfree(shell
);
1785 r
= specifier_printf(shell
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_shell
);
1787 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1788 "Failed to replace specifiers in '%s': %m", shell
);
1790 path_simplify(resolved_shell
);
1792 if (!valid_shell(resolved_shell
))
1793 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1794 "'%s' is not a valid login shell field.", resolved_shell
);
1797 switch (action
[0]) {
1801 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1802 "Lines of type 'r' don't take a name field.");
1805 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1806 "Lines of type 'r' require an ID range in the third field.");
1808 if (description
|| home
|| shell
)
1809 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1810 "Lines of type '%c' don't take a %s field.",
1812 description
? "GECOS" : home
? "home directory" : "login shell");
1814 r
= uid_range_add_str(&c
->uid_range
, resolved_id
);
1816 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1817 "Invalid UID range %s.", resolved_id
);
1822 /* Try to extend an existing member or group item */
1824 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1825 "Lines of type 'm' require a user name in the second field.");
1828 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1829 "Lines of type 'm' require a group name in the third field.");
1831 if (!valid_user_group_name(resolved_id
, 0))
1832 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1833 "'%s' is not a valid user or group name.", resolved_id
);
1835 if (description
|| home
|| shell
)
1836 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1837 "Lines of type '%c' don't take a %s field.",
1839 description
? "GECOS" : home
? "home directory" : "login shell");
1841 r
= string_strv_ordered_hashmap_put(&c
->members
, resolved_id
, resolved_name
);
1843 return log_error_errno(r
, "Failed to store mapping for %s: %m", resolved_id
);
1850 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1851 "Lines of type 'u' require a user name in the second field.");
1853 r
= ordered_hashmap_ensure_allocated(&c
->users
, &item_hash_ops
);
1857 i
= item_new(ADD_USER
, resolved_name
, fname
, line
);
1862 if (path_is_absolute(resolved_id
))
1863 i
->uid_path
= path_simplify(TAKE_PTR(resolved_id
));
1865 _cleanup_free_
char *uid
= NULL
, *gid
= NULL
;
1866 if (split_pair(resolved_id
, ":", &uid
, &gid
) == 0) {
1867 r
= parse_gid(gid
, &i
->gid
);
1869 if (valid_user_group_name(gid
, 0))
1870 i
->group_name
= TAKE_PTR(gid
);
1872 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1873 "Failed to parse GID: '%s': %m", id
);
1876 i
->id_set_strict
= true;
1878 free_and_replace(resolved_id
, uid
);
1880 if (!streq(resolved_id
, "-")) {
1881 r
= parse_uid(resolved_id
, &i
->uid
);
1883 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1884 "Failed to parse UID: '%s': %m", id
);
1890 i
->description
= TAKE_PTR(resolved_description
);
1891 i
->home
= TAKE_PTR(resolved_home
);
1892 i
->shell
= TAKE_PTR(resolved_shell
);
1899 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1900 "Lines of type 'g' require a user name in the second field.");
1902 if (description
|| home
|| shell
)
1903 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1904 "Lines of type '%c' don't take a %s field.",
1906 description
? "GECOS" : home
? "home directory" : "login shell");
1908 r
= ordered_hashmap_ensure_allocated(&c
->groups
, &item_hash_ops
);
1912 i
= item_new(ADD_GROUP
, resolved_name
, fname
, line
);
1917 if (path_is_absolute(resolved_id
))
1918 i
->gid_path
= path_simplify(TAKE_PTR(resolved_id
));
1920 r
= parse_gid(resolved_id
, &i
->gid
);
1922 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1923 "Failed to parse GID: '%s': %m", id
);
1933 assert_not_reached();
1936 existing
= ordered_hashmap_get(h
, i
->name
);
1938 /* Two functionally-equivalent items are fine */
1939 r
= item_equivalent(i
, existing
);
1943 if (existing
->filename
)
1944 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0,
1945 "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
1946 item_type_to_string(i
->type
),
1948 existing
->filename
, existing
->line
);
1950 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0,
1951 "Conflict with earlier configuration for %s '%s', ignoring line.",
1952 item_type_to_string(i
->type
),
1959 r
= ordered_hashmap_put(h
, i
->name
, i
);
1967 static int read_config_file(Context
*c
, const char *fn
, bool ignore_enoent
) {
1968 return conf_file_read(
1970 (const char**) CONF_PATHS_STRV("sysusers.d"),
1975 /* invalid_config= */ NULL
);
1978 static int cat_config(void) {
1979 _cleanup_strv_free_
char **files
= NULL
;
1982 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
1986 pager_open(arg_pager_flags
);
1988 return cat_files(NULL
, files
, arg_cat_flags
);
1991 static int help(void) {
1992 _cleanup_free_
char *link
= NULL
;
1995 r
= terminal_urlify_man("systemd-sysusers.service", "8", &link
);
1999 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
2000 "Creates system user accounts.\n\n"
2001 " -h --help Show this help\n"
2002 " --version Show package version\n"
2003 " --cat-config Show configuration files\n"
2004 " --tldr Show non-comment parts of configuration\n"
2005 " --root=PATH Operate on an alternate filesystem root\n"
2006 " --image=PATH Operate on disk image as filesystem root\n"
2007 " --image-policy=POLICY Specify disk image dissection policy\n"
2008 " --replace=PATH Treat arguments as replacement for PATH\n"
2009 " --dry-run Just print what would be done\n"
2010 " --inline Treat arguments as configuration lines\n"
2011 " --no-pager Do not pipe output into a pager\n"
2012 "\nSee the %s for details.\n",
2013 program_invocation_short_name
,
2019 static int parse_argv(int argc
, char *argv
[]) {
2022 ARG_VERSION
= 0x100,
2034 static const struct option options
[] = {
2035 { "help", no_argument
, NULL
, 'h' },
2036 { "version", no_argument
, NULL
, ARG_VERSION
},
2037 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
2038 { "tldr", no_argument
, NULL
, ARG_TLDR
},
2039 { "root", required_argument
, NULL
, ARG_ROOT
},
2040 { "image", required_argument
, NULL
, ARG_IMAGE
},
2041 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
2042 { "replace", required_argument
, NULL
, ARG_REPLACE
},
2043 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
2044 { "inline", no_argument
, NULL
, ARG_INLINE
},
2045 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
2054 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2064 case ARG_CAT_CONFIG
:
2065 arg_cat_flags
= CAT_CONFIG_ON
;
2069 arg_cat_flags
= CAT_TLDR
;
2073 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
2080 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2081 "This systemd-sysusers version is compiled without support for --image=.");
2083 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
2089 case ARG_IMAGE_POLICY
:
2090 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
2096 if (!path_is_absolute(optarg
))
2097 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2098 "The argument to --replace= must be an absolute path.");
2099 if (!endswith(optarg
, ".conf"))
2100 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2101 "The argument to --replace= must have the extension '.conf'.");
2103 arg_replace
= optarg
;
2115 arg_pager_flags
|= PAGER_DISABLE
;
2122 assert_not_reached();
2125 if (arg_replace
&& arg_cat_flags
!= CAT_CONFIG_OFF
)
2126 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2127 "Option --replace= is not supported with --cat-config/--tldr.");
2129 if (arg_replace
&& optind
>= argc
)
2130 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2131 "When --replace= is given, some configuration items must be specified.");
2133 if (arg_image
&& arg_root
)
2134 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2135 "Use either --root= or --image=, the combination of both is not supported.");
2140 static int parse_arguments(Context
*c
, char **args
) {
2146 STRV_FOREACH(arg
, args
) {
2148 /* Use (argument):n, where n==1 for the first positional arg */
2149 r
= parse_line("(argument)", pos
, *arg
, /* invalid_config= */ NULL
, c
);
2151 r
= read_config_file(c
, *arg
, /* ignore_enoent= */ false);
2161 static int read_config_files(Context
*c
, char **args
) {
2162 _cleanup_strv_free_
char **files
= NULL
;
2163 _cleanup_free_
char *p
= NULL
;
2168 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
2172 STRV_FOREACH(f
, files
)
2173 if (p
&& path_equal(*f
, p
)) {
2174 log_debug("Parsing arguments at position \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
2176 r
= parse_arguments(c
, args
);
2180 log_debug("Reading config file \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
2182 /* Just warn, ignore result otherwise */
2183 (void) read_config_file(c
, *f
, /* ignore_enoent= */ true);
2189 static int read_credential_lines(Context
*c
) {
2190 _cleanup_free_
char *j
= NULL
;
2196 r
= get_credentials_dir(&d
);
2200 return log_error_errno(r
, "Failed to get credentials directory: %m");
2202 j
= path_join(d
, "sysusers.extra");
2206 (void) read_config_file(c
, j
, /* ignore_enoent= */ true);
2210 static int run(int argc
, char *argv
[]) {
2212 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2213 _cleanup_(umount_and_freep
) char *mounted_dir
= NULL
;
2215 _cleanup_close_
int lock
= -EBADF
;
2216 _cleanup_(context_done
) Context c
= {
2217 .search_uid
= UID_INVALID
,
2223 r
= parse_argv(argc
, argv
);
2229 if (arg_cat_flags
!= CAT_CONFIG_OFF
)
2230 return cat_config();
2242 r
= mount_image_privately_interactively(
2245 DISSECT_IMAGE_GENERIC_ROOT
|
2246 DISSECT_IMAGE_REQUIRE_ROOT
|
2247 DISSECT_IMAGE_VALIDATE_OS
|
2248 DISSECT_IMAGE_RELAX_VAR_CHECK
|
2249 DISSECT_IMAGE_FSCK
|
2250 DISSECT_IMAGE_GROWFS
|
2251 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
,
2253 /* ret_dir_fd= */ NULL
,
2258 arg_root
= strdup(mounted_dir
);
2266 /* If command line arguments are specified along with --replace, read all configuration files and
2267 * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2268 * specified, execute just them, and finally, without --replace= or any positional arguments, just
2269 * read configuration and execute it. */
2270 if (arg_replace
|| optind
>= argc
)
2271 r
= read_config_files(&c
, argv
+ optind
);
2273 r
= parse_arguments(&c
, argv
+ optind
);
2277 r
= read_credential_lines(&c
);
2281 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our
2282 * detection whether the names or UID/GID area already used otherwise doesn't get confused. After
2283 * all, even though nss-systemd synthesizes these users/groups, they should still appear in
2284 * /etc/passwd and /etc/group, as the synthesizing logic is merely supposed to be fallback for cases
2285 * where we run with a completely unpopulated /etc. */
2286 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
2287 return log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
2290 /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2291 r
= read_login_defs(&c
.login_defs
, NULL
, arg_root
);
2293 return log_error_errno(r
, "Failed to read %s%s: %m",
2294 strempty(arg_root
), "/etc/login.defs");
2296 c
.login_defs_need_warning
= true;
2298 /* We pick a range that very conservative: we look at compiled-in maximum and the value in
2299 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
2300 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2301 * it's only used during allocation, so we use the configured value directly). */
2302 uid_t begin
= c
.login_defs
.system_alloc_uid_min
,
2303 end
= MIN3((uid_t
) SYSTEM_UID_MAX
, c
.login_defs
.system_uid_max
, c
.login_defs
.system_gid_max
);
2305 r
= uid_range_add(&c
.uid_range
, begin
, end
- begin
+ 1);
2311 r
= add_implicit(&c
);
2316 lock
= take_etc_passwd_lock(arg_root
);
2318 return log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
2321 r
= load_user_database(&c
);
2323 return log_error_errno(r
, "Failed to load user database: %m");
2325 r
= load_group_database(&c
);
2327 return log_error_errno(r
, "Failed to read group database: %m");
2329 ORDERED_HASHMAP_FOREACH(i
, c
.groups
)
2330 (void) process_item(&c
, i
);
2332 ORDERED_HASHMAP_FOREACH(i
, c
.users
)
2333 (void) process_item(&c
, i
);
2335 return write_files(&c
);
2338 DEFINE_MAIN_FUNCTION(run
);