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

systemd / systemd / 20401947236

20 Dec 2025 09:56PM UTC coverage: 72.701% (+0.1%) from 72.578%
20401947236

push

github

DaanDeMeyer
core/socket: modernize listen/accept_in_cgroup

4 of 9 new or added lines in 1 file covered. (44.44%)

7723 existing lines in 114 files now uncovered.

309972 of 426363 relevant lines covered (72.7%)

1133403.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 "env-util.h"
16
#include "errno-util.h"
17
#include "extract-word.h"
18
#include "fd-util.h"
19
#include "fileio.h"
20
#include "format-util.h"
21
#include "fs-util.h"
22
#include "hashmap.h"
23
#include "image-policy.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 usec_t epoch_or_now(void) {
87✔
600
        uint64_t epoch;
87✔
601

602
        if (secure_getenv_uint64("SOURCE_DATE_EPOCH", &epoch) >= 0) {
87✔
603
                if (epoch > UINT64_MAX/USEC_PER_SEC) /* Overflow check */
×
604
                        return USEC_INFINITY;
87✔
605
                return (usec_t) epoch * USEC_PER_SEC;
×
606
        }
607

608
        return now(CLOCK_REALTIME);
87✔
609
}
610

611
static int write_temporary_shadow(
113✔
612
                Context *c,
613
                const char *shadow_path,
614
                FILE **ret_tmpfile,
615
                char **ret_tmpfile_path) {
616

617
        _cleanup_fclose_ FILE *original = NULL, *shadow = NULL;
113✔
618
        _cleanup_(unlink_and_freep) char *shadow_tmp = NULL;
113✔
619
        struct spwd *sp = NULL;
113✔
620
        long lstchg;
113✔
621
        Item *i;
113✔
622
        int r;
113✔
623

624
        assert(c);
113✔
625

626
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
627
                goto done;
26✔
628

629
        if (arg_dry_run) {
87✔
630
                log_info("Would write /etc/shadow%s", glyph(GLYPH_ELLIPSIS));
×
631
                goto done;
×
632
        }
633

634
        r = fopen_temporary_label("/etc/shadow", shadow_path, &shadow, &shadow_tmp);
87✔
635
        if (r < 0)
87✔
636
                return log_debug_errno(r, "Failed to open temporary copy of %s: %m", shadow_path);
×
637

638
        lstchg = (long) (epoch_or_now() / USEC_PER_DAY);
87✔
639

640
        original = fopen(shadow_path, "re");
87✔
641
        if (original) {
87✔
642

643
                r = copy_rights_with_fallback(fileno(original), fileno(shadow), shadow_tmp);
4✔
644
                if (r < 0)
4✔
645
                        return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
×
646
                                               shadow_path, shadow_tmp);
647

648
                while ((r = fgetspent_sane(original, &sp)) > 0) {
107✔
649
                        i = ordered_hashmap_get(c->users, sp->sp_namp);
103✔
650
                        if (i && i->todo_user) {
103✔
651
                                /* we will update the existing entry */
652
                                sp->sp_lstchg = lstchg;
×
653

654
                                /* only the /etc/shadow stage is left, so we can
655
                                 * safely remove the item from the todo set */
656
                                i->todo_user = false;
×
657
                                ordered_hashmap_remove(c->todo_uids, UID_TO_PTR(i->uid));
×
658
                        }
659

660
                        /* Make sure we keep the NIS entries (if any) at the end. */
661
                        if (IN_SET(sp->sp_namp[0], '+', '-'))
103✔
662
                                break;
663

664
                        r = putspent_sane(sp, shadow);
103✔
665
                        if (r < 0)
103✔
666
                                return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
×
667
                                                       sp->sp_namp);
668

669
                }
670
                if (r < 0)
4✔
671
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
×
672

673
        } else {
674
                if (errno != ENOENT)
83✔
675
                        return log_debug_errno(errno, "Failed to open %s: %m", shadow_path);
×
676
                if (fchmod(fileno(shadow), 0000) < 0)
83✔
677
                        return log_debug_errno(errno, "Failed to fchmod %s: %m", shadow_tmp);
×
678
        }
679

680
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
355✔
681
                _cleanup_(erase_and_freep) char *creds_password = NULL;
268✔
682
                bool is_hashed;
268✔
683

684
                struct spwd n = {
536✔
685
                        .sp_namp = i->name,
268✔
686
                        .sp_lstchg = lstchg,
687
                        .sp_min = -1,
688
                        .sp_max = -1,
689
                        .sp_warn = -1,
690
                        .sp_inact = -1,
691
                        .sp_expire = i->locked ? 1 : -1, /* Negative expiration means "unset". Expiration 0 or 1 means "locked" */
268✔
692
                        .sp_flag = ULONG_MAX, /* this appears to be what everybody does ... */
693
                };
694

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

699
                if (creds_password && !is_hashed) {
268✔
700
                        _cleanup_(erase_and_freep) char* plaintext_password = TAKE_PTR(creds_password);
×
701
                        r = hash_password(plaintext_password, &creds_password);
×
702
                        if (r < 0)
×
703
                                return log_debug_errno(r, "Failed to hash password: %m");
×
704
                }
705

706
                if (creds_password)
268✔
707
                        n.sp_pwdp = creds_password;
×
708
                else if (streq(i->name, "root"))
268✔
709
                        /* Let firstboot set the password later */
710
                        n.sp_pwdp = (char*) PASSWORD_UNPROVISIONED;
10✔
711
                else
712
                        n.sp_pwdp = (char*) PASSWORD_LOCKED_AND_INVALID;
258✔
713

714
                r = putspent_sane(&n, shadow);
268✔
715
                if (r < 0)
268✔
716
                        return log_debug_errno(r, "Failed to add new user \"%s\" to temporary shadow file: %m",
×
717
                                               i->name);
718
        }
719

720
        /* Append the remaining NIS entries if any */
721
        while (sp) {
87✔
722
                r = putspent_sane(sp, shadow);
×
723
                if (r < 0)
×
724
                        return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
×
725
                                               sp->sp_namp);
726

727
                r = fgetspent_sane(original, &sp);
×
728
                if (r < 0)
×
729
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
×
730
                if (r == 0)
×
731
                        break;
732
        }
733
        if (!IN_SET(errno, 0, ENOENT))
87✔
734
                return -errno;
×
735

736
        r = fflush_sync_and_check(shadow);
87✔
737
        if (r < 0)
87✔
738
                return log_debug_errno(r, "Failed to flush %s: %m", shadow_tmp);
×
739

740
done:
87✔
741
        *ret_tmpfile = TAKE_PTR(shadow);
113✔
742
        *ret_tmpfile_path = TAKE_PTR(shadow_tmp);
113✔
743
        return 0;
113✔
744
}
745

746
static int write_temporary_group(
113✔
747
                Context *c,
748
                const char *group_path,
749
                FILE **ret_tmpfile,
750
                char **ret_tmpfile_path) {
751

752
        _cleanup_fclose_ FILE *original = NULL, *group = NULL;
113✔
753
        _cleanup_(unlink_and_freep) char *group_tmp = NULL;
113✔
754
        bool group_changed = false;
113✔
755
        struct group *gr = NULL;
113✔
756
        Item *i;
113✔
757
        int r;
113✔
758

759
        assert(c);
113✔
760

761
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
762
                goto done;
26✔
763

764
        if (arg_dry_run) {
87✔
765
                log_info("Would write /etc/group%s", glyph(GLYPH_ELLIPSIS));
×
766
                goto done;
×
767
        }
768

769
        r = fopen_temporary_label("/etc/group", group_path, &group, &group_tmp);
87✔
770
        if (r < 0)
87✔
771
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", group_path);
×
772

773
        original = fopen(group_path, "re");
87✔
774
        if (original) {
87✔
775

776
                r = copy_rights_with_fallback(fileno(original), fileno(group), group_tmp);
14✔
777
                if (r < 0)
14✔
778
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
×
779
                                               group_path, group_tmp);
780

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

787
                        i = ordered_hashmap_get(c->groups, gr->gr_name);
250✔
788
                        if (i && i->todo_group)
250✔
789
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
790
                                                       "%s: Group \"%s\" already exists.",
791
                                                       group_path, gr->gr_name);
792

793
                        if (ordered_hashmap_contains(c->todo_gids, GID_TO_PTR(gr->gr_gid)))
250✔
794
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
795
                                                       "%s: Detected collision for GID " GID_FMT ".",
796
                                                       group_path, gr->gr_gid);
797

798
                        /* Make sure we keep the NIS entries (if any) at the end. */
799
                        if (IN_SET(gr->gr_name[0], '+', '-'))
250✔
800
                                break;
801

802
                        r = putgrent_with_members(c, gr, group);
245✔
803
                        if (r < 0)
245✔
804
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
×
805
                                                       gr->gr_name);
806
                        if (r > 0)
245✔
807
                                group_changed = true;
×
808
                }
809
                if (r < 0)
14✔
810
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
×
811

812
        } else {
813
                if (errno != ENOENT)
73✔
814
                        return log_error_errno(errno, "Failed to open %s: %m", group_path);
×
815
                if (fchmod(fileno(group), 0644) < 0)
73✔
816
                        return log_error_errno(errno, "Failed to fchmod %s: %m", group_tmp);
×
817
        }
818

819
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
603✔
820
                struct group n = {
516✔
821
                        .gr_name = i->name,
516✔
822
                        .gr_gid = i->gid,
516✔
823
                        .gr_passwd = (char*) PASSWORD_SEE_SHADOW,
824
                };
825

826
                r = putgrent_with_members(c, &n, group);
516✔
827
                if (r < 0)
516✔
828
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary group file: %m",
×
829
                                               gr->gr_name);
830

831
                group_changed = true;
516✔
832
        }
833

834
        /* Append the remaining NIS entries if any */
835
        while (gr) {
97✔
836
                r = putgrent_sane(gr, group);
15✔
837
                if (r < 0)
15✔
838
                        return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
×
839
                                               gr->gr_name);
840

841
                r = fgetgrent_sane(original, &gr);
15✔
842
                if (r < 0)
15✔
843
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
×
844
                if (r == 0)
15✔
845
                        break;
846
        }
847

848
        r = fflush_sync_and_check(group);
87✔
849
        if (r < 0)
87✔
850
                return log_error_errno(r, "Failed to flush %s: %m", group_tmp);
×
851

852
done:
87✔
853
        if (group_changed) {
113✔
854
                *ret_tmpfile = TAKE_PTR(group);
87✔
855
                *ret_tmpfile_path = TAKE_PTR(group_tmp);
87✔
856
        } else {
857
                *ret_tmpfile = NULL;
26✔
858
                *ret_tmpfile_path = NULL;
26✔
859
        }
860
        return 0;
861
}
862

863
static int write_temporary_gshadow(
113✔
864
                Context *c,
865
                const char * gshadow_path,
866
                FILE **ret_tmpfile,
867
                char **ret_tmpfile_path) {
868

869
#if ENABLE_GSHADOW
870
        _cleanup_fclose_ FILE *original = NULL, *gshadow = NULL;
113✔
871
        _cleanup_(unlink_and_freep) char *gshadow_tmp = NULL;
113✔
872
        bool group_changed = false;
113✔
873
        Item *i;
113✔
874
        int r;
113✔
875

876
        assert(c);
113✔
877

878
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
879
                goto done;
26✔
880

881
        if (arg_dry_run) {
87✔
882
                log_info("Would write /etc/gshadow%s", glyph(GLYPH_ELLIPSIS));
×
883
                goto done;
×
884
        }
885

886
        r = fopen_temporary_label("/etc/gshadow", gshadow_path, &gshadow, &gshadow_tmp);
87✔
887
        if (r < 0)
87✔
888
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", gshadow_path);
×
889

890
        original = fopen(gshadow_path, "re");
87✔
891
        if (original) {
87✔
892
                struct sgrp *sg;
4✔
893

894
                r = copy_rights_with_fallback(fileno(original), fileno(gshadow), gshadow_tmp);
4✔
895
                if (r < 0)
4✔
896
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
×
897
                                               gshadow_path, gshadow_tmp);
898

899
                while ((r = fgetsgent_sane(original, &sg)) > 0) {
239✔
900

901
                        i = ordered_hashmap_get(c->groups, sg->sg_namp);
235✔
902
                        if (i && i->todo_group)
235✔
903
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
904
                                                       "%s: Group \"%s\" already exists.",
905
                                                       gshadow_path, sg->sg_namp);
906

907
                        r = putsgent_with_members(c, sg, gshadow);
235✔
908
                        if (r < 0)
235✔
909
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
×
910
                                                       sg->sg_namp);
911
                        if (r > 0)
235✔
912
                                group_changed = true;
×
913
                }
914
                if (r < 0)
4✔
915
                        return r;
916

917
        } else {
918
                if (errno != ENOENT)
83✔
919
                        return log_error_errno(errno, "Failed to open %s: %m", gshadow_path);
×
920
                if (fchmod(fileno(gshadow), 0000) < 0)
83✔
921
                        return log_error_errno(errno, "Failed to fchmod %s: %m", gshadow_tmp);
×
922
        }
923

924
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
603✔
925
                struct sgrp n = {
516✔
926
                        .sg_namp = i->name,
516✔
927
                        .sg_passwd = (char*) PASSWORD_LOCKED_AND_INVALID,
928
                };
929

930
                r = putsgent_with_members(c, &n, gshadow);
516✔
931
                if (r < 0)
516✔
932
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary gshadow file: %m",
×
933
                                               n.sg_namp);
934

935
                group_changed = true;
516✔
936
        }
937

938
        r = fflush_sync_and_check(gshadow);
87✔
939
        if (r < 0)
87✔
940
                return log_error_errno(r, "Failed to flush %s: %m", gshadow_tmp);
×
941

942
done:
87✔
943
        if (group_changed) {
113✔
944
                *ret_tmpfile = TAKE_PTR(gshadow);
87✔
945
                *ret_tmpfile_path = TAKE_PTR(gshadow_tmp);
87✔
946
        } else
947
#endif
948
        {
949
                *ret_tmpfile = NULL;
26✔
950
                *ret_tmpfile_path = NULL;
26✔
951
        }
952
        return 0;
953
}
954

955
static int write_files(Context *c) {
113✔
956
        _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;
339✔
957
        _cleanup_(unlink_and_freep) char *passwd_tmp = NULL, *group_tmp = NULL, *shadow_tmp = NULL, *gshadow_tmp = NULL;
113✔
958
        int r;
113✔
959

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

964
        _cleanup_free_ char *shadow_path = path_join(arg_root, "/etc/shadow");
226✔
965
        if (!shadow_path)
113✔
966
                return log_oom();
×
967

968
        _cleanup_free_ char *group_path = path_join(arg_root, "/etc/group");
226✔
969
        if (!group_path)
113✔
970
                return log_oom();
×
971

972
        _cleanup_free_ char *gshadow_path = path_join(arg_root, "/etc/gshadow");
226✔
973
        if (!gshadow_path)
113✔
974
                return log_oom();
×
975

976
        assert(c);
113✔
977

978
        r = write_temporary_group(c, group_path, &group, &group_tmp);
113✔
979
        if (r < 0)
113✔
980
                return r;
981

982
        r = write_temporary_gshadow(c, gshadow_path, &gshadow, &gshadow_tmp);
113✔
983
        if (r < 0)
113✔
984
                return r;
985

986
        r = write_temporary_passwd(c, passwd_path, &passwd, &passwd_tmp);
113✔
987
        if (r < 0)
113✔
988
                return r;
989

990
        r = write_temporary_shadow(c, shadow_path, &shadow, &shadow_tmp);
113✔
991
        if (r < 0)
113✔
992
                return r;
993

994
        /* Make a backup of the old files */
995
        if (group) {
113✔
996
                r = make_backup("/etc/group", group_path);
87✔
997
                if (r < 0)
87✔
998
                        return log_error_errno(r, "Failed to backup %s: %m", group_path);
×
999
        }
1000
        if (gshadow) {
113✔
1001
                r = make_backup("/etc/gshadow", gshadow_path);
87✔
1002
                if (r < 0)
87✔
1003
                        return log_error_errno(r, "Failed to backup %s: %m", gshadow_path);
×
1004
        }
1005

1006
        if (passwd) {
113✔
1007
                r = make_backup("/etc/passwd", passwd_path);
87✔
1008
                if (r < 0)
87✔
1009
                        return log_error_errno(r, "Failed to backup %s: %m", passwd_path);
×
1010
        }
1011
        if (shadow) {
113✔
1012
                r = make_backup("/etc/shadow", shadow_path);
87✔
1013
                if (r < 0)
87✔
1014
                        return log_error_errno(r, "Failed to backup %s: %m", shadow_path);
×
1015
        }
1016

1017
        /* And make the new files count */
1018
        if (group) {
113✔
1019
                r = rename_and_apply_smack_floor_label(group_tmp, group_path);
87✔
1020
                if (r < 0)
87✔
1021
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1022
                                               group_tmp, group_path);
1023
                group_tmp = mfree(group_tmp);
87✔
1024
        }
1025
        /* OK, we have written the group entries successfully */
1026
        log_audit_accounts(c, ADD_GROUP);
113✔
1027
        if (gshadow) {
113✔
1028
                r = rename_and_apply_smack_floor_label(gshadow_tmp, gshadow_path);
87✔
1029
                if (r < 0)
87✔
1030
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1031
                                               gshadow_tmp, gshadow_path);
1032

1033
                gshadow_tmp = mfree(gshadow_tmp);
87✔
1034
        }
1035

1036
        if (passwd) {
113✔
1037
                r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
87✔
1038
                if (r < 0)
87✔
1039
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1040
                                               passwd_tmp, passwd_path);
1041

1042
                passwd_tmp = mfree(passwd_tmp);
87✔
1043
        }
1044
        /* OK, we have written the user entries successfully */
1045
        log_audit_accounts(c, ADD_USER);
113✔
1046
        if (shadow) {
113✔
1047
                r = rename_and_apply_smack_floor_label(shadow_tmp, shadow_path);
87✔
1048
                if (r < 0)
87✔
1049
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1050
                                               shadow_tmp, shadow_path);
1051

1052
                shadow_tmp = mfree(shadow_tmp);
87✔
1053
        }
1054

1055
        return 0;
1056
}
1057

1058
static int uid_is_ok(
288✔
1059
                Context *c,
1060
                uid_t uid,
1061
                const char *name,
1062
                bool check_with_gid) {
1063

1064
        int r;
288✔
1065
        assert(c);
288✔
1066

1067
        /* Let's see if we already have assigned the UID a second time */
1068
        if (ordered_hashmap_get(c->todo_uids, UID_TO_PTR(uid)))
288✔
1069
                return 0;
1070

1071
        /* Try to avoid using uids that are already used by a group
1072
         * that doesn't have the same name as our new user. */
1073
        if (check_with_gid) {
283✔
1074
                Item *i;
203✔
1075

1076
                i = ordered_hashmap_get(c->todo_gids, GID_TO_PTR(uid));
203✔
1077
                if (i && !streq(i->name, name))
203✔
1078
                        return 0;
1079
        }
1080

1081
        /* Let's check the files directly */
1082
        if (hashmap_contains(c->database_by_uid, UID_TO_PTR(uid)))
273✔
1083
                return 0;
1084

1085
        if (check_with_gid) {
273✔
1086
                const char *n;
193✔
1087

1088
                n = hashmap_get(c->database_by_gid, GID_TO_PTR(uid));
193✔
1089
                if (n && !streq(n, name))
193✔
1090
                        return 0;
1091
        }
1092

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

1097
                r = getpwuid_malloc(uid, /* ret= */ NULL);
5✔
1098
                if (r >= 0)
5✔
1099
                        return 0;
1100
                if (r != -ESRCH)
5✔
1101
                        log_warning_errno(r, "Unexpected failure while looking up UID '" UID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
×
1102

1103
                if (check_with_gid) {
5✔
1104
                        r = getgrgid_malloc((gid_t) uid, &g);
5✔
1105
                        if (r >= 0) {
5✔
1106
                                if (!streq(g->gr_name, name))
×
1107
                                        return 0;
1108
                        } else if (r != -ESRCH)
5✔
1109
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
5✔
1110
                }
1111
        }
1112

1113
        return 1;
1114
}
1115

1116
static int root_stat(const char *p, struct stat *ret_st) {
×
1117
        return chase_and_stat(p, arg_root, CHASE_PREFIX_ROOT, /* ret_path= */ NULL, ret_st);
×
1118
}
1119

1120
static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
70✔
1121
        struct stat st;
70✔
1122
        bool found_uid = false, found_gid = false;
70✔
1123
        uid_t uid = 0;
70✔
1124
        gid_t gid = 0;
70✔
1125

1126
        assert(i);
70✔
1127

1128
        /* First, try to get the GID directly */
1129
        if (ret_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
70✔
1130
                gid = st.st_gid;
×
1131
                found_gid = true;
×
1132
        }
1133

1134
        /* Then, try to get the UID directly */
1135
        if ((ret_uid || (ret_gid && !found_gid))
70✔
1136
            && i->uid_path
70✔
1137
            && root_stat(i->uid_path, &st) >= 0) {
×
1138

1139
                uid = st.st_uid;
×
1140
                found_uid = true;
×
1141

1142
                /* If we need the gid, but had no success yet, also derive it from the UID path */
1143
                if (ret_gid && !found_gid) {
×
1144
                        gid = st.st_gid;
×
1145
                        found_gid = true;
×
1146
                }
1147
        }
1148

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

1152
                if (found_gid) {
×
1153
                        uid = (uid_t) gid;
1154
                        found_uid = true;
1155
                } else if (root_stat(i->gid_path, &st) >= 0) {
×
1156
                        uid = (uid_t) st.st_gid;
×
1157
                        found_uid = true;
×
1158
                }
1159
        }
1160

1161
        if (ret_uid) {
70✔
1162
                if (!found_uid)
40✔
1163
                        return 0;
70✔
1164

1165
                *ret_uid = uid;
×
1166
        }
1167

1168
        if (ret_gid) {
30✔
1169
                if (!found_gid)
30✔
1170
                        return 0;
1171

1172
                *ret_gid = gid;
×
1173
        }
1174

1175
        return 1;
1176
}
1177

1178
static int add_user(Context *c, Item *i) {
298✔
1179
        void *z;
298✔
1180
        int r;
298✔
1181

1182
        assert(c);
298✔
1183
        assert(i);
298✔
1184

1185
        /* Check the database directly */
1186
        z = hashmap_get(c->database_by_username, i->name);
298✔
1187
        if (z) {
298✔
1188
                log_debug("User %s already exists.", i->name);
30✔
1189
                i->uid = PTR_TO_UID(z);
30✔
1190
                i->uid_set = true;
30✔
1191
                return 0;
30✔
1192
        }
1193

1194
        if (!arg_root) {
268✔
1195
                _cleanup_free_ struct passwd *p = NULL;
5✔
1196

1197
                /* Also check NSS */
1198
                r = getpwnam_malloc(i->name, &p);
5✔
1199
                if (r >= 0) {
5✔
1200
                        log_debug("User %s already exists.", i->name);
×
1201
                        i->uid = p->pw_uid;
×
1202
                        i->uid_set = true;
×
1203

1204
                        r = free_and_strdup(&i->description, p->pw_gecos);
×
1205
                        if (r < 0)
×
1206
                                return log_oom();
×
1207

1208
                        return 0;
1209
                }
1210
                if (r != -ESRCH)
5✔
1211
                        log_warning_errno(r, "Unexpected failure while looking up user '%s' via NSS, assuming it doesn't exist: %m", i->name);
5✔
1212
        }
1213

1214
        /* Try to use the suggested numeric UID */
1215
        if (i->uid_set) {
268✔
1216
                r = uid_is_ok(c, i->uid, i->name, !i->id_set_strict);
233✔
1217
                if (r < 0)
233✔
1218
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1219
                if (r == 0) {
233✔
1220
                        log_info("Suggested user ID " UID_FMT " for %s already used.", i->uid, i->name);
5✔
1221
                        i->uid_set = false;
5✔
1222
                }
1223
        }
1224

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

1229
                if (read_id_from_file(i, &candidate, NULL) > 0) {
40✔
1230

1231
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
1232
                                log_debug("User ID " UID_FMT " of file not suitable for %s.", candidate, i->name);
×
1233
                        else {
1234
                                r = uid_is_ok(c, candidate, i->name, true);
×
1235
                                if (r < 0)
×
1236
                                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1237
                                else if (r > 0) {
×
1238
                                        i->uid = candidate;
×
1239
                                        i->uid_set = true;
×
1240
                                } else
1241
                                        log_debug("User ID " UID_FMT " of file for %s is already used.", candidate, i->name);
×
1242
                        }
1243
                }
1244
        }
1245

1246
        /* Otherwise, try to reuse the group ID */
1247
        if (!i->uid_set && i->gid_set) {
268✔
1248
                r = uid_is_ok(c, (uid_t) i->gid, i->name, true);
40✔
1249
                if (r < 0)
40✔
1250
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1251
                if (r > 0) {
40✔
1252
                        i->uid = (uid_t) i->gid;
25✔
1253
                        i->uid_set = true;
25✔
1254
                }
1255
        }
1256

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

1261
                for (;;) {
15✔
1262
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
15✔
1263
                        if (r < 0)
15✔
1264
                                return log_error_errno(r, "No free user ID available for %s.", i->name);
×
1265

1266
                        r = uid_is_ok(c, c->search_uid, i->name, true);
15✔
1267
                        if (r < 0)
15✔
1268
                                return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1269
                        else if (r > 0)
15✔
1270
                                break;
1271
                }
1272

1273
                i->uid_set = true;
15✔
1274
                i->uid = c->search_uid;
15✔
1275
        }
1276

1277
        r = ordered_hashmap_ensure_put(&c->todo_uids, NULL, UID_TO_PTR(i->uid), i);
268✔
1278
        if (r == -EEXIST)
268✔
1279
                return log_error_errno(r, "Requested user %s with UID " UID_FMT " and gid" GID_FMT " to be created is duplicated "
×
1280
                                       "or conflicts with another user.", i->name, i->uid, i->gid);
1281
        if (r == -ENOMEM)
268✔
1282
                return log_oom();
×
1283
        if (r < 0)
268✔
1284
                return log_error_errno(r, "Failed to store user %s with UID " UID_FMT " and GID " GID_FMT " to be created: %m",
×
1285
                                       i->name, i->uid, i->gid);
1286

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

1291
        return 0;
1292
}
1293

1294
static int gid_is_ok(
728✔
1295
                Context *c,
1296
                gid_t gid,
1297
                const char *groupname,
1298
                bool check_with_uid) {
1299

1300
        Item *user;
728✔
1301
        char *username;
728✔
1302
        int r;
728✔
1303

1304
        assert(c);
728✔
1305
        assert(groupname);
728✔
1306

1307
        if (ordered_hashmap_get(c->todo_gids, GID_TO_PTR(gid)))
728✔
1308
                return 0;
1309

1310
        /* Avoid reusing gids that are already used by a different user */
1311
        if (check_with_uid) {
663✔
1312
                user = ordered_hashmap_get(c->todo_uids, UID_TO_PTR(gid));
329✔
1313
                if (user && !streq(user->name, groupname))
329✔
1314
                        return 0;
1315
        }
1316

1317
        if (hashmap_contains(c->database_by_gid, GID_TO_PTR(gid)))
663✔
1318
                return 0;
1319

1320
        if (check_with_uid) {
517✔
1321
                username = hashmap_get(c->database_by_uid, UID_TO_PTR(gid));
183✔
1322
                if (username && !streq(username, groupname))
183✔
1323
                        return 0;
1324
        }
1325

1326
        if (!arg_root) {
517✔
1327
                r = getgrgid_malloc(gid, /* ret= */ NULL);
5✔
1328
                if (r >= 0)
5✔
1329
                        return 0;
1330
                if (r != -ESRCH)
5✔
1331
                        log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", gid);
×
1332

1333
                if (check_with_uid) {
5✔
1334
                        r = getpwuid_malloc(gid, /* ret= */ NULL);
5✔
1335
                        if (r >= 0)
5✔
1336
                                return 0;
1337
                        if (r != -ESRCH)
5✔
1338
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", gid);
×
1339
                }
1340
        }
1341

1342
        return 1;
1343
}
1344

1345
static int get_gid_by_name(
647✔
1346
                Context *c,
1347
                const char *name,
1348
                gid_t *ret_gid) {
1349

1350
        void *z;
647✔
1351
        int r;
647✔
1352

1353
        assert(c);
647✔
1354
        assert(ret_gid);
647✔
1355

1356
        /* Check the database directly */
1357
        z = hashmap_get(c->database_by_groupname, name);
647✔
1358
        if (z) {
647✔
1359
                *ret_gid = PTR_TO_GID(z);
69✔
1360
                return 0;
69✔
1361
        }
1362

1363
        /* Also check NSS */
1364
        if (!arg_root) {
578✔
1365
                _cleanup_free_ struct group *g = NULL;
5✔
1366

1367
                r = getgrnam_malloc(name, &g);
5✔
1368
                if (r >= 0) {
5✔
1369
                        *ret_gid = g->gr_gid;
×
1370
                        return 0;
×
1371
                }
1372
                if (r != -ESRCH)
5✔
1373
                        log_warning_errno(r, "Unexpected failure while looking up group '%s' via NSS, assuming it doesn't exist: %m", name);
5✔
1374
        }
1375

1376
        return -ENOENT;
1377
}
1378

1379
static int add_group(Context *c, Item *i) {
641✔
1380
        int r;
641✔
1381

1382
        assert(c);
641✔
1383
        assert(i);
641✔
1384

1385
        r = get_gid_by_name(c, i->name, &i->gid);
641✔
1386
        if (r != -ENOENT) {
641✔
1387
                if (r < 0)
64✔
1388
                        return r;
1389
                log_debug("Group %s already exists.", i->name);
64✔
1390
                i->gid_set = true;
64✔
1391
                return 0;
64✔
1392
        }
1393

1394
        /* Try to use the suggested numeric GID */
1395
        if (i->gid_set) {
577✔
1396
                r = gid_is_ok(c, i->gid, i->name, false);
394✔
1397
                if (r < 0)
394✔
1398
                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1399
                if (i->id_set_strict) {
394✔
1400
                        /* If we require the GID to already exist we can return here:
1401
                         * r > 0: means the GID does not exist -> fail
1402
                         * r == 0: means the GID exists -> nothing more to do.
1403
                         */
1404
                        if (r > 0)
61✔
1405
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
1406
                                                       "Failed to create %s: please create GID " GID_FMT,
1407
                                                       i->name, i->gid);
1408
                        if (r == 0)
60✔
1409
                                return 0;
1410
                }
1411
                if (r == 0) {
333✔
1412
                        log_info("Suggested group ID " GID_FMT " for %s already used.", i->gid, i->name);
×
1413
                        i->gid_set = false;
×
1414
                }
1415
        }
1416

1417
        /* Try to reuse the numeric uid, if there's one */
1418
        if (!i->gid_set && i->uid_set) {
516✔
1419
                r = gid_is_ok(c, (gid_t) i->uid, i->name, true);
158✔
1420
                if (r < 0)
158✔
1421
                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1422
                if (r > 0) {
158✔
1423
                        i->gid = (gid_t) i->uid;
153✔
1424
                        i->gid_set = true;
153✔
1425
                }
1426
        }
1427

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

1432
                if (read_id_from_file(i, NULL, &candidate) > 0) {
30✔
1433

1434
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
1435
                                log_debug("Group ID " GID_FMT " of file not suitable for %s.", candidate, i->name);
×
1436
                        else {
1437
                                r = gid_is_ok(c, candidate, i->name, true);
×
1438
                                if (r < 0)
×
1439
                                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1440
                                else if (r > 0) {
×
1441
                                        i->gid = candidate;
×
1442
                                        i->gid_set = true;
×
1443
                                } else
1444
                                        log_debug("Group ID " GID_FMT " of file for %s already used.", candidate, i->name);
×
1445
                        }
1446
                }
1447
        }
1448

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

1453
                for (;;) {
176✔
1454
                        /* We look for new GIDs in the UID pool! */
1455
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
176✔
1456
                        if (r < 0)
176✔
1457
                                return log_error_errno(r, "No free group ID available for %s.", i->name);
×
1458

1459
                        r = gid_is_ok(c, c->search_uid, i->name, true);
176✔
1460
                        if (r < 0)
176✔
1461
                                return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1462
                        else if (r > 0)
176✔
1463
                                break;
1464
                }
1465

1466
                i->gid_set = true;
30✔
1467
                i->gid = c->search_uid;
30✔
1468
        }
1469

1470
        r = ordered_hashmap_ensure_put(&c->todo_gids, NULL, GID_TO_PTR(i->gid), i);
516✔
1471
        if (r == -EEXIST)
516✔
1472
                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);
×
1473
        if (r == -ENOMEM)
516✔
1474
                return log_oom();
×
1475
        if (r < 0)
516✔
1476
                return log_error_errno(r, "Failed to store group %s with GID " GID_FMT " to be created: %m", i->name, i->gid);
×
1477

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

1481
        return 0;
1482
}
1483

1484
static int process_item(Context *c, Item *i) {
677✔
1485
        int r;
677✔
1486

1487
        assert(c);
677✔
1488
        assert(i);
677✔
1489

1490
        switch (i->type) {
677✔
1491

1492
        case ADD_USER: {
300✔
1493
                Item *j = NULL;
300✔
1494

1495
                if (!i->gid_set) {
300✔
1496
                        j = ordered_hashmap_get(c->groups, i->group_name ?: i->name);
236✔
1497

1498
                        /* If that's not a match, also check if the group name
1499
                         * matches a user name in the queue. */
1500
                        if (!j && i->group_name)
236✔
1501
                                j = ordered_hashmap_get(c->users, i->group_name);
11✔
1502
                }
1503

1504
                if (j && j->todo_group) {
236✔
1505
                        /* When a group with the target name is already in queue,
1506
                         * use the information about the group and do not create
1507
                         * duplicated group entry. */
1508
                        i->gid_set = j->gid_set;
30✔
1509
                        i->gid = j->gid;
30✔
1510
                        i->id_set_strict = true;
30✔
1511
                } else if (i->group_name) {
270✔
1512
                        /* When a group name was given instead of a GID and it's
1513
                         * not in queue, then it must already exist. */
1514
                        r = get_gid_by_name(c, i->group_name, &i->gid);
6✔
1515
                        if (r < 0)
6✔
1516
                                return log_error_errno(r, "Group %s not found.", i->group_name);
1✔
1517
                        i->gid_set = true;
5✔
1518
                        i->id_set_strict = true;
5✔
1519
                } else {
1520
                        r = add_group(c, i);
264✔
1521
                        if (r < 0)
264✔
1522
                                return r;
1523
                }
1524

1525
                return add_user(c, i);
298✔
1526
        }
1527

1528
        case ADD_GROUP:
377✔
1529
                return add_group(c, i);
377✔
1530

1531
        default:
×
1532
                assert_not_reached();
×
1533
        }
1534
}
1535

1536
static Item* item_free(Item *i) {
679✔
1537
        if (!i)
679✔
1538
                return NULL;
1539

1540
        free(i->name);
679✔
1541
        free(i->group_name);
679✔
1542
        free(i->uid_path);
679✔
1543
        free(i->gid_path);
679✔
1544
        free(i->description);
679✔
1545
        free(i->home);
679✔
1546
        free(i->shell);
679✔
1547
        free(i->filename);
679✔
1548
        return mfree(i);
679✔
1549
}
1550

1551
DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1,368✔
1552
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
677✔
1553

1554
static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
679✔
1555
        assert(name);
679✔
1556
        assert(!!filename == (line > 0));
679✔
1557

1558
        _cleanup_(item_freep) Item *new = new(Item, 1);
1,358✔
1559
        if (!new)
679✔
1560
                return NULL;
1561

1562
        *new = (Item) {
679✔
1563
                .type = type,
1564
                .line = line,
1565
        };
1566

1567
        if (free_and_strdup(&new->name, name) < 0 ||
1,358✔
1568
            free_and_strdup(&new->filename, filename) < 0)
679✔
1569
                return NULL;
×
1570

1571
        return TAKE_PTR(new);
679✔
1572
}
1573

1574
static int add_implicit(Context *c) {
113✔
1575
        char *g, **l;
113✔
1576
        int r;
113✔
1577

1578
        assert(c);
113✔
1579

1580
        /* Implicitly create additional users and groups, if they were listed in "m" lines */
1581
        ORDERED_HASHMAP_FOREACH_KEY(l, g, c->members) {
236✔
1582
                STRV_FOREACH(m, l)
20✔
1583
                        if (!ordered_hashmap_get(c->users, *m)) {
10✔
1584
                                _cleanup_(item_freep) Item *j =
×
1585
                                        item_new(ADD_USER, *m, /* filename= */ NULL, /* line= */ 0);
5✔
1586
                                if (!j)
5✔
1587
                                        return log_oom();
×
1588

1589
                                r = ordered_hashmap_ensure_put(&c->users, &item_hash_ops, j->name, j);
5✔
1590
                                if (r == -ENOMEM)
5✔
1591
                                        return log_oom();
×
1592
                                if (r < 0)
5✔
1593
                                        return log_error_errno(r, "Failed to add implicit user '%s': %m", j->name);
×
1594

1595
                                log_debug("Adding implicit user '%s' due to m line", j->name);
5✔
1596
                                TAKE_PTR(j);
5✔
1597
                        }
1598

1599
                if (!(ordered_hashmap_get(c->users, g) ||
10✔
1600
                      ordered_hashmap_get(c->groups, g))) {
2✔
1601
                        _cleanup_(item_freep) Item *j =
×
1602
                                item_new(ADD_GROUP, g, /* filename= */ NULL, /* line= */ 0);
×
1603
                        if (!j)
×
1604
                                return log_oom();
×
1605

1606
                        r = ordered_hashmap_ensure_put(&c->groups, &item_hash_ops, j->name, j);
×
1607
                        if (r == -ENOMEM)
×
1608
                                return log_oom();
×
1609
                        if (r < 0)
×
1610
                                return log_error_errno(r, "Failed to add implicit group '%s': %m", j->name);
×
1611

1612
                        log_debug("Adding implicit group '%s' due to m line", j->name);
×
1613
                        TAKE_PTR(j);
×
1614
                }
1615
        }
1616

1617
        return 0;
113✔
1618
}
1619

1620
static int item_equivalent(Item *a, Item *b) {
1✔
1621
        int r;
1✔
1622

1623
        assert(a);
1✔
1624
        assert(b);
1✔
1625

1626
        if (a->type != b->type) {
1✔
1627
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1628
                           "Item not equivalent because types differ");
1629
                return false;
×
1630
        }
1631

1632
        if (!streq_ptr(a->name, b->name)) {
1✔
1633
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1634
                           "Item not equivalent because names differ ('%s' vs. '%s')",
1635
                           a->name, b->name);
1636
                return false;
×
1637
        }
1638

1639
        /* Paths were simplified previously, so we can use streq. */
1640
        if (!streq_ptr(a->uid_path, b->uid_path)) {
1✔
1641
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1642
                           "Item not equivalent because UID paths differ (%s vs. %s)",
1643
                           a->uid_path ?: "(unset)", b->uid_path ?: "(unset)");
1644
                return false;
×
1645
        }
1646

1647
        if (!streq_ptr(a->gid_path, b->gid_path)) {
1✔
1648
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1649
                           "Item not equivalent because GID paths differ (%s vs. %s)",
1650
                           a->gid_path ?: "(unset)", b->gid_path ?: "(unset)");
1651
                return false;
×
1652
        }
1653

1654
        if (!streq_ptr(a->description, b->description))  {
1✔
1655
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1656
                           "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1657
                           strempty(a->description), strempty(b->description));
1658
                return false;
×
1659
        }
1660

1661
        if ((a->uid_set != b->uid_set) ||
1✔
1662
            (a->uid_set && a->uid != b->uid)) {
×
1663
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1664
                           "Item not equivalent because UIDs differ (%s vs. %s)",
1665
                           a->uid_set ? FORMAT_UID(a->uid) : "(unset)",
1666
                           b->uid_set ? FORMAT_UID(b->uid) : "(unset)");
1667
                return false;
×
1668
        }
1669

1670
        if ((a->gid_set != b->gid_set) ||
1✔
1671
            (a->gid_set && a->gid != b->gid)) {
1✔
1672
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1673
                           "Item not equivalent because GIDs differ (%s vs. %s)",
1674
                           a->gid_set ? FORMAT_GID(a->gid) : "(unset)",
1675
                           b->gid_set ? FORMAT_GID(b->gid) : "(unset)");
1676
                return false;
×
1677
        }
1678

1679
        if (!streq_ptr(a->home, b->home)) {
1✔
1680
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1681
                           "Item not equivalent because home directories differ ('%s' vs. '%s')",
1682
                           strempty(a->description), strempty(b->description));
1683
                return false;
×
1684
        }
1685

1686
        /* Check if the two paths refer to the same file.
1687
         * If the paths are equal (after normalization), it's obviously the same file.
1688
         * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1689
         * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1690
         * /usr/sbin/nologin).
1691
         * If we can't resolve something, treat different paths as different. */
1692

1693
        const char *a_shell = pick_shell(a),
1✔
1694
                   *b_shell = pick_shell(b);
1✔
1695
        if (!path_equal(a_shell, b_shell) &&
1✔
1696
            !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
×
1697
                _cleanup_free_ char *pa = NULL, *pb = NULL;
×
1698

1699
                r = chase(a_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pa, NULL);
×
1700
                if (r < 0) {
×
1701
                        log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
×
1702
                                       r, "Failed to look up path '%s%s%s': %m",
1703
                                       strempty(arg_root), arg_root ? "/" : "", a_shell);
1704
                        return ERRNO_IS_RESOURCE(r) ? r : false;
×
1705
                }
1706

1707
                r = chase(b_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pb, NULL);
×
1708
                if (r < 0) {
×
1709
                        log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
×
1710
                                       r, "Failed to look up path '%s%s%s': %m",
1711
                                       strempty(arg_root), arg_root ? "/" : "", b_shell);
1712
                        return ERRNO_IS_RESOURCE(r) ? r : false;
×
1713
                }
1714

1715
                if (!path_equal(pa, pb)) {
×
1716
                        log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1717
                                   "Item not equivalent because shells differ ('%s' vs. '%s')",
1718
                                   pa, pb);
1719
                        return false;
×
1720
                }
1721
        }
1722

1723
        return true;
1724
}
1725

1726
static int parse_line(
684✔
1727
                const char *fname,
1728
                unsigned line,
1729
                const char *buffer,
1730
                bool *invalid_config,
1731
                void *context) {
1732

1733
        Context *c = ASSERT_PTR(context);
684✔
1734
        _cleanup_free_ char *action = NULL,
1,368✔
1735
                *name = NULL, *resolved_name = NULL,
×
1736
                *id = NULL, *resolved_id = NULL,
×
1737
                *description = NULL, *resolved_description = NULL,
×
1738
                *home = NULL, *resolved_home = NULL,
×
1739
                *shell = NULL, *resolved_shell = NULL;
684✔
1740
        _cleanup_(item_freep) Item *i = NULL;
684✔
1741
        Item *existing;
684✔
1742
        OrderedHashmap *h;
684✔
1743
        int r;
684✔
1744
        const char *p;
684✔
1745

1746
        assert(fname);
684✔
1747
        assert(line >= 1);
684✔
1748
        assert(buffer);
684✔
1749
        assert(!invalid_config); /* We don't support invalid_config yet. */
684✔
1750

1751
        /* Parse columns */
1752
        p = buffer;
684✔
1753
        r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
684✔
1754
                               &action, &name, &id, &description, &home, &shell);
1755
        if (r < 0)
684✔
1756
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Syntax error.");
×
1757
        if (r < 2)
684✔
1758
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1759
                                  "Missing action and name columns.");
1760
        if (!isempty(p))
684✔
1761
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1762
                                  "Trailing garbage.");
1763

1764
        if (isempty(action))
684✔
1765
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1766
                                  "Empty command specification.");
1767

1768
        bool locked = false;
1769
        for (int pos = 1; action[pos]; pos++)
702✔
1770
                if (action[pos] == '!' && !locked)
18✔
1771
                        locked = true;
18✔
1772
                else
1773
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1774
                                          "Unknown modifiers in command '%s'.", action);
1775

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

1780
        /* Verify name */
1781
        if (empty_or_dash(name))
684✔
1782
                name = mfree(name);
×
1783

1784
        if (name) {
684✔
1785
                r = specifier_printf(name, NAME_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_name);
684✔
1786
                if (r < 0)
684✔
1787
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", name);
×
1788

1789
                if (!valid_user_group_name(resolved_name, 0))
684✔
1790
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1791
                                          "'%s' is not a valid user or group name.", resolved_name);
1792
        }
1793

1794
        /* Verify id */
1795
        if (empty_or_dash(id))
684✔
1796
                id = mfree(id);
57✔
1797

1798
        if (id) {
684✔
1799
                r = specifier_printf(id, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_id);
627✔
1800
                if (r < 0)
627✔
1801
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1802
                                          "Failed to replace specifiers in '%s': %m", name);
1803
        }
1804

1805
        /* Verify description */
1806
        if (empty_or_dash(description))
684✔
1807
                description = mfree(description);
632✔
1808

1809
        if (description) {
684✔
1810
                r = specifier_printf(description, LONG_LINE_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_description);
52✔
1811
                if (r < 0)
52✔
1812
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1813
                                          "Failed to replace specifiers in '%s': %m", description);
1814

1815
                if (!valid_gecos(resolved_description))
52✔
1816
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1817
                                          "'%s' is not a valid GECOS field.", resolved_description);
1818
        }
1819

1820
        /* Verify home */
1821
        if (empty_or_dash(home))
684✔
1822
                home = mfree(home);
544✔
1823

1824
        if (home) {
684✔
1825
                r = specifier_printf(home, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_home);
140✔
1826
                if (r < 0)
140✔
1827
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1828
                                          "Failed to replace specifiers in '%s': %m", home);
1829

1830
                path_simplify(resolved_home);
140✔
1831

1832
                if (!valid_home(resolved_home))
140✔
1833
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1834
                                          "'%s' is not a valid home directory field.", resolved_home);
1835
        }
1836

1837
        /* Verify shell */
1838
        if (empty_or_dash(shell))
684✔
1839
                shell = mfree(shell);
663✔
1840

1841
        if (shell) {
684✔
1842
                r = specifier_printf(shell, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_shell);
21✔
1843
                if (r < 0)
21✔
1844
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1845
                                          "Failed to replace specifiers in '%s': %m", shell);
1846

1847
                path_simplify(resolved_shell);
21✔
1848

1849
                if (!valid_shell(resolved_shell))
21✔
1850
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1851
                                          "'%s' is not a valid login shell field.", resolved_shell);
1852
        }
1853

1854
        switch (action[0]) {
684✔
1855

1856
        case ADD_RANGE:
×
1857
                if (locked)
×
1858
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1859
                                          "Flag '!' not permitted on lines of type 'r'.");
1860

1861
                if (resolved_name)
×
1862
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1863
                                          "Lines of type 'r' don't take a name field.");
1864

1865
                if (!resolved_id)
×
1866
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1867
                                          "Lines of type 'r' require an ID range in the third field.");
1868

1869
                if (description || home || shell)
×
1870
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1871
                                          "Lines of type '%c' don't take a %s field.",
1872
                                          action[0],
1873
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1874

1875
                r = uid_range_add_str(&c->uid_range, resolved_id);
×
1876
                if (r < 0)
×
1877
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1878
                                          "Invalid UID range %s.", resolved_id);
1879

1880
                return 0;
1881

1882
        case ADD_MEMBER: {
10✔
1883
                /* Try to extend an existing member or group item */
1884
                if (!name)
10✔
1885
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1886
                                          "Lines of type 'm' require a user name in the second field.");
1887

1888
                if (locked)
10✔
1889
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1890
                                          "Flag '!' not permitted on lines of type 'm'.");
1891

1892
                if (!resolved_id)
10✔
1893
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1894
                                          "Lines of type 'm' require a group name in the third field.");
1895

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

1900
                if (description || home || shell)
10✔
1901
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1902
                                          "Lines of type '%c' don't take a %s field.",
1903
                                          action[0],
1904
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1905

1906
                r = string_strv_ordered_hashmap_put(&c->members, resolved_id, resolved_name);
10✔
1907
                if (r < 0)
10✔
1908
                        return log_error_errno(r, "Failed to store mapping for %s: %m", resolved_id);
×
1909

1910
                return 0;
1911
        }
1912

1913
        case ADD_USER:
296✔
1914
                if (!name)
296✔
1915
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1916
                                          "Lines of type 'u' require a user name in the second field.");
1917

1918
                r = ordered_hashmap_ensure_allocated(&c->users, &item_hash_ops);
296✔
1919
                if (r < 0)
296✔
1920
                        return log_oom();
×
1921

1922
                i = item_new(ADD_USER, resolved_name, fname, line);
296✔
1923
                if (!i)
296✔
1924
                        return log_oom();
×
1925

1926
                if (resolved_id) {
296✔
1927
                        if (path_is_absolute(resolved_id))
266✔
1928
                                i->uid_path = path_simplify(TAKE_PTR(resolved_id));
×
1929
                        else {
1930
                                _cleanup_free_ char *uid = NULL, *gid = NULL;
266✔
1931
                                if (split_pair(resolved_id, ":", &uid, &gid) == 0) {
266✔
1932
                                        r = parse_gid(gid, &i->gid);
90✔
1933
                                        if (r < 0) {
90✔
1934
                                                if (valid_user_group_name(gid, 0))
26✔
1935
                                                        i->group_name = TAKE_PTR(gid);
26✔
1936
                                                else
1937
                                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1938
                                                                          "Failed to parse GID: '%s': %m", id);
1939
                                        } else {
1940
                                                i->gid_set = true;
64✔
1941
                                                i->id_set_strict = true;
64✔
1942
                                        }
1943
                                        free_and_replace(resolved_id, uid);
90✔
1944
                                }
1945
                                if (!streq(resolved_id, "-")) {
266✔
1946
                                        r = parse_uid(resolved_id, &i->uid);
251✔
1947
                                        if (r < 0)
251✔
1948
                                                return log_syntax(NULL, LOG_ERR, fname, line, r,
1✔
1949
                                                                  "Failed to parse UID: '%s': %m", id);
1950
                                        i->uid_set = true;
250✔
1951
                                }
1952
                        }
1953
                }
1954

1955
                i->description = TAKE_PTR(resolved_description);
295✔
1956
                i->home = TAKE_PTR(resolved_home);
295✔
1957
                i->shell = TAKE_PTR(resolved_shell);
295✔
1958
                i->locked = locked;
295✔
1959

1960
                h = c->users;
295✔
1961
                break;
295✔
1962

1963
        case ADD_GROUP:
378✔
1964
                if (!name)
378✔
1965
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1966
                                          "Lines of type 'g' require a user name in the second field.");
1967

1968
                if (locked)
378✔
1969
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1970
                                          "Flag '!' not permitted on lines of type 'g'.");
1971

1972
                if (description || home || shell)
378✔
1973
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1974
                                          "Lines of type '%c' don't take a %s field.",
1975
                                          action[0],
1976
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1977

1978
                r = ordered_hashmap_ensure_allocated(&c->groups, &item_hash_ops);
378✔
1979
                if (r < 0)
378✔
1980
                        return log_oom();
×
1981

1982
                i = item_new(ADD_GROUP, resolved_name, fname, line);
378✔
1983
                if (!i)
378✔
1984
                        return log_oom();
×
1985

1986
                if (resolved_id) {
378✔
1987
                        if (path_is_absolute(resolved_id))
351✔
1988
                                i->gid_path = path_simplify(TAKE_PTR(resolved_id));
×
1989
                        else {
1990
                                r = parse_gid(resolved_id, &i->gid);
351✔
1991
                                if (r < 0)
351✔
1992
                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1993
                                                          "Failed to parse GID: '%s': %m", id);
1994

1995
                                i->gid_set = true;
351✔
1996
                        }
1997
                }
1998

1999
                h = c->groups;
378✔
2000
                break;
378✔
2001

2002
        default:
×
2003
                assert_not_reached();
×
2004
        }
2005

2006
        existing = ordered_hashmap_get(h, i->name);
673✔
2007
        if (existing) {
673✔
2008
                /* Two functionally-equivalent items are fine */
2009
                r = item_equivalent(i, existing);
1✔
2010
                if (r < 0)
1✔
2011
                        return r;
2012
                if (r == 0) {
1✔
2013
                        if (existing->filename)
×
2014
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
2015
                                           "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
2016
                                           item_type_to_string(i->type),
2017
                                           i->name,
2018
                                           existing->filename, existing->line);
2019
                        else
2020
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
2021
                                           "Conflict with earlier configuration for %s '%s', ignoring line.",
2022
                                           item_type_to_string(i->type),
2023
                                           i->name);
2024
                }
2025

2026
                return 0;
1✔
2027
        }
2028

2029
        r = ordered_hashmap_put(h, i->name, i);
672✔
2030
        if (r < 0)
672✔
2031
                return log_oom();
×
2032

2033
        i = NULL;
672✔
2034
        return 0;
672✔
2035
}
2036

2037
static int read_config_file(Context *c, const char *fn, bool ignore_enoent) {
133✔
2038
        return conf_file_read(
399✔
2039
                        arg_root,
2040
                        (const char**) CONF_PATHS_STRV("sysusers.d"),
133✔
2041
                        ASSERT_PTR(fn),
133✔
2042
                        parse_line,
2043
                        ASSERT_PTR(c),
133✔
2044
                        ignore_enoent,
2045
                        /* invalid_config= */ NULL);
2046
}
2047

2048
static int cat_config(void) {
×
2049
        _cleanup_strv_free_ char **files = NULL;
×
2050
        int r;
×
2051

2052
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
×
2053
        if (r < 0)
×
2054
                return r;
2055

2056
        pager_open(arg_pager_flags);
×
2057

2058
        return cat_files(NULL, files, arg_cat_flags);
×
2059
}
2060

2061
static int help(void) {
×
2062
        _cleanup_free_ char *link = NULL;
×
2063
        int r;
×
2064

2065
        r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
×
2066
        if (r < 0)
×
2067
                return log_oom();
×
2068

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

2091
        return 0;
2092
}
2093

2094
static int parse_argv(int argc, char *argv[]) {
113✔
2095

2096
        enum {
113✔
2097
                ARG_VERSION = 0x100,
2098
                ARG_CAT_CONFIG,
2099
                ARG_TLDR,
2100
                ARG_ROOT,
2101
                ARG_IMAGE,
2102
                ARG_IMAGE_POLICY,
2103
                ARG_REPLACE,
2104
                ARG_DRY_RUN,
2105
                ARG_INLINE,
2106
                ARG_NO_PAGER,
2107
        };
2108

2109
        static const struct option options[] = {
113✔
2110
                { "help",         no_argument,       NULL, 'h'              },
2111
                { "version",      no_argument,       NULL, ARG_VERSION      },
2112
                { "cat-config",   no_argument,       NULL, ARG_CAT_CONFIG   },
2113
                { "tldr",         no_argument,       NULL, ARG_TLDR         },
2114
                { "root",         required_argument, NULL, ARG_ROOT         },
2115
                { "image",        required_argument, NULL, ARG_IMAGE        },
2116
                { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
2117
                { "replace",      required_argument, NULL, ARG_REPLACE      },
2118
                { "dry-run",      no_argument,       NULL, ARG_DRY_RUN      },
2119
                { "inline",       no_argument,       NULL, ARG_INLINE       },
2120
                { "no-pager",     no_argument,       NULL, ARG_NO_PAGER     },
2121
                {}
2122
        };
2123

2124
        int c, r;
113✔
2125

2126
        assert(argc >= 0);
113✔
2127
        assert(argv);
113✔
2128

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

2131
                switch (c) {
147✔
2132

2133
                case 'h':
×
2134
                        return help();
×
2135

2136
                case ARG_VERSION:
×
2137
                        return version();
×
2138

2139
                case ARG_CAT_CONFIG:
×
2140
                        arg_cat_flags = CAT_CONFIG_ON;
×
2141
                        break;
×
2142

2143
                case ARG_TLDR:
×
2144
                        arg_cat_flags = CAT_TLDR;
×
2145
                        break;
×
2146

2147
                case ARG_ROOT:
108✔
2148
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
108✔
2149
                        if (r < 0)
108✔
2150
                                return r;
2151
                        break;
2152

2153
                case ARG_IMAGE:
×
UNCOV
2154
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
UNCOV
2155
                        if (r < 0)
×
2156
                                return r;
2157
                        break;
2158

2159
                case ARG_IMAGE_POLICY:
×
UNCOV
2160
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
UNCOV
2161
                        if (r < 0)
×
2162
                                return r;
2163
                        break;
2164

2165
                case ARG_REPLACE:
35✔
2166
                        if (!path_is_absolute(optarg))
35✔
UNCOV
2167
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2168
                                                       "The argument to --replace= must be an absolute path.");
2169
                        if (!endswith(optarg, ".conf"))
35✔
UNCOV
2170
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2171
                                                       "The argument to --replace= must have the extension '.conf'.");
2172

2173
                        arg_replace = optarg;
35✔
2174
                        break;
35✔
2175

UNCOV
2176
                case ARG_DRY_RUN:
×
UNCOV
2177
                        arg_dry_run = true;
×
UNCOV
2178
                        break;
×
2179

2180
                case ARG_INLINE:
4✔
2181
                        arg_inline = true;
4✔
2182
                        break;
4✔
2183

UNCOV
2184
                case ARG_NO_PAGER:
×
UNCOV
2185
                        arg_pager_flags |= PAGER_DISABLE;
×
UNCOV
2186
                        break;
×
2187

2188
                case '?':
2189
                        return -EINVAL;
2190

2191
                default:
×
UNCOV
2192
                        assert_not_reached();
×
2193
                }
2194

2195
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
113✔
2196
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2197
                                       "Option --replace= is not supported with --cat-config/--tldr.");
2198

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

2203
        if (arg_image && arg_root)
113✔
UNCOV
2204
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2205
                                       "Use either --root= or --image=, the combination of both is not supported.");
2206

2207
        return 1;
2208
}
2209

2210
static int parse_arguments(Context *c, char **args) {
41✔
2211
        unsigned pos = 1;
41✔
2212
        int r;
41✔
2213

2214
        assert(c);
41✔
2215

2216
        STRV_FOREACH(arg, args) {
85✔
2217
                if (arg_inline)
44✔
2218
                        /* Use (argument):n, where n==1 for the first positional arg */
2219
                        r = parse_line("(argument)", pos, *arg, /* invalid_config= */ NULL, c);
7✔
2220
                else
2221
                        r = read_config_file(c, *arg, /* ignore_enoent= */ false);
37✔
2222
                if (r < 0)
44✔
2223
                        return r;
2224

2225
                pos++;
44✔
2226
        }
2227

2228
        return 0;
2229
}
2230

2231
static int read_config_files(Context *c, char **args) {
90✔
UNCOV
2232
        _cleanup_strv_free_ char **files = NULL;
×
2233
        _cleanup_free_ char *p = NULL;
90✔
2234
        int r;
90✔
2235

2236
        assert(c);
90✔
2237

2238
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
90✔
2239
        if (r < 0)
90✔
2240
                return r;
2241

2242
        STRV_FOREACH(f, files)
203✔
2243
                if (p && path_equal(*f, p)) {
113✔
2244
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
18✔
2245

2246
                        r = parse_arguments(c, args);
18✔
2247
                        if (r < 0)
18✔
2248
                                return r;
2249
                } else {
2250
                        log_debug("Reading config file \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
118✔
2251

2252
                        /* Just warn, ignore result otherwise */
2253
                        (void) read_config_file(c, *f, /* ignore_enoent= */ true);
95✔
2254
                }
2255

2256
        return 0;
2257
}
2258

2259
static int read_credential_lines(Context *c) {
113✔
2260
        _cleanup_free_ char *j = NULL;
113✔
2261
        const char *d;
113✔
2262
        int r;
113✔
2263

2264
        assert(c);
113✔
2265

2266
        r = get_credentials_dir(&d);
113✔
2267
        if (r == -ENXIO)
113✔
2268
                return 0;
2269
        if (r < 0)
1✔
UNCOV
2270
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
2271

2272
        j = path_join(d, "sysusers.extra");
1✔
2273
        if (!j)
1✔
UNCOV
2274
                return log_oom();
×
2275

2276
        (void) read_config_file(c, j, /* ignore_enoent= */ true);
1✔
2277
        return 0;
2278
}
2279

2280
static int run(int argc, char *argv[]) {
113✔
2281
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
113✔
UNCOV
2282
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
×
2283
        _cleanup_close_ int lock = -EBADF;
113✔
2284
        _cleanup_(context_done) Context c = {
113✔
2285
                .audit_fd = -EBADF,
2286
                .search_uid = UID_INVALID,
2287
        };
2288

2289
        Item *i;
113✔
2290
        int r;
113✔
2291

2292
        r = parse_argv(argc, argv);
113✔
2293
        if (r <= 0)
113✔
2294
                return r;
2295

2296
        log_setup();
113✔
2297

2298
        if (arg_cat_flags != CAT_CONFIG_OFF)
113✔
UNCOV
2299
                return cat_config();
×
2300

2301
        if (should_bypass("SYSTEMD_SYSUSERS"))
113✔
2302
                return 0;
2303

2304
        umask(0022);
113✔
2305

2306
        r = mac_init();
113✔
2307
        if (r < 0)
113✔
2308
                return r;
2309

2310
        if (arg_image) {
113✔
UNCOV
2311
                assert(!arg_root);
×
2312

UNCOV
2313
                r = mount_image_privately_interactively(
×
2314
                                arg_image,
2315
                                arg_image_policy,
2316
                                DISSECT_IMAGE_GENERIC_ROOT |
2317
                                DISSECT_IMAGE_REQUIRE_ROOT |
2318
                                DISSECT_IMAGE_VALIDATE_OS |
2319
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
2320
                                DISSECT_IMAGE_FSCK |
2321
                                DISSECT_IMAGE_GROWFS |
2322
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
2323
                                &mounted_dir,
2324
                                /* ret_dir_fd= */ NULL,
2325
                                &loop_device);
UNCOV
2326
                if (r < 0)
×
2327
                        return r;
2328

UNCOV
2329
                arg_root = strdup(mounted_dir);
×
UNCOV
2330
                if (!arg_root)
×
UNCOV
2331
                        return log_oom();
×
2332
        }
2333

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

2338
        /* If command line arguments are specified along with --replace, read all configuration files and
2339
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2340
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
2341
         * read configuration and execute it. */
2342
        if (arg_replace || optind >= argc)
113✔
2343
                r = read_config_files(&c, argv + optind);
90✔
2344
        else
2345
                r = parse_arguments(&c, argv + optind);
23✔
2346
        if (r < 0)
113✔
2347
                return r;
2348

2349
        r = read_credential_lines(&c);
113✔
2350
        if (r < 0)
113✔
2351
                return r;
2352

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

2361
        if (!c.uid_range) {
113✔
2362
                /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2363
                r = read_login_defs(&c.login_defs, NULL, arg_root);
113✔
2364
                if (r < 0)
113✔
UNCOV
2365
                        return log_error_errno(r, "Failed to read %s%s: %m",
×
2366
                                               strempty(arg_root), "/etc/login.defs");
2367

2368
                c.login_defs_need_warning = true;
113✔
2369

2370
                /* We pick a range that very conservative: we look at compiled-in maximum and the value in
2371
                 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
2372
                 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2373
                 * it's only used during allocation, so we use the configured value directly). */
2374
                uid_t begin = c.login_defs.system_alloc_uid_min,
113✔
2375
                      end = MIN3((uid_t) SYSTEM_UID_MAX, c.login_defs.system_uid_max, c.login_defs.system_gid_max);
113✔
2376
                if (begin < end) {
113✔
2377
                        r = uid_range_add(&c.uid_range, begin, end - begin + 1);
113✔
2378
                        if (r < 0)
113✔
UNCOV
2379
                                return log_oom();
×
2380
                }
2381
        }
2382

2383
        r = add_implicit(&c);
113✔
2384
        if (r < 0)
113✔
2385
                return r;
2386

2387
        if (!arg_dry_run) {
113✔
2388
                lock = take_etc_passwd_lock(arg_root);
113✔
2389
                if (lock < 0)
113✔
2390
                        return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
×
2391
        }
2392

2393
        r = load_user_database(&c);
113✔
2394
        if (r < 0)
113✔
UNCOV
2395
                return log_error_errno(r, "Failed to load user database: %m");
×
2396

2397
        r = load_group_database(&c);
113✔
2398
        if (r < 0)
113✔
UNCOV
2399
                return log_error_errno(r, "Failed to read group database: %m");
×
2400

2401
        ORDERED_HASHMAP_FOREACH(i, c.groups)
490✔
2402
                (void) process_item(&c, i);
377✔
2403

2404
        ORDERED_HASHMAP_FOREACH(i, c.users)
413✔
2405
                (void) process_item(&c, i);
300✔
2406

2407
        return write_files(&c);
113✔
2408
}
2409

2410
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