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 /* Note: the lifetime of the compound literal is the immediately surrounding block,
145 * see C11 §6.5.2.5, and
146 * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */
147 #define FORMAT_UID(is_set, uid) \
148 ((is_set) ? snprintf_ok((char[DECIMAL_STR_MAX(uid_t)]){}, DECIMAL_STR_MAX(uid_t), UID_FMT, uid) : "(unset)")
149 #define FORMAT_GID(is_set, gid) \
150 ((is_set) ? snprintf_ok((char[DECIMAL_STR_MAX(gid_t)]){}, DECIMAL_STR_MAX(gid_t), GID_FMT, gid) : "(unset)")
152 static void maybe_emit_login_defs_warning(Context
*c
) {
155 if (!c
->login_defs_need_warning
)
158 if (c
->login_defs
.system_alloc_uid_min
!= SYSTEM_ALLOC_UID_MIN
||
159 c
->login_defs
.system_uid_max
!= SYSTEM_UID_MAX
)
160 log_warning("login.defs specifies UID allocation range "UID_FMT
"–"UID_FMT
161 " that is different than the built-in defaults ("UID_FMT
"–"UID_FMT
")",
162 c
->login_defs
.system_alloc_uid_min
, c
->login_defs
.system_uid_max
,
163 (uid_t
) SYSTEM_ALLOC_UID_MIN
, (uid_t
) SYSTEM_UID_MAX
);
164 if (c
->login_defs
.system_alloc_gid_min
!= SYSTEM_ALLOC_GID_MIN
||
165 c
->login_defs
.system_gid_max
!= SYSTEM_GID_MAX
)
166 log_warning("login.defs specifies GID allocation range "GID_FMT
"–"GID_FMT
167 " that is different than the built-in defaults ("GID_FMT
"–"GID_FMT
")",
168 c
->login_defs
.system_alloc_gid_min
, c
->login_defs
.system_gid_max
,
169 (gid_t
) SYSTEM_ALLOC_GID_MIN
, (gid_t
) SYSTEM_GID_MAX
);
171 c
->login_defs_need_warning
= false;
174 static int load_user_database(Context
*c
) {
175 _cleanup_fclose_
FILE *f
= NULL
;
176 const char *passwd_path
;
182 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
183 f
= fopen(passwd_path
, "re");
185 return errno
== ENOENT
? 0 : -errno
;
187 r
= hashmap_ensure_allocated(&c
->database_by_username
, &string_hash_ops
);
191 r
= hashmap_ensure_allocated(&c
->database_by_uid
, NULL
);
195 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
196 r
= set_ensure_allocated(&c
->names
, NULL
);
200 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
202 char *n
= strdup(pw
->pw_name
);
206 r
= set_consume(c
->names
, n
);
209 assert(r
> 0); /* The set uses pointer comparisons, so n must not be in the set. */
211 r
= hashmap_put(c
->database_by_username
, n
, UID_TO_PTR(pw
->pw_uid
));
213 log_debug_errno(r
, "%s: user '%s' is listed twice, ignoring duplicate uid.",
218 r
= hashmap_put(c
->database_by_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
220 log_debug_errno(r
, "%s: uid "UID_FMT
" is listed twice, ignoring duplicate name.",
221 passwd_path
, pw
->pw_uid
);
228 static int load_group_database(Context
*c
) {
229 _cleanup_fclose_
FILE *f
= NULL
;
230 const char *group_path
;
236 group_path
= prefix_roota(arg_root
, "/etc/group");
237 f
= fopen(group_path
, "re");
239 return errno
== ENOENT
? 0 : -errno
;
241 r
= hashmap_ensure_allocated(&c
->database_by_groupname
, &string_hash_ops
);
245 r
= hashmap_ensure_allocated(&c
->database_by_gid
, NULL
);
249 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
250 r
= set_ensure_allocated(&c
->names
, NULL
);
254 while ((r
= fgetgrent_sane(f
, &gr
)) > 0) {
256 char *n
= strdup(gr
->gr_name
);
260 r
= set_consume(c
->names
, n
);
263 assert(r
> 0); /* The set uses pointer comparisons, so n must not be in the set. */
265 r
= hashmap_put(c
->database_by_groupname
, n
, GID_TO_PTR(gr
->gr_gid
));
267 log_debug_errno(r
, "%s: group '%s' is listed twice, ignoring duplicate gid.",
272 r
= hashmap_put(c
->database_by_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
274 log_debug_errno(r
, "%s: gid "GID_FMT
" is listed twice, ignoring duplicate name.",
275 group_path
, gr
->gr_gid
);
282 static int make_backup(const char *target
, const char *x
) {
283 _cleanup_(unlink_and_freep
) char *dst_tmp
= NULL
;
284 _cleanup_fclose_
FILE *dst
= NULL
;
285 _cleanup_close_
int src
= -EBADF
;
293 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
295 if (errno
== ENOENT
) /* No backup necessary... */
301 if (fstat(src
, &st
) < 0)
304 r
= fopen_temporary_label(
305 target
, /* The path for which to the look up the label */
306 x
, /* Where we want the file actually to end up */
307 &dst
, /* The temporary file we write to */
312 r
= copy_bytes(src
, fileno(dst
), UINT64_MAX
, COPY_REFLINK
);
316 backup
= strjoina(x
, "-");
318 /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
319 * unreadable by others, then it isn't too bad... */
320 r
= fchmod_and_chown_with_fallback(fileno(dst
), dst_tmp
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
322 log_warning_errno(r
, "Failed to change access mode or ownership of %s: %m", backup
);
324 if (futimens(fileno(dst
), (const struct timespec
[2]) { st
.st_atim
, st
.st_mtim
}) < 0)
325 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
327 r
= fsync_full(fileno(dst
));
331 if (rename(dst_tmp
, backup
) < 0)
334 dst_tmp
= mfree(dst_tmp
); /* disable the unlink_and_freep() hook now that the file has been renamed */
338 static int putgrent_with_members(
340 const struct group
*gr
,
350 a
= ordered_hashmap_get(c
->members
, gr
->gr_name
);
352 _cleanup_strv_free_
char **l
= NULL
;
355 l
= strv_copy(gr
->gr_mem
);
360 if (strv_contains(l
, *i
))
363 r
= strv_extend(&l
, *i
);
379 r
= putgrent_sane(&t
, group
);
380 return r
< 0 ? r
: 1;
384 return putgrent_sane(gr
, group
);
388 static int putsgent_with_members(
390 const struct sgrp
*sg
,
399 a
= ordered_hashmap_get(c
->members
, sg
->sg_namp
);
401 _cleanup_strv_free_
char **l
= NULL
;
404 l
= strv_copy(sg
->sg_mem
);
409 if (strv_contains(l
, *i
))
412 r
= strv_extend(&l
, *i
);
428 r
= putsgent_sane(&t
, gshadow
);
429 return r
< 0 ? r
: 1;
433 return putsgent_sane(sg
, gshadow
);
437 static const char* pick_shell(const Item
*i
) {
438 if (i
->type
!= ADD_USER
)
442 if (i
->uid_set
&& i
->uid
== 0)
443 return default_root_shell(arg_root
);
447 static int write_temporary_passwd(
449 const char *passwd_path
,
451 char **ret_tmpfile_path
) {
453 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
454 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
455 struct passwd
*pw
= NULL
;
461 if (ordered_hashmap_isempty(c
->todo_uids
))
465 log_info("Would write /etc/passwd%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
469 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
471 return log_debug_errno(r
, "Failed to open temporary copy of %s: %m", passwd_path
);
473 original
= fopen(passwd_path
, "re");
476 /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
477 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
478 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
479 * it easier to depend on sysusers in packaging scripts and suchlike. */
480 r
= copy_rights_with_fallback(fileno(original
), fileno(passwd
), passwd_tmp
);
482 return log_debug_errno(r
, "Failed to copy permissions from %s to %s: %m",
483 passwd_path
, passwd_tmp
);
485 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
486 i
= ordered_hashmap_get(c
->users
, pw
->pw_name
);
487 if (i
&& i
->todo_user
)
488 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
489 "%s: User \"%s\" already exists.",
490 passwd_path
, pw
->pw_name
);
492 if (ordered_hashmap_contains(c
->todo_uids
, UID_TO_PTR(pw
->pw_uid
)))
493 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
494 "%s: Detected collision for UID " UID_FMT
".",
495 passwd_path
, pw
->pw_uid
);
497 /* Make sure we keep the NIS entries (if any) at the end. */
498 if (IN_SET(pw
->pw_name
[0], '+', '-'))
501 r
= putpwent_sane(pw
, passwd
);
503 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary passwd file: %m",
507 return log_debug_errno(r
, "Failed to read %s: %m", passwd_path
);
511 return log_debug_errno(errno
, "Failed to open %s: %m", passwd_path
);
512 if (fchmod(fileno(passwd
), 0644) < 0)
513 return log_debug_errno(errno
, "Failed to fchmod %s: %m", passwd_tmp
);
516 ORDERED_HASHMAP_FOREACH(i
, c
->todo_uids
) {
517 _cleanup_free_
char *creds_shell
= NULL
, *cn
= NULL
;
523 .pw_gecos
= (char*) strempty(i
->description
),
525 /* "x" means the password is stored in the shadow file */
526 .pw_passwd
= (char*) PASSWORD_SEE_SHADOW
,
528 /* We default to the root directory as home */
529 .pw_dir
= i
->home
?: (char*) "/",
531 /* Initialize the shell to nologin, with one exception:
532 * for root we patch in something special */
533 .pw_shell
= (char*) pick_shell(i
),
536 /* Try to pick up the shell for this account via the credentials logic */
537 cn
= strjoin("passwd.shell.", i
->name
);
541 r
= read_credential(cn
, (void**) &creds_shell
, NULL
);
543 log_debug_errno(r
, "Couldn't read credential '%s', ignoring: %m", cn
);
545 n
.pw_shell
= creds_shell
;
547 r
= putpwent_sane(&n
, passwd
);
549 return log_debug_errno(r
, "Failed to add new user \"%s\" to temporary passwd file: %m",
553 /* Append the remaining NIS entries if any */
555 r
= putpwent_sane(pw
, passwd
);
557 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary passwd file: %m",
560 r
= fgetpwent_sane(original
, &pw
);
562 return log_debug_errno(r
, "Failed to read %s: %m", passwd_path
);
567 r
= fflush_sync_and_check(passwd
);
569 return log_debug_errno(r
, "Failed to flush %s: %m", passwd_tmp
);
571 *ret_tmpfile
= TAKE_PTR(passwd
);
572 *ret_tmpfile_path
= TAKE_PTR(passwd_tmp
);
577 static usec_t
epoch_or_now(void) {
580 if (getenv_uint64_secure("SOURCE_DATE_EPOCH", &epoch
) >= 0) {
581 if (epoch
> UINT64_MAX
/USEC_PER_SEC
) /* Overflow check */
582 return USEC_INFINITY
;
583 return (usec_t
) epoch
* USEC_PER_SEC
;
586 return now(CLOCK_REALTIME
);
589 static int write_temporary_shadow(
591 const char *shadow_path
,
593 char **ret_tmpfile_path
) {
595 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
596 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
597 struct spwd
*sp
= NULL
;
604 if (ordered_hashmap_isempty(c
->todo_uids
))
608 log_info("Would write /etc/shadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
612 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
614 return log_debug_errno(r
, "Failed to open temporary copy of %s: %m", shadow_path
);
616 lstchg
= (long) (epoch_or_now() / USEC_PER_DAY
);
618 original
= fopen(shadow_path
, "re");
621 r
= copy_rights_with_fallback(fileno(original
), fileno(shadow
), shadow_tmp
);
623 return log_debug_errno(r
, "Failed to copy permissions from %s to %s: %m",
624 shadow_path
, shadow_tmp
);
626 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
627 i
= ordered_hashmap_get(c
->users
, sp
->sp_namp
);
628 if (i
&& i
->todo_user
) {
629 /* we will update the existing entry */
630 sp
->sp_lstchg
= lstchg
;
632 /* only the /etc/shadow stage is left, so we can
633 * safely remove the item from the todo set */
634 i
->todo_user
= false;
635 ordered_hashmap_remove(c
->todo_uids
, UID_TO_PTR(i
->uid
));
638 /* Make sure we keep the NIS entries (if any) at the end. */
639 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
642 r
= putspent_sane(sp
, shadow
);
644 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary shadow file: %m",
649 return log_debug_errno(r
, "Failed to read %s: %m", shadow_path
);
653 return log_debug_errno(errno
, "Failed to open %s: %m", shadow_path
);
654 if (fchmod(fileno(shadow
), 0000) < 0)
655 return log_debug_errno(errno
, "Failed to fchmod %s: %m", shadow_tmp
);
658 ORDERED_HASHMAP_FOREACH(i
, c
->todo_uids
) {
659 _cleanup_(erase_and_freep
) char *creds_password
= NULL
;
670 .sp_flag
= ULONG_MAX
, /* this appears to be what everybody does ... */
673 r
= get_credential_user_password(i
->name
, &creds_password
, &is_hashed
);
675 log_debug_errno(r
, "Couldn't read password credential for user '%s', ignoring: %m", i
->name
);
677 if (creds_password
&& !is_hashed
) {
678 _cleanup_(erase_and_freep
) char* plaintext_password
= TAKE_PTR(creds_password
);
679 r
= hash_password(plaintext_password
, &creds_password
);
681 return log_debug_errno(r
, "Failed to hash password: %m");
685 n
.sp_pwdp
= creds_password
;
686 else if (streq(i
->name
, "root"))
687 /* Let firstboot set the password later */
688 n
.sp_pwdp
= (char*) PASSWORD_UNPROVISIONED
;
690 n
.sp_pwdp
= (char*) PASSWORD_LOCKED_AND_INVALID
;
692 r
= putspent_sane(&n
, shadow
);
694 return log_debug_errno(r
, "Failed to add new user \"%s\" to temporary shadow file: %m",
698 /* Append the remaining NIS entries if any */
700 r
= putspent_sane(sp
, shadow
);
702 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary shadow file: %m",
705 r
= fgetspent_sane(original
, &sp
);
707 return log_debug_errno(r
, "Failed to read %s: %m", shadow_path
);
711 if (!IN_SET(errno
, 0, ENOENT
))
714 r
= fflush_sync_and_check(shadow
);
716 return log_debug_errno(r
, "Failed to flush %s: %m", shadow_tmp
);
718 *ret_tmpfile
= TAKE_PTR(shadow
);
719 *ret_tmpfile_path
= TAKE_PTR(shadow_tmp
);
724 static int write_temporary_group(
726 const char *group_path
,
728 char **ret_tmpfile_path
) {
730 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
731 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
732 bool group_changed
= false;
733 struct group
*gr
= NULL
;
739 if (ordered_hashmap_isempty(c
->todo_gids
) && ordered_hashmap_isempty(c
->members
))
743 log_info("Would write /etc/group%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
747 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
749 return log_error_errno(r
, "Failed to open temporary copy of %s: %m", group_path
);
751 original
= fopen(group_path
, "re");
754 r
= copy_rights_with_fallback(fileno(original
), fileno(group
), group_tmp
);
756 return log_error_errno(r
, "Failed to copy permissions from %s to %s: %m",
757 group_path
, group_tmp
);
759 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
760 /* Safety checks against name and GID collisions. Normally,
761 * this should be unnecessary, but given that we look at the
762 * entries anyway here, let's make an extra verification
763 * step that we don't generate duplicate entries. */
765 i
= ordered_hashmap_get(c
->groups
, gr
->gr_name
);
766 if (i
&& i
->todo_group
)
767 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
768 "%s: Group \"%s\" already exists.",
769 group_path
, gr
->gr_name
);
771 if (ordered_hashmap_contains(c
->todo_gids
, GID_TO_PTR(gr
->gr_gid
)))
772 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
773 "%s: Detected collision for GID " GID_FMT
".",
774 group_path
, gr
->gr_gid
);
776 /* Make sure we keep the NIS entries (if any) at the end. */
777 if (IN_SET(gr
->gr_name
[0], '+', '-'))
780 r
= putgrent_with_members(c
, gr
, group
);
782 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary group file: %m",
785 group_changed
= true;
788 return log_error_errno(r
, "Failed to read %s: %m", group_path
);
792 return log_error_errno(errno
, "Failed to open %s: %m", group_path
);
793 if (fchmod(fileno(group
), 0644) < 0)
794 return log_error_errno(errno
, "Failed to fchmod %s: %m", group_tmp
);
797 ORDERED_HASHMAP_FOREACH(i
, c
->todo_gids
) {
801 .gr_passwd
= (char*) PASSWORD_SEE_SHADOW
,
804 r
= putgrent_with_members(c
, &n
, group
);
806 return log_error_errno(r
, "Failed to add new group \"%s\" to temporary group file: %m",
809 group_changed
= true;
812 /* Append the remaining NIS entries if any */
814 r
= putgrent_sane(gr
, group
);
816 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary group file: %m",
819 r
= fgetgrent_sane(original
, &gr
);
821 return log_error_errno(r
, "Failed to read %s: %m", group_path
);
826 r
= fflush_sync_and_check(group
);
828 return log_error_errno(r
, "Failed to flush %s: %m", group_tmp
);
831 *ret_tmpfile
= TAKE_PTR(group
);
832 *ret_tmpfile_path
= TAKE_PTR(group_tmp
);
837 static int write_temporary_gshadow(
839 const char * gshadow_path
,
841 char **ret_tmpfile_path
) {
844 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
845 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
846 bool group_changed
= false;
852 if (ordered_hashmap_isempty(c
->todo_gids
) && ordered_hashmap_isempty(c
->members
))
856 log_info("Would write /etc/gshadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
860 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
862 return log_error_errno(r
, "Failed to open temporary copy of %s: %m", gshadow_path
);
864 original
= fopen(gshadow_path
, "re");
868 r
= copy_rights_with_fallback(fileno(original
), fileno(gshadow
), gshadow_tmp
);
870 return log_error_errno(r
, "Failed to copy permissions from %s to %s: %m",
871 gshadow_path
, gshadow_tmp
);
873 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
875 i
= ordered_hashmap_get(c
->groups
, sg
->sg_namp
);
876 if (i
&& i
->todo_group
)
877 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
878 "%s: Group \"%s\" already exists.",
879 gshadow_path
, sg
->sg_namp
);
881 r
= putsgent_with_members(c
, sg
, gshadow
);
883 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
886 group_changed
= true;
893 return log_error_errno(errno
, "Failed to open %s: %m", gshadow_path
);
894 if (fchmod(fileno(gshadow
), 0000) < 0)
895 return log_error_errno(errno
, "Failed to fchmod %s: %m", gshadow_tmp
);
898 ORDERED_HASHMAP_FOREACH(i
, c
->todo_gids
) {
901 .sg_passwd
= (char*) PASSWORD_LOCKED_AND_INVALID
,
904 r
= putsgent_with_members(c
, &n
, gshadow
);
906 return log_error_errno(r
, "Failed to add new group \"%s\" to temporary gshadow file: %m",
909 group_changed
= true;
912 r
= fflush_sync_and_check(gshadow
);
914 return log_error_errno(r
, "Failed to flush %s: %m", gshadow_tmp
);
917 *ret_tmpfile
= TAKE_PTR(gshadow
);
918 *ret_tmpfile_path
= TAKE_PTR(gshadow_tmp
);
924 static int write_files(Context
*c
) {
925 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
926 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
930 *passwd_path
= prefix_roota(arg_root
, "/etc/passwd"),
931 *shadow_path
= prefix_roota(arg_root
, "/etc/shadow"),
932 *group_path
= prefix_roota(arg_root
, "/etc/group"),
933 *gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
937 r
= write_temporary_group(c
, group_path
, &group
, &group_tmp
);
941 r
= write_temporary_gshadow(c
, gshadow_path
, &gshadow
, &gshadow_tmp
);
945 r
= write_temporary_passwd(c
, passwd_path
, &passwd
, &passwd_tmp
);
949 r
= write_temporary_shadow(c
, shadow_path
, &shadow
, &shadow_tmp
);
953 /* Make a backup of the old files */
955 r
= make_backup("/etc/group", group_path
);
957 return log_error_errno(r
, "Failed to backup %s: %m", group_path
);
960 r
= make_backup("/etc/gshadow", gshadow_path
);
962 return log_error_errno(r
, "Failed to backup %s: %m", gshadow_path
);
966 r
= make_backup("/etc/passwd", passwd_path
);
968 return log_error_errno(r
, "Failed to backup %s: %m", passwd_path
);
971 r
= make_backup("/etc/shadow", shadow_path
);
973 return log_error_errno(r
, "Failed to backup %s: %m", shadow_path
);
976 /* And make the new files count */
978 r
= rename_and_apply_smack_floor_label(group_tmp
, group_path
);
980 return log_error_errno(r
, "Failed to rename %s to %s: %m",
981 group_tmp
, group_path
);
982 group_tmp
= mfree(group_tmp
);
984 if (!arg_root
&& !arg_image
)
985 (void) nscd_flush_cache(STRV_MAKE("group"));
988 r
= rename_and_apply_smack_floor_label(gshadow_tmp
, gshadow_path
);
990 return log_error_errno(r
, "Failed to rename %s to %s: %m",
991 gshadow_tmp
, gshadow_path
);
993 gshadow_tmp
= mfree(gshadow_tmp
);
997 r
= rename_and_apply_smack_floor_label(passwd_tmp
, passwd_path
);
999 return log_error_errno(r
, "Failed to rename %s to %s: %m",
1000 passwd_tmp
, passwd_path
);
1002 passwd_tmp
= mfree(passwd_tmp
);
1004 if (!arg_root
&& !arg_image
)
1005 (void) nscd_flush_cache(STRV_MAKE("passwd"));
1008 r
= rename_and_apply_smack_floor_label(shadow_tmp
, shadow_path
);
1010 return log_error_errno(r
, "Failed to rename %s to %s: %m",
1011 shadow_tmp
, shadow_path
);
1013 shadow_tmp
= mfree(shadow_tmp
);
1019 static int uid_is_ok(
1023 bool check_with_gid
) {
1028 /* Let's see if we already have assigned the UID a second time */
1029 if (ordered_hashmap_get(c
->todo_uids
, UID_TO_PTR(uid
)))
1032 /* Try to avoid using uids that are already used by a group
1033 * that doesn't have the same name as our new user. */
1034 if (check_with_gid
) {
1037 i
= ordered_hashmap_get(c
->todo_gids
, GID_TO_PTR(uid
));
1038 if (i
&& !streq(i
->name
, name
))
1042 /* Let's check the files directly */
1043 if (hashmap_contains(c
->database_by_uid
, UID_TO_PTR(uid
)))
1046 if (check_with_gid
) {
1049 n
= hashmap_get(c
->database_by_gid
, GID_TO_PTR(uid
));
1050 if (n
&& !streq(n
, name
))
1054 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
1056 _cleanup_free_
struct group
*g
= NULL
;
1058 r
= getpwuid_malloc(uid
, /* ret= */ NULL
);
1064 if (check_with_gid
) {
1065 r
= getgrgid_malloc((gid_t
) uid
, &g
);
1067 if (!streq(g
->gr_name
, name
))
1069 } else if (r
!= -ESRCH
)
1077 static int root_stat(const char *p
, struct stat
*st
) {
1080 fix
= prefix_roota(arg_root
, p
);
1081 return RET_NERRNO(stat(fix
, st
));
1084 static int read_id_from_file(Item
*i
, uid_t
*ret_uid
, gid_t
*ret_gid
) {
1086 bool found_uid
= false, found_gid
= false;
1092 /* First, try to get the GID directly */
1093 if (ret_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
1098 /* Then, try to get the UID directly */
1099 if ((ret_uid
|| (ret_gid
&& !found_gid
))
1101 && root_stat(i
->uid_path
, &st
) >= 0) {
1106 /* If we need the gid, but had no success yet, also derive it from the UID path */
1107 if (ret_gid
&& !found_gid
) {
1113 /* If that didn't work yet, then let's reuse the GID as UID */
1114 if (ret_uid
&& !found_uid
&& i
->gid_path
) {
1119 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
1120 uid
= (uid_t
) st
.st_gid
;
1142 static int add_user(Context
*c
, Item
*i
) {
1149 /* Check the database directly */
1150 z
= hashmap_get(c
->database_by_username
, i
->name
);
1152 log_debug("User %s already exists.", i
->name
);
1153 i
->uid
= PTR_TO_UID(z
);
1159 _cleanup_free_
struct passwd
*p
= NULL
;
1161 /* Also check NSS */
1162 r
= getpwnam_malloc(i
->name
, &p
);
1164 log_debug("User %s already exists.", i
->name
);
1168 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
1175 return log_error_errno(r
, "Failed to check if user %s already exists: %m", i
->name
);
1178 /* Try to use the suggested numeric UID */
1180 r
= uid_is_ok(c
, i
->uid
, i
->name
, !i
->id_set_strict
);
1182 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1184 log_info("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
1189 /* If that didn't work, try to read it from the specified path */
1193 if (read_id_from_file(i
, &candidate
, NULL
) > 0) {
1195 if (candidate
<= 0 || !uid_range_contains(c
->uid_range
, candidate
))
1196 log_debug("User ID " UID_FMT
" of file not suitable for %s.", candidate
, i
->name
);
1198 r
= uid_is_ok(c
, candidate
, i
->name
, true);
1200 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1205 log_debug("User ID " UID_FMT
" of file for %s is already used.", candidate
, i
->name
);
1210 /* Otherwise, try to reuse the group ID */
1211 if (!i
->uid_set
&& i
->gid_set
) {
1212 r
= uid_is_ok(c
, (uid_t
) i
->gid
, i
->name
, true);
1214 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1216 i
->uid
= (uid_t
) i
->gid
;
1221 /* And if that didn't work either, let's try to find a free one */
1223 maybe_emit_login_defs_warning(c
);
1226 r
= uid_range_next_lower(c
->uid_range
, &c
->search_uid
);
1228 return log_error_errno(r
, "No free user ID available for %s.", i
->name
);
1230 r
= uid_is_ok(c
, c
->search_uid
, i
->name
, true);
1232 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1238 i
->uid
= c
->search_uid
;
1241 r
= ordered_hashmap_ensure_put(&c
->todo_uids
, NULL
, UID_TO_PTR(i
->uid
), i
);
1243 return log_error_errno(r
, "Requested user %s with UID " UID_FMT
" and gid" GID_FMT
" to be created is duplicated "
1244 "or conflicts with another user.", i
->name
, i
->uid
, i
->gid
);
1248 return log_error_errno(r
, "Failed to store user %s with UID " UID_FMT
" and GID " GID_FMT
" to be created: %m",
1249 i
->name
, i
->uid
, i
->gid
);
1251 i
->todo_user
= true;
1252 log_info("Creating user '%s' (%s) with UID " UID_FMT
" and GID " GID_FMT
".",
1253 i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1258 static int gid_is_ok(
1261 const char *groupname
,
1262 bool check_with_uid
) {
1271 if (ordered_hashmap_get(c
->todo_gids
, GID_TO_PTR(gid
)))
1274 /* Avoid reusing gids that are already used by a different user */
1275 if (check_with_uid
) {
1276 user
= ordered_hashmap_get(c
->todo_uids
, UID_TO_PTR(gid
));
1277 if (user
&& !streq(user
->name
, groupname
))
1281 if (hashmap_contains(c
->database_by_gid
, GID_TO_PTR(gid
)))
1284 if (check_with_uid
) {
1285 username
= hashmap_get(c
->database_by_uid
, UID_TO_PTR(gid
));
1286 if (username
&& !streq(username
, groupname
))
1291 r
= getgrgid_malloc(gid
, /* ret= */ NULL
);
1297 if (check_with_uid
) {
1298 r
= getpwuid_malloc(gid
, /* ret= */ NULL
);
1309 static int get_gid_by_name(
1320 /* Check the database directly */
1321 z
= hashmap_get(c
->database_by_groupname
, name
);
1323 *ret_gid
= PTR_TO_GID(z
);
1327 /* Also check NSS */
1329 _cleanup_free_
struct group
*g
= NULL
;
1331 r
= getgrnam_malloc(name
, &g
);
1333 *ret_gid
= g
->gr_gid
;
1337 return log_error_errno(r
, "Failed to check if group %s already exists: %m", name
);
1343 static int add_group(Context
*c
, Item
*i
) {
1349 r
= get_gid_by_name(c
, i
->name
, &i
->gid
);
1353 log_debug("Group %s already exists.", i
->name
);
1358 /* Try to use the suggested numeric GID */
1360 r
= gid_is_ok(c
, i
->gid
, i
->name
, false);
1362 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1363 if (i
->id_set_strict
) {
1364 /* If we require the GID to already exist we can return here:
1365 * r > 0: means the GID does not exist -> fail
1366 * r == 0: means the GID exists -> nothing more to do.
1369 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1370 "Failed to create %s: please create GID " GID_FMT
,
1376 log_info("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1381 /* Try to reuse the numeric uid, if there's one */
1382 if (!i
->gid_set
&& i
->uid_set
) {
1383 r
= gid_is_ok(c
, (gid_t
) i
->uid
, i
->name
, true);
1385 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1387 i
->gid
= (gid_t
) i
->uid
;
1392 /* If that didn't work, try to read it from the specified path */
1396 if (read_id_from_file(i
, NULL
, &candidate
) > 0) {
1398 if (candidate
<= 0 || !uid_range_contains(c
->uid_range
, candidate
))
1399 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", candidate
, i
->name
);
1401 r
= gid_is_ok(c
, candidate
, i
->name
, true);
1403 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1408 log_debug("Group ID " GID_FMT
" of file for %s already used.", candidate
, i
->name
);
1413 /* And if that didn't work either, let's try to find a free one */
1415 maybe_emit_login_defs_warning(c
);
1418 /* We look for new GIDs in the UID pool! */
1419 r
= uid_range_next_lower(c
->uid_range
, &c
->search_uid
);
1421 return log_error_errno(r
, "No free group ID available for %s.", i
->name
);
1423 r
= gid_is_ok(c
, c
->search_uid
, i
->name
, true);
1425 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1431 i
->gid
= c
->search_uid
;
1434 r
= ordered_hashmap_ensure_put(&c
->todo_gids
, NULL
, GID_TO_PTR(i
->gid
), i
);
1436 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
);
1440 return log_error_errno(r
, "Failed to store group %s with GID " GID_FMT
" to be created: %m", i
->name
, i
->gid
);
1442 i
->todo_group
= true;
1443 log_info("Creating group '%s' with GID " GID_FMT
".", i
->name
, i
->gid
);
1448 static int process_item(Context
*c
, Item
*i
) {
1460 j
= ordered_hashmap_get(c
->groups
, i
->group_name
?: i
->name
);
1462 if (j
&& j
->todo_group
) {
1463 /* When a group with the target name is already in queue,
1464 * use the information about the group and do not create
1465 * duplicated group entry. */
1466 i
->gid_set
= j
->gid_set
;
1468 i
->id_set_strict
= true;
1469 } else if (i
->group_name
) {
1470 /* When a group name was given instead of a GID and it's
1471 * not in queue, then it must already exist. */
1472 r
= get_gid_by_name(c
, i
->group_name
, &i
->gid
);
1474 return log_error_errno(r
, "Group %s not found.", i
->group_name
);
1476 i
->id_set_strict
= true;
1478 r
= add_group(c
, i
);
1483 return add_user(c
, i
);
1487 return add_group(c
, i
);
1490 assert_not_reached();
1494 static Item
* item_free(Item
*i
) {
1499 free(i
->group_name
);
1502 free(i
->description
);
1509 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1510 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops
, char, string_hash_func
, string_compare_func
, Item
, item_free
);
1512 static Item
* item_new(ItemType type
, const char *name
, const char *filename
, unsigned line
) {
1514 assert(!!filename
== (line
> 0));
1516 _cleanup_(item_freep
) Item
*new = new(Item
, 1);
1525 if (free_and_strdup(&new->name
, name
) < 0 ||
1526 free_and_strdup(&new->filename
, filename
) < 0)
1529 return TAKE_PTR(new);
1532 static int add_implicit(Context
*c
) {
1538 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1539 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, c
->members
) {
1541 if (!ordered_hashmap_get(c
->users
, *m
)) {
1542 _cleanup_(item_freep
) Item
*j
=
1543 item_new(ADD_USER
, *m
, /* filename= */ NULL
, /* line= */ 0);
1547 r
= ordered_hashmap_ensure_put(&c
->users
, &item_hash_ops
, j
->name
, j
);
1551 return log_error_errno(r
, "Failed to add implicit user '%s': %m", j
->name
);
1553 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1557 if (!(ordered_hashmap_get(c
->users
, g
) ||
1558 ordered_hashmap_get(c
->groups
, g
))) {
1559 _cleanup_(item_freep
) Item
*j
=
1560 item_new(ADD_GROUP
, g
, /* filename= */ NULL
, /* line= */ 0);
1564 r
= ordered_hashmap_ensure_put(&c
->groups
, &item_hash_ops
, j
->name
, j
);
1568 return log_error_errno(r
, "Failed to add implicit group '%s': %m", j
->name
);
1570 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1578 static int item_equivalent(Item
*a
, Item
*b
) {
1584 if (a
->type
!= b
->type
) {
1585 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1586 "Item not equivalent because types differ");
1590 if (!streq_ptr(a
->name
, b
->name
)) {
1591 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1592 "Item not equivalent because names differ ('%s' vs. '%s')",
1597 /* Paths were simplified previously, so we can use streq. */
1598 if (!streq_ptr(a
->uid_path
, b
->uid_path
)) {
1599 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1600 "Item not equivalent because UID paths differ (%s vs. %s)",
1601 a
->uid_path
?: "(unset)", b
->uid_path
?: "(unset)");
1605 if (!streq_ptr(a
->gid_path
, b
->gid_path
)) {
1606 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1607 "Item not equivalent because GID paths differ (%s vs. %s)",
1608 a
->gid_path
?: "(unset)", b
->gid_path
?: "(unset)");
1612 if (!streq_ptr(a
->description
, b
->description
)) {
1613 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1614 "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1615 strempty(a
->description
), strempty(b
->description
));
1619 if ((a
->uid_set
!= b
->uid_set
) ||
1620 (a
->uid_set
&& a
->uid
!= b
->uid
)) {
1621 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1622 "Item not equivalent because UIDs differ (%s vs. %s)",
1623 FORMAT_UID(a
->uid_set
, a
->uid
), FORMAT_UID(b
->uid_set
, b
->uid
));
1627 if ((a
->gid_set
!= b
->gid_set
) ||
1628 (a
->gid_set
&& a
->gid
!= b
->gid
)) {
1629 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1630 "Item not equivalent because GIDs differ (%s vs. %s)",
1631 FORMAT_GID(a
->gid_set
, a
->gid
), FORMAT_GID(b
->gid_set
, b
->gid
));
1635 if (!streq_ptr(a
->home
, b
->home
)) {
1636 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1637 "Item not equivalent because home directories differ ('%s' vs. '%s')",
1638 strempty(a
->description
), strempty(b
->description
));
1642 /* Check if the two paths refer to the same file.
1643 * If the paths are equal (after normalization), it's obviously the same file.
1644 * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1645 * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1646 * /usr/sbin/nologin).
1647 * If we can't resolve something, treat different paths as different. */
1649 const char *a_shell
= pick_shell(a
),
1650 *b_shell
= pick_shell(b
);
1651 if (!path_equal_ptr(a_shell
, b_shell
) &&
1652 !(is_nologin_shell(a_shell
) && is_nologin_shell(b_shell
))) {
1653 _cleanup_free_
char *pa
= NULL
, *pb
= NULL
;
1655 r
= chase(a_shell
, arg_root
, CHASE_PREFIX_ROOT
| CHASE_NONEXISTENT
, &pa
, NULL
);
1657 log_full_errno(ERRNO_IS_RESOURCE(r
) ? LOG_ERR
: LOG_DEBUG
,
1658 r
, "Failed to look up path '%s%s%s': %m",
1659 strempty(arg_root
), arg_root
? "/" : "", a_shell
);
1660 return ERRNO_IS_RESOURCE(r
) ? r
: false;
1663 r
= chase(b_shell
, arg_root
, CHASE_PREFIX_ROOT
| CHASE_NONEXISTENT
, &pb
, NULL
);
1665 log_full_errno(ERRNO_IS_RESOURCE(r
) ? LOG_ERR
: LOG_DEBUG
,
1666 r
, "Failed to look up path '%s%s%s': %m",
1667 strempty(arg_root
), arg_root
? "/" : "", b_shell
);
1668 return ERRNO_IS_RESOURCE(r
) ? r
: false;
1671 if (!path_equal(pa
, pb
)) {
1672 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1673 "Item not equivalent because shells differ ('%s' vs. '%s')",
1682 static int parse_line(
1686 const char *buffer
) {
1688 _cleanup_free_
char *action
= NULL
,
1689 *name
= NULL
, *resolved_name
= NULL
,
1690 *id
= NULL
, *resolved_id
= NULL
,
1691 *description
= NULL
, *resolved_description
= NULL
,
1692 *home
= NULL
, *resolved_home
= NULL
,
1693 *shell
= NULL
, *resolved_shell
= NULL
;
1694 _cleanup_(item_freep
) Item
*i
= NULL
;
1707 r
= extract_many_words(&p
, NULL
, EXTRACT_UNQUOTE
,
1708 &action
, &name
, &id
, &description
, &home
, &shell
, NULL
);
1710 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Syntax error.");
1712 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1713 "Missing action and name columns.");
1715 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1716 "Trailing garbage.");
1719 if (strlen(action
) != 1)
1720 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1721 "Unknown modifier '%s'.", action
);
1723 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
))
1724 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
1725 "Unknown command type '%c'.", action
[0]);
1728 if (empty_or_dash(name
))
1732 r
= specifier_printf(name
, NAME_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_name
);
1734 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to replace specifiers in '%s': %m", name
);
1736 if (!valid_user_group_name(resolved_name
, 0))
1737 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1738 "'%s' is not a valid user or group name.", resolved_name
);
1742 if (empty_or_dash(id
))
1746 r
= specifier_printf(id
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_id
);
1748 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1749 "Failed to replace specifiers in '%s': %m", name
);
1752 /* Verify description */
1753 if (empty_or_dash(description
))
1754 description
= mfree(description
);
1757 r
= specifier_printf(description
, LONG_LINE_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_description
);
1759 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1760 "Failed to replace specifiers in '%s': %m", description
);
1762 if (!valid_gecos(resolved_description
))
1763 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1764 "'%s' is not a valid GECOS field.", resolved_description
);
1768 if (empty_or_dash(home
))
1772 r
= specifier_printf(home
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_home
);
1774 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1775 "Failed to replace specifiers in '%s': %m", home
);
1777 path_simplify(resolved_home
);
1779 if (!valid_home(resolved_home
))
1780 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1781 "'%s' is not a valid home directory field.", resolved_home
);
1785 if (empty_or_dash(shell
))
1786 shell
= mfree(shell
);
1789 r
= specifier_printf(shell
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_shell
);
1791 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1792 "Failed to replace specifiers in '%s': %m", shell
);
1794 path_simplify(resolved_shell
);
1796 if (!valid_shell(resolved_shell
))
1797 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1798 "'%s' is not a valid login shell field.", resolved_shell
);
1801 switch (action
[0]) {
1805 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1806 "Lines of type 'r' don't take a name field.");
1809 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1810 "Lines of type 'r' require an ID range in the third field.");
1812 if (description
|| home
|| shell
)
1813 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1814 "Lines of type '%c' don't take a %s field.",
1816 description
? "GECOS" : home
? "home directory" : "login shell");
1818 r
= uid_range_add_str(&c
->uid_range
, resolved_id
);
1820 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1821 "Invalid UID range %s.", resolved_id
);
1826 /* Try to extend an existing member or group item */
1828 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1829 "Lines of type 'm' require a user name in the second field.");
1832 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1833 "Lines of type 'm' require a group name in the third field.");
1835 if (!valid_user_group_name(resolved_id
, 0))
1836 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1837 "'%s' is not a valid user or group name.", resolved_id
);
1839 if (description
|| home
|| shell
)
1840 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1841 "Lines of type '%c' don't take a %s field.",
1843 description
? "GECOS" : home
? "home directory" : "login shell");
1845 r
= string_strv_ordered_hashmap_put(&c
->members
, resolved_id
, resolved_name
);
1847 return log_error_errno(r
, "Failed to store mapping for %s: %m", resolved_id
);
1854 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1855 "Lines of type 'u' require a user name in the second field.");
1857 r
= ordered_hashmap_ensure_allocated(&c
->users
, &item_hash_ops
);
1861 i
= item_new(ADD_USER
, resolved_name
, fname
, line
);
1866 if (path_is_absolute(resolved_id
))
1867 i
->uid_path
= path_simplify(TAKE_PTR(resolved_id
));
1869 _cleanup_free_
char *uid
= NULL
, *gid
= NULL
;
1870 if (split_pair(resolved_id
, ":", &uid
, &gid
) == 0) {
1871 r
= parse_gid(gid
, &i
->gid
);
1873 if (valid_user_group_name(gid
, 0))
1874 i
->group_name
= TAKE_PTR(gid
);
1876 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1877 "Failed to parse GID: '%s': %m", id
);
1880 i
->id_set_strict
= true;
1882 free_and_replace(resolved_id
, uid
);
1884 if (!streq(resolved_id
, "-")) {
1885 r
= parse_uid(resolved_id
, &i
->uid
);
1887 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1888 "Failed to parse UID: '%s': %m", id
);
1894 i
->description
= TAKE_PTR(resolved_description
);
1895 i
->home
= TAKE_PTR(resolved_home
);
1896 i
->shell
= TAKE_PTR(resolved_shell
);
1903 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1904 "Lines of type 'g' require a user name in the second field.");
1906 if (description
|| home
|| shell
)
1907 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1908 "Lines of type '%c' don't take a %s field.",
1910 description
? "GECOS" : home
? "home directory" : "login shell");
1912 r
= ordered_hashmap_ensure_allocated(&c
->groups
, &item_hash_ops
);
1916 i
= item_new(ADD_GROUP
, resolved_name
, fname
, line
);
1921 if (path_is_absolute(resolved_id
))
1922 i
->gid_path
= path_simplify(TAKE_PTR(resolved_id
));
1924 r
= parse_gid(resolved_id
, &i
->gid
);
1926 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1927 "Failed to parse GID: '%s': %m", id
);
1937 assert_not_reached();
1940 existing
= ordered_hashmap_get(h
, i
->name
);
1942 /* Two functionally-equivalent items are fine */
1943 r
= item_equivalent(i
, existing
);
1947 if (existing
->filename
)
1948 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0,
1949 "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
1950 item_type_to_string(i
->type
),
1952 existing
->filename
, existing
->line
);
1954 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0,
1955 "Conflict with earlier configuration for %s '%s', ignoring line.",
1956 item_type_to_string(i
->type
),
1963 r
= ordered_hashmap_put(h
, i
->name
, i
);
1971 static int read_config_file(Context
*c
, const char *fn
, bool ignore_enoent
) {
1972 _cleanup_fclose_
FILE *rf
= NULL
;
1973 _cleanup_free_
char *pp
= NULL
;
1984 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf
, &pp
);
1986 if (ignore_enoent
&& r
== -ENOENT
)
1989 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
1997 _cleanup_free_
char *line
= NULL
;
2000 k
= read_stripped_line(f
, LONG_LINE_MAX
, &line
);
2002 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
2008 if (IN_SET(line
[0], 0, '#'))
2011 k
= parse_line(c
, fn
, v
, line
);
2012 if (k
< 0 && r
== 0)
2017 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
2025 static int cat_config(void) {
2026 _cleanup_strv_free_
char **files
= NULL
;
2029 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
2033 pager_open(arg_pager_flags
);
2035 return cat_files(NULL
, files
, arg_cat_flags
);
2038 static int help(void) {
2039 _cleanup_free_
char *link
= NULL
;
2042 r
= terminal_urlify_man("systemd-sysusers.service", "8", &link
);
2046 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
2047 "Creates system user accounts.\n\n"
2048 " -h --help Show this help\n"
2049 " --version Show package version\n"
2050 " --cat-config Show configuration files\n"
2051 " --tldr Show non-comment parts of configuration\n"
2052 " --root=PATH Operate on an alternate filesystem root\n"
2053 " --image=PATH Operate on disk image as filesystem root\n"
2054 " --image-policy=POLICY Specify disk image dissection policy\n"
2055 " --replace=PATH Treat arguments as replacement for PATH\n"
2056 " --dry-run Just print what would be done\n"
2057 " --inline Treat arguments as configuration lines\n"
2058 " --no-pager Do not pipe output into a pager\n"
2059 "\nSee the %s for details.\n",
2060 program_invocation_short_name
,
2066 static int parse_argv(int argc
, char *argv
[]) {
2069 ARG_VERSION
= 0x100,
2081 static const struct option options
[] = {
2082 { "help", no_argument
, NULL
, 'h' },
2083 { "version", no_argument
, NULL
, ARG_VERSION
},
2084 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
2085 { "tldr", no_argument
, NULL
, ARG_TLDR
},
2086 { "root", required_argument
, NULL
, ARG_ROOT
},
2087 { "image", required_argument
, NULL
, ARG_IMAGE
},
2088 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
2089 { "replace", required_argument
, NULL
, ARG_REPLACE
},
2090 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
2091 { "inline", no_argument
, NULL
, ARG_INLINE
},
2092 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
2101 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2111 case ARG_CAT_CONFIG
:
2112 arg_cat_flags
= CAT_CONFIG_ON
;
2116 arg_cat_flags
= CAT_TLDR
;
2120 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
2127 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2128 "This systemd-sysusers version is compiled without support for --image=.");
2130 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
2136 case ARG_IMAGE_POLICY
:
2137 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
2143 if (!path_is_absolute(optarg
) ||
2144 !endswith(optarg
, ".conf"))
2145 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2146 "The argument to --replace= must an absolute path to a config file");
2148 arg_replace
= optarg
;
2160 arg_pager_flags
|= PAGER_DISABLE
;
2167 assert_not_reached();
2170 if (arg_replace
&& arg_cat_flags
!= CAT_CONFIG_OFF
)
2171 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2172 "Option --replace= is not supported with --cat-config/--tldr.");
2174 if (arg_replace
&& optind
>= argc
)
2175 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2176 "When --replace= is given, some configuration items must be specified.");
2178 if (arg_image
&& arg_root
)
2179 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2180 "Use either --root= or --image=, the combination of both is not supported.");
2185 static int parse_arguments(Context
*c
, char **args
) {
2191 STRV_FOREACH(arg
, args
) {
2193 /* Use (argument):n, where n==1 for the first positional arg */
2194 r
= parse_line(c
, "(argument)", pos
, *arg
);
2196 r
= read_config_file(c
, *arg
, /* ignore_enoent= */ false);
2206 static int read_config_files(Context
*c
, char **args
) {
2207 _cleanup_strv_free_
char **files
= NULL
;
2208 _cleanup_free_
char *p
= NULL
;
2213 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
2217 STRV_FOREACH(f
, files
)
2218 if (p
&& path_equal(*f
, p
)) {
2219 log_debug("Parsing arguments at position \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
2221 r
= parse_arguments(c
, args
);
2225 log_debug("Reading config file \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
2227 /* Just warn, ignore result otherwise */
2228 (void) read_config_file(c
, *f
, /* ignore_enoent= */ true);
2234 static int read_credential_lines(Context
*c
) {
2235 _cleanup_free_
char *j
= NULL
;
2241 r
= get_credentials_dir(&d
);
2245 return log_error_errno(r
, "Failed to get credentials directory: %m");
2247 j
= path_join(d
, "sysusers.extra");
2251 (void) read_config_file(c
, j
, /* ignore_enoent= */ true);
2255 static int run(int argc
, char *argv
[]) {
2257 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2258 _cleanup_(umount_and_freep
) char *mounted_dir
= NULL
;
2260 _cleanup_close_
int lock
= -EBADF
;
2261 _cleanup_(context_done
) Context c
= {
2262 .search_uid
= UID_INVALID
,
2268 r
= parse_argv(argc
, argv
);
2274 if (arg_cat_flags
!= CAT_CONFIG_OFF
)
2275 return cat_config();
2287 r
= mount_image_privately_interactively(
2290 DISSECT_IMAGE_GENERIC_ROOT
|
2291 DISSECT_IMAGE_REQUIRE_ROOT
|
2292 DISSECT_IMAGE_VALIDATE_OS
|
2293 DISSECT_IMAGE_RELAX_VAR_CHECK
|
2294 DISSECT_IMAGE_FSCK
|
2295 DISSECT_IMAGE_GROWFS
,
2297 /* ret_dir_fd= */ NULL
,
2302 arg_root
= strdup(mounted_dir
);
2310 /* If command line arguments are specified along with --replace, read all configuration files and
2311 * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2312 * specified, execute just them, and finally, without --replace= or any positional arguments, just
2313 * read configuration and execute it. */
2314 if (arg_replace
|| optind
>= argc
)
2315 r
= read_config_files(&c
, argv
+ optind
);
2317 r
= parse_arguments(&c
, argv
+ optind
);
2321 r
= read_credential_lines(&c
);
2325 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our
2326 * detection whether the names or UID/GID area already used otherwise doesn't get confused. After
2327 * all, even though nss-systemd synthesizes these users/groups, they should still appear in
2328 * /etc/passwd and /etc/group, as the synthesizing logic is merely supposed to be fallback for cases
2329 * where we run with a completely unpopulated /etc. */
2330 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
2331 return log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
2334 /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2335 r
= read_login_defs(&c
.login_defs
, NULL
, arg_root
);
2337 return log_error_errno(r
, "Failed to read %s%s: %m",
2338 strempty(arg_root
), "/etc/login.defs");
2340 c
.login_defs_need_warning
= true;
2342 /* We pick a range that very conservative: we look at compiled-in maximum and the value in
2343 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
2344 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2345 * it's only used during allocation, so we use the configured value directly). */
2346 uid_t begin
= c
.login_defs
.system_alloc_uid_min
,
2347 end
= MIN3((uid_t
) SYSTEM_UID_MAX
, c
.login_defs
.system_uid_max
, c
.login_defs
.system_gid_max
);
2349 r
= uid_range_add(&c
.uid_range
, begin
, end
- begin
+ 1);
2355 r
= add_implicit(&c
);
2360 lock
= take_etc_passwd_lock(arg_root
);
2362 return log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
2365 r
= load_user_database(&c
);
2367 return log_error_errno(r
, "Failed to load user database: %m");
2369 r
= load_group_database(&c
);
2371 return log_error_errno(r
, "Failed to read group database: %m");
2373 ORDERED_HASHMAP_FOREACH(i
, c
.groups
)
2374 (void) process_item(&c
, i
);
2376 ORDERED_HASHMAP_FOREACH(i
, c
.users
)
2377 (void) process_item(&c
, i
);
2379 return write_files(&c
);
2382 DEFINE_MAIN_FUNCTION(run
);