• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 21192089104

20 Jan 2026 11:35PM UTC coverage: 72.524% (-0.3%) from 72.818%
21192089104

push

github

yuwata
mkdir: reset mtime *after* fchown()

Follow-up for 34c3d5747

Also, drop pointless shortcut.

1 of 2 new or added lines in 1 file covered. (50.0%)

2960 existing lines in 48 files now uncovered.

309808 of 427181 relevant lines covered (72.52%)

1236537.64 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.46
/src/sysusers/sysusers.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <getopt.h>
4
#include <stdlib.h>
5
#include <sys/stat.h>
6

7
#include "alloc-util.h"
8
#include "build.h"
9
#include "chase.h"
10
#include "conf-files.h"
11
#include "constants.h"
12
#include "copy.h"
13
#include "creds-util.h"
14
#include "dissect-image.h"
15
#include "errno-util.h"
16
#include "extract-word.h"
17
#include "fd-util.h"
18
#include "fileio.h"
19
#include "format-util.h"
20
#include "fs-util.h"
21
#include "hashmap.h"
22
#include "image-policy.h"
23
#include "install-file.h"
24
#include "label-util.h"
25
#include "libaudit-util.h"
26
#include "libcrypt-util.h"
27
#include "log.h"
28
#include "loop-util.h"
29
#include "main-func.h"
30
#include "mount-util.h"
31
#include "pager.h"
32
#include "parse-argument.h"
33
#include "path-util.h"
34
#include "pretty-print.h"
35
#include "set.h"
36
#include "smack-util.h"
37
#include "specifier.h"
38
#include "string-util.h"
39
#include "strv.h"
40
#include "sync-util.h"
41
#include "time-util.h"
42
#include "tmpfile-util-label.h"
43
#include "uid-classification.h"
44
#include "uid-range.h"
45
#include "user-util.h"
46
#include "verbs.h"
47

48
typedef enum ItemType {
49
        ADD_USER =   'u',
50
        ADD_GROUP =  'g',
51
        ADD_MEMBER = 'm',
52
        ADD_RANGE =  'r',
53
} ItemType;
54

55
static const char* item_type_to_string(ItemType t) {
×
56
        switch (t) {
×
57
        case ADD_USER:
58
                return "user";
59
        case ADD_GROUP:
×
60
                return "group";
×
61
        case ADD_MEMBER:
×
62
                return "member";
×
63
        case ADD_RANGE:
×
64
                return "range";
×
65
        default:
×
66
                assert_not_reached();
×
67
        }
68
}
69

70
typedef struct Item {
71
        ItemType type;
72

73
        char *name;
74
        char *group_name;
75
        char *uid_path;
76
        char *gid_path;
77
        char *description;
78
        char *home;
79
        char *shell;
80

81
        gid_t gid;
82
        uid_t uid;
83

84
        char *filename;
85
        unsigned line;
86

87
        bool gid_set;
88

89
        /* When set the group with the specified GID must exist
90
         * and the check if a UID clashes with the GID is skipped.
91
         */
92
        bool id_set_strict;
93

94
        bool uid_set;
95

96
        bool locked;
97

98
        bool todo_user;
99
        bool todo_group;
100
} Item;
101

102
static char *arg_root = NULL;
103
static char *arg_image = NULL;
104
static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
105
static const char *arg_replace = NULL;
106
static bool arg_dry_run = false;
107
static bool arg_inline = false;
108
static PagerFlags arg_pager_flags = 0;
109
static ImagePolicy *arg_image_policy = NULL;
110

111
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
113✔
112
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
113✔
113
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
113✔
114

115
typedef struct Context {
116
        int audit_fd;
117

118
        OrderedHashmap *users, *groups;
119
        OrderedHashmap *todo_uids, *todo_gids;
120
        OrderedHashmap *members;
121

122
        Hashmap *database_by_uid, *database_by_username;
123
        Hashmap *database_by_gid, *database_by_groupname;
124

125
        /* A helper set to hold names that are used by database_by_{uid,gid,username,groupname} above. */
126
        Set *names;
127

128
        uid_t search_uid;
129
        UIDRange *uid_range;
130

131
        UGIDAllocationRange login_defs;
132
        bool login_defs_need_warning;
133
} Context;
134

135
static void context_done(Context *c) {
113✔
136
        assert(c);
113✔
137

138
        c->audit_fd = close_audit_fd(c->audit_fd);
113✔
139

140
        ordered_hashmap_free(c->groups);
113✔
141
        ordered_hashmap_free(c->users);
113✔
142
        ordered_hashmap_free(c->members);
113✔
143
        ordered_hashmap_free(c->todo_uids);
113✔
144
        ordered_hashmap_free(c->todo_gids);
113✔
145

146
        hashmap_free(c->database_by_uid);
113✔
147
        hashmap_free(c->database_by_username);
113✔
148
        hashmap_free(c->database_by_gid);
113✔
149
        hashmap_free(c->database_by_groupname);
113✔
150

151
        set_free(c->names);
113✔
152
        uid_range_free(c->uid_range);
113✔
153
}
113✔
154

155
static void maybe_emit_login_defs_warning(Context *c) {
45✔
156
        assert(c);
45✔
157

158
        if (!c->login_defs_need_warning)
45✔
159
                return;
160

161
        if (c->login_defs.system_alloc_uid_min != SYSTEM_ALLOC_UID_MIN ||
44✔
162
            c->login_defs.system_uid_max != SYSTEM_UID_MAX)
44✔
163
                log_warning("login.defs specifies UID allocation range "UID_FMT"–"UID_FMT
×
164
                            " that is different than the built-in defaults ("UID_FMT"–"UID_FMT")",
165
                            c->login_defs.system_alloc_uid_min, c->login_defs.system_uid_max,
166
                            (uid_t) SYSTEM_ALLOC_UID_MIN, (uid_t) SYSTEM_UID_MAX);
167
        if (c->login_defs.system_alloc_gid_min != SYSTEM_ALLOC_GID_MIN ||
44✔
168
            c->login_defs.system_gid_max != SYSTEM_GID_MAX)
44✔
169
                log_warning("login.defs specifies GID allocation range "GID_FMT"–"GID_FMT
×
170
                            " that is different than the built-in defaults ("GID_FMT"–"GID_FMT")",
171
                            c->login_defs.system_alloc_gid_min, c->login_defs.system_gid_max,
172
                            (gid_t) SYSTEM_ALLOC_GID_MIN, (gid_t) SYSTEM_GID_MAX);
173

174
        c->login_defs_need_warning = false;
44✔
175
}
176

177
static void log_audit_accounts(Context *c, ItemType what) {
226✔
178
#if HAVE_AUDIT
179
        assert(c);
226✔
180
        assert(IN_SET(what, ADD_USER, ADD_GROUP));
226✔
181

182
        if (arg_dry_run || c->audit_fd < 0)
226✔
183
                return;
226✔
184

185
        Item *i;
×
186
        int type = what == ADD_USER ? AUDIT_ADD_USER : AUDIT_ADD_GROUP;
×
187
        const char *op = what == ADD_USER ? "adding-user" : "adding-group";
×
188

189
        /* Notes:
190
         *
191
         * The op must not contain whitespace. The format with a dash matches what Fedora shadow-utils uses.
192
         *
193
         * We send id == -1, even though we know the number, in particular on success. This is because if we
194
         * send the id, the generated audit message will not contain the name. The name seems more useful
195
         * than the number, hence send just the name:
196
         *
197
         * type=ADD_USER msg=audit(01/10/2025 16:02:00.639:3854) :
198
         *   pid=3846380 uid=root auid=zbyszek ses=2 msg='op=adding-user id=unknown(952) exe=systemd-sysusers ... res=success'
199
         * vs.
200
         * type=ADD_USER msg=audit(01/10/2025 16:03:15.457:3908) :
201
         *   pid=3846607 uid=root auid=zbyszek ses=2 msg='op=adding-user acct=foo5 exe=systemd-sysusers ... res=success'
202
         */
203

204
        ORDERED_HASHMAP_FOREACH(i, what == ADD_USER ? c->todo_uids : c->todo_gids)
×
205
                sym_audit_log_acct_message(
×
206
                                c->audit_fd,
207
                                type,
208
                                program_invocation_short_name,
209
                                op,
210
                                i->name,
×
211
                                /* id= */ (unsigned) -1,
212
                                /* host= */ NULL,
213
                                /* addr= */ NULL,
214
                                /* tty= */ NULL,
215
                                /* success= */ 1);
216
#endif
217
}
218

219
static int load_user_database(Context *c) {
113✔
220
        _cleanup_free_ char *passwd_path = NULL;
113✔
221
        _cleanup_fclose_ FILE *f = NULL;
113✔
222
        struct passwd *pw;
113✔
223
        int r;
113✔
224

225
        assert(c);
113✔
226

227
        r = chase_and_fopen_unlocked("/etc/passwd", arg_root, CHASE_PREFIX_ROOT, "re", &passwd_path, &f);
113✔
228
        if (r == -ENOENT)
113✔
229
                return 0;
230
        if (r < 0)
37✔
231
                return r;
232

233
        while ((r = fgetpwent_sane(f, &pw)) > 0) {
259✔
234

235
                char *n = strdup(pw->pw_name);
222✔
236
                if (!n)
222✔
237
                        return -ENOMEM;
238

239
                /* Note that we use trivial_hash_ops_free here, so identical strings can exist in the set. */
240
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, n);
222✔
241
                if (r < 0)
222✔
242
                        return r;
243
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
222✔
244

245
                r = hashmap_ensure_put(&c->database_by_username, &string_hash_ops, n, UID_TO_PTR(pw->pw_uid));
222✔
246
                if (r == -EEXIST)
222✔
247
                        log_debug_errno(r, "%s: user '%s' is listed twice, ignoring duplicate uid.",
×
248
                                        passwd_path, n);
249
                else if (r < 0)
222✔
250
                        return r;
251

252
                r = hashmap_ensure_put(&c->database_by_uid, /* hash_ops= */ NULL, UID_TO_PTR(pw->pw_uid), n);
222✔
253
                if (r == -EEXIST)
222✔
254
                        log_debug_errno(r, "%s: uid "UID_FMT" is listed twice, ignoring duplicate name.",
265✔
255
                                        passwd_path, pw->pw_uid);
256
                else if (r < 0)
216✔
257
                        return r;
258
        }
259
        return r;
260
}
261

262
static int load_group_database(Context *c) {
113✔
263
        _cleanup_free_ char *group_path = NULL;
113✔
264
        _cleanup_fclose_ FILE *f = NULL;
113✔
265
        struct group *gr;
113✔
266
        int r;
113✔
267

268
        assert(c);
113✔
269

270
        r = chase_and_fopen_unlocked("/etc/group", arg_root, CHASE_PREFIX_ROOT, "re", &group_path, &f);
113✔
271
        if (r == -ENOENT)
113✔
272
                return 0;
273
        if (r < 0)
37✔
274
                return r;
275

276
        while ((r = fgetgrent_sane(f, &gr)) > 0) {
467✔
277
                char *n = strdup(gr->gr_name);
430✔
278
                if (!n)
430✔
279
                        return -ENOMEM;
280

281
                /* Note that we use trivial_hash_ops_free here, so identical strings can exist in the set. */
282
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, n);
430✔
283
                if (r < 0)
430✔
284
                        return r;
285
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
430✔
286

287
                r = hashmap_ensure_put(&c->database_by_groupname, &string_hash_ops, n, GID_TO_PTR(gr->gr_gid));
430✔
288
                if (r == -EEXIST)
430✔
289
                        log_debug_errno(r, "%s: group '%s' is listed twice, ignoring duplicate gid.",
×
290
                                        group_path, n);
291
                else if (r < 0)
430✔
292
                        return r;
293

294
                r = hashmap_ensure_put(&c->database_by_gid, /* hash_ops= */ NULL, GID_TO_PTR(gr->gr_gid), n);
430✔
295
                if (r == -EEXIST)
430✔
296
                        log_debug_errno(r, "%s: gid "GID_FMT" is listed twice, ignoring duplicate name.",
479✔
297
                                        group_path, gr->gr_gid);
298
                else if (r < 0)
418✔
299
                        return r;
300
        }
301
        return r;
302
}
303

304
static int make_backup(const char *target, const char *x) {
348✔
305
        _cleanup_(unlink_and_freep) char *dst_tmp = NULL;
×
306
        _cleanup_fclose_ FILE *dst = NULL;
348✔
307
        _cleanup_close_ int src = -EBADF;
348✔
308
        const char *backup;
348✔
309
        struct stat st;
348✔
310
        int r;
348✔
311

312
        assert(target);
348✔
313
        assert(x);
348✔
314

315
        src = open(x, O_RDONLY|O_CLOEXEC|O_NOCTTY);
348✔
316
        if (src < 0) {
348✔
317
                if (errno == ENOENT) /* No backup necessary... */
312✔
318
                        return 0;
319

320
                return -errno;
×
321
        }
322

323
        if (fstat(src, &st) < 0)
36✔
324
                return -errno;
×
325

326
        r = fopen_temporary_label(
36✔
327
                        target,   /* The path for which to the look up the label */
328
                        x,        /* Where we want the file actually to end up */
329
                        &dst,     /* The temporary file we write to */
330
                        &dst_tmp);
331
        if (r < 0)
36✔
332
                return r;
333

334
        r = copy_bytes(src, fileno(dst), UINT64_MAX, COPY_REFLINK);
36✔
335
        if (r < 0)
36✔
336
                return r;
337

338
        backup = strjoina(x, "-");
180✔
339

340
        /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
341
         * unreadable by others, then it isn't too bad... */
342
        r = fchmod_and_chown_with_fallback(fileno(dst), dst_tmp, st.st_mode & 07777, st.st_uid, st.st_gid);
36✔
343
        if (r < 0)
36✔
344
                log_warning_errno(r, "Failed to change access mode or ownership of %s: %m", backup);
×
345

346
        if (futimens(fileno(dst), (const struct timespec[2]) { st.st_atim, st.st_mtim }) < 0)
36✔
347
                log_warning_errno(errno, "Failed to fix access and modification time of %s: %m", backup);
×
348

349
        r = fsync_full(fileno(dst));
36✔
350
        if (r < 0)
36✔
351
                return r;
352

353
        if (rename(dst_tmp, backup) < 0)
36✔
354
                return errno;
×
355

356
        dst_tmp = mfree(dst_tmp); /* disable the unlink_and_freep() hook now that the file has been renamed */
36✔
357
        return 0;
36✔
358
}
359

360
static int putgrent_with_members(
761✔
361
                Context *c,
362
                const struct group *gr,
363
                FILE *group) {
364

365
        char **a;
761✔
366
        int r;
761✔
367

368
        assert(c);
761✔
369
        assert(gr);
761✔
370
        assert(group);
761✔
371

372
        a = ordered_hashmap_get(c->members, gr->gr_name);
761✔
373
        if (a) {
761✔
374
                _cleanup_strv_free_ char **l = NULL;
10✔
375
                bool added = false;
10✔
376

377
                l = strv_copy(gr->gr_mem);
10✔
378
                if (!l)
10✔
379
                        return -ENOMEM;
380

381
                STRV_FOREACH(i, a) {
20✔
382
                        if (strv_contains(l, *i))
10✔
383
                                continue;
5✔
384

385
                        r = strv_extend(&l, *i);
5✔
386
                        if (r < 0)
5✔
387
                                return r;
388

389
                        added = true;
390
                }
391

392
                if (added) {
10✔
393
                        struct group t;
5✔
394

395
                        strv_sort_uniq(l);
5✔
396

397
                        t = *gr;
5✔
398
                        t.gr_mem = l;
5✔
399

400
                        r = putgrent_sane(&t, group);
5✔
401
                        return r < 0 ? r : 1;
10✔
402
                }
403
        }
404

405
        return putgrent_sane(gr, group);
756✔
406
}
407

408
#if ENABLE_GSHADOW
409
static int putsgent_with_members(
751✔
410
                Context *c,
411
                const struct sgrp *sg,
412
                FILE *gshadow) {
413

414
        char **a;
751✔
415
        int r;
751✔
416

417
        assert(sg);
751✔
418
        assert(gshadow);
751✔
419

420
        a = ordered_hashmap_get(c->members, sg->sg_namp);
751✔
421
        if (a) {
751✔
422
                _cleanup_strv_free_ char **l = NULL;
10✔
423
                bool added = false;
10✔
424

425
                l = strv_copy(sg->sg_mem);
10✔
426
                if (!l)
10✔
427
                        return -ENOMEM;
428

429
                STRV_FOREACH(i, a) {
20✔
430
                        if (strv_contains(l, *i))
10✔
431
                                continue;
5✔
432

433
                        r = strv_extend(&l, *i);
5✔
434
                        if (r < 0)
5✔
435
                                return r;
436

437
                        added = true;
438
                }
439

440
                if (added) {
10✔
441
                        struct sgrp t;
5✔
442

443
                        strv_sort_uniq(l);
5✔
444

445
                        t = *sg;
5✔
446
                        t.sg_mem = l;
5✔
447

448
                        r = putsgent_sane(&t, gshadow);
5✔
449
                        return r < 0 ? r : 1;
10✔
450
                }
451
        }
452

453
        return putsgent_sane(sg, gshadow);
746✔
454
}
455
#endif
456

457
static const char* pick_shell(const Item *i) {
270✔
458
        assert(i);
270✔
459

460
        if (i->type != ADD_USER)
270✔
461
                return NULL;
462
        if (i->shell)
268✔
463
                return i->shell;
464
        if (i->uid_set && i->uid == 0)
248✔
465
                return default_root_shell(arg_root);
10✔
466
        return NOLOGIN;
467
}
468

469
static int write_temporary_passwd(
113✔
470
                Context *c,
471
                const char *passwd_path,
472
                FILE **ret_tmpfile,
473
                char **ret_tmpfile_path) {
474

475
        _cleanup_fclose_ FILE *original = NULL, *passwd = NULL;
113✔
476
        _cleanup_(unlink_and_freep) char *passwd_tmp = NULL;
113✔
477
        struct passwd *pw = NULL;
113✔
478
        Item *i;
113✔
479
        int r;
113✔
480

481
        assert(c);
113✔
482

483
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
484
                goto done;
26✔
485

486
        if (arg_dry_run) {
87✔
487
                log_info("Would write /etc/passwd%s", glyph(GLYPH_ELLIPSIS));
×
488
                goto done;
×
489
        }
490

491
        r = fopen_temporary_label("/etc/passwd", passwd_path, &passwd, &passwd_tmp);
87✔
492
        if (r < 0)
87✔
493
                return log_debug_errno(r, "Failed to open temporary copy of %s: %m", passwd_path);
×
494

495
        original = fopen(passwd_path, "re");
87✔
496
        if (original) {
87✔
497

498
                /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
499
                 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
500
                 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
501
                 * it easier to depend on sysusers in packaging scripts and suchlike. */
502
                r = copy_rights_with_fallback(fileno(original), fileno(passwd), passwd_tmp);
14✔
503
                if (r < 0)
14✔
504
                        return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
×
505
                                               passwd_path, passwd_tmp);
506

507
                while ((r = fgetpwent_sane(original, &pw)) > 0) {
142✔
508
                        i = ordered_hashmap_get(c->users, pw->pw_name);
133✔
509
                        if (i && i->todo_user)
133✔
510
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
511
                                                       "%s: User \"%s\" already exists.",
512
                                                       passwd_path, pw->pw_name);
513

514
                        if (ordered_hashmap_contains(c->todo_uids, UID_TO_PTR(pw->pw_uid)))
133✔
515
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
516
                                                       "%s: Detected collision for UID " UID_FMT ".",
517
                                                       passwd_path, pw->pw_uid);
518

519
                        /* Make sure we keep the NIS entries (if any) at the end. */
520
                        if (IN_SET(pw->pw_name[0], '+', '-'))
133✔
521
                                break;
522

523
                        r = putpwent_sane(pw, passwd);
128✔
524
                        if (r < 0)
128✔
525
                                return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
×
526
                                                       pw->pw_name);
527
                }
528
                if (r < 0)
14✔
529
                        return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
×
530

531
        } else {
532
                if (errno != ENOENT)
73✔
533
                        return log_debug_errno(errno, "Failed to open %s: %m", passwd_path);
×
534
                if (fchmod(fileno(passwd), 0644) < 0)
73✔
535
                        return log_debug_errno(errno, "Failed to fchmod %s: %m", passwd_tmp);
×
536
        }
537

538
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
355✔
539
                _cleanup_free_ char *creds_shell = NULL, *cn = NULL;
268✔
540

541
                struct passwd n = {
1,072✔
542
                        .pw_name = i->name,
268✔
543
                        .pw_uid = i->uid,
268✔
544
                        .pw_gid = i->gid,
268✔
545
                        .pw_gecos = (char*) strempty(i->description),
268✔
546

547
                        /* "x" means the password is stored in the shadow file */
548
                        .pw_passwd = (char*) PASSWORD_SEE_SHADOW,
549

550
                        /* We default to the root directory as home */
551
                        .pw_dir = i->home ?: (char*) "/",
268✔
552

553
                        /* Initialize the shell to nologin, with one exception:
554
                         * for root we patch in something special */
555
                        .pw_shell = (char*) pick_shell(i),
268✔
556
                };
557

558
                /* Try to pick up the shell for this account via the credentials logic */
559
                cn = strjoin("passwd.shell.", i->name);
268✔
560
                if (!cn)
268✔
561
                        return -ENOMEM;
562

563
                r = read_credential(cn, (void**) &creds_shell, NULL);
268✔
564
                if (r < 0)
268✔
565
                        log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
268✔
566
                else
567
                        n.pw_shell = creds_shell;
×
568

569
                r = putpwent_sane(&n, passwd);
268✔
570
                if (r < 0)
268✔
571
                        return log_debug_errno(r, "Failed to add new user \"%s\" to temporary passwd file: %m",
×
572
                                               i->name);
573
        }
574

575
        /* Append the remaining NIS entries if any */
576
        while (pw) {
87✔
577
                r = putpwent_sane(pw, passwd);
5✔
578
                if (r < 0)
5✔
579
                        return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
×
580
                                               pw->pw_name);
581

582
                r = fgetpwent_sane(original, &pw);
5✔
583
                if (r < 0)
5✔
584
                        return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
×
585
                if (r == 0)
5✔
586
                        break;
587
        }
588

589
        r = fflush_sync_and_check(passwd);
87✔
590
        if (r < 0)
87✔
591
                return log_debug_errno(r, "Failed to flush %s: %m", passwd_tmp);
×
592

593
done:
87✔
594
        *ret_tmpfile = TAKE_PTR(passwd);
113✔
595
        *ret_tmpfile_path = TAKE_PTR(passwd_tmp);
113✔
596
        return 0;
113✔
597
}
598

599
static int write_temporary_shadow(
113✔
600
                Context *c,
601
                const char *shadow_path,
602
                FILE **ret_tmpfile,
603
                char **ret_tmpfile_path) {
604

605
        _cleanup_fclose_ FILE *original = NULL, *shadow = NULL;
113✔
606
        _cleanup_(unlink_and_freep) char *shadow_tmp = NULL;
113✔
607
        struct spwd *sp = NULL;
113✔
608
        long lstchg;
113✔
609
        Item *i;
113✔
610
        int r;
113✔
611

612
        assert(c);
113✔
613

614
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
615
                goto done;
26✔
616

617
        if (arg_dry_run) {
87✔
UNCOV
618
                log_info("Would write /etc/shadow%s", glyph(GLYPH_ELLIPSIS));
×
UNCOV
619
                goto done;
×
620
        }
621

622
        r = fopen_temporary_label("/etc/shadow", shadow_path, &shadow, &shadow_tmp);
87✔
623
        if (r < 0)
87✔
UNCOV
624
                return log_debug_errno(r, "Failed to open temporary copy of %s: %m", shadow_path);
×
625

626
        lstchg = (long) (source_date_epoch_or_now() / USEC_PER_DAY);
87✔
627

628
        original = fopen(shadow_path, "re");
87✔
629
        if (original) {
87✔
630

631
                r = copy_rights_with_fallback(fileno(original), fileno(shadow), shadow_tmp);
4✔
632
                if (r < 0)
4✔
UNCOV
633
                        return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
×
634
                                               shadow_path, shadow_tmp);
635

636
                while ((r = fgetspent_sane(original, &sp)) > 0) {
107✔
637
                        i = ordered_hashmap_get(c->users, sp->sp_namp);
103✔
638
                        if (i && i->todo_user) {
103✔
639
                                /* we will update the existing entry */
UNCOV
640
                                sp->sp_lstchg = lstchg;
×
641

642
                                /* only the /etc/shadow stage is left, so we can
643
                                 * safely remove the item from the todo set */
UNCOV
644
                                i->todo_user = false;
×
645
                                ordered_hashmap_remove(c->todo_uids, UID_TO_PTR(i->uid));
×
646
                        }
647

648
                        /* Make sure we keep the NIS entries (if any) at the end. */
649
                        if (IN_SET(sp->sp_namp[0], '+', '-'))
103✔
650
                                break;
651

652
                        r = putspent_sane(sp, shadow);
103✔
653
                        if (r < 0)
103✔
UNCOV
654
                                return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
×
655
                                                       sp->sp_namp);
656

657
                }
658
                if (r < 0)
4✔
UNCOV
659
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
×
660

661
        } else {
662
                if (errno != ENOENT)
83✔
UNCOV
663
                        return log_debug_errno(errno, "Failed to open %s: %m", shadow_path);
×
664
                if (fchmod(fileno(shadow), 0000) < 0)
83✔
UNCOV
665
                        return log_debug_errno(errno, "Failed to fchmod %s: %m", shadow_tmp);
×
666
        }
667

668
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
355✔
669
                _cleanup_(erase_and_freep) char *creds_password = NULL;
268✔
670
                bool is_hashed;
268✔
671

672
                struct spwd n = {
536✔
673
                        .sp_namp = i->name,
268✔
674
                        .sp_lstchg = lstchg,
675
                        .sp_min = -1,
676
                        .sp_max = -1,
677
                        .sp_warn = -1,
678
                        .sp_inact = -1,
679
                        .sp_expire = i->locked ? 1 : -1, /* Negative expiration means "unset". Expiration 0 or 1 means "locked" */
268✔
680
                        .sp_flag = ULONG_MAX, /* this appears to be what everybody does ... */
681
                };
682

683
                r = get_credential_user_password(i->name, &creds_password, &is_hashed);
268✔
684
                if (r < 0)
268✔
685
                        log_debug_errno(r, "Couldn't read password credential for user '%s', ignoring: %m", i->name);
268✔
686

687
                if (creds_password && !is_hashed) {
268✔
UNCOV
688
                        _cleanup_(erase_and_freep) char* plaintext_password = TAKE_PTR(creds_password);
×
UNCOV
689
                        r = hash_password(plaintext_password, &creds_password);
×
UNCOV
690
                        if (r < 0)
×
UNCOV
691
                                return log_debug_errno(r, "Failed to hash password: %m");
×
692
                }
693

694
                if (creds_password)
268✔
UNCOV
695
                        n.sp_pwdp = creds_password;
×
696
                else if (streq(i->name, "root"))
268✔
697
                        /* Let firstboot set the password later */
698
                        n.sp_pwdp = (char*) PASSWORD_UNPROVISIONED;
10✔
699
                else
700
                        n.sp_pwdp = (char*) PASSWORD_LOCKED_AND_INVALID;
258✔
701

702
                r = putspent_sane(&n, shadow);
268✔
703
                if (r < 0)
268✔
UNCOV
704
                        return log_debug_errno(r, "Failed to add new user \"%s\" to temporary shadow file: %m",
×
705
                                               i->name);
706
        }
707

708
        /* Append the remaining NIS entries if any */
709
        while (sp) {
87✔
UNCOV
710
                r = putspent_sane(sp, shadow);
×
UNCOV
711
                if (r < 0)
×
UNCOV
712
                        return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
×
713
                                               sp->sp_namp);
714

UNCOV
715
                r = fgetspent_sane(original, &sp);
×
716
                if (r < 0)
×
UNCOV
717
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
×
UNCOV
718
                if (r == 0)
×
719
                        break;
720
        }
721
        if (!IN_SET(errno, 0, ENOENT))
87✔
722
                return -errno;
×
723

724
        r = fflush_sync_and_check(shadow);
87✔
725
        if (r < 0)
87✔
UNCOV
726
                return log_debug_errno(r, "Failed to flush %s: %m", shadow_tmp);
×
727

728
done:
87✔
729
        *ret_tmpfile = TAKE_PTR(shadow);
113✔
730
        *ret_tmpfile_path = TAKE_PTR(shadow_tmp);
113✔
731
        return 0;
113✔
732
}
733

734
static int write_temporary_group(
113✔
735
                Context *c,
736
                const char *group_path,
737
                FILE **ret_tmpfile,
738
                char **ret_tmpfile_path) {
739

740
        _cleanup_fclose_ FILE *original = NULL, *group = NULL;
113✔
741
        _cleanup_(unlink_and_freep) char *group_tmp = NULL;
113✔
742
        bool group_changed = false;
113✔
743
        struct group *gr = NULL;
113✔
744
        Item *i;
113✔
745
        int r;
113✔
746

747
        assert(c);
113✔
748

749
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
750
                goto done;
26✔
751

752
        if (arg_dry_run) {
87✔
UNCOV
753
                log_info("Would write /etc/group%s", glyph(GLYPH_ELLIPSIS));
×
UNCOV
754
                goto done;
×
755
        }
756

757
        r = fopen_temporary_label("/etc/group", group_path, &group, &group_tmp);
87✔
758
        if (r < 0)
87✔
UNCOV
759
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", group_path);
×
760

761
        original = fopen(group_path, "re");
87✔
762
        if (original) {
87✔
763

764
                r = copy_rights_with_fallback(fileno(original), fileno(group), group_tmp);
14✔
765
                if (r < 0)
14✔
766
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
×
767
                                               group_path, group_tmp);
768

769
                while ((r = fgetgrent_sane(original, &gr)) > 0) {
259✔
770
                        /* Safety checks against name and GID collisions. Normally,
771
                         * this should be unnecessary, but given that we look at the
772
                         * entries anyway here, let's make an extra verification
773
                         * step that we don't generate duplicate entries. */
774

775
                        i = ordered_hashmap_get(c->groups, gr->gr_name);
250✔
776
                        if (i && i->todo_group)
250✔
UNCOV
777
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
778
                                                       "%s: Group \"%s\" already exists.",
779
                                                       group_path, gr->gr_name);
780

781
                        if (ordered_hashmap_contains(c->todo_gids, GID_TO_PTR(gr->gr_gid)))
250✔
UNCOV
782
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
783
                                                       "%s: Detected collision for GID " GID_FMT ".",
784
                                                       group_path, gr->gr_gid);
785

786
                        /* Make sure we keep the NIS entries (if any) at the end. */
787
                        if (IN_SET(gr->gr_name[0], '+', '-'))
250✔
788
                                break;
789

790
                        r = putgrent_with_members(c, gr, group);
245✔
791
                        if (r < 0)
245✔
UNCOV
792
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
×
793
                                                       gr->gr_name);
794
                        if (r > 0)
245✔
UNCOV
795
                                group_changed = true;
×
796
                }
797
                if (r < 0)
14✔
UNCOV
798
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
×
799

800
        } else {
801
                if (errno != ENOENT)
73✔
UNCOV
802
                        return log_error_errno(errno, "Failed to open %s: %m", group_path);
×
803
                if (fchmod(fileno(group), 0644) < 0)
73✔
804
                        return log_error_errno(errno, "Failed to fchmod %s: %m", group_tmp);
×
805
        }
806

807
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
603✔
808
                struct group n = {
516✔
809
                        .gr_name = i->name,
516✔
810
                        .gr_gid = i->gid,
516✔
811
                        .gr_passwd = (char*) PASSWORD_SEE_SHADOW,
812
                };
813

814
                r = putgrent_with_members(c, &n, group);
516✔
815
                if (r < 0)
516✔
816
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary group file: %m",
×
817
                                               gr->gr_name);
818

819
                group_changed = true;
516✔
820
        }
821

822
        /* Append the remaining NIS entries if any */
823
        while (gr) {
97✔
824
                r = putgrent_sane(gr, group);
15✔
825
                if (r < 0)
15✔
UNCOV
826
                        return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
×
827
                                               gr->gr_name);
828

829
                r = fgetgrent_sane(original, &gr);
15✔
830
                if (r < 0)
15✔
UNCOV
831
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
×
832
                if (r == 0)
15✔
833
                        break;
834
        }
835

836
        r = fflush_sync_and_check(group);
87✔
837
        if (r < 0)
87✔
838
                return log_error_errno(r, "Failed to flush %s: %m", group_tmp);
×
839

840
done:
87✔
841
        if (group_changed) {
113✔
842
                *ret_tmpfile = TAKE_PTR(group);
87✔
843
                *ret_tmpfile_path = TAKE_PTR(group_tmp);
87✔
844
        } else {
845
                *ret_tmpfile = NULL;
26✔
846
                *ret_tmpfile_path = NULL;
26✔
847
        }
848
        return 0;
849
}
850

851
static int write_temporary_gshadow(
113✔
852
                Context *c,
853
                const char * gshadow_path,
854
                FILE **ret_tmpfile,
855
                char **ret_tmpfile_path) {
856

857
#if ENABLE_GSHADOW
858
        _cleanup_fclose_ FILE *original = NULL, *gshadow = NULL;
113✔
859
        _cleanup_(unlink_and_freep) char *gshadow_tmp = NULL;
113✔
860
        bool group_changed = false;
113✔
861
        Item *i;
113✔
862
        int r;
113✔
863

864
        assert(c);
113✔
865

866
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
867
                goto done;
26✔
868

869
        if (arg_dry_run) {
87✔
UNCOV
870
                log_info("Would write /etc/gshadow%s", glyph(GLYPH_ELLIPSIS));
×
UNCOV
871
                goto done;
×
872
        }
873

874
        r = fopen_temporary_label("/etc/gshadow", gshadow_path, &gshadow, &gshadow_tmp);
87✔
875
        if (r < 0)
87✔
UNCOV
876
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", gshadow_path);
×
877

878
        original = fopen(gshadow_path, "re");
87✔
879
        if (original) {
87✔
880
                struct sgrp *sg;
4✔
881

882
                r = copy_rights_with_fallback(fileno(original), fileno(gshadow), gshadow_tmp);
4✔
883
                if (r < 0)
4✔
UNCOV
884
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
×
885
                                               gshadow_path, gshadow_tmp);
886

887
                while ((r = fgetsgent_sane(original, &sg)) > 0) {
239✔
888

889
                        i = ordered_hashmap_get(c->groups, sg->sg_namp);
235✔
890
                        if (i && i->todo_group)
235✔
UNCOV
891
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
892
                                                       "%s: Group \"%s\" already exists.",
893
                                                       gshadow_path, sg->sg_namp);
894

895
                        r = putsgent_with_members(c, sg, gshadow);
235✔
896
                        if (r < 0)
235✔
UNCOV
897
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
×
898
                                                       sg->sg_namp);
899
                        if (r > 0)
235✔
UNCOV
900
                                group_changed = true;
×
901
                }
902
                if (r < 0)
4✔
903
                        return r;
904

905
        } else {
906
                if (errno != ENOENT)
83✔
UNCOV
907
                        return log_error_errno(errno, "Failed to open %s: %m", gshadow_path);
×
908
                if (fchmod(fileno(gshadow), 0000) < 0)
83✔
909
                        return log_error_errno(errno, "Failed to fchmod %s: %m", gshadow_tmp);
×
910
        }
911

912
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
603✔
913
                struct sgrp n = {
516✔
914
                        .sg_namp = i->name,
516✔
915
                        .sg_passwd = (char*) PASSWORD_LOCKED_AND_INVALID,
916
                };
917

918
                r = putsgent_with_members(c, &n, gshadow);
516✔
919
                if (r < 0)
516✔
UNCOV
920
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary gshadow file: %m",
×
921
                                               n.sg_namp);
922

923
                group_changed = true;
516✔
924
        }
925

926
        r = fflush_sync_and_check(gshadow);
87✔
927
        if (r < 0)
87✔
UNCOV
928
                return log_error_errno(r, "Failed to flush %s: %m", gshadow_tmp);
×
929

930
done:
87✔
931
        if (group_changed) {
113✔
932
                *ret_tmpfile = TAKE_PTR(gshadow);
87✔
933
                *ret_tmpfile_path = TAKE_PTR(gshadow_tmp);
87✔
934
        } else
935
#endif
936
        {
937
                *ret_tmpfile = NULL;
26✔
938
                *ret_tmpfile_path = NULL;
26✔
939
        }
940
        return 0;
941
}
942

943
static int write_files(Context *c) {
113✔
944
        _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;
339✔
945
        _cleanup_(unlink_and_freep) char *passwd_tmp = NULL, *group_tmp = NULL, *shadow_tmp = NULL, *gshadow_tmp = NULL;
113✔
946
        int r;
113✔
947

948
        _cleanup_free_ char *passwd_path = path_join(arg_root, "/etc/passwd");
226✔
949
        if (!passwd_path)
113✔
UNCOV
950
                return log_oom();
×
951

952
        _cleanup_free_ char *shadow_path = path_join(arg_root, "/etc/shadow");
226✔
953
        if (!shadow_path)
113✔
UNCOV
954
                return log_oom();
×
955

956
        _cleanup_free_ char *group_path = path_join(arg_root, "/etc/group");
226✔
957
        if (!group_path)
113✔
UNCOV
958
                return log_oom();
×
959

960
        _cleanup_free_ char *gshadow_path = path_join(arg_root, "/etc/gshadow");
226✔
961
        if (!gshadow_path)
113✔
962
                return log_oom();
×
963

964
        assert(c);
113✔
965

966
        r = write_temporary_group(c, group_path, &group, &group_tmp);
113✔
967
        if (r < 0)
113✔
968
                return r;
969

970
        r = write_temporary_gshadow(c, gshadow_path, &gshadow, &gshadow_tmp);
113✔
971
        if (r < 0)
113✔
972
                return r;
973

974
        r = write_temporary_passwd(c, passwd_path, &passwd, &passwd_tmp);
113✔
975
        if (r < 0)
113✔
976
                return r;
977

978
        r = write_temporary_shadow(c, shadow_path, &shadow, &shadow_tmp);
113✔
979
        if (r < 0)
113✔
980
                return r;
981

982
        /* Make a backup of the old files */
983
        if (group) {
113✔
984
                r = make_backup("/etc/group", group_path);
87✔
985
                if (r < 0)
87✔
UNCOV
986
                        return log_error_errno(r, "Failed to backup %s: %m", group_path);
×
987
        }
988
        if (gshadow) {
113✔
989
                r = make_backup("/etc/gshadow", gshadow_path);
87✔
990
                if (r < 0)
87✔
UNCOV
991
                        return log_error_errno(r, "Failed to backup %s: %m", gshadow_path);
×
992
        }
993

994
        if (passwd) {
113✔
995
                r = make_backup("/etc/passwd", passwd_path);
87✔
996
                if (r < 0)
87✔
UNCOV
997
                        return log_error_errno(r, "Failed to backup %s: %m", passwd_path);
×
998
        }
999
        if (shadow) {
113✔
1000
                r = make_backup("/etc/shadow", shadow_path);
87✔
1001
                if (r < 0)
87✔
UNCOV
1002
                        return log_error_errno(r, "Failed to backup %s: %m", shadow_path);
×
1003
        }
1004

1005
        /* And make the new files count */
1006
        if (group) {
113✔
1007
                r = rename_and_apply_smack_floor_label(group_tmp, group_path);
87✔
1008
                if (r < 0)
87✔
1009
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1010
                                               group_tmp, group_path);
1011
                group_tmp = mfree(group_tmp);
87✔
1012
        }
1013
        /* OK, we have written the group entries successfully */
1014
        log_audit_accounts(c, ADD_GROUP);
113✔
1015
        if (gshadow) {
113✔
1016
                r = rename_and_apply_smack_floor_label(gshadow_tmp, gshadow_path);
87✔
1017
                if (r < 0)
87✔
UNCOV
1018
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1019
                                               gshadow_tmp, gshadow_path);
1020

1021
                gshadow_tmp = mfree(gshadow_tmp);
87✔
1022
        }
1023

1024
        if (passwd) {
113✔
1025
                r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
87✔
1026
                if (r < 0)
87✔
UNCOV
1027
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1028
                                               passwd_tmp, passwd_path);
1029

1030
                passwd_tmp = mfree(passwd_tmp);
87✔
1031
        }
1032
        /* OK, we have written the user entries successfully */
1033
        log_audit_accounts(c, ADD_USER);
113✔
1034
        if (shadow) {
113✔
1035
                r = rename_and_apply_smack_floor_label(shadow_tmp, shadow_path);
87✔
1036
                if (r < 0)
87✔
UNCOV
1037
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1038
                                               shadow_tmp, shadow_path);
1039

1040
                shadow_tmp = mfree(shadow_tmp);
87✔
1041
        }
1042

1043
        return 0;
1044
}
1045

1046
static int uid_is_ok(
288✔
1047
                Context *c,
1048
                uid_t uid,
1049
                const char *name,
1050
                bool check_with_gid) {
1051

1052
        int r;
288✔
1053
        assert(c);
288✔
1054

1055
        /* Let's see if we already have assigned the UID a second time */
1056
        if (ordered_hashmap_get(c->todo_uids, UID_TO_PTR(uid)))
288✔
1057
                return 0;
1058

1059
        /* Try to avoid using uids that are already used by a group
1060
         * that doesn't have the same name as our new user. */
1061
        if (check_with_gid) {
283✔
1062
                Item *i;
203✔
1063

1064
                i = ordered_hashmap_get(c->todo_gids, GID_TO_PTR(uid));
203✔
1065
                if (i && !streq(i->name, name))
203✔
1066
                        return 0;
1067
        }
1068

1069
        /* Let's check the files directly */
1070
        if (hashmap_contains(c->database_by_uid, UID_TO_PTR(uid)))
273✔
1071
                return 0;
1072

1073
        if (check_with_gid) {
273✔
1074
                const char *n;
193✔
1075

1076
                n = hashmap_get(c->database_by_gid, GID_TO_PTR(uid));
193✔
1077
                if (n && !streq(n, name))
193✔
1078
                        return 0;
1079
        }
1080

1081
        /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
1082
        if (!arg_root) {
268✔
1083
                _cleanup_free_ struct group *g = NULL;
5✔
1084

1085
                r = getpwuid_malloc(uid, /* ret= */ NULL);
5✔
1086
                if (r >= 0)
5✔
1087
                        return 0;
1088
                if (r != -ESRCH)
5✔
UNCOV
1089
                        log_warning_errno(r, "Unexpected failure while looking up UID '" UID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
×
1090

1091
                if (check_with_gid) {
5✔
1092
                        r = getgrgid_malloc((gid_t) uid, &g);
5✔
1093
                        if (r >= 0) {
5✔
UNCOV
1094
                                if (!streq(g->gr_name, name))
×
1095
                                        return 0;
1096
                        } else if (r != -ESRCH)
5✔
1097
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
5✔
1098
                }
1099
        }
1100

1101
        return 1;
1102
}
1103

UNCOV
1104
static int root_stat(const char *p, struct stat *ret_st) {
×
UNCOV
1105
        return chase_and_stat(p, arg_root, CHASE_PREFIX_ROOT, /* ret_path= */ NULL, ret_st);
×
1106
}
1107

1108
static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
70✔
1109
        struct stat st;
70✔
1110
        bool found_uid = false, found_gid = false;
70✔
1111
        uid_t uid = 0;
70✔
1112
        gid_t gid = 0;
70✔
1113

1114
        assert(i);
70✔
1115

1116
        /* First, try to get the GID directly */
1117
        if (ret_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
70✔
UNCOV
1118
                gid = st.st_gid;
×
UNCOV
1119
                found_gid = true;
×
1120
        }
1121

1122
        /* Then, try to get the UID directly */
1123
        if ((ret_uid || (ret_gid && !found_gid))
70✔
1124
            && i->uid_path
70✔
UNCOV
1125
            && root_stat(i->uid_path, &st) >= 0) {
×
1126

UNCOV
1127
                uid = st.st_uid;
×
UNCOV
1128
                found_uid = true;
×
1129

1130
                /* If we need the gid, but had no success yet, also derive it from the UID path */
1131
                if (ret_gid && !found_gid) {
×
UNCOV
1132
                        gid = st.st_gid;
×
UNCOV
1133
                        found_gid = true;
×
1134
                }
1135
        }
1136

1137
        /* If that didn't work yet, then let's reuse the GID as UID */
1138
        if (ret_uid && !found_uid && i->gid_path) {
70✔
1139

1140
                if (found_gid) {
×
1141
                        uid = (uid_t) gid;
1142
                        found_uid = true;
1143
                } else if (root_stat(i->gid_path, &st) >= 0) {
×
1144
                        uid = (uid_t) st.st_gid;
×
1145
                        found_uid = true;
×
1146
                }
1147
        }
1148

1149
        if (ret_uid) {
70✔
1150
                if (!found_uid)
40✔
1151
                        return 0;
70✔
1152

UNCOV
1153
                *ret_uid = uid;
×
1154
        }
1155

1156
        if (ret_gid) {
30✔
1157
                if (!found_gid)
30✔
1158
                        return 0;
1159

UNCOV
1160
                *ret_gid = gid;
×
1161
        }
1162

1163
        return 1;
1164
}
1165

1166
static int add_user(Context *c, Item *i) {
298✔
1167
        void *z;
298✔
1168
        int r;
298✔
1169

1170
        assert(c);
298✔
1171
        assert(i);
298✔
1172

1173
        /* Check the database directly */
1174
        z = hashmap_get(c->database_by_username, i->name);
298✔
1175
        if (z) {
298✔
1176
                log_debug("User %s already exists.", i->name);
30✔
1177
                i->uid = PTR_TO_UID(z);
30✔
1178
                i->uid_set = true;
30✔
1179
                return 0;
30✔
1180
        }
1181

1182
        if (!arg_root) {
268✔
1183
                _cleanup_free_ struct passwd *p = NULL;
5✔
1184

1185
                /* Also check NSS */
1186
                r = getpwnam_malloc(i->name, &p);
5✔
1187
                if (r >= 0) {
5✔
UNCOV
1188
                        log_debug("User %s already exists.", i->name);
×
UNCOV
1189
                        i->uid = p->pw_uid;
×
UNCOV
1190
                        i->uid_set = true;
×
1191

UNCOV
1192
                        r = free_and_strdup(&i->description, p->pw_gecos);
×
UNCOV
1193
                        if (r < 0)
×
UNCOV
1194
                                return log_oom();
×
1195

1196
                        return 0;
1197
                }
1198
                if (r != -ESRCH)
5✔
1199
                        log_warning_errno(r, "Unexpected failure while looking up user '%s' via NSS, assuming it doesn't exist: %m", i->name);
5✔
1200
        }
1201

1202
        /* Try to use the suggested numeric UID */
1203
        if (i->uid_set) {
268✔
1204
                r = uid_is_ok(c, i->uid, i->name, !i->id_set_strict);
233✔
1205
                if (r < 0)
233✔
1206
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1207
                if (r == 0) {
233✔
1208
                        log_info("Suggested user ID " UID_FMT " for %s already used.", i->uid, i->name);
5✔
1209
                        i->uid_set = false;
5✔
1210
                }
1211
        }
1212

1213
        /* If that didn't work, try to read it from the specified path */
1214
        if (!i->uid_set) {
268✔
1215
                uid_t candidate;
40✔
1216

1217
                if (read_id_from_file(i, &candidate, NULL) > 0) {
40✔
1218

UNCOV
1219
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
UNCOV
1220
                                log_debug("User ID " UID_FMT " of file not suitable for %s.", candidate, i->name);
×
1221
                        else {
UNCOV
1222
                                r = uid_is_ok(c, candidate, i->name, true);
×
UNCOV
1223
                                if (r < 0)
×
UNCOV
1224
                                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
UNCOV
1225
                                else if (r > 0) {
×
UNCOV
1226
                                        i->uid = candidate;
×
UNCOV
1227
                                        i->uid_set = true;
×
1228
                                } else
UNCOV
1229
                                        log_debug("User ID " UID_FMT " of file for %s is already used.", candidate, i->name);
×
1230
                        }
1231
                }
1232
        }
1233

1234
        /* Otherwise, try to reuse the group ID */
1235
        if (!i->uid_set && i->gid_set) {
268✔
1236
                r = uid_is_ok(c, (uid_t) i->gid, i->name, true);
40✔
1237
                if (r < 0)
40✔
1238
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1239
                if (r > 0) {
40✔
1240
                        i->uid = (uid_t) i->gid;
25✔
1241
                        i->uid_set = true;
25✔
1242
                }
1243
        }
1244

1245
        /* And if that didn't work either, let's try to find a free one */
1246
        if (!i->uid_set) {
268✔
1247
                maybe_emit_login_defs_warning(c);
15✔
1248

1249
                for (;;) {
15✔
1250
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
15✔
1251
                        if (r < 0)
15✔
UNCOV
1252
                                return log_error_errno(r, "No free user ID available for %s.", i->name);
×
1253

1254
                        r = uid_is_ok(c, c->search_uid, i->name, true);
15✔
1255
                        if (r < 0)
15✔
UNCOV
1256
                                return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1257
                        else if (r > 0)
15✔
1258
                                break;
1259
                }
1260

1261
                i->uid_set = true;
15✔
1262
                i->uid = c->search_uid;
15✔
1263
        }
1264

1265
        r = ordered_hashmap_ensure_put(&c->todo_uids, NULL, UID_TO_PTR(i->uid), i);
268✔
1266
        if (r == -EEXIST)
268✔
UNCOV
1267
                return log_error_errno(r, "Requested user %s with UID " UID_FMT " and gid" GID_FMT " to be created is duplicated "
×
1268
                                       "or conflicts with another user.", i->name, i->uid, i->gid);
1269
        if (r == -ENOMEM)
268✔
UNCOV
1270
                return log_oom();
×
1271
        if (r < 0)
268✔
UNCOV
1272
                return log_error_errno(r, "Failed to store user %s with UID " UID_FMT " and GID " GID_FMT " to be created: %m",
×
1273
                                       i->name, i->uid, i->gid);
1274

1275
        i->todo_user = true;
268✔
1276
        log_info("Creating user '%s' (%s) with UID " UID_FMT " and GID " GID_FMT ".",
509✔
1277
                 i->name, strna(i->description), i->uid, i->gid);
1278

1279
        return 0;
1280
}
1281

1282
static int gid_is_ok(
728✔
1283
                Context *c,
1284
                gid_t gid,
1285
                const char *groupname,
1286
                bool check_with_uid) {
1287

1288
        Item *user;
728✔
1289
        char *username;
728✔
1290
        int r;
728✔
1291

1292
        assert(c);
728✔
1293
        assert(groupname);
728✔
1294

1295
        if (ordered_hashmap_get(c->todo_gids, GID_TO_PTR(gid)))
728✔
1296
                return 0;
1297

1298
        /* Avoid reusing gids that are already used by a different user */
1299
        if (check_with_uid) {
663✔
1300
                user = ordered_hashmap_get(c->todo_uids, UID_TO_PTR(gid));
329✔
1301
                if (user && !streq(user->name, groupname))
329✔
1302
                        return 0;
1303
        }
1304

1305
        if (hashmap_contains(c->database_by_gid, GID_TO_PTR(gid)))
663✔
1306
                return 0;
1307

1308
        if (check_with_uid) {
517✔
1309
                username = hashmap_get(c->database_by_uid, UID_TO_PTR(gid));
183✔
1310
                if (username && !streq(username, groupname))
183✔
1311
                        return 0;
1312
        }
1313

1314
        if (!arg_root) {
517✔
1315
                r = getgrgid_malloc(gid, /* ret= */ NULL);
5✔
1316
                if (r >= 0)
5✔
1317
                        return 0;
1318
                if (r != -ESRCH)
5✔
UNCOV
1319
                        log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", gid);
×
1320

1321
                if (check_with_uid) {
5✔
1322
                        r = getpwuid_malloc(gid, /* ret= */ NULL);
5✔
1323
                        if (r >= 0)
5✔
1324
                                return 0;
1325
                        if (r != -ESRCH)
5✔
UNCOV
1326
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", gid);
×
1327
                }
1328
        }
1329

1330
        return 1;
1331
}
1332

1333
static int get_gid_by_name(
647✔
1334
                Context *c,
1335
                const char *name,
1336
                gid_t *ret_gid) {
1337

1338
        void *z;
647✔
1339
        int r;
647✔
1340

1341
        assert(c);
647✔
1342
        assert(ret_gid);
647✔
1343

1344
        /* Check the database directly */
1345
        z = hashmap_get(c->database_by_groupname, name);
647✔
1346
        if (z) {
647✔
1347
                *ret_gid = PTR_TO_GID(z);
69✔
1348
                return 0;
69✔
1349
        }
1350

1351
        /* Also check NSS */
1352
        if (!arg_root) {
578✔
1353
                _cleanup_free_ struct group *g = NULL;
5✔
1354

1355
                r = getgrnam_malloc(name, &g);
5✔
1356
                if (r >= 0) {
5✔
UNCOV
1357
                        *ret_gid = g->gr_gid;
×
UNCOV
1358
                        return 0;
×
1359
                }
1360
                if (r != -ESRCH)
5✔
1361
                        log_warning_errno(r, "Unexpected failure while looking up group '%s' via NSS, assuming it doesn't exist: %m", name);
5✔
1362
        }
1363

1364
        return -ENOENT;
1365
}
1366

1367
static int add_group(Context *c, Item *i) {
641✔
1368
        int r;
641✔
1369

1370
        assert(c);
641✔
1371
        assert(i);
641✔
1372

1373
        r = get_gid_by_name(c, i->name, &i->gid);
641✔
1374
        if (r != -ENOENT) {
641✔
1375
                if (r < 0)
64✔
1376
                        return r;
1377
                log_debug("Group %s already exists.", i->name);
64✔
1378
                i->gid_set = true;
64✔
1379
                return 0;
64✔
1380
        }
1381

1382
        /* Try to use the suggested numeric GID */
1383
        if (i->gid_set) {
577✔
1384
                r = gid_is_ok(c, i->gid, i->name, false);
394✔
1385
                if (r < 0)
394✔
UNCOV
1386
                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1387
                if (i->id_set_strict) {
394✔
1388
                        /* If we require the GID to already exist we can return here:
1389
                         * r > 0: means the GID does not exist -> fail
1390
                         * r == 0: means the GID exists -> nothing more to do.
1391
                         */
1392
                        if (r > 0)
61✔
1393
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
1394
                                                       "Failed to create %s: please create GID " GID_FMT,
1395
                                                       i->name, i->gid);
1396
                        if (r == 0)
60✔
1397
                                return 0;
1398
                }
1399
                if (r == 0) {
333✔
UNCOV
1400
                        log_info("Suggested group ID " GID_FMT " for %s already used.", i->gid, i->name);
×
UNCOV
1401
                        i->gid_set = false;
×
1402
                }
1403
        }
1404

1405
        /* Try to reuse the numeric uid, if there's one */
1406
        if (!i->gid_set && i->uid_set) {
516✔
1407
                r = gid_is_ok(c, (gid_t) i->uid, i->name, true);
158✔
1408
                if (r < 0)
158✔
UNCOV
1409
                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1410
                if (r > 0) {
158✔
1411
                        i->gid = (gid_t) i->uid;
153✔
1412
                        i->gid_set = true;
153✔
1413
                }
1414
        }
1415

1416
        /* If that didn't work, try to read it from the specified path */
1417
        if (!i->gid_set) {
516✔
1418
                gid_t candidate;
30✔
1419

1420
                if (read_id_from_file(i, NULL, &candidate) > 0) {
30✔
1421

UNCOV
1422
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
UNCOV
1423
                                log_debug("Group ID " GID_FMT " of file not suitable for %s.", candidate, i->name);
×
1424
                        else {
UNCOV
1425
                                r = gid_is_ok(c, candidate, i->name, true);
×
UNCOV
1426
                                if (r < 0)
×
UNCOV
1427
                                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
UNCOV
1428
                                else if (r > 0) {
×
UNCOV
1429
                                        i->gid = candidate;
×
UNCOV
1430
                                        i->gid_set = true;
×
1431
                                } else
UNCOV
1432
                                        log_debug("Group ID " GID_FMT " of file for %s already used.", candidate, i->name);
×
1433
                        }
1434
                }
1435
        }
1436

1437
        /* And if that didn't work either, let's try to find a free one */
1438
        if (!i->gid_set) {
516✔
1439
                maybe_emit_login_defs_warning(c);
30✔
1440

1441
                for (;;) {
176✔
1442
                        /* We look for new GIDs in the UID pool! */
1443
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
176✔
1444
                        if (r < 0)
176✔
UNCOV
1445
                                return log_error_errno(r, "No free group ID available for %s.", i->name);
×
1446

1447
                        r = gid_is_ok(c, c->search_uid, i->name, true);
176✔
1448
                        if (r < 0)
176✔
UNCOV
1449
                                return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1450
                        else if (r > 0)
176✔
1451
                                break;
1452
                }
1453

1454
                i->gid_set = true;
30✔
1455
                i->gid = c->search_uid;
30✔
1456
        }
1457

1458
        r = ordered_hashmap_ensure_put(&c->todo_gids, NULL, GID_TO_PTR(i->gid), i);
516✔
1459
        if (r == -EEXIST)
516✔
UNCOV
1460
                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);
×
1461
        if (r == -ENOMEM)
516✔
UNCOV
1462
                return log_oom();
×
1463
        if (r < 0)
516✔
UNCOV
1464
                return log_error_errno(r, "Failed to store group %s with GID " GID_FMT " to be created: %m", i->name, i->gid);
×
1465

1466
        i->todo_group = true;
516✔
1467
        log_info("Creating group '%s' with GID " GID_FMT ".", i->name, i->gid);
516✔
1468

1469
        return 0;
1470
}
1471

1472
static int process_item(Context *c, Item *i) {
677✔
1473
        int r;
677✔
1474

1475
        assert(c);
677✔
1476
        assert(i);
677✔
1477

1478
        switch (i->type) {
677✔
1479

1480
        case ADD_USER: {
300✔
1481
                Item *j = NULL;
300✔
1482

1483
                if (!i->gid_set) {
300✔
1484
                        j = ordered_hashmap_get(c->groups, i->group_name ?: i->name);
236✔
1485

1486
                        /* If that's not a match, also check if the group name
1487
                         * matches a user name in the queue. */
1488
                        if (!j && i->group_name)
236✔
1489
                                j = ordered_hashmap_get(c->users, i->group_name);
11✔
1490
                }
1491

1492
                if (j && j->todo_group) {
236✔
1493
                        /* When a group with the target name is already in queue,
1494
                         * use the information about the group and do not create
1495
                         * duplicated group entry. */
1496
                        i->gid_set = j->gid_set;
30✔
1497
                        i->gid = j->gid;
30✔
1498
                        i->id_set_strict = true;
30✔
1499
                } else if (i->group_name) {
270✔
1500
                        /* When a group name was given instead of a GID and it's
1501
                         * not in queue, then it must already exist. */
1502
                        r = get_gid_by_name(c, i->group_name, &i->gid);
6✔
1503
                        if (r < 0)
6✔
1504
                                return log_error_errno(r, "Group %s not found.", i->group_name);
1✔
1505
                        i->gid_set = true;
5✔
1506
                        i->id_set_strict = true;
5✔
1507
                } else {
1508
                        r = add_group(c, i);
264✔
1509
                        if (r < 0)
264✔
1510
                                return r;
1511
                }
1512

1513
                return add_user(c, i);
298✔
1514
        }
1515

1516
        case ADD_GROUP:
377✔
1517
                return add_group(c, i);
377✔
1518

UNCOV
1519
        default:
×
UNCOV
1520
                assert_not_reached();
×
1521
        }
1522
}
1523

1524
static Item* item_free(Item *i) {
679✔
1525
        if (!i)
679✔
1526
                return NULL;
1527

1528
        free(i->name);
679✔
1529
        free(i->group_name);
679✔
1530
        free(i->uid_path);
679✔
1531
        free(i->gid_path);
679✔
1532
        free(i->description);
679✔
1533
        free(i->home);
679✔
1534
        free(i->shell);
679✔
1535
        free(i->filename);
679✔
1536
        return mfree(i);
679✔
1537
}
1538

1539
DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1,368✔
1540
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
677✔
1541

1542
static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
679✔
1543
        assert(name);
679✔
1544
        assert(!!filename == (line > 0));
679✔
1545

1546
        _cleanup_(item_freep) Item *new = new(Item, 1);
1,358✔
1547
        if (!new)
679✔
1548
                return NULL;
1549

1550
        *new = (Item) {
679✔
1551
                .type = type,
1552
                .line = line,
1553
        };
1554

1555
        if (free_and_strdup(&new->name, name) < 0 ||
1,358✔
1556
            free_and_strdup(&new->filename, filename) < 0)
679✔
UNCOV
1557
                return NULL;
×
1558

1559
        return TAKE_PTR(new);
679✔
1560
}
1561

1562
static int add_implicit(Context *c) {
113✔
1563
        char *g, **l;
113✔
1564
        int r;
113✔
1565

1566
        assert(c);
113✔
1567

1568
        /* Implicitly create additional users and groups, if they were listed in "m" lines */
1569
        ORDERED_HASHMAP_FOREACH_KEY(l, g, c->members) {
236✔
1570
                STRV_FOREACH(m, l)
20✔
1571
                        if (!ordered_hashmap_get(c->users, *m)) {
10✔
UNCOV
1572
                                _cleanup_(item_freep) Item *j =
×
1573
                                        item_new(ADD_USER, *m, /* filename= */ NULL, /* line= */ 0);
5✔
1574
                                if (!j)
5✔
UNCOV
1575
                                        return log_oom();
×
1576

1577
                                r = ordered_hashmap_ensure_put(&c->users, &item_hash_ops, j->name, j);
5✔
1578
                                if (r == -ENOMEM)
5✔
UNCOV
1579
                                        return log_oom();
×
1580
                                if (r < 0)
5✔
UNCOV
1581
                                        return log_error_errno(r, "Failed to add implicit user '%s': %m", j->name);
×
1582

1583
                                log_debug("Adding implicit user '%s' due to m line", j->name);
5✔
1584
                                TAKE_PTR(j);
5✔
1585
                        }
1586

1587
                if (!(ordered_hashmap_get(c->users, g) ||
10✔
1588
                      ordered_hashmap_get(c->groups, g))) {
2✔
UNCOV
1589
                        _cleanup_(item_freep) Item *j =
×
UNCOV
1590
                                item_new(ADD_GROUP, g, /* filename= */ NULL, /* line= */ 0);
×
1591
                        if (!j)
×
UNCOV
1592
                                return log_oom();
×
1593

UNCOV
1594
                        r = ordered_hashmap_ensure_put(&c->groups, &item_hash_ops, j->name, j);
×
UNCOV
1595
                        if (r == -ENOMEM)
×
UNCOV
1596
                                return log_oom();
×
UNCOV
1597
                        if (r < 0)
×
UNCOV
1598
                                return log_error_errno(r, "Failed to add implicit group '%s': %m", j->name);
×
1599

UNCOV
1600
                        log_debug("Adding implicit group '%s' due to m line", j->name);
×
1601
                        TAKE_PTR(j);
×
1602
                }
1603
        }
1604

1605
        return 0;
113✔
1606
}
1607

1608
static int item_equivalent(Item *a, Item *b) {
1✔
1609
        int r;
1✔
1610

1611
        assert(a);
1✔
1612
        assert(b);
1✔
1613

1614
        if (a->type != b->type) {
1✔
UNCOV
1615
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1616
                           "Item not equivalent because types differ");
UNCOV
1617
                return false;
×
1618
        }
1619

1620
        if (!streq_ptr(a->name, b->name)) {
1✔
UNCOV
1621
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1622
                           "Item not equivalent because names differ ('%s' vs. '%s')",
1623
                           a->name, b->name);
UNCOV
1624
                return false;
×
1625
        }
1626

1627
        /* Paths were simplified previously, so we can use streq. */
1628
        if (!streq_ptr(a->uid_path, b->uid_path)) {
1✔
1629
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1630
                           "Item not equivalent because UID paths differ (%s vs. %s)",
1631
                           a->uid_path ?: "(unset)", b->uid_path ?: "(unset)");
UNCOV
1632
                return false;
×
1633
        }
1634

1635
        if (!streq_ptr(a->gid_path, b->gid_path)) {
1✔
1636
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1637
                           "Item not equivalent because GID paths differ (%s vs. %s)",
1638
                           a->gid_path ?: "(unset)", b->gid_path ?: "(unset)");
UNCOV
1639
                return false;
×
1640
        }
1641

1642
        if (!streq_ptr(a->description, b->description))  {
1✔
UNCOV
1643
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1644
                           "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1645
                           strempty(a->description), strempty(b->description));
UNCOV
1646
                return false;
×
1647
        }
1648

1649
        if ((a->uid_set != b->uid_set) ||
1✔
UNCOV
1650
            (a->uid_set && a->uid != b->uid)) {
×
1651
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1652
                           "Item not equivalent because UIDs differ (%s vs. %s)",
1653
                           a->uid_set ? FORMAT_UID(a->uid) : "(unset)",
1654
                           b->uid_set ? FORMAT_UID(b->uid) : "(unset)");
1655
                return false;
×
1656
        }
1657

1658
        if ((a->gid_set != b->gid_set) ||
1✔
1659
            (a->gid_set && a->gid != b->gid)) {
1✔
UNCOV
1660
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1661
                           "Item not equivalent because GIDs differ (%s vs. %s)",
1662
                           a->gid_set ? FORMAT_GID(a->gid) : "(unset)",
1663
                           b->gid_set ? FORMAT_GID(b->gid) : "(unset)");
UNCOV
1664
                return false;
×
1665
        }
1666

1667
        if (!streq_ptr(a->home, b->home)) {
1✔
UNCOV
1668
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1669
                           "Item not equivalent because home directories differ ('%s' vs. '%s')",
1670
                           strempty(a->description), strempty(b->description));
UNCOV
1671
                return false;
×
1672
        }
1673

1674
        /* Check if the two paths refer to the same file.
1675
         * If the paths are equal (after normalization), it's obviously the same file.
1676
         * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1677
         * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1678
         * /usr/sbin/nologin).
1679
         * If we can't resolve something, treat different paths as different. */
1680

1681
        const char *a_shell = pick_shell(a),
1✔
1682
                   *b_shell = pick_shell(b);
1✔
1683
        if (!path_equal(a_shell, b_shell) &&
1✔
UNCOV
1684
            !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
×
UNCOV
1685
                _cleanup_free_ char *pa = NULL, *pb = NULL;
×
1686

UNCOV
1687
                r = chase(a_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pa, NULL);
×
UNCOV
1688
                if (r < 0) {
×
UNCOV
1689
                        log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
×
1690
                                       r, "Failed to look up path '%s%s%s': %m",
1691
                                       strempty(arg_root), arg_root ? "/" : "", a_shell);
UNCOV
1692
                        return ERRNO_IS_RESOURCE(r) ? r : false;
×
1693
                }
1694

UNCOV
1695
                r = chase(b_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pb, NULL);
×
1696
                if (r < 0) {
×
1697
                        log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
×
1698
                                       r, "Failed to look up path '%s%s%s': %m",
1699
                                       strempty(arg_root), arg_root ? "/" : "", b_shell);
1700
                        return ERRNO_IS_RESOURCE(r) ? r : false;
×
1701
                }
1702

UNCOV
1703
                if (!path_equal(pa, pb)) {
×
1704
                        log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1705
                                   "Item not equivalent because shells differ ('%s' vs. '%s')",
1706
                                   pa, pb);
1707
                        return false;
×
1708
                }
1709
        }
1710

1711
        return true;
1712
}
1713

1714
static int parse_line(
684✔
1715
                const char *fname,
1716
                unsigned line,
1717
                const char *buffer,
1718
                bool *invalid_config,
1719
                void *context) {
1720

1721
        Context *c = ASSERT_PTR(context);
684✔
1722
        _cleanup_free_ char *action = NULL,
1,368✔
UNCOV
1723
                *name = NULL, *resolved_name = NULL,
×
UNCOV
1724
                *id = NULL, *resolved_id = NULL,
×
UNCOV
1725
                *description = NULL, *resolved_description = NULL,
×
UNCOV
1726
                *home = NULL, *resolved_home = NULL,
×
1727
                *shell = NULL, *resolved_shell = NULL;
684✔
1728
        _cleanup_(item_freep) Item *i = NULL;
684✔
1729
        Item *existing;
684✔
1730
        OrderedHashmap *h;
684✔
1731
        int r;
684✔
1732
        const char *p;
684✔
1733

1734
        assert(fname);
684✔
1735
        assert(line >= 1);
684✔
1736
        assert(buffer);
684✔
1737
        assert(!invalid_config); /* We don't support invalid_config yet. */
684✔
1738

1739
        /* Parse columns */
1740
        p = buffer;
684✔
1741
        r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
684✔
1742
                               &action, &name, &id, &description, &home, &shell);
1743
        if (r < 0)
684✔
UNCOV
1744
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Syntax error.");
×
1745
        if (r < 2)
684✔
UNCOV
1746
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1747
                                  "Missing action and name columns.");
1748
        if (!isempty(p))
684✔
UNCOV
1749
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1750
                                  "Trailing garbage.");
1751

1752
        if (isempty(action))
684✔
UNCOV
1753
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1754
                                  "Empty command specification.");
1755

1756
        bool locked = false;
1757
        for (int pos = 1; action[pos]; pos++)
702✔
1758
                if (action[pos] == '!' && !locked)
18✔
1759
                        locked = true;
18✔
1760
                else
1761
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1762
                                          "Unknown modifiers in command '%s'.", action);
1763

1764
        if (!IN_SET(action[0], ADD_USER, ADD_GROUP, ADD_MEMBER, ADD_RANGE))
684✔
1765
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1766
                                  "Unknown command type '%c'.", action[0]);
1767

1768
        /* Verify name */
1769
        if (empty_or_dash(name))
684✔
UNCOV
1770
                name = mfree(name);
×
1771

1772
        if (name) {
684✔
1773
                r = specifier_printf(name, NAME_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_name);
684✔
1774
                if (r < 0)
684✔
UNCOV
1775
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", name);
×
1776

1777
                if (!valid_user_group_name(resolved_name, 0))
684✔
UNCOV
1778
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1779
                                          "'%s' is not a valid user or group name.", resolved_name);
1780
        }
1781

1782
        /* Verify id */
1783
        if (empty_or_dash(id))
684✔
1784
                id = mfree(id);
57✔
1785

1786
        if (id) {
684✔
1787
                r = specifier_printf(id, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_id);
627✔
1788
                if (r < 0)
627✔
UNCOV
1789
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1790
                                          "Failed to replace specifiers in '%s': %m", name);
1791
        }
1792

1793
        /* Verify description */
1794
        if (empty_or_dash(description))
684✔
1795
                description = mfree(description);
632✔
1796

1797
        if (description) {
684✔
1798
                r = specifier_printf(description, LONG_LINE_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_description);
52✔
1799
                if (r < 0)
52✔
UNCOV
1800
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1801
                                          "Failed to replace specifiers in '%s': %m", description);
1802

1803
                if (!valid_gecos(resolved_description))
52✔
UNCOV
1804
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1805
                                          "'%s' is not a valid GECOS field.", resolved_description);
1806
        }
1807

1808
        /* Verify home */
1809
        if (empty_or_dash(home))
684✔
1810
                home = mfree(home);
544✔
1811

1812
        if (home) {
684✔
1813
                r = specifier_printf(home, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_home);
140✔
1814
                if (r < 0)
140✔
UNCOV
1815
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1816
                                          "Failed to replace specifiers in '%s': %m", home);
1817

1818
                path_simplify(resolved_home);
140✔
1819

1820
                if (!valid_home(resolved_home))
140✔
UNCOV
1821
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1822
                                          "'%s' is not a valid home directory field.", resolved_home);
1823
        }
1824

1825
        /* Verify shell */
1826
        if (empty_or_dash(shell))
684✔
1827
                shell = mfree(shell);
663✔
1828

1829
        if (shell) {
684✔
1830
                r = specifier_printf(shell, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_shell);
21✔
1831
                if (r < 0)
21✔
UNCOV
1832
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1833
                                          "Failed to replace specifiers in '%s': %m", shell);
1834

1835
                path_simplify(resolved_shell);
21✔
1836

1837
                if (!valid_shell(resolved_shell))
21✔
UNCOV
1838
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1839
                                          "'%s' is not a valid login shell field.", resolved_shell);
1840
        }
1841

1842
        switch (action[0]) {
684✔
1843

1844
        case ADD_RANGE:
×
UNCOV
1845
                if (locked)
×
UNCOV
1846
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1847
                                          "Flag '!' not permitted on lines of type 'r'.");
1848

UNCOV
1849
                if (resolved_name)
×
1850
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1851
                                          "Lines of type 'r' don't take a name field.");
1852

UNCOV
1853
                if (!resolved_id)
×
UNCOV
1854
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1855
                                          "Lines of type 'r' require an ID range in the third field.");
1856

1857
                if (description || home || shell)
×
1858
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1859
                                          "Lines of type '%c' don't take a %s field.",
1860
                                          action[0],
1861
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1862

UNCOV
1863
                r = uid_range_add_str(&c->uid_range, resolved_id);
×
UNCOV
1864
                if (r < 0)
×
1865
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1866
                                          "Invalid UID range %s.", resolved_id);
1867

1868
                return 0;
1869

1870
        case ADD_MEMBER: {
10✔
1871
                /* Try to extend an existing member or group item */
1872
                if (!name)
10✔
UNCOV
1873
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1874
                                          "Lines of type 'm' require a user name in the second field.");
1875

1876
                if (locked)
10✔
1877
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1878
                                          "Flag '!' not permitted on lines of type 'm'.");
1879

1880
                if (!resolved_id)
10✔
UNCOV
1881
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1882
                                          "Lines of type 'm' require a group name in the third field.");
1883

1884
                if (!valid_user_group_name(resolved_id, 0))
10✔
1885
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1886
                                               "'%s' is not a valid user or group name.", resolved_id);
1887

1888
                if (description || home || shell)
10✔
1889
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1890
                                          "Lines of type '%c' don't take a %s field.",
1891
                                          action[0],
1892
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1893

1894
                r = string_strv_ordered_hashmap_put(&c->members, resolved_id, resolved_name);
10✔
1895
                if (r < 0)
10✔
UNCOV
1896
                        return log_error_errno(r, "Failed to store mapping for %s: %m", resolved_id);
×
1897

1898
                return 0;
1899
        }
1900

1901
        case ADD_USER:
296✔
1902
                if (!name)
296✔
UNCOV
1903
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1904
                                          "Lines of type 'u' require a user name in the second field.");
1905

1906
                r = ordered_hashmap_ensure_allocated(&c->users, &item_hash_ops);
296✔
1907
                if (r < 0)
296✔
1908
                        return log_oom();
×
1909

1910
                i = item_new(ADD_USER, resolved_name, fname, line);
296✔
1911
                if (!i)
296✔
UNCOV
1912
                        return log_oom();
×
1913

1914
                if (resolved_id) {
296✔
1915
                        if (path_is_absolute(resolved_id))
266✔
UNCOV
1916
                                i->uid_path = path_simplify(TAKE_PTR(resolved_id));
×
1917
                        else {
1918
                                _cleanup_free_ char *uid = NULL, *gid = NULL;
266✔
1919
                                if (split_pair(resolved_id, ":", &uid, &gid) == 0) {
266✔
1920
                                        r = parse_gid(gid, &i->gid);
90✔
1921
                                        if (r < 0) {
90✔
1922
                                                if (valid_user_group_name(gid, 0))
26✔
1923
                                                        i->group_name = TAKE_PTR(gid);
26✔
1924
                                                else
UNCOV
1925
                                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1926
                                                                          "Failed to parse GID: '%s': %m", id);
1927
                                        } else {
1928
                                                i->gid_set = true;
64✔
1929
                                                i->id_set_strict = true;
64✔
1930
                                        }
1931
                                        free_and_replace(resolved_id, uid);
90✔
1932
                                }
1933
                                if (!streq(resolved_id, "-")) {
266✔
1934
                                        r = parse_uid(resolved_id, &i->uid);
251✔
1935
                                        if (r < 0)
251✔
1936
                                                return log_syntax(NULL, LOG_ERR, fname, line, r,
1✔
1937
                                                                  "Failed to parse UID: '%s': %m", id);
1938
                                        i->uid_set = true;
250✔
1939
                                }
1940
                        }
1941
                }
1942

1943
                i->description = TAKE_PTR(resolved_description);
295✔
1944
                i->home = TAKE_PTR(resolved_home);
295✔
1945
                i->shell = TAKE_PTR(resolved_shell);
295✔
1946
                i->locked = locked;
295✔
1947

1948
                h = c->users;
295✔
1949
                break;
295✔
1950

1951
        case ADD_GROUP:
378✔
1952
                if (!name)
378✔
UNCOV
1953
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1954
                                          "Lines of type 'g' require a user name in the second field.");
1955

1956
                if (locked)
378✔
UNCOV
1957
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1958
                                          "Flag '!' not permitted on lines of type 'g'.");
1959

1960
                if (description || home || shell)
378✔
UNCOV
1961
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1962
                                          "Lines of type '%c' don't take a %s field.",
1963
                                          action[0],
1964
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1965

1966
                r = ordered_hashmap_ensure_allocated(&c->groups, &item_hash_ops);
378✔
1967
                if (r < 0)
378✔
UNCOV
1968
                        return log_oom();
×
1969

1970
                i = item_new(ADD_GROUP, resolved_name, fname, line);
378✔
1971
                if (!i)
378✔
UNCOV
1972
                        return log_oom();
×
1973

1974
                if (resolved_id) {
378✔
1975
                        if (path_is_absolute(resolved_id))
351✔
UNCOV
1976
                                i->gid_path = path_simplify(TAKE_PTR(resolved_id));
×
1977
                        else {
1978
                                r = parse_gid(resolved_id, &i->gid);
351✔
1979
                                if (r < 0)
351✔
1980
                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1981
                                                          "Failed to parse GID: '%s': %m", id);
1982

1983
                                i->gid_set = true;
351✔
1984
                        }
1985
                }
1986

1987
                h = c->groups;
378✔
1988
                break;
378✔
1989

UNCOV
1990
        default:
×
UNCOV
1991
                assert_not_reached();
×
1992
        }
1993

1994
        existing = ordered_hashmap_get(h, i->name);
673✔
1995
        if (existing) {
673✔
1996
                /* Two functionally-equivalent items are fine */
1997
                r = item_equivalent(i, existing);
1✔
1998
                if (r < 0)
1✔
1999
                        return r;
2000
                if (r == 0) {
1✔
UNCOV
2001
                        if (existing->filename)
×
2002
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
2003
                                           "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
2004
                                           item_type_to_string(i->type),
2005
                                           i->name,
2006
                                           existing->filename, existing->line);
2007
                        else
UNCOV
2008
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
2009
                                           "Conflict with earlier configuration for %s '%s', ignoring line.",
2010
                                           item_type_to_string(i->type),
2011
                                           i->name);
2012
                }
2013

2014
                return 0;
1✔
2015
        }
2016

2017
        r = ordered_hashmap_put(h, i->name, i);
672✔
2018
        if (r < 0)
672✔
UNCOV
2019
                return log_oom();
×
2020

2021
        i = NULL;
672✔
2022
        return 0;
672✔
2023
}
2024

2025
static int read_config_file(Context *c, const char *fn, bool ignore_enoent) {
133✔
2026
        return conf_file_read(
399✔
2027
                        arg_root,
2028
                        (const char**) CONF_PATHS_STRV("sysusers.d"),
133✔
2029
                        ASSERT_PTR(fn),
133✔
2030
                        parse_line,
2031
                        ASSERT_PTR(c),
133✔
2032
                        ignore_enoent,
2033
                        /* invalid_config= */ NULL);
2034
}
2035

UNCOV
2036
static int cat_config(void) {
×
UNCOV
2037
        _cleanup_strv_free_ char **files = NULL;
×
UNCOV
2038
        int r;
×
2039

UNCOV
2040
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
×
UNCOV
2041
        if (r < 0)
×
2042
                return r;
2043

UNCOV
2044
        pager_open(arg_pager_flags);
×
2045

UNCOV
2046
        return cat_files(NULL, files, arg_cat_flags);
×
2047
}
2048

2049
static int help(void) {
×
2050
        _cleanup_free_ char *link = NULL;
×
UNCOV
2051
        int r;
×
2052

2053
        r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
×
UNCOV
2054
        if (r < 0)
×
UNCOV
2055
                return log_oom();
×
2056

UNCOV
2057
        printf("%1$s [OPTIONS...] [CONFIGURATION FILE...]\n"
×
2058
               "\n%2$sCreates system user and group accounts.%4$s\n"
2059
               "\n%3$sCommands:%4$s\n"
2060
               "     --cat-config           Show configuration files\n"
2061
               "     --tldr                 Show non-comment parts of configuration\n"
2062
               "  -h --help                 Show this help\n"
2063
               "     --version              Show package version\n"
2064
               "\n%3$sOptions:%4$s\n"
2065
               "     --root=PATH            Operate on an alternate filesystem root\n"
2066
               "     --image=PATH           Operate on disk image as filesystem root\n"
2067
               "     --image-policy=POLICY  Specify disk image dissection policy\n"
2068
               "     --replace=PATH         Treat arguments as replacement for PATH\n"
2069
               "     --dry-run              Just print what would be done\n"
2070
               "     --inline               Treat arguments as configuration lines\n"
2071
               "     --no-pager             Do not pipe output into a pager\n"
2072
               "\nSee the %5$s for details.\n",
2073
               program_invocation_short_name,
2074
               ansi_highlight(),
2075
               ansi_underline(),
2076
               ansi_normal(),
2077
               link);
2078

2079
        return 0;
2080
}
2081

2082
static int parse_argv(int argc, char *argv[]) {
113✔
2083

2084
        enum {
113✔
2085
                ARG_VERSION = 0x100,
2086
                ARG_CAT_CONFIG,
2087
                ARG_TLDR,
2088
                ARG_ROOT,
2089
                ARG_IMAGE,
2090
                ARG_IMAGE_POLICY,
2091
                ARG_REPLACE,
2092
                ARG_DRY_RUN,
2093
                ARG_INLINE,
2094
                ARG_NO_PAGER,
2095
        };
2096

2097
        static const struct option options[] = {
113✔
2098
                { "help",         no_argument,       NULL, 'h'              },
2099
                { "version",      no_argument,       NULL, ARG_VERSION      },
2100
                { "cat-config",   no_argument,       NULL, ARG_CAT_CONFIG   },
2101
                { "tldr",         no_argument,       NULL, ARG_TLDR         },
2102
                { "root",         required_argument, NULL, ARG_ROOT         },
2103
                { "image",        required_argument, NULL, ARG_IMAGE        },
2104
                { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
2105
                { "replace",      required_argument, NULL, ARG_REPLACE      },
2106
                { "dry-run",      no_argument,       NULL, ARG_DRY_RUN      },
2107
                { "inline",       no_argument,       NULL, ARG_INLINE       },
2108
                { "no-pager",     no_argument,       NULL, ARG_NO_PAGER     },
2109
                {}
2110
        };
2111

2112
        int c, r;
113✔
2113

2114
        assert(argc >= 0);
113✔
2115
        assert(argv);
113✔
2116

2117
        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
260✔
2118

2119
                switch (c) {
147✔
2120

UNCOV
2121
                case 'h':
×
UNCOV
2122
                        return help();
×
2123

UNCOV
2124
                case ARG_VERSION:
×
UNCOV
2125
                        return version();
×
2126

UNCOV
2127
                case ARG_CAT_CONFIG:
×
UNCOV
2128
                        arg_cat_flags = CAT_CONFIG_ON;
×
UNCOV
2129
                        break;
×
2130

UNCOV
2131
                case ARG_TLDR:
×
UNCOV
2132
                        arg_cat_flags = CAT_TLDR;
×
2133
                        break;
×
2134

2135
                case ARG_ROOT:
108✔
2136
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
108✔
2137
                        if (r < 0)
108✔
2138
                                return r;
2139
                        break;
2140

2141
                case ARG_IMAGE:
×
UNCOV
2142
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
2143
                        if (r < 0)
×
2144
                                return r;
2145
                        break;
2146

UNCOV
2147
                case ARG_IMAGE_POLICY:
×
UNCOV
2148
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
UNCOV
2149
                        if (r < 0)
×
2150
                                return r;
2151
                        break;
2152

2153
                case ARG_REPLACE:
35✔
2154
                        if (!path_is_absolute(optarg))
35✔
2155
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2156
                                                       "The argument to --replace= must be an absolute path.");
2157
                        if (!endswith(optarg, ".conf"))
35✔
UNCOV
2158
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2159
                                                       "The argument to --replace= must have the extension '.conf'.");
2160

2161
                        arg_replace = optarg;
35✔
2162
                        break;
35✔
2163

UNCOV
2164
                case ARG_DRY_RUN:
×
UNCOV
2165
                        arg_dry_run = true;
×
UNCOV
2166
                        break;
×
2167

2168
                case ARG_INLINE:
4✔
2169
                        arg_inline = true;
4✔
2170
                        break;
4✔
2171

UNCOV
2172
                case ARG_NO_PAGER:
×
UNCOV
2173
                        arg_pager_flags |= PAGER_DISABLE;
×
UNCOV
2174
                        break;
×
2175

2176
                case '?':
2177
                        return -EINVAL;
2178

UNCOV
2179
                default:
×
UNCOV
2180
                        assert_not_reached();
×
2181
                }
2182

2183
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
113✔
2184
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2185
                                       "Option --replace= is not supported with --cat-config/--tldr.");
2186

2187
        if (arg_replace && optind >= argc)
113✔
UNCOV
2188
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2189
                                       "When --replace= is given, some configuration items must be specified.");
2190

2191
        if (arg_image && arg_root)
113✔
2192
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2193
                                       "Use either --root= or --image=, the combination of both is not supported.");
2194

2195
        return 1;
2196
}
2197

2198
static int parse_arguments(Context *c, char **args) {
41✔
2199
        unsigned pos = 1;
41✔
2200
        int r;
41✔
2201

2202
        assert(c);
41✔
2203

2204
        STRV_FOREACH(arg, args) {
85✔
2205
                if (arg_inline)
44✔
2206
                        /* Use (argument):n, where n==1 for the first positional arg */
2207
                        r = parse_line("(argument)", pos, *arg, /* invalid_config= */ NULL, c);
7✔
2208
                else
2209
                        r = read_config_file(c, *arg, /* ignore_enoent= */ false);
37✔
2210
                if (r < 0)
44✔
2211
                        return r;
2212

2213
                pos++;
44✔
2214
        }
2215

2216
        return 0;
2217
}
2218

2219
static int read_config_files(Context *c, char **args) {
90✔
UNCOV
2220
        _cleanup_strv_free_ char **files = NULL;
×
2221
        _cleanup_free_ char *p = NULL;
90✔
2222
        int r;
90✔
2223

2224
        assert(c);
90✔
2225

2226
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
90✔
2227
        if (r < 0)
90✔
2228
                return r;
2229

2230
        STRV_FOREACH(f, files)
203✔
2231
                if (p && path_equal(*f, p)) {
113✔
2232
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
18✔
2233

2234
                        r = parse_arguments(c, args);
18✔
2235
                        if (r < 0)
18✔
2236
                                return r;
2237
                } else {
2238
                        log_debug("Reading config file \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
118✔
2239

2240
                        /* Just warn, ignore result otherwise */
2241
                        (void) read_config_file(c, *f, /* ignore_enoent= */ true);
95✔
2242
                }
2243

2244
        return 0;
2245
}
2246

2247
static int read_credential_lines(Context *c) {
113✔
2248
        _cleanup_free_ char *j = NULL;
113✔
2249
        const char *d;
113✔
2250
        int r;
113✔
2251

2252
        assert(c);
113✔
2253

2254
        r = get_credentials_dir(&d);
113✔
2255
        if (r == -ENXIO)
113✔
2256
                return 0;
2257
        if (r < 0)
1✔
UNCOV
2258
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
2259

2260
        j = path_join(d, "sysusers.extra");
1✔
2261
        if (!j)
1✔
UNCOV
2262
                return log_oom();
×
2263

2264
        (void) read_config_file(c, j, /* ignore_enoent= */ true);
1✔
2265
        return 0;
2266
}
2267

2268
static int run(int argc, char *argv[]) {
113✔
2269
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
113✔
2270
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
×
2271
        _cleanup_close_ int lock = -EBADF;
113✔
2272
        _cleanup_(context_done) Context c = {
113✔
2273
                .audit_fd = -EBADF,
2274
                .search_uid = UID_INVALID,
2275
        };
2276

2277
        Item *i;
113✔
2278
        int r;
113✔
2279

2280
        r = parse_argv(argc, argv);
113✔
2281
        if (r <= 0)
113✔
2282
                return r;
2283

2284
        log_setup();
113✔
2285

2286
        if (arg_cat_flags != CAT_CONFIG_OFF)
113✔
UNCOV
2287
                return cat_config();
×
2288

2289
        if (should_bypass("SYSTEMD_SYSUSERS"))
113✔
2290
                return 0;
2291

2292
        umask(0022);
113✔
2293

2294
        r = mac_init();
113✔
2295
        if (r < 0)
113✔
2296
                return r;
2297

2298
        if (arg_image) {
113✔
2299
                assert(!arg_root);
×
2300

UNCOV
2301
                r = mount_image_privately_interactively(
×
2302
                                arg_image,
2303
                                arg_image_policy,
2304
                                DISSECT_IMAGE_GENERIC_ROOT |
2305
                                DISSECT_IMAGE_REQUIRE_ROOT |
2306
                                DISSECT_IMAGE_VALIDATE_OS |
2307
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
2308
                                DISSECT_IMAGE_FSCK |
2309
                                DISSECT_IMAGE_GROWFS |
2310
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
2311
                                &mounted_dir,
2312
                                /* ret_dir_fd= */ NULL,
2313
                                &loop_device);
UNCOV
2314
                if (r < 0)
×
2315
                        return r;
2316

UNCOV
2317
                arg_root = strdup(mounted_dir);
×
UNCOV
2318
                if (!arg_root)
×
UNCOV
2319
                        return log_oom();
×
2320
        }
2321

2322
        /* Prepare to emit audit events, but only if we're operating on the host system. */
2323
        if (!arg_root)
113✔
2324
                c.audit_fd = open_audit_fd_or_warn();
5✔
2325

2326
        /* If command line arguments are specified along with --replace, read all configuration files and
2327
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2328
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
2329
         * read configuration and execute it. */
2330
        if (arg_replace || optind >= argc)
113✔
2331
                r = read_config_files(&c, argv + optind);
90✔
2332
        else
2333
                r = parse_arguments(&c, argv + optind);
23✔
2334
        if (r < 0)
113✔
2335
                return r;
2336

2337
        r = read_credential_lines(&c);
113✔
2338
        if (r < 0)
113✔
2339
                return r;
2340

2341
        /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our
2342
         * detection whether the names or UID/GID area already used otherwise doesn't get confused. After
2343
         * all, even though nss-systemd synthesizes these users/groups, they should still appear in
2344
         * /etc/passwd and /etc/group, as the synthesizing logic is merely supposed to be fallback for cases
2345
         * where we run with a completely unpopulated /etc. */
2346
        if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
113✔
UNCOV
2347
                return log_error_errno(errno, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
×
2348

2349
        if (!c.uid_range) {
113✔
2350
                /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2351
                r = read_login_defs(&c.login_defs, NULL, arg_root);
113✔
2352
                if (r < 0)
113✔
UNCOV
2353
                        return log_error_errno(r, "Failed to read %s%s: %m",
×
2354
                                               strempty(arg_root), "/etc/login.defs");
2355

2356
                c.login_defs_need_warning = true;
113✔
2357

2358
                /* We pick a range that very conservative: we look at compiled-in maximum and the value in
2359
                 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
2360
                 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2361
                 * it's only used during allocation, so we use the configured value directly). */
2362
                uid_t begin = c.login_defs.system_alloc_uid_min,
113✔
2363
                      end = MIN3((uid_t) SYSTEM_UID_MAX, c.login_defs.system_uid_max, c.login_defs.system_gid_max);
113✔
2364
                if (begin < end) {
113✔
2365
                        r = uid_range_add(&c.uid_range, begin, end - begin + 1);
113✔
2366
                        if (r < 0)
113✔
UNCOV
2367
                                return log_oom();
×
2368
                }
2369
        }
2370

2371
        r = add_implicit(&c);
113✔
2372
        if (r < 0)
113✔
2373
                return r;
2374

2375
        if (!arg_dry_run) {
113✔
2376
                lock = take_etc_passwd_lock(arg_root);
113✔
2377
                if (lock < 0)
113✔
UNCOV
2378
                        return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
×
2379
        }
2380

2381
        r = load_user_database(&c);
113✔
2382
        if (r < 0)
113✔
UNCOV
2383
                return log_error_errno(r, "Failed to load user database: %m");
×
2384

2385
        r = load_group_database(&c);
113✔
2386
        if (r < 0)
113✔
UNCOV
2387
                return log_error_errno(r, "Failed to read group database: %m");
×
2388

2389
        ORDERED_HASHMAP_FOREACH(i, c.groups)
490✔
2390
                (void) process_item(&c, i);
377✔
2391

2392
        ORDERED_HASHMAP_FOREACH(i, c.users)
413✔
2393
                (void) process_item(&c, i);
300✔
2394

2395
        return write_files(&c);
113✔
2396
}
2397

2398
DEFINE_MAIN_FUNCTION(run);
113✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc