HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/sysusers/sysusers.c

92,777 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 3771185f538a8e5a5122153e1bfaf83112f378fe

Lines 1–1000 of 2,416

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <stdlib.h>
#include <sys/stat.h>
 
#include "sd-json.h"
 
#include "alloc-util.h"
#include "build.h"
#include "chase.h"
#include "conf-files.h"
#include "constants.h"
#include "copy.h"
#include "creds-util.h"
#include "dissect-image.h"
#include "dlopen-note.h"
#include "errno-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "hashmap.h"
#include "image-policy.h"
#include "install-file.h"
#include "label-util.h"
#include "libaudit-util.h"
#include "libcrypt-util.h"
#include "log.h"
#include "loop-util.h"
#include "main-func.h"
#include "mount-util.h"
#include "pager.h"
#include "parse-argument.h"
#include "path-util.h"
#include "pretty-print.h"
#include "set.h"
#include "smack-util.h"
#include "specifier.h"
#include "string-util.h"
#include "strv.h"
#include "sync-util.h"
#include "time-util.h"
#include "tmpfile-util.h"
#include "uid-classification.h"
#include "uid-range.h"
#include "user-util.h"
#include "verbs.h"
 
typedef enum ItemType {
        ADD_USER =   'u',
        ADD_GROUP =  'g',
        ADD_MEMBER = 'm',
        ADD_RANGE =  'r',
} ItemType;
 
static const char* item_type_to_string(ItemType t) {
        switch (t) {
        case ADD_USER:
                return "user";
        case ADD_GROUP:
                return "group";
        case ADD_MEMBER:
                return "member";
        case ADD_RANGE:
                return "range";
        default:
                assert_not_reached();
        }
}
 
typedef struct Item {
        ItemType type;
 
        char *name;
        char *group_name;
        char *uid_path;
        char *gid_path;
        char *description;
        char *home;
        char *shell;
 
        gid_t gid;
        uid_t uid;
 
        char *filename;
        unsigned line;
 
        bool gid_set;
 
        /* When set the group with the specified GID must exist
         * and the check if a UID clashes with the GID is skipped.
         */
        bool id_set_strict;
 
        bool uid_set;
 
        bool locked;
 
        bool todo_user;
        bool todo_group;
} Item;
 
static char *arg_root = NULL;
static char *arg_image = NULL;
static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
static const char *arg_replace = NULL;
static bool arg_dry_run = false;
static bool arg_inline = false;
static PagerFlags arg_pager_flags = 0;
static ImagePolicy *arg_image_policy = NULL;
 
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
 
COMMAND(
        "systemd-sysusers\0",
        "Create system user and group accounts.",
        .argspec = "[CONFIGURATION FILE…]\0",
        .man_pages = "systemd-sysusers.service(8)\0",
        .pager_flags = &arg_pager_flags,
);
 
typedef struct Context {
        int audit_fd;
 
        OrderedHashmap *users, *groups;
        OrderedHashmap *todo_uids, *todo_gids;
        OrderedHashmap *members;
 
        Hashmap *database_by_uid, *database_by_username;
        Hashmap *database_by_gid, *database_by_groupname;
 
        /* A helper set to hold names that are used by database_by_{uid,gid,username,groupname} above. */
        Set *names;
 
        uid_t search_uid;
        UIDRange *uid_range;
 
        UGIDAllocationRange login_defs;
        bool login_defs_need_warning;
 
        LabelContext *label_context;
} Context;
 
static void context_done(Context *c) {
        assert(c);
 
        c->audit_fd = close_audit_fd(c->audit_fd);
 
        ordered_hashmap_free(c->groups);
        ordered_hashmap_free(c->users);
        ordered_hashmap_free(c->members);
        ordered_hashmap_free(c->todo_uids);
        ordered_hashmap_free(c->todo_gids);
 
        hashmap_free(c->database_by_uid);
        hashmap_free(c->database_by_username);
        hashmap_free(c->database_by_gid);
        hashmap_free(c->database_by_groupname);
 
        set_free(c->names);
        uid_range_free(c->uid_range);
        mac_label_context_free(c->label_context);
}
 
static void maybe_emit_login_defs_warning(Context *c) {
        assert(c);
 
        if (!c->login_defs_need_warning)
                return;
 
        if (c->login_defs.system_alloc_uid_min != SYSTEM_ALLOC_UID_MIN ||
            c->login_defs.system_uid_max != SYSTEM_UID_MAX)
                log_warning("login.defs specifies UID allocation range "UID_FMT"–"UID_FMT
                            " that is different than the built-in defaults ("UID_FMT"–"UID_FMT")",
                            c->login_defs.system_alloc_uid_min, c->login_defs.system_uid_max,
                            (uid_t) SYSTEM_ALLOC_UID_MIN, (uid_t) SYSTEM_UID_MAX);
        if (c->login_defs.system_alloc_gid_min != SYSTEM_ALLOC_GID_MIN ||
            c->login_defs.system_gid_max != SYSTEM_GID_MAX)
                log_warning("login.defs specifies GID allocation range "GID_FMT"–"GID_FMT
                            " that is different than the built-in defaults ("GID_FMT"–"GID_FMT")",
                            c->login_defs.system_alloc_gid_min, c->login_defs.system_gid_max,
                            (gid_t) SYSTEM_ALLOC_GID_MIN, (gid_t) SYSTEM_GID_MAX);
 
        c->login_defs_need_warning = false;
}
 
static void log_audit_accounts(Context *c, ItemType what) {
#if HAVE_AUDIT
        assert(c);
        assert(IN_SET(what, ADD_USER, ADD_GROUP));
 
        if (arg_dry_run || c->audit_fd < 0)
                return;
 
        Item *i;
        int type = what == ADD_USER ? AUDIT_ADD_USER : AUDIT_ADD_GROUP;
        const char *op = what == ADD_USER ? "adding-user" : "adding-group";
 
        /* Notes:
         *
         * The op must not contain whitespace. The format with a dash matches what Fedora shadow-utils uses.
         *
         * We send id == -1, even though we know the number, in particular on success. This is because if we
         * send the id, the generated audit message will not contain the name. The name seems more useful
         * than the number, hence send just the name:
         *
         * type=ADD_USER msg=audit(01/10/2025 16:02:00.639:3854) :
         *   pid=3846380 uid=root auid=zbyszek ses=2 msg='op=adding-user id=unknown(952) exe=systemd-sysusers ... res=success'
         * vs.
         * type=ADD_USER msg=audit(01/10/2025 16:03:15.457:3908) :
         *   pid=3846607 uid=root auid=zbyszek ses=2 msg='op=adding-user acct=foo5 exe=systemd-sysusers ... res=success'
         */
 
        ORDERED_HASHMAP_FOREACH(i, what == ADD_USER ? c->todo_uids : c->todo_gids)
                sym_audit_log_acct_message(
                                c->audit_fd,
                                type,
                                program_invocation_short_name,
                                op,
                                i->name,
                                /* id= */ (unsigned) -1,
                                /* host= */ NULL,
                                /* addr= */ NULL,
                                /* tty= */ NULL,
                                /* success= */ 1);
#endif
}
 
static int load_user_database(Context *c) {
        _cleanup_free_ char *passwd_path = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        struct passwd *pw;
        int r;
 
        assert(c);
 
        r = chase_and_fopen_unlocked("/etc/passwd", arg_root, CHASE_PREFIX_ROOT, "re", &passwd_path, &f);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return r;
 
        while ((r = fgetpwent_sane(f, &pw)) > 0) {
 
                char *n = strdup(pw->pw_name);
                if (!n)
                        return -ENOMEM;
 
                /* Note that we use trivial_hash_ops_free here, so identical strings can exist in the set. */
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, n);
                if (r < 0)
                        return r;
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
 
                r = hashmap_ensure_put(&c->database_by_username, &string_hash_ops, n, UID_TO_PTR(pw->pw_uid));
                if (r == -EEXIST)
                        log_debug_errno(r, "%s: user '%s' is listed twice, ignoring duplicate uid.",
                                        passwd_path, n);
                else if (r < 0)
                        return r;
 
                r = hashmap_ensure_put(&c->database_by_uid, /* hash_ops= */ NULL, UID_TO_PTR(pw->pw_uid), n);
                if (r == -EEXIST)
                        log_debug_errno(r, "%s: uid "UID_FMT" is listed twice, ignoring duplicate name.",
                                        passwd_path, pw->pw_uid);
                else if (r < 0)
                        return r;
        }
        return r;
}
 
static int load_group_database(Context *c) {
        _cleanup_free_ char *group_path = NULL;
        _cleanup_fclose_ FILE *f = NULL;
        struct group *gr;
        int r;
 
        assert(c);
 
        r = chase_and_fopen_unlocked("/etc/group", arg_root, CHASE_PREFIX_ROOT, "re", &group_path, &f);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return r;
 
        while ((r = fgetgrent_sane(f, &gr)) > 0) {
                char *n = strdup(gr->gr_name);
                if (!n)
                        return -ENOMEM;
 
                /* Note that we use trivial_hash_ops_free here, so identical strings can exist in the set. */
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, n);
                if (r < 0)
                        return r;
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
 
                r = hashmap_ensure_put(&c->database_by_groupname, &string_hash_ops, n, GID_TO_PTR(gr->gr_gid));
                if (r == -EEXIST)
                        log_debug_errno(r, "%s: group '%s' is listed twice, ignoring duplicate gid.",
                                        group_path, n);
                else if (r < 0)
                        return r;
 
                r = hashmap_ensure_put(&c->database_by_gid, /* hash_ops= */ NULL, GID_TO_PTR(gr->gr_gid), n);
                if (r == -EEXIST)
                        log_debug_errno(r, "%s: gid "GID_FMT" is listed twice, ignoring duplicate name.",
                                        group_path, gr->gr_gid);
                else if (r < 0)
                        return r;
        }
        return r;
}
 
static int make_backup(const char *target, const char *x, LabelContext *label_context) {
        _cleanup_(unlink_and_freep) char *dst_tmp = NULL;
        _cleanup_fclose_ FILE *dst = NULL;
        _cleanup_close_ int src = -EBADF;
        const char *backup;
        struct stat st;
        int r;
 
        assert(target);
        assert(x);
 
        src = open(x, O_RDONLY|O_CLOEXEC|O_NOCTTY);
        if (src < 0) {
                if (errno == ENOENT) /* No backup necessary... */
                        return 0;
 
                return -errno;
        }
 
        if (fstat(src, &st) < 0)
                return -errno;
 
        r = fopen_temporary_at_label(
                        AT_FDCWD,
                        target,   /* The path for which to the look up the label */
                        x,        /* Where we want the file actually to end up */
                        &dst,     /* The temporary file we write to */
                        &dst_tmp,
                        label_context);
        if (r < 0)
                return r;
 
        r = copy_bytes(src, fileno(dst), UINT64_MAX, /* copy_flags= */ 0);
        if (r < 0)
                return r;
 
        backup = strjoina(x, "-");
 
        /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
         * unreadable by others, then it isn't too bad... */
        r = fchmod_and_chown_with_fallback(fileno(dst), dst_tmp, st.st_mode & 07777, st.st_uid, st.st_gid);
        if (r < 0)
                log_warning_errno(r, "Failed to change access mode or ownership of %s: %m", backup);
 
        if (futimens(fileno(dst), (const struct timespec[2]) { st.st_atim, st.st_mtim }) < 0)
                log_warning_errno(errno, "Failed to fix access and modification time of %s: %m", backup);
 
        r = fsync_full(fileno(dst));
        if (r < 0)
                return r;
 
        if (rename(dst_tmp, backup) < 0)
                return -errno;
 
        dst_tmp = mfree(dst_tmp); /* disable the unlink_and_freep() hook now that the file has been renamed */
        return 0;
}
 
static int putgrent_with_members(
                Context *c,
                const struct group *gr,
                FILE *group) {
 
        char **a;
        int r;
 
        assert(c);
        assert(gr);
        assert(group);
 
        a = ordered_hashmap_get(c->members, gr->gr_name);
        if (a) {
                _cleanup_strv_free_ char **l = NULL;
                bool added = false;
 
                l = strv_copy(gr->gr_mem);
                if (!l)
                        return -ENOMEM;
 
                STRV_FOREACH(i, a) {
                        if (strv_contains(l, *i))
                                continue;
 
                        r = strv_extend(&l, *i);
                        if (r < 0)
                                return r;
 
                        added = true;
                }
 
                if (added) {
                        struct group t;
 
                        strv_sort_uniq(l);
 
                        t = *gr;
                        t.gr_mem = l;
 
                        r = putgrent_sane(&t, group);
                        return r < 0 ? r : 1;
                }
        }
 
        return putgrent_sane(gr, group);
}
 
#if ENABLE_GSHADOW
static int putsgent_with_members(
                Context *c,
                const struct sgrp *sg,
                FILE *gshadow) {
 
        char **a;
        int r;
 
        assert(sg);
        assert(gshadow);
 
        a = ordered_hashmap_get(c->members, sg->sg_namp);
        if (a) {
                _cleanup_strv_free_ char **l = NULL;
                bool added = false;
 
                l = strv_copy(sg->sg_mem);
                if (!l)
                        return -ENOMEM;
 
                STRV_FOREACH(i, a) {
                        if (strv_contains(l, *i))
                                continue;
 
                        r = strv_extend(&l, *i);
                        if (r < 0)
                                return r;
 
                        added = true;
                }
 
                if (added) {
                        struct sgrp t;
 
                        strv_sort_uniq(l);
 
                        t = *sg;
                        t.sg_mem = l;
 
                        r = putsgent_sane(&t, gshadow);
                        return r < 0 ? r : 1;
                }
        }
 
        return putsgent_sane(sg, gshadow);
}
#endif
 
static const char* pick_shell(const Item *i) {
        assert(i);
 
        if (i->type != ADD_USER)
                return NULL;
        if (i->shell)
                return i->shell;
        if (i->uid_set && i->uid == 0)
                return default_root_shell(arg_root);
        return NOLOGIN;
}
 
static int read_shell_credential(const Item *i, char **ret) {
        _cleanup_free_ char *cn = NULL, *shell = NULL;
        int r;
 
        assert(i);
 
        cn = strjoin("passwd.shell.", i->name);
        if (!cn)
                return -ENOMEM;
 
        r = read_credential(cn, (void**) &shell, /* ret_size= */ NULL);
        if (r < 0) {
                log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
                if (ret)
                        *ret = NULL;
                return 0;
        }
 
        path_simplify(shell);
        if (!valid_shell(shell))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Shell credential '%s' specifies invalid login shell '%s'.",
                                       cn, shell);
 
        if (ret)
                *ret = TAKE_PTR(shell);
        return 0;
}
 
static int write_temporary_passwd(
                Context *c,
                const char *passwd_path,
                FILE **ret_tmpfile,
                char **ret_tmpfile_path) {
 
        _cleanup_fclose_ FILE *original = NULL, *passwd = NULL;
        _cleanup_(unlink_and_freep) char *passwd_tmp = NULL;
        struct passwd *pw = NULL;
        Item *i;
        int r;
 
        assert(c);
        assert(ret_tmpfile);
        assert(ret_tmpfile_path);
 
        if (ordered_hashmap_isempty(c->todo_uids))
                goto done;
 
        if (arg_dry_run) {
                ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
                        r = read_shell_credential(i, /* ret= */ NULL);
                        if (r < 0)
                                return r;
                }
 
                log_info("Would write /etc/passwd%s", glyph(GLYPH_ELLIPSIS));
                goto done;
        }
 
        r = fopen_temporary_at_label(AT_FDCWD, passwd_path, passwd_path, &passwd, &passwd_tmp, c->label_context);
        if (r < 0)
                return log_debug_errno(r, "Failed to open temporary copy of %s: %m", passwd_path);
 
        original = fopen(passwd_path, "re");
        if (original) {
 
                /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
                 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
                 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
                 * it easier to depend on sysusers in packaging scripts and suchlike. */
                r = copy_rights_with_fallback(fileno(original), fileno(passwd), passwd_tmp);
                if (r < 0)
                        return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
                                               passwd_path, passwd_tmp);
 
                while ((r = fgetpwent_sane(original, &pw)) > 0) {
                        i = ordered_hashmap_get(c->users, pw->pw_name);
                        if (i && i->todo_user)
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                                       "%s: User \"%s\" already exists.",
                                                       passwd_path, pw->pw_name);
 
                        if (ordered_hashmap_contains(c->todo_uids, UID_TO_PTR(pw->pw_uid)))
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                                       "%s: Detected collision for UID " UID_FMT ".",
                                                       passwd_path, pw->pw_uid);
 
                        /* Make sure we keep the NIS entries (if any) at the end. */
                        if (IN_SET(pw->pw_name[0], '+', '-'))
                                break;
 
                        r = putpwent_sane(pw, passwd);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
                                                       pw->pw_name);
                }
                if (r < 0)
                        return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
 
        } else {
                if (errno != ENOENT)
                        return log_debug_errno(errno, "Failed to open %s: %m", passwd_path);
                if (fchmod(fileno(passwd), 0644) < 0)
                        return log_debug_errno(errno, "Failed to fchmod %s: %m", passwd_tmp);
        }
 
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
                _cleanup_free_ char *creds_shell = NULL;
 
                struct passwd n = {
                        .pw_name = i->name,
                        .pw_uid = i->uid,
                        .pw_gid = i->gid,
                        .pw_gecos = (char*) strempty(i->description),
 
                        /* "x" means the password is stored in the shadow file */
                        .pw_passwd = (char*) PASSWORD_SEE_SHADOW,
 
                        /* We default to the root directory as home */
                        .pw_dir = i->home ?: (char*) "/",
 
                        /* Initialize the shell to nologin, with one exception:
                         * for root we patch in something special */
                        .pw_shell = (char*) pick_shell(i),
                };
 
                r = read_shell_credential(i, &creds_shell);
                if (r < 0)
                        return r;
                if (creds_shell)
                        n.pw_shell = creds_shell;
 
                r = putpwent_sane(&n, passwd);
                if (r < 0)
                        return log_debug_errno(r, "Failed to add new user \"%s\" to temporary passwd file: %m",
                                               i->name);
        }
 
        /* Append the remaining NIS entries if any */
        while (pw) {
                r = putpwent_sane(pw, passwd);
                if (r < 0)
                        return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
                                               pw->pw_name);
 
                r = fgetpwent_sane(original, &pw);
                if (r < 0)
                        return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
                if (r == 0)
                        break;
        }
 
        r = fflush_sync_and_check(passwd);
        if (r < 0)
                return log_debug_errno(r, "Failed to flush %s: %m", passwd_tmp);
 
done:
        *ret_tmpfile = TAKE_PTR(passwd);
        *ret_tmpfile_path = TAKE_PTR(passwd_tmp);
        return 0;
}
 
static int write_temporary_shadow(
                Context *c,
                const char *shadow_path,
                FILE **ret_tmpfile,
                char **ret_tmpfile_path) {
 
        _cleanup_fclose_ FILE *original = NULL, *shadow = NULL;
        _cleanup_(unlink_and_freep) char *shadow_tmp = NULL;
        struct spwd *sp = NULL;
        long lstchg;
        Item *i;
        int r;
 
        assert(c);
        assert(ret_tmpfile);
        assert(ret_tmpfile_path);
 
        if (ordered_hashmap_isempty(c->todo_uids))
                goto done;
 
        if (arg_dry_run) {
                log_info("Would write /etc/shadow%s", glyph(GLYPH_ELLIPSIS));
                goto done;
        }
 
        r = fopen_temporary_at_label(AT_FDCWD, shadow_path, shadow_path, &shadow, &shadow_tmp, c->label_context);
        if (r < 0)
                return log_debug_errno(r, "Failed to open temporary copy of %s: %m", shadow_path);
 
        lstchg = (long) (source_date_epoch_or_now() / USEC_PER_DAY);
 
        original = fopen(shadow_path, "re");
        if (original) {
 
                r = copy_rights_with_fallback(fileno(original), fileno(shadow), shadow_tmp);
                if (r < 0)
                        return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
                                               shadow_path, shadow_tmp);
 
                while ((r = fgetspent_sane(original, &sp)) > 0) {
                        i = ordered_hashmap_get(c->users, sp->sp_namp);
                        if (i && i->todo_user) {
                                /* we will update the existing entry */
                                sp->sp_lstchg = lstchg;
 
                                /* only the /etc/shadow stage is left, so we can
                                 * safely remove the item from the todo set */
                                i->todo_user = false;
                                ordered_hashmap_remove(c->todo_uids, UID_TO_PTR(i->uid));
                        }
 
                        /* Make sure we keep the NIS entries (if any) at the end. */
                        if (IN_SET(sp->sp_namp[0], '+', '-'))
                                break;
 
                        r = putspent_sane(sp, shadow);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
                                                       sp->sp_namp);
 
                }
                if (r < 0)
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
 
        } else {
                if (errno != ENOENT)
                        return log_debug_errno(errno, "Failed to open %s: %m", shadow_path);
                if (fchmod(fileno(shadow), 0000) < 0)
                        return log_debug_errno(errno, "Failed to fchmod %s: %m", shadow_tmp);
        }
 
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
                _cleanup_(erase_and_freep) char *creds_password = NULL;
                bool is_hashed;
 
                struct spwd n = {
                        .sp_namp = i->name,
                        .sp_lstchg = lstchg,
                        .sp_min = -1,
                        .sp_max = -1,
                        .sp_warn = -1,
                        .sp_inact = -1,
                        .sp_expire = i->locked ? 1 : -1, /* Negative expiration means "unset". Expiration 0 or 1 means "locked" */
                        .sp_flag = ULONG_MAX, /* this appears to be what everybody does ... */
                };
 
                r = get_credential_user_password(i->name, &creds_password, &is_hashed);
                if (r < 0)
                        log_debug_errno(r, "Couldn't read password credential for user '%s', ignoring: %m", i->name);
 
                if (creds_password && !is_hashed) {
                        _cleanup_(erase_and_freep) char* plaintext_password = TAKE_PTR(creds_password);
                        r = hash_password(plaintext_password, &creds_password);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to hash password: %m");
                }
 
                if (creds_password)
                        n.sp_pwdp = creds_password;
                else if (streq(i->name, "root"))
                        /* Let firstboot set the password later */
                        n.sp_pwdp = (char*) PASSWORD_UNPROVISIONED;
                else
                        n.sp_pwdp = (char*) PASSWORD_LOCKED_AND_INVALID;
 
                r = putspent_sane(&n, shadow);
                if (r < 0)
                        return log_debug_errno(r, "Failed to add new user \"%s\" to temporary shadow file: %m",
                                               i->name);
        }
 
        /* Append the remaining NIS entries if any */
        while (sp) {
                r = putspent_sane(sp, shadow);
                if (r < 0)
                        return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
                                               sp->sp_namp);
 
                r = fgetspent_sane(original, &sp);
                if (r < 0)
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
                if (r == 0)
                        break;
        }
        if (!IN_SET(errno, 0, ENOENT))
                return -errno;
 
        r = fflush_sync_and_check(shadow);
        if (r < 0)
                return log_debug_errno(r, "Failed to flush %s: %m", shadow_tmp);
 
done:
        *ret_tmpfile = TAKE_PTR(shadow);
        *ret_tmpfile_path = TAKE_PTR(shadow_tmp);
        return 0;
}
 
static int write_temporary_group(
                Context *c,
                const char *group_path,
                FILE **ret_tmpfile,
                char **ret_tmpfile_path) {
 
        _cleanup_fclose_ FILE *original = NULL, *group = NULL;
        _cleanup_(unlink_and_freep) char *group_tmp = NULL;
        bool group_changed = false;
        struct group *gr = NULL;
        Item *i;
        int r;
 
        assert(c);
        assert(ret_tmpfile);
        assert(ret_tmpfile_path);
 
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
                goto done;
 
        if (arg_dry_run) {
                log_info("Would write /etc/group%s", glyph(GLYPH_ELLIPSIS));
                goto done;
        }
 
        r = fopen_temporary_at_label(AT_FDCWD, group_path, group_path, &group, &group_tmp, c->label_context);
        if (r < 0)
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", group_path);
 
        original = fopen(group_path, "re");
        if (original) {
 
                r = copy_rights_with_fallback(fileno(original), fileno(group), group_tmp);
                if (r < 0)
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
                                               group_path, group_tmp);
 
                while ((r = fgetgrent_sane(original, &gr)) > 0) {
                        /* Safety checks against name and GID collisions. Normally,
                         * this should be unnecessary, but given that we look at the
                         * entries anyway here, let's make an extra verification
                         * step that we don't generate duplicate entries. */
 
                        i = ordered_hashmap_get(c->groups, gr->gr_name);
                        if (i && i->todo_group)
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                                       "%s: Group \"%s\" already exists.",
                                                       group_path, gr->gr_name);
 
                        if (ordered_hashmap_contains(c->todo_gids, GID_TO_PTR(gr->gr_gid)))
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
                                                       "%s: Detected collision for GID " GID_FMT ".",
                                                       group_path, gr->gr_gid);
 
                        /* Make sure we keep the NIS entries (if any) at the end. */
                        if (IN_SET(gr->gr_name[0], '+', '-'))
                                break;
 
                        r = putgrent_with_members(c, gr, group);
                        if (r < 0)
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
                                                       gr->gr_name);
                        if (r > 0)
                                group_changed = true;
                }
                if (r < 0)
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
 
        } else {
                if (errno != ENOENT)
                        return log_error_errno(errno, "Failed to open %s: %m", group_path);
                if (fchmod(fileno(group), 0644) < 0)
                        return log_error_errno(errno, "Failed to fchmod %s: %m", group_tmp);
        }
 
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
                struct group n = {
                        .gr_name = i->name,
                        .gr_gid = i->gid,
                        .gr_passwd = (char*) PASSWORD_SEE_SHADOW,
                };
 
                r = putgrent_with_members(c, &n, group);
                if (r < 0)
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary group file: %m",
                                               n.gr_name);
 
                group_changed = true;
        }
 
        /* Append the remaining NIS entries if any */
        while (gr) {
                r = putgrent_sane(gr, group);
                if (r < 0)
                        return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
                                               gr->gr_name);
 
                r = fgetgrent_sane(original, &gr);
                if (r < 0)
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
                if (r == 0)
                        break;
        }
 
        r = fflush_sync_and_check(group);
        if (r < 0)
                return log_error_errno(r, "Failed to flush %s: %m", group_tmp);
 
done:
        if (group_changed) {
                *ret_tmpfile = TAKE_PTR(group);
                *ret_tmpfile_path = TAKE_PTR(group_tmp);
        } else {
                *ret_tmpfile = NULL;
                *ret_tmpfile_path = NULL;
        }
        return 0;
}
 
static int write_temporary_gshadow(
                Context *c,
                const char * gshadow_path,
                FILE **ret_tmpfile,
                char **ret_tmpfile_path) {
 
#if ENABLE_GSHADOW
        _cleanup_fclose_ FILE *original = NULL, *gshadow = NULL;
        _cleanup_(unlink_and_freep) char *gshadow_tmp = NULL;
        bool group_changed = false;
        Item *i;
        int r;
 
        assert(c);
        assert(ret_tmpfile);
        assert(ret_tmpfile_path);
 
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
                goto done;
 
        if (arg_dry_run) {
                log_info("Would write /etc/gshadow%s", glyph(GLYPH_ELLIPSIS));
                goto done;
        }
 
        r = fopen_temporary_at_label(AT_FDCWD, gshadow_path, gshadow_path, &gshadow, &gshadow_tmp, c->label_context);
        if (r < 0)
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", gshadow_path);
 
        original = fopen(gshadow_path, "re");
        if (original) {
                struct sgrp *sg;
 
                r = copy_rights_with_fallback(fileno(original), fileno(gshadow), gshadow_tmp);
                if (r < 0)
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
                                               gshadow_path, gshadow_tmp);
 
                while ((r = fgetsgent_sane(original, &sg)) > 0) {
 
                        i = ordered_hashmap_get(c->groups, sg->sg_namp);
                        if (i && i->todo_group) {
                                /* The group already exists in /etc/gshadow. Only the
                                 * /etc/gshadow stage is left, so we can safely remove
                                 * the item from the todo set. */
                                i->todo_group = false;
                                ordered_hashmap_remove(c->todo_gids, GID_TO_PTR(i->gid));
                        }
 
                        r = putsgent_with_members(c, sg, gshadow);
                        if (r < 0)
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
                                                       sg->sg_namp);
                        if (r > 0)
                                group_changed = true;
                }
                if (r < 0)
                        return r;
 
        } else {
                if (errno != ENOENT)
                        return log_error_errno(errno, "Failed to open %s: %m", gshadow_path);
                if (fchmod(fileno(gshadow), 0000) < 0)
                        return log_error_errno(errno, "Failed to fchmod %s: %m", gshadow_tmp);
        }
 
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
                struct sgrp n = {
                        .sg_namp = i->name,
                        .sg_passwd = (char*) PASSWORD_LOCKED_AND_INVALID,
                };
 
                r = putsgent_with_members(c, &n, gshadow);
                if (r < 0)
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary gshadow file: %m",
                                               n.sg_namp);
 
                group_changed = true;
        }
 
        r = fflush_sync_and_check(gshadow);
        if (r < 0)
                return log_error_errno(r, "Failed to flush %s: %m", gshadow_tmp);
 
done:
        if (group_changed) {
                *ret_tmpfile = TAKE_PTR(gshadow);
                *ret_tmpfile_path = TAKE_PTR(gshadow_tmp);
        } else
#endif
        {
                *ret_tmpfile = NULL;
                *ret_tmpfile_path = NULL;
        }
        return 0;
}
 
static int write_files(Context *c) {
        _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;