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 int errno_is_not_exists(int code
) {
145 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
147 return IN_SET(code
, 0, ENOENT
, ESRCH
, EBADF
, EPERM
);
150 /* Note: the lifetime of the compound literal is the immediately surrounding block,
151 * see C11 §6.5.2.5, and
152 * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */
153 #define FORMAT_UID(is_set, uid) \
154 ((is_set) ? snprintf_ok((char[DECIMAL_STR_MAX(uid_t)]){}, DECIMAL_STR_MAX(uid_t), UID_FMT, uid) : "(unset)")
155 #define FORMAT_GID(is_set, gid) \
156 ((is_set) ? snprintf_ok((char[DECIMAL_STR_MAX(gid_t)]){}, DECIMAL_STR_MAX(gid_t), GID_FMT, gid) : "(unset)")
158 static void maybe_emit_login_defs_warning(Context
*c
) {
161 if (!c
->login_defs_need_warning
)
164 if (c
->login_defs
.system_alloc_uid_min
!= SYSTEM_ALLOC_UID_MIN
||
165 c
->login_defs
.system_uid_max
!= SYSTEM_UID_MAX
)
166 log_warning("login.defs specifies UID allocation range "UID_FMT
"–"UID_FMT
167 " that is different than the built-in defaults ("UID_FMT
"–"UID_FMT
")",
168 c
->login_defs
.system_alloc_uid_min
, c
->login_defs
.system_uid_max
,
169 (uid_t
) SYSTEM_ALLOC_UID_MIN
, (uid_t
) SYSTEM_UID_MAX
);
170 if (c
->login_defs
.system_alloc_gid_min
!= SYSTEM_ALLOC_GID_MIN
||
171 c
->login_defs
.system_gid_max
!= SYSTEM_GID_MAX
)
172 log_warning("login.defs specifies GID allocation range "GID_FMT
"–"GID_FMT
173 " that is different than the built-in defaults ("GID_FMT
"–"GID_FMT
")",
174 c
->login_defs
.system_alloc_gid_min
, c
->login_defs
.system_gid_max
,
175 (gid_t
) SYSTEM_ALLOC_GID_MIN
, (gid_t
) SYSTEM_GID_MAX
);
177 c
->login_defs_need_warning
= false;
180 static int load_user_database(Context
*c
) {
181 _cleanup_fclose_
FILE *f
= NULL
;
182 const char *passwd_path
;
188 passwd_path
= prefix_roota(arg_root
, "/etc/passwd");
189 f
= fopen(passwd_path
, "re");
191 return errno
== ENOENT
? 0 : -errno
;
193 r
= hashmap_ensure_allocated(&c
->database_by_username
, &string_hash_ops
);
197 r
= hashmap_ensure_allocated(&c
->database_by_uid
, NULL
);
201 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
202 r
= set_ensure_allocated(&c
->names
, NULL
);
206 while ((r
= fgetpwent_sane(f
, &pw
)) > 0) {
208 char *n
= strdup(pw
->pw_name
);
212 r
= set_consume(c
->names
, n
);
215 assert(r
> 0); /* The set uses pointer comparisons, so n must not be in the set. */
217 r
= hashmap_put(c
->database_by_username
, n
, UID_TO_PTR(pw
->pw_uid
));
219 log_debug_errno(r
, "%s: user '%s' is listed twice, ignoring duplicate uid.",
224 r
= hashmap_put(c
->database_by_uid
, UID_TO_PTR(pw
->pw_uid
), n
);
226 log_debug_errno(r
, "%s: uid "UID_FMT
" is listed twice, ignoring duplicate name.",
227 passwd_path
, pw
->pw_uid
);
234 static int load_group_database(Context
*c
) {
235 _cleanup_fclose_
FILE *f
= NULL
;
236 const char *group_path
;
242 group_path
= prefix_roota(arg_root
, "/etc/group");
243 f
= fopen(group_path
, "re");
245 return errno
== ENOENT
? 0 : -errno
;
247 r
= hashmap_ensure_allocated(&c
->database_by_groupname
, &string_hash_ops
);
251 r
= hashmap_ensure_allocated(&c
->database_by_gid
, NULL
);
255 /* Note that we use NULL, i.e. trivial_hash_ops here, so identical strings can exist in the set. */
256 r
= set_ensure_allocated(&c
->names
, NULL
);
260 while ((r
= fgetgrent_sane(f
, &gr
)) > 0) {
262 char *n
= strdup(gr
->gr_name
);
266 r
= set_consume(c
->names
, n
);
269 assert(r
> 0); /* The set uses pointer comparisons, so n must not be in the set. */
271 r
= hashmap_put(c
->database_by_groupname
, n
, GID_TO_PTR(gr
->gr_gid
));
273 log_debug_errno(r
, "%s: group '%s' is listed twice, ignoring duplicate gid.",
278 r
= hashmap_put(c
->database_by_gid
, GID_TO_PTR(gr
->gr_gid
), n
);
280 log_debug_errno(r
, "%s: gid "GID_FMT
" is listed twice, ignoring duplicate name.",
281 group_path
, gr
->gr_gid
);
288 static int make_backup(const char *target
, const char *x
) {
289 _cleanup_(unlink_and_freep
) char *dst_tmp
= NULL
;
290 _cleanup_fclose_
FILE *dst
= NULL
;
291 _cleanup_close_
int src
= -EBADF
;
299 src
= open(x
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
301 if (errno
== ENOENT
) /* No backup necessary... */
307 if (fstat(src
, &st
) < 0)
310 r
= fopen_temporary_label(
311 target
, /* The path for which to the look up the label */
312 x
, /* Where we want the file actually to end up */
313 &dst
, /* The temporary file we write to */
318 r
= copy_bytes(src
, fileno(dst
), UINT64_MAX
, COPY_REFLINK
);
322 backup
= strjoina(x
, "-");
324 /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
325 * unreadable by others, then it isn't too bad... */
326 r
= fchmod_and_chown_with_fallback(fileno(dst
), dst_tmp
, st
.st_mode
& 07777, st
.st_uid
, st
.st_gid
);
328 log_warning_errno(r
, "Failed to change access mode or ownership of %s: %m", backup
);
330 if (futimens(fileno(dst
), (const struct timespec
[2]) { st
.st_atim
, st
.st_mtim
}) < 0)
331 log_warning_errno(errno
, "Failed to fix access and modification time of %s: %m", backup
);
333 r
= fsync_full(fileno(dst
));
337 if (rename(dst_tmp
, backup
) < 0)
340 dst_tmp
= mfree(dst_tmp
); /* disable the unlink_and_freep() hook now that the file has been renamed */
344 static int putgrent_with_members(
346 const struct group
*gr
,
356 a
= ordered_hashmap_get(c
->members
, gr
->gr_name
);
358 _cleanup_strv_free_
char **l
= NULL
;
361 l
= strv_copy(gr
->gr_mem
);
366 if (strv_contains(l
, *i
))
369 r
= strv_extend(&l
, *i
);
385 r
= putgrent_sane(&t
, group
);
386 return r
< 0 ? r
: 1;
390 return putgrent_sane(gr
, group
);
394 static int putsgent_with_members(
396 const struct sgrp
*sg
,
405 a
= ordered_hashmap_get(c
->members
, sg
->sg_namp
);
407 _cleanup_strv_free_
char **l
= NULL
;
410 l
= strv_copy(sg
->sg_mem
);
415 if (strv_contains(l
, *i
))
418 r
= strv_extend(&l
, *i
);
434 r
= putsgent_sane(&t
, gshadow
);
435 return r
< 0 ? r
: 1;
439 return putsgent_sane(sg
, gshadow
);
443 static const char* pick_shell(const Item
*i
) {
444 if (i
->type
!= ADD_USER
)
448 if (i
->uid_set
&& i
->uid
== 0)
449 return default_root_shell(arg_root
);
453 static int write_temporary_passwd(
455 const char *passwd_path
,
457 char **ret_tmpfile_path
) {
459 _cleanup_fclose_
FILE *original
= NULL
, *passwd
= NULL
;
460 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
;
461 struct passwd
*pw
= NULL
;
467 if (ordered_hashmap_isempty(c
->todo_uids
))
471 log_info("Would write /etc/passwd%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
475 r
= fopen_temporary_label("/etc/passwd", passwd_path
, &passwd
, &passwd_tmp
);
477 return log_debug_errno(r
, "Failed to open temporary copy of %s: %m", passwd_path
);
479 original
= fopen(passwd_path
, "re");
482 /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
483 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
484 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
485 * it easier to depend on sysusers in packaging scripts and suchlike. */
486 r
= copy_rights_with_fallback(fileno(original
), fileno(passwd
), passwd_tmp
);
488 return log_debug_errno(r
, "Failed to copy permissions from %s to %s: %m",
489 passwd_path
, passwd_tmp
);
491 while ((r
= fgetpwent_sane(original
, &pw
)) > 0) {
492 i
= ordered_hashmap_get(c
->users
, pw
->pw_name
);
493 if (i
&& i
->todo_user
)
494 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
495 "%s: User \"%s\" already exists.",
496 passwd_path
, pw
->pw_name
);
498 if (ordered_hashmap_contains(c
->todo_uids
, UID_TO_PTR(pw
->pw_uid
)))
499 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
500 "%s: Detected collision for UID " UID_FMT
".",
501 passwd_path
, pw
->pw_uid
);
503 /* Make sure we keep the NIS entries (if any) at the end. */
504 if (IN_SET(pw
->pw_name
[0], '+', '-'))
507 r
= putpwent_sane(pw
, passwd
);
509 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary passwd file: %m",
513 return log_debug_errno(r
, "Failed to read %s: %m", passwd_path
);
517 return log_debug_errno(errno
, "Failed to open %s: %m", passwd_path
);
518 if (fchmod(fileno(passwd
), 0644) < 0)
519 return log_debug_errno(errno
, "Failed to fchmod %s: %m", passwd_tmp
);
522 ORDERED_HASHMAP_FOREACH(i
, c
->todo_uids
) {
523 _cleanup_free_
char *creds_shell
= NULL
, *cn
= NULL
;
529 .pw_gecos
= (char*) strempty(i
->description
),
531 /* "x" means the password is stored in the shadow file */
532 .pw_passwd
= (char*) PASSWORD_SEE_SHADOW
,
534 /* We default to the root directory as home */
535 .pw_dir
= i
->home
?: (char*) "/",
537 /* Initialize the shell to nologin, with one exception:
538 * for root we patch in something special */
539 .pw_shell
= (char*) pick_shell(i
),
542 /* Try to pick up the shell for this account via the credentials logic */
543 cn
= strjoin("passwd.shell.", i
->name
);
547 r
= read_credential(cn
, (void**) &creds_shell
, NULL
);
549 log_debug_errno(r
, "Couldn't read credential '%s', ignoring: %m", cn
);
551 n
.pw_shell
= creds_shell
;
553 r
= putpwent_sane(&n
, passwd
);
555 return log_debug_errno(r
, "Failed to add new user \"%s\" to temporary passwd file: %m",
559 /* Append the remaining NIS entries if any */
561 r
= putpwent_sane(pw
, passwd
);
563 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary passwd file: %m",
566 r
= fgetpwent_sane(original
, &pw
);
568 return log_debug_errno(r
, "Failed to read %s: %m", passwd_path
);
573 r
= fflush_sync_and_check(passwd
);
575 return log_debug_errno(r
, "Failed to flush %s: %m", passwd_tmp
);
577 *ret_tmpfile
= TAKE_PTR(passwd
);
578 *ret_tmpfile_path
= TAKE_PTR(passwd_tmp
);
583 static usec_t
epoch_or_now(void) {
586 if (getenv_uint64_secure("SOURCE_DATE_EPOCH", &epoch
) >= 0) {
587 if (epoch
> UINT64_MAX
/USEC_PER_SEC
) /* Overflow check */
588 return USEC_INFINITY
;
589 return (usec_t
) epoch
* USEC_PER_SEC
;
592 return now(CLOCK_REALTIME
);
595 static int write_temporary_shadow(
597 const char *shadow_path
,
599 char **ret_tmpfile_path
) {
601 _cleanup_fclose_
FILE *original
= NULL
, *shadow
= NULL
;
602 _cleanup_(unlink_and_freep
) char *shadow_tmp
= NULL
;
603 struct spwd
*sp
= NULL
;
610 if (ordered_hashmap_isempty(c
->todo_uids
))
614 log_info("Would write /etc/shadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
618 r
= fopen_temporary_label("/etc/shadow", shadow_path
, &shadow
, &shadow_tmp
);
620 return log_debug_errno(r
, "Failed to open temporary copy of %s: %m", shadow_path
);
622 lstchg
= (long) (epoch_or_now() / USEC_PER_DAY
);
624 original
= fopen(shadow_path
, "re");
627 r
= copy_rights_with_fallback(fileno(original
), fileno(shadow
), shadow_tmp
);
629 return log_debug_errno(r
, "Failed to copy permissions from %s to %s: %m",
630 shadow_path
, shadow_tmp
);
632 while ((r
= fgetspent_sane(original
, &sp
)) > 0) {
633 i
= ordered_hashmap_get(c
->users
, sp
->sp_namp
);
634 if (i
&& i
->todo_user
) {
635 /* we will update the existing entry */
636 sp
->sp_lstchg
= lstchg
;
638 /* only the /etc/shadow stage is left, so we can
639 * safely remove the item from the todo set */
640 i
->todo_user
= false;
641 ordered_hashmap_remove(c
->todo_uids
, UID_TO_PTR(i
->uid
));
644 /* Make sure we keep the NIS entries (if any) at the end. */
645 if (IN_SET(sp
->sp_namp
[0], '+', '-'))
648 r
= putspent_sane(sp
, shadow
);
650 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary shadow file: %m",
655 return log_debug_errno(r
, "Failed to read %s: %m", shadow_path
);
659 return log_debug_errno(errno
, "Failed to open %s: %m", shadow_path
);
660 if (fchmod(fileno(shadow
), 0000) < 0)
661 return log_debug_errno(errno
, "Failed to fchmod %s: %m", shadow_tmp
);
664 ORDERED_HASHMAP_FOREACH(i
, c
->todo_uids
) {
665 _cleanup_(erase_and_freep
) char *creds_password
= NULL
;
676 .sp_flag
= ULONG_MAX
, /* this appears to be what everybody does ... */
679 r
= get_credential_user_password(i
->name
, &creds_password
, &is_hashed
);
681 log_debug_errno(r
, "Couldn't read password credential for user '%s', ignoring: %m", i
->name
);
683 if (creds_password
&& !is_hashed
) {
684 _cleanup_(erase_and_freep
) char* plaintext_password
= TAKE_PTR(creds_password
);
685 r
= hash_password(plaintext_password
, &creds_password
);
687 return log_debug_errno(r
, "Failed to hash password: %m");
691 n
.sp_pwdp
= creds_password
;
692 else if (streq(i
->name
, "root"))
693 /* Let firstboot set the password later */
694 n
.sp_pwdp
= (char*) PASSWORD_UNPROVISIONED
;
696 n
.sp_pwdp
= (char*) PASSWORD_LOCKED_AND_INVALID
;
698 r
= putspent_sane(&n
, shadow
);
700 return log_debug_errno(r
, "Failed to add new user \"%s\" to temporary shadow file: %m",
704 /* Append the remaining NIS entries if any */
706 r
= putspent_sane(sp
, shadow
);
708 return log_debug_errno(r
, "Failed to add existing user \"%s\" to temporary shadow file: %m",
711 r
= fgetspent_sane(original
, &sp
);
713 return log_debug_errno(r
, "Failed to read %s: %m", shadow_path
);
717 if (!IN_SET(errno
, 0, ENOENT
))
720 r
= fflush_sync_and_check(shadow
);
722 return log_debug_errno(r
, "Failed to flush %s: %m", shadow_tmp
);
724 *ret_tmpfile
= TAKE_PTR(shadow
);
725 *ret_tmpfile_path
= TAKE_PTR(shadow_tmp
);
730 static int write_temporary_group(
732 const char *group_path
,
734 char **ret_tmpfile_path
) {
736 _cleanup_fclose_
FILE *original
= NULL
, *group
= NULL
;
737 _cleanup_(unlink_and_freep
) char *group_tmp
= NULL
;
738 bool group_changed
= false;
739 struct group
*gr
= NULL
;
745 if (ordered_hashmap_isempty(c
->todo_gids
) && ordered_hashmap_isempty(c
->members
))
749 log_info("Would write /etc/group%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
753 r
= fopen_temporary_label("/etc/group", group_path
, &group
, &group_tmp
);
755 return log_error_errno(r
, "Failed to open temporary copy of %s: %m", group_path
);
757 original
= fopen(group_path
, "re");
760 r
= copy_rights_with_fallback(fileno(original
), fileno(group
), group_tmp
);
762 return log_error_errno(r
, "Failed to copy permissions from %s to %s: %m",
763 group_path
, group_tmp
);
765 while ((r
= fgetgrent_sane(original
, &gr
)) > 0) {
766 /* Safety checks against name and GID collisions. Normally,
767 * this should be unnecessary, but given that we look at the
768 * entries anyway here, let's make an extra verification
769 * step that we don't generate duplicate entries. */
771 i
= ordered_hashmap_get(c
->groups
, gr
->gr_name
);
772 if (i
&& i
->todo_group
)
773 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
774 "%s: Group \"%s\" already exists.",
775 group_path
, gr
->gr_name
);
777 if (ordered_hashmap_contains(c
->todo_gids
, GID_TO_PTR(gr
->gr_gid
)))
778 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
779 "%s: Detected collision for GID " GID_FMT
".",
780 group_path
, gr
->gr_gid
);
782 /* Make sure we keep the NIS entries (if any) at the end. */
783 if (IN_SET(gr
->gr_name
[0], '+', '-'))
786 r
= putgrent_with_members(c
, gr
, group
);
788 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary group file: %m",
791 group_changed
= true;
794 return log_error_errno(r
, "Failed to read %s: %m", group_path
);
798 return log_error_errno(errno
, "Failed to open %s: %m", group_path
);
799 if (fchmod(fileno(group
), 0644) < 0)
800 return log_error_errno(errno
, "Failed to fchmod %s: %m", group_tmp
);
803 ORDERED_HASHMAP_FOREACH(i
, c
->todo_gids
) {
807 .gr_passwd
= (char*) PASSWORD_SEE_SHADOW
,
810 r
= putgrent_with_members(c
, &n
, group
);
812 return log_error_errno(r
, "Failed to add new group \"%s\" to temporary group file: %m",
815 group_changed
= true;
818 /* Append the remaining NIS entries if any */
820 r
= putgrent_sane(gr
, group
);
822 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary group file: %m",
825 r
= fgetgrent_sane(original
, &gr
);
827 return log_error_errno(r
, "Failed to read %s: %m", group_path
);
832 r
= fflush_sync_and_check(group
);
834 return log_error_errno(r
, "Failed to flush %s: %m", group_tmp
);
837 *ret_tmpfile
= TAKE_PTR(group
);
838 *ret_tmpfile_path
= TAKE_PTR(group_tmp
);
843 static int write_temporary_gshadow(
845 const char * gshadow_path
,
847 char **ret_tmpfile_path
) {
850 _cleanup_fclose_
FILE *original
= NULL
, *gshadow
= NULL
;
851 _cleanup_(unlink_and_freep
) char *gshadow_tmp
= NULL
;
852 bool group_changed
= false;
858 if (ordered_hashmap_isempty(c
->todo_gids
) && ordered_hashmap_isempty(c
->members
))
862 log_info("Would write /etc/gshadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
866 r
= fopen_temporary_label("/etc/gshadow", gshadow_path
, &gshadow
, &gshadow_tmp
);
868 return log_error_errno(r
, "Failed to open temporary copy of %s: %m", gshadow_path
);
870 original
= fopen(gshadow_path
, "re");
874 r
= copy_rights_with_fallback(fileno(original
), fileno(gshadow
), gshadow_tmp
);
876 return log_error_errno(r
, "Failed to copy permissions from %s to %s: %m",
877 gshadow_path
, gshadow_tmp
);
879 while ((r
= fgetsgent_sane(original
, &sg
)) > 0) {
881 i
= ordered_hashmap_get(c
->groups
, sg
->sg_namp
);
882 if (i
&& i
->todo_group
)
883 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
884 "%s: Group \"%s\" already exists.",
885 gshadow_path
, sg
->sg_namp
);
887 r
= putsgent_with_members(c
, sg
, gshadow
);
889 return log_error_errno(r
, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
892 group_changed
= true;
899 return log_error_errno(errno
, "Failed to open %s: %m", gshadow_path
);
900 if (fchmod(fileno(gshadow
), 0000) < 0)
901 return log_error_errno(errno
, "Failed to fchmod %s: %m", gshadow_tmp
);
904 ORDERED_HASHMAP_FOREACH(i
, c
->todo_gids
) {
907 .sg_passwd
= (char*) PASSWORD_LOCKED_AND_INVALID
,
910 r
= putsgent_with_members(c
, &n
, gshadow
);
912 return log_error_errno(r
, "Failed to add new group \"%s\" to temporary gshadow file: %m",
915 group_changed
= true;
918 r
= fflush_sync_and_check(gshadow
);
920 return log_error_errno(r
, "Failed to flush %s: %m", gshadow_tmp
);
923 *ret_tmpfile
= TAKE_PTR(gshadow
);
924 *ret_tmpfile_path
= TAKE_PTR(gshadow_tmp
);
930 static int write_files(Context
*c
) {
931 _cleanup_fclose_
FILE *passwd
= NULL
, *group
= NULL
, *shadow
= NULL
, *gshadow
= NULL
;
932 _cleanup_(unlink_and_freep
) char *passwd_tmp
= NULL
, *group_tmp
= NULL
, *shadow_tmp
= NULL
, *gshadow_tmp
= NULL
;
936 *passwd_path
= prefix_roota(arg_root
, "/etc/passwd"),
937 *shadow_path
= prefix_roota(arg_root
, "/etc/shadow"),
938 *group_path
= prefix_roota(arg_root
, "/etc/group"),
939 *gshadow_path
= prefix_roota(arg_root
, "/etc/gshadow");
943 r
= write_temporary_group(c
, group_path
, &group
, &group_tmp
);
947 r
= write_temporary_gshadow(c
, gshadow_path
, &gshadow
, &gshadow_tmp
);
951 r
= write_temporary_passwd(c
, passwd_path
, &passwd
, &passwd_tmp
);
955 r
= write_temporary_shadow(c
, shadow_path
, &shadow
, &shadow_tmp
);
959 /* Make a backup of the old files */
961 r
= make_backup("/etc/group", group_path
);
963 return log_error_errno(r
, "Failed to backup %s: %m", group_path
);
966 r
= make_backup("/etc/gshadow", gshadow_path
);
968 return log_error_errno(r
, "Failed to backup %s: %m", gshadow_path
);
972 r
= make_backup("/etc/passwd", passwd_path
);
974 return log_error_errno(r
, "Failed to backup %s: %m", passwd_path
);
977 r
= make_backup("/etc/shadow", shadow_path
);
979 return log_error_errno(r
, "Failed to backup %s: %m", shadow_path
);
982 /* And make the new files count */
984 r
= rename_and_apply_smack_floor_label(group_tmp
, group_path
);
986 return log_error_errno(r
, "Failed to rename %s to %s: %m",
987 group_tmp
, group_path
);
988 group_tmp
= mfree(group_tmp
);
990 if (!arg_root
&& !arg_image
)
991 (void) nscd_flush_cache(STRV_MAKE("group"));
994 r
= rename_and_apply_smack_floor_label(gshadow_tmp
, gshadow_path
);
996 return log_error_errno(r
, "Failed to rename %s to %s: %m",
997 gshadow_tmp
, gshadow_path
);
999 gshadow_tmp
= mfree(gshadow_tmp
);
1003 r
= rename_and_apply_smack_floor_label(passwd_tmp
, passwd_path
);
1005 return log_error_errno(r
, "Failed to rename %s to %s: %m",
1006 passwd_tmp
, passwd_path
);
1008 passwd_tmp
= mfree(passwd_tmp
);
1010 if (!arg_root
&& !arg_image
)
1011 (void) nscd_flush_cache(STRV_MAKE("passwd"));
1014 r
= rename_and_apply_smack_floor_label(shadow_tmp
, shadow_path
);
1016 return log_error_errno(r
, "Failed to rename %s to %s: %m",
1017 shadow_tmp
, shadow_path
);
1019 shadow_tmp
= mfree(shadow_tmp
);
1025 static int uid_is_ok(
1029 bool check_with_gid
) {
1033 /* Let's see if we already have assigned the UID a second time */
1034 if (ordered_hashmap_get(c
->todo_uids
, UID_TO_PTR(uid
)))
1037 /* Try to avoid using uids that are already used by a group
1038 * that doesn't have the same name as our new user. */
1039 if (check_with_gid
) {
1042 i
= ordered_hashmap_get(c
->todo_gids
, GID_TO_PTR(uid
));
1043 if (i
&& !streq(i
->name
, name
))
1047 /* Let's check the files directly */
1048 if (hashmap_contains(c
->database_by_uid
, UID_TO_PTR(uid
)))
1051 if (check_with_gid
) {
1054 n
= hashmap_get(c
->database_by_gid
, GID_TO_PTR(uid
));
1055 if (n
&& !streq(n
, name
))
1059 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
1068 if (!IN_SET(errno
, 0, ENOENT
))
1071 if (check_with_gid
) {
1073 g
= getgrgid((gid_t
) uid
);
1075 if (!streq(g
->gr_name
, name
))
1077 } else if (!IN_SET(errno
, 0, ENOENT
))
1085 static int root_stat(const char *p
, struct stat
*st
) {
1088 fix
= prefix_roota(arg_root
, p
);
1089 return RET_NERRNO(stat(fix
, st
));
1092 static int read_id_from_file(Item
*i
, uid_t
*ret_uid
, gid_t
*ret_gid
) {
1094 bool found_uid
= false, found_gid
= false;
1100 /* First, try to get the GID directly */
1101 if (ret_gid
&& i
->gid_path
&& root_stat(i
->gid_path
, &st
) >= 0) {
1106 /* Then, try to get the UID directly */
1107 if ((ret_uid
|| (ret_gid
&& !found_gid
))
1109 && root_stat(i
->uid_path
, &st
) >= 0) {
1114 /* If we need the gid, but had no success yet, also derive it from the UID path */
1115 if (ret_gid
&& !found_gid
) {
1121 /* If that didn't work yet, then let's reuse the GID as UID */
1122 if (ret_uid
&& !found_uid
&& i
->gid_path
) {
1127 } else if (root_stat(i
->gid_path
, &st
) >= 0) {
1128 uid
= (uid_t
) st
.st_gid
;
1150 static int add_user(Context
*c
, Item
*i
) {
1157 /* Check the database directly */
1158 z
= hashmap_get(c
->database_by_username
, i
->name
);
1160 log_debug("User %s already exists.", i
->name
);
1161 i
->uid
= PTR_TO_UID(z
);
1169 /* Also check NSS */
1171 p
= getpwnam(i
->name
);
1173 log_debug("User %s already exists.", i
->name
);
1177 r
= free_and_strdup(&i
->description
, p
->pw_gecos
);
1183 if (!errno_is_not_exists(errno
))
1184 return log_error_errno(errno
, "Failed to check if user %s already exists: %m", i
->name
);
1187 /* Try to use the suggested numeric UID */
1189 r
= uid_is_ok(c
, i
->uid
, i
->name
, !i
->id_set_strict
);
1191 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1193 log_info("Suggested user ID " UID_FMT
" for %s already used.", i
->uid
, i
->name
);
1198 /* If that didn't work, try to read it from the specified path */
1202 if (read_id_from_file(i
, &candidate
, NULL
) > 0) {
1204 if (candidate
<= 0 || !uid_range_contains(c
->uid_range
, candidate
))
1205 log_debug("User ID " UID_FMT
" of file not suitable for %s.", candidate
, i
->name
);
1207 r
= uid_is_ok(c
, candidate
, i
->name
, true);
1209 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1214 log_debug("User ID " UID_FMT
" of file for %s is already used.", candidate
, i
->name
);
1219 /* Otherwise, try to reuse the group ID */
1220 if (!i
->uid_set
&& i
->gid_set
) {
1221 r
= uid_is_ok(c
, (uid_t
) i
->gid
, i
->name
, true);
1223 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1225 i
->uid
= (uid_t
) i
->gid
;
1230 /* And if that didn't work either, let's try to find a free one */
1232 maybe_emit_login_defs_warning(c
);
1235 r
= uid_range_next_lower(c
->uid_range
, &c
->search_uid
);
1237 return log_error_errno(r
, "No free user ID available for %s.", i
->name
);
1239 r
= uid_is_ok(c
, c
->search_uid
, i
->name
, true);
1241 return log_error_errno(r
, "Failed to verify UID " UID_FMT
": %m", i
->uid
);
1247 i
->uid
= c
->search_uid
;
1250 r
= ordered_hashmap_ensure_put(&c
->todo_uids
, NULL
, UID_TO_PTR(i
->uid
), i
);
1252 return log_error_errno(r
, "Requested user %s with UID " UID_FMT
" and gid" GID_FMT
" to be created is duplicated "
1253 "or conflicts with another user.", i
->name
, i
->uid
, i
->gid
);
1257 return log_error_errno(r
, "Failed to store user %s with UID " UID_FMT
" and GID " GID_FMT
" to be created: %m",
1258 i
->name
, i
->uid
, i
->gid
);
1260 i
->todo_user
= true;
1261 log_info("Creating user '%s' (%s) with UID " UID_FMT
" and GID " GID_FMT
".",
1262 i
->name
, strna(i
->description
), i
->uid
, i
->gid
);
1267 static int gid_is_ok(
1270 const char *groupname
,
1271 bool check_with_uid
) {
1281 if (ordered_hashmap_get(c
->todo_gids
, GID_TO_PTR(gid
)))
1284 /* Avoid reusing gids that are already used by a different user */
1285 if (check_with_uid
) {
1286 user
= ordered_hashmap_get(c
->todo_uids
, UID_TO_PTR(gid
));
1287 if (user
&& !streq(user
->name
, groupname
))
1291 if (hashmap_contains(c
->database_by_gid
, GID_TO_PTR(gid
)))
1294 if (check_with_uid
) {
1295 username
= hashmap_get(c
->database_by_uid
, UID_TO_PTR(gid
));
1296 if (username
&& !streq(username
, groupname
))
1305 if (!IN_SET(errno
, 0, ENOENT
))
1308 if (check_with_uid
) {
1310 p
= getpwuid((uid_t
) gid
);
1313 if (!IN_SET(errno
, 0, ENOENT
))
1321 static int get_gid_by_name(
1331 /* Check the database directly */
1332 z
= hashmap_get(c
->database_by_groupname
, name
);
1334 *ret_gid
= PTR_TO_GID(z
);
1338 /* Also check NSS */
1345 *ret_gid
= g
->gr_gid
;
1348 if (!errno_is_not_exists(errno
))
1349 return log_error_errno(errno
, "Failed to check if group %s already exists: %m", name
);
1355 static int add_group(Context
*c
, Item
*i
) {
1361 r
= get_gid_by_name(c
, i
->name
, &i
->gid
);
1365 log_debug("Group %s already exists.", i
->name
);
1370 /* Try to use the suggested numeric GID */
1372 r
= gid_is_ok(c
, i
->gid
, i
->name
, false);
1374 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1375 if (i
->id_set_strict
) {
1376 /* If we require the GID to already exist we can return here:
1377 * r > 0: means the GID does not exist -> fail
1378 * r == 0: means the GID exists -> nothing more to do.
1381 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1382 "Failed to create %s: please create GID " GID_FMT
,
1388 log_info("Suggested group ID " GID_FMT
" for %s already used.", i
->gid
, i
->name
);
1393 /* Try to reuse the numeric uid, if there's one */
1394 if (!i
->gid_set
&& i
->uid_set
) {
1395 r
= gid_is_ok(c
, (gid_t
) i
->uid
, i
->name
, true);
1397 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1399 i
->gid
= (gid_t
) i
->uid
;
1404 /* If that didn't work, try to read it from the specified path */
1408 if (read_id_from_file(i
, NULL
, &candidate
) > 0) {
1410 if (candidate
<= 0 || !uid_range_contains(c
->uid_range
, candidate
))
1411 log_debug("Group ID " GID_FMT
" of file not suitable for %s.", candidate
, i
->name
);
1413 r
= gid_is_ok(c
, candidate
, i
->name
, true);
1415 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1420 log_debug("Group ID " GID_FMT
" of file for %s already used.", candidate
, i
->name
);
1425 /* And if that didn't work either, let's try to find a free one */
1427 maybe_emit_login_defs_warning(c
);
1430 /* We look for new GIDs in the UID pool! */
1431 r
= uid_range_next_lower(c
->uid_range
, &c
->search_uid
);
1433 return log_error_errno(r
, "No free group ID available for %s.", i
->name
);
1435 r
= gid_is_ok(c
, c
->search_uid
, i
->name
, true);
1437 return log_error_errno(r
, "Failed to verify GID " GID_FMT
": %m", i
->gid
);
1443 i
->gid
= c
->search_uid
;
1446 r
= ordered_hashmap_ensure_put(&c
->todo_gids
, NULL
, GID_TO_PTR(i
->gid
), i
);
1448 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
);
1452 return log_error_errno(r
, "Failed to store group %s with GID " GID_FMT
" to be created: %m", i
->name
, i
->gid
);
1454 i
->todo_group
= true;
1455 log_info("Creating group '%s' with GID " GID_FMT
".", i
->name
, i
->gid
);
1460 static int process_item(Context
*c
, Item
*i
) {
1472 j
= ordered_hashmap_get(c
->groups
, i
->group_name
?: i
->name
);
1474 if (j
&& j
->todo_group
) {
1475 /* When a group with the target name is already in queue,
1476 * use the information about the group and do not create
1477 * duplicated group entry. */
1478 i
->gid_set
= j
->gid_set
;
1480 i
->id_set_strict
= true;
1481 } else if (i
->group_name
) {
1482 /* When a group name was given instead of a GID and it's
1483 * not in queue, then it must already exist. */
1484 r
= get_gid_by_name(c
, i
->group_name
, &i
->gid
);
1486 return log_error_errno(r
, "Group %s not found.", i
->group_name
);
1488 i
->id_set_strict
= true;
1490 r
= add_group(c
, i
);
1495 return add_user(c
, i
);
1499 return add_group(c
, i
);
1502 assert_not_reached();
1506 static Item
* item_free(Item
*i
) {
1511 free(i
->group_name
);
1514 free(i
->description
);
1521 DEFINE_TRIVIAL_CLEANUP_FUNC(Item
*, item_free
);
1522 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops
, char, string_hash_func
, string_compare_func
, Item
, item_free
);
1524 static Item
* item_new(ItemType type
, const char *name
, const char *filename
, unsigned line
) {
1526 assert(!!filename
== (line
> 0));
1528 _cleanup_(item_freep
) Item
*new = new(Item
, 1);
1537 if (free_and_strdup(&new->name
, name
) < 0 ||
1538 free_and_strdup(&new->filename
, filename
) < 0)
1541 return TAKE_PTR(new);
1544 static int add_implicit(Context
*c
) {
1550 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1551 ORDERED_HASHMAP_FOREACH_KEY(l
, g
, c
->members
) {
1553 if (!ordered_hashmap_get(c
->users
, *m
)) {
1554 _cleanup_(item_freep
) Item
*j
=
1555 item_new(ADD_USER
, *m
, /* filename= */ NULL
, /* line= */ 0);
1559 r
= ordered_hashmap_ensure_put(&c
->users
, &item_hash_ops
, j
->name
, j
);
1563 return log_error_errno(r
, "Failed to add implicit user '%s': %m", j
->name
);
1565 log_debug("Adding implicit user '%s' due to m line", j
->name
);
1569 if (!(ordered_hashmap_get(c
->users
, g
) ||
1570 ordered_hashmap_get(c
->groups
, g
))) {
1571 _cleanup_(item_freep
) Item
*j
=
1572 item_new(ADD_GROUP
, g
, /* filename= */ NULL
, /* line= */ 0);
1576 r
= ordered_hashmap_ensure_put(&c
->groups
, &item_hash_ops
, j
->name
, j
);
1580 return log_error_errno(r
, "Failed to add implicit group '%s': %m", j
->name
);
1582 log_debug("Adding implicit group '%s' due to m line", j
->name
);
1590 static int item_equivalent(Item
*a
, Item
*b
) {
1596 if (a
->type
!= b
->type
) {
1597 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1598 "Item not equivalent because types differ");
1602 if (!streq_ptr(a
->name
, b
->name
)) {
1603 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1604 "Item not equivalent because names differ ('%s' vs. '%s')",
1609 /* Paths were simplified previously, so we can use streq. */
1610 if (!streq_ptr(a
->uid_path
, b
->uid_path
)) {
1611 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1612 "Item not equivalent because UID paths differ (%s vs. %s)",
1613 a
->uid_path
?: "(unset)", b
->uid_path
?: "(unset)");
1617 if (!streq_ptr(a
->gid_path
, b
->gid_path
)) {
1618 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1619 "Item not equivalent because GID paths differ (%s vs. %s)",
1620 a
->gid_path
?: "(unset)", b
->gid_path
?: "(unset)");
1624 if (!streq_ptr(a
->description
, b
->description
)) {
1625 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1626 "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1627 strempty(a
->description
), strempty(b
->description
));
1631 if ((a
->uid_set
!= b
->uid_set
) ||
1632 (a
->uid_set
&& a
->uid
!= b
->uid
)) {
1633 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1634 "Item not equivalent because UIDs differ (%s vs. %s)",
1635 FORMAT_UID(a
->uid_set
, a
->uid
), FORMAT_UID(b
->uid_set
, b
->uid
));
1639 if ((a
->gid_set
!= b
->gid_set
) ||
1640 (a
->gid_set
&& a
->gid
!= b
->gid
)) {
1641 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1642 "Item not equivalent because GIDs differ (%s vs. %s)",
1643 FORMAT_GID(a
->gid_set
, a
->gid
), FORMAT_GID(b
->gid_set
, b
->gid
));
1647 if (!streq_ptr(a
->home
, b
->home
)) {
1648 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1649 "Item not equivalent because home directories differ ('%s' vs. '%s')",
1650 strempty(a
->description
), strempty(b
->description
));
1654 /* Check if the two paths refer to the same file.
1655 * If the paths are equal (after normalization), it's obviously the same file.
1656 * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1657 * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1658 * /usr/sbin/nologin).
1659 * If we can't resolve something, treat different paths as different. */
1661 const char *a_shell
= pick_shell(a
),
1662 *b_shell
= pick_shell(b
);
1663 if (!path_equal_ptr(a_shell
, b_shell
) &&
1664 !(is_nologin_shell(a_shell
) && is_nologin_shell(b_shell
))) {
1665 _cleanup_free_
char *pa
= NULL
, *pb
= NULL
;
1667 r
= chase(a_shell
, arg_root
, CHASE_PREFIX_ROOT
| CHASE_NONEXISTENT
, &pa
, NULL
);
1669 log_full_errno(ERRNO_IS_RESOURCE(r
) ? LOG_ERR
: LOG_DEBUG
,
1670 r
, "Failed to look up path '%s%s%s': %m",
1671 strempty(arg_root
), arg_root
? "/" : "", a_shell
);
1672 return ERRNO_IS_RESOURCE(r
) ? r
: false;
1675 r
= chase(b_shell
, arg_root
, CHASE_PREFIX_ROOT
| CHASE_NONEXISTENT
, &pb
, NULL
);
1677 log_full_errno(ERRNO_IS_RESOURCE(r
) ? LOG_ERR
: LOG_DEBUG
,
1678 r
, "Failed to look up path '%s%s%s': %m",
1679 strempty(arg_root
), arg_root
? "/" : "", b_shell
);
1680 return ERRNO_IS_RESOURCE(r
) ? r
: false;
1683 if (!path_equal(pa
, pb
)) {
1684 log_syntax(NULL
, LOG_DEBUG
, a
->filename
, a
->line
, 0,
1685 "Item not equivalent because shells differ ('%s' vs. '%s')",
1694 static int parse_line(
1698 const char *buffer
) {
1700 _cleanup_free_
char *action
= NULL
,
1701 *name
= NULL
, *resolved_name
= NULL
,
1702 *id
= NULL
, *resolved_id
= NULL
,
1703 *description
= NULL
, *resolved_description
= NULL
,
1704 *home
= NULL
, *resolved_home
= NULL
,
1705 *shell
= NULL
, *resolved_shell
= NULL
;
1706 _cleanup_(item_freep
) Item
*i
= NULL
;
1719 r
= extract_many_words(&p
, NULL
, EXTRACT_UNQUOTE
,
1720 &action
, &name
, &id
, &description
, &home
, &shell
, NULL
);
1722 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Syntax error.");
1724 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1725 "Missing action and name columns.");
1727 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1728 "Trailing garbage.");
1731 if (strlen(action
) != 1)
1732 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1733 "Unknown modifier '%s'.", action
);
1735 if (!IN_SET(action
[0], ADD_USER
, ADD_GROUP
, ADD_MEMBER
, ADD_RANGE
))
1736 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
1737 "Unknown command type '%c'.", action
[0]);
1740 if (empty_or_dash(name
))
1744 r
= specifier_printf(name
, NAME_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_name
);
1746 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to replace specifiers in '%s': %m", name
);
1748 if (!valid_user_group_name(resolved_name
, 0))
1749 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1750 "'%s' is not a valid user or group name.", resolved_name
);
1754 if (empty_or_dash(id
))
1758 r
= specifier_printf(id
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_id
);
1760 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1761 "Failed to replace specifiers in '%s': %m", name
);
1764 /* Verify description */
1765 if (empty_or_dash(description
))
1766 description
= mfree(description
);
1769 r
= specifier_printf(description
, LONG_LINE_MAX
, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_description
);
1771 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1772 "Failed to replace specifiers in '%s': %m", description
);
1774 if (!valid_gecos(resolved_description
))
1775 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1776 "'%s' is not a valid GECOS field.", resolved_description
);
1780 if (empty_or_dash(home
))
1784 r
= specifier_printf(home
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_home
);
1786 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1787 "Failed to replace specifiers in '%s': %m", home
);
1789 path_simplify(resolved_home
);
1791 if (!valid_home(resolved_home
))
1792 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1793 "'%s' is not a valid home directory field.", resolved_home
);
1797 if (empty_or_dash(shell
))
1798 shell
= mfree(shell
);
1801 r
= specifier_printf(shell
, PATH_MAX
-1, system_and_tmp_specifier_table
, arg_root
, NULL
, &resolved_shell
);
1803 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1804 "Failed to replace specifiers in '%s': %m", shell
);
1806 path_simplify(resolved_shell
);
1808 if (!valid_shell(resolved_shell
))
1809 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1810 "'%s' is not a valid login shell field.", resolved_shell
);
1813 switch (action
[0]) {
1817 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1818 "Lines of type 'r' don't take a name field.");
1821 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1822 "Lines of type 'r' require an ID range in the third field.");
1824 if (description
|| home
|| shell
)
1825 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1826 "Lines of type '%c' don't take a %s field.",
1828 description
? "GECOS" : home
? "home directory" : "login shell");
1830 r
= uid_range_add_str(&c
->uid_range
, resolved_id
);
1832 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1833 "Invalid UID range %s.", resolved_id
);
1838 /* Try to extend an existing member or group item */
1840 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1841 "Lines of type 'm' require a user name in the second field.");
1844 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1845 "Lines of type 'm' require a group name in the third field.");
1847 if (!valid_user_group_name(resolved_id
, 0))
1848 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1849 "'%s' is not a valid user or group name.", resolved_id
);
1851 if (description
|| home
|| shell
)
1852 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1853 "Lines of type '%c' don't take a %s field.",
1855 description
? "GECOS" : home
? "home directory" : "login shell");
1857 r
= string_strv_ordered_hashmap_put(&c
->members
, resolved_id
, resolved_name
);
1859 return log_error_errno(r
, "Failed to store mapping for %s: %m", resolved_id
);
1866 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1867 "Lines of type 'u' require a user name in the second field.");
1869 r
= ordered_hashmap_ensure_allocated(&c
->users
, &item_hash_ops
);
1873 i
= item_new(ADD_USER
, resolved_name
, fname
, line
);
1878 if (path_is_absolute(resolved_id
))
1879 i
->uid_path
= path_simplify(TAKE_PTR(resolved_id
));
1881 _cleanup_free_
char *uid
= NULL
, *gid
= NULL
;
1882 if (split_pair(resolved_id
, ":", &uid
, &gid
) == 0) {
1883 r
= parse_gid(gid
, &i
->gid
);
1885 if (valid_user_group_name(gid
, 0))
1886 i
->group_name
= TAKE_PTR(gid
);
1888 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1889 "Failed to parse GID: '%s': %m", id
);
1892 i
->id_set_strict
= true;
1894 free_and_replace(resolved_id
, uid
);
1896 if (!streq(resolved_id
, "-")) {
1897 r
= parse_uid(resolved_id
, &i
->uid
);
1899 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1900 "Failed to parse UID: '%s': %m", id
);
1906 i
->description
= TAKE_PTR(resolved_description
);
1907 i
->home
= TAKE_PTR(resolved_home
);
1908 i
->shell
= TAKE_PTR(resolved_shell
);
1915 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1916 "Lines of type 'g' require a user name in the second field.");
1918 if (description
|| home
|| shell
)
1919 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
1920 "Lines of type '%c' don't take a %s field.",
1922 description
? "GECOS" : home
? "home directory" : "login shell");
1924 r
= ordered_hashmap_ensure_allocated(&c
->groups
, &item_hash_ops
);
1928 i
= item_new(ADD_GROUP
, resolved_name
, fname
, line
);
1933 if (path_is_absolute(resolved_id
))
1934 i
->gid_path
= path_simplify(TAKE_PTR(resolved_id
));
1936 r
= parse_gid(resolved_id
, &i
->gid
);
1938 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
1939 "Failed to parse GID: '%s': %m", id
);
1949 assert_not_reached();
1952 existing
= ordered_hashmap_get(h
, i
->name
);
1954 /* Two functionally-equivalent items are fine */
1955 r
= item_equivalent(i
, existing
);
1959 if (existing
->filename
)
1960 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0,
1961 "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
1962 item_type_to_string(i
->type
),
1964 existing
->filename
, existing
->line
);
1966 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0,
1967 "Conflict with earlier configuration for %s '%s', ignoring line.",
1968 item_type_to_string(i
->type
),
1975 r
= ordered_hashmap_put(h
, i
->name
, i
);
1983 static int read_config_file(Context
*c
, const char *fn
, bool ignore_enoent
) {
1984 _cleanup_fclose_
FILE *rf
= NULL
;
1985 _cleanup_free_
char *pp
= NULL
;
1996 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf
, &pp
);
1998 if (ignore_enoent
&& r
== -ENOENT
)
2001 return log_error_errno(r
, "Failed to open '%s', ignoring: %m", fn
);
2009 _cleanup_free_
char *line
= NULL
;
2012 k
= read_stripped_line(f
, LONG_LINE_MAX
, &line
);
2014 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
2020 if (IN_SET(line
[0], 0, '#'))
2023 k
= parse_line(c
, fn
, v
, line
);
2024 if (k
< 0 && r
== 0)
2029 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
2037 static int cat_config(void) {
2038 _cleanup_strv_free_
char **files
= NULL
;
2041 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, NULL
);
2045 pager_open(arg_pager_flags
);
2047 return cat_files(NULL
, files
, arg_cat_flags
);
2050 static int help(void) {
2051 _cleanup_free_
char *link
= NULL
;
2054 r
= terminal_urlify_man("systemd-sysusers.service", "8", &link
);
2058 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
2059 "Creates system user accounts.\n\n"
2060 " -h --help Show this help\n"
2061 " --version Show package version\n"
2062 " --cat-config Show configuration files\n"
2063 " --tldr Show non-comment parts of configuration\n"
2064 " --root=PATH Operate on an alternate filesystem root\n"
2065 " --image=PATH Operate on disk image as filesystem root\n"
2066 " --image-policy=POLICY Specify disk image dissection policy\n"
2067 " --replace=PATH Treat arguments as replacement for PATH\n"
2068 " --dry-run Just print what would be done\n"
2069 " --inline Treat arguments as configuration lines\n"
2070 " --no-pager Do not pipe output into a pager\n"
2071 "\nSee the %s for details.\n",
2072 program_invocation_short_name
,
2078 static int parse_argv(int argc
, char *argv
[]) {
2081 ARG_VERSION
= 0x100,
2093 static const struct option options
[] = {
2094 { "help", no_argument
, NULL
, 'h' },
2095 { "version", no_argument
, NULL
, ARG_VERSION
},
2096 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
2097 { "tldr", no_argument
, NULL
, ARG_TLDR
},
2098 { "root", required_argument
, NULL
, ARG_ROOT
},
2099 { "image", required_argument
, NULL
, ARG_IMAGE
},
2100 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
2101 { "replace", required_argument
, NULL
, ARG_REPLACE
},
2102 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
2103 { "inline", no_argument
, NULL
, ARG_INLINE
},
2104 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
2113 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2123 case ARG_CAT_CONFIG
:
2124 arg_cat_flags
= CAT_CONFIG_ON
;
2128 arg_cat_flags
= CAT_TLDR
;
2132 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
2139 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2140 "This systemd-sysusers version is compiled without support for --image=.");
2142 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
2148 case ARG_IMAGE_POLICY
:
2149 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
2155 if (!path_is_absolute(optarg
) ||
2156 !endswith(optarg
, ".conf"))
2157 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2158 "The argument to --replace= must an absolute path to a config file");
2160 arg_replace
= optarg
;
2172 arg_pager_flags
|= PAGER_DISABLE
;
2179 assert_not_reached();
2182 if (arg_replace
&& arg_cat_flags
!= CAT_CONFIG_OFF
)
2183 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2184 "Option --replace= is not supported with --cat-config/--tldr.");
2186 if (arg_replace
&& optind
>= argc
)
2187 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2188 "When --replace= is given, some configuration items must be specified.");
2190 if (arg_image
&& arg_root
)
2191 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2192 "Use either --root= or --image=, the combination of both is not supported.");
2197 static int parse_arguments(Context
*c
, char **args
) {
2203 STRV_FOREACH(arg
, args
) {
2205 /* Use (argument):n, where n==1 for the first positional arg */
2206 r
= parse_line(c
, "(argument)", pos
, *arg
);
2208 r
= read_config_file(c
, *arg
, /* ignore_enoent= */ false);
2218 static int read_config_files(Context
*c
, char **args
) {
2219 _cleanup_strv_free_
char **files
= NULL
;
2220 _cleanup_free_
char *p
= NULL
;
2225 r
= conf_files_list_with_replacement(arg_root
, CONF_PATHS_STRV("sysusers.d"), arg_replace
, &files
, &p
);
2229 STRV_FOREACH(f
, files
)
2230 if (p
&& path_equal(*f
, p
)) {
2231 log_debug("Parsing arguments at position \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
2233 r
= parse_arguments(c
, args
);
2237 log_debug("Reading config file \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
2239 /* Just warn, ignore result otherwise */
2240 (void) read_config_file(c
, *f
, /* ignore_enoent= */ true);
2246 static int read_credential_lines(Context
*c
) {
2247 _cleanup_free_
char *j
= NULL
;
2253 r
= get_credentials_dir(&d
);
2257 return log_error_errno(r
, "Failed to get credentials directory: %m");
2259 j
= path_join(d
, "sysusers.extra");
2263 (void) read_config_file(c
, j
, /* ignore_enoent= */ true);
2267 static int run(int argc
, char *argv
[]) {
2269 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
2270 _cleanup_(umount_and_freep
) char *mounted_dir
= NULL
;
2272 _cleanup_close_
int lock
= -EBADF
;
2273 _cleanup_(context_done
) Context c
= {
2274 .search_uid
= UID_INVALID
,
2280 r
= parse_argv(argc
, argv
);
2286 if (arg_cat_flags
!= CAT_CONFIG_OFF
)
2287 return cat_config();
2299 r
= mount_image_privately_interactively(
2302 DISSECT_IMAGE_GENERIC_ROOT
|
2303 DISSECT_IMAGE_REQUIRE_ROOT
|
2304 DISSECT_IMAGE_VALIDATE_OS
|
2305 DISSECT_IMAGE_RELAX_VAR_CHECK
|
2306 DISSECT_IMAGE_FSCK
|
2307 DISSECT_IMAGE_GROWFS
,
2309 /* ret_dir_fd= */ NULL
,
2314 arg_root
= strdup(mounted_dir
);
2322 /* If command line arguments are specified along with --replace, read all configuration files and
2323 * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2324 * specified, execute just them, and finally, without --replace= or any positional arguments, just
2325 * read configuration and execute it. */
2326 if (arg_replace
|| optind
>= argc
)
2327 r
= read_config_files(&c
, argv
+ optind
);
2329 r
= parse_arguments(&c
, argv
+ optind
);
2333 r
= read_credential_lines(&c
);
2337 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our
2338 * detection whether the names or UID/GID area already used otherwise doesn't get confused. After
2339 * all, even though nss-systemd synthesizes these users/groups, they should still appear in
2340 * /etc/passwd and /etc/group, as the synthesizing logic is merely supposed to be fallback for cases
2341 * where we run with a completely unpopulated /etc. */
2342 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
2343 return log_error_errno(errno
, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
2346 /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2347 r
= read_login_defs(&c
.login_defs
, NULL
, arg_root
);
2349 return log_error_errno(r
, "Failed to read %s%s: %m",
2350 strempty(arg_root
), "/etc/login.defs");
2352 c
.login_defs_need_warning
= true;
2354 /* We pick a range that very conservative: we look at compiled-in maximum and the value in
2355 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
2356 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2357 * it's only used during allocation, so we use the configured value directly). */
2358 uid_t begin
= c
.login_defs
.system_alloc_uid_min
,
2359 end
= MIN3((uid_t
) SYSTEM_UID_MAX
, c
.login_defs
.system_uid_max
, c
.login_defs
.system_gid_max
);
2361 r
= uid_range_add(&c
.uid_range
, begin
, end
- begin
+ 1);
2367 r
= add_implicit(&c
);
2372 lock
= take_etc_passwd_lock(arg_root
);
2374 return log_error_errno(lock
, "Failed to take /etc/passwd lock: %m");
2377 r
= load_user_database(&c
);
2379 return log_error_errno(r
, "Failed to load user database: %m");
2381 r
= load_group_database(&c
);
2383 return log_error_errno(r
, "Failed to read group database: %m");
2385 ORDERED_HASHMAP_FOREACH(i
, c
.groups
)
2386 (void) process_item(&c
, i
);
2388 ORDERED_HASHMAP_FOREACH(i
, c
.users
)
2389 (void) process_item(&c
, i
);
2391 return write_files(&c
);
2394 DEFINE_MAIN_FUNCTION(run
);