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

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 hits per line

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

72.18
/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
#if HAVE_AUDIT
8
#  include <libaudit.h>
9
#endif
10

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

51
typedef enum ItemType {
52
        ADD_USER =   'u',
53
        ADD_GROUP =  'g',
54
        ADD_MEMBER = 'm',
55
        ADD_RANGE =  'r',
56
} ItemType;
57

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

73
typedef struct Item {
74
        ItemType type;
75

76
        char *name;
77
        char *group_name;
78
        char *uid_path;
79
        char *gid_path;
80
        char *description;
81
        char *home;
82
        char *shell;
83

84
        gid_t gid;
85
        uid_t uid;
86

87
        char *filename;
88
        unsigned line;
89

90
        bool gid_set;
91

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

97
        bool uid_set;
98

99
        bool locked;
100

101
        bool todo_user;
102
        bool todo_group;
103
} Item;
104

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

114
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
113✔
115
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
113✔
116
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
113✔
117

118
typedef struct Context {
119
        int audit_fd;
120

121
        OrderedHashmap *users, *groups;
122
        OrderedHashmap *todo_uids, *todo_gids;
123
        OrderedHashmap *members;
124

125
        Hashmap *database_by_uid, *database_by_username;
126
        Hashmap *database_by_gid, *database_by_groupname;
127

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

131
        uid_t search_uid;
132
        UIDRange *uid_range;
133

134
        UGIDAllocationRange login_defs;
135
        bool login_defs_need_warning;
136
} Context;
137

138
static void context_done(Context *c) {
113✔
139
        assert(c);
113✔
140

141
        c->audit_fd = close_audit_fd(c->audit_fd);
113✔
142

143
        ordered_hashmap_free(c->groups);
113✔
144
        ordered_hashmap_free(c->users);
113✔
145
        ordered_hashmap_free(c->members);
113✔
146
        ordered_hashmap_free(c->todo_uids);
113✔
147
        ordered_hashmap_free(c->todo_gids);
113✔
148

149
        hashmap_free(c->database_by_uid);
113✔
150
        hashmap_free(c->database_by_username);
113✔
151
        hashmap_free(c->database_by_gid);
113✔
152
        hashmap_free(c->database_by_groupname);
113✔
153

154
        set_free(c->names);
113✔
155
        uid_range_free(c->uid_range);
113✔
156
}
113✔
157

158
static void maybe_emit_login_defs_warning(Context *c) {
45✔
159
        assert(c);
45✔
160

161
        if (!c->login_defs_need_warning)
45✔
162
                return;
163

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

177
        c->login_defs_need_warning = false;
44✔
178
}
179

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

185
        if (arg_dry_run || c->audit_fd < 0)
226✔
186
                return;
226✔
187

188
        Item *i;
×
189
        int type = what == ADD_USER ? AUDIT_ADD_USER : AUDIT_ADD_GROUP;
×
190
        const char *op = what == ADD_USER ? "adding-user" : "adding-group";
×
191

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

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

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

228
        assert(c);
113✔
229

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

236
        while ((r = fgetpwent_sane(f, &pw)) > 0) {
254✔
237

238
                char *n = strdup(pw->pw_name);
217✔
239
                if (!n)
217✔
240
                        return -ENOMEM;
241

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

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

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

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

271
        assert(c);
113✔
272

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

279
        while ((r = fgetgrent_sane(f, &gr)) > 0) {
457✔
280
                char *n = strdup(gr->gr_name);
420✔
281
                if (!n)
420✔
282
                        return -ENOMEM;
283

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

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

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

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

315
        assert(target);
348✔
316
        assert(x);
348✔
317

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

323
                return -errno;
×
324
        }
325

326
        if (fstat(src, &st) < 0)
36✔
327
                return -errno;
×
328

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

337
        r = copy_bytes(src, fileno(dst), UINT64_MAX, COPY_REFLINK);
36✔
338
        if (r < 0)
36✔
339
                return r;
340

341
        backup = strjoina(x, "-");
180✔
342

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

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

352
        r = fsync_full(fileno(dst));
36✔
353
        if (r < 0)
36✔
354
                return r;
355

356
        if (rename(dst_tmp, backup) < 0)
36✔
357
                return errno;
×
358

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

363
static int putgrent_with_members(
753✔
364
                Context *c,
365
                const struct group *gr,
366
                FILE *group) {
367

368
        char **a;
753✔
369
        int r;
753✔
370

371
        assert(c);
753✔
372
        assert(gr);
753✔
373
        assert(group);
753✔
374

375
        a = ordered_hashmap_get(c->members, gr->gr_name);
753✔
376
        if (a) {
753✔
377
                _cleanup_strv_free_ char **l = NULL;
10✔
378
                bool added = false;
10✔
379

380
                l = strv_copy(gr->gr_mem);
10✔
381
                if (!l)
10✔
382
                        return -ENOMEM;
383

384
                STRV_FOREACH(i, a) {
20✔
385
                        if (strv_contains(l, *i))
10✔
386
                                continue;
5✔
387

388
                        r = strv_extend(&l, *i);
5✔
389
                        if (r < 0)
5✔
390
                                return r;
391

392
                        added = true;
393
                }
394

395
                if (added) {
10✔
396
                        struct group t;
5✔
397

398
                        strv_sort_uniq(l);
5✔
399

400
                        t = *gr;
5✔
401
                        t.gr_mem = l;
5✔
402

403
                        r = putgrent_sane(&t, group);
5✔
404
                        return r < 0 ? r : 1;
10✔
405
                }
406
        }
407

408
        return putgrent_sane(gr, group);
748✔
409
}
410

411
#if ENABLE_GSHADOW
412
static int putsgent_with_members(
743✔
413
                Context *c,
414
                const struct sgrp *sg,
415
                FILE *gshadow) {
416

417
        char **a;
743✔
418
        int r;
743✔
419

420
        assert(sg);
743✔
421
        assert(gshadow);
743✔
422

423
        a = ordered_hashmap_get(c->members, sg->sg_namp);
743✔
424
        if (a) {
743✔
425
                _cleanup_strv_free_ char **l = NULL;
10✔
426
                bool added = false;
10✔
427

428
                l = strv_copy(sg->sg_mem);
10✔
429
                if (!l)
10✔
430
                        return -ENOMEM;
431

432
                STRV_FOREACH(i, a) {
20✔
433
                        if (strv_contains(l, *i))
10✔
434
                                continue;
5✔
435

436
                        r = strv_extend(&l, *i);
5✔
437
                        if (r < 0)
5✔
438
                                return r;
439

440
                        added = true;
441
                }
442

443
                if (added) {
10✔
444
                        struct sgrp t;
5✔
445

446
                        strv_sort_uniq(l);
5✔
447

448
                        t = *sg;
5✔
449
                        t.sg_mem = l;
5✔
450

451
                        r = putsgent_sane(&t, gshadow);
5✔
452
                        return r < 0 ? r : 1;
10✔
453
                }
454
        }
455

456
        return putsgent_sane(sg, gshadow);
738✔
457
}
458
#endif
459

460
static const char* pick_shell(const Item *i) {
270✔
461
        assert(i);
270✔
462

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

472
static int write_temporary_passwd(
113✔
473
                Context *c,
474
                const char *passwd_path,
475
                FILE **ret_tmpfile,
476
                char **ret_tmpfile_path) {
477

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

484
        assert(c);
113✔
485

486
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
487
                return 0;
488

489
        if (arg_dry_run) {
87✔
490
                log_info("Would write /etc/passwd%s", glyph(GLYPH_ELLIPSIS));
×
491
                return 0;
×
492
        }
493

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

498
        original = fopen(passwd_path, "re");
87✔
499
        if (original) {
87✔
500

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

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

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

522
                        /* Make sure we keep the NIS entries (if any) at the end. */
523
                        if (IN_SET(pw->pw_name[0], '+', '-'))
129✔
524
                                break;
525

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

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

541
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
355✔
542
                _cleanup_free_ char *creds_shell = NULL, *cn = NULL;
268✔
543

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

550
                        /* "x" means the password is stored in the shadow file */
551
                        .pw_passwd = (char*) PASSWORD_SEE_SHADOW,
552

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

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

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

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

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

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

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

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

596
        *ret_tmpfile = TAKE_PTR(passwd);
87✔
597
        *ret_tmpfile_path = TAKE_PTR(passwd_tmp);
87✔
598

599
        return 0;
87✔
600
}
601

602
static usec_t epoch_or_now(void) {
87✔
603
        uint64_t epoch;
87✔
604

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

611
        return now(CLOCK_REALTIME);
87✔
612
}
613

614
static int write_temporary_shadow(
113✔
615
                Context *c,
616
                const char *shadow_path,
617
                FILE **ret_tmpfile,
618
                char **ret_tmpfile_path) {
619

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

627
        assert(c);
113✔
628

629
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
630
                return 0;
631

632
        if (arg_dry_run) {
87✔
633
                log_info("Would write /etc/shadow%s", glyph(GLYPH_ELLIPSIS));
×
634
                return 0;
×
635
        }
636

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

641
        lstchg = (long) (epoch_or_now() / USEC_PER_DAY);
87✔
642

643
        original = fopen(shadow_path, "re");
87✔
644
        if (original) {
87✔
645

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

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

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

663
                        /* Make sure we keep the NIS entries (if any) at the end. */
664
                        if (IN_SET(sp->sp_namp[0], '+', '-'))
99✔
665
                                break;
666

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

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

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

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

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

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

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

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

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

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

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

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

743
        *ret_tmpfile = TAKE_PTR(shadow);
87✔
744
        *ret_tmpfile_path = TAKE_PTR(shadow_tmp);
87✔
745

746
        return 0;
87✔
747
}
748

749
static int write_temporary_group(
113✔
750
                Context *c,
751
                const char *group_path,
752
                FILE **ret_tmpfile,
753
                char **ret_tmpfile_path) {
754

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

762
        assert(c);
113✔
763

764
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
765
                return 0;
766

767
        if (arg_dry_run) {
87✔
768
                log_info("Would write /etc/group%s", glyph(GLYPH_ELLIPSIS));
×
769
                return 0;
×
770
        }
771

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

776
        original = fopen(group_path, "re");
87✔
777
        if (original) {
87✔
778

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

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

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

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

801
                        /* Make sure we keep the NIS entries (if any) at the end. */
802
                        if (IN_SET(gr->gr_name[0], '+', '-'))
242✔
803
                                break;
804

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

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

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

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

834
                group_changed = true;
516✔
835
        }
836

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

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

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

855
        if (group_changed) {
87✔
856
                *ret_tmpfile = TAKE_PTR(group);
87✔
857
                *ret_tmpfile_path = TAKE_PTR(group_tmp);
87✔
858
        }
859
        return 0;
860
}
861

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

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

875
        assert(c);
113✔
876

877
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
878
                return 0;
879

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

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

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

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

898
                while ((r = fgetsgent_sane(original, &sg)) > 0) {
231✔
899

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

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

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

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

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

934
                group_changed = true;
516✔
935
        }
936

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

941
        if (group_changed) {
87✔
942
                *ret_tmpfile = TAKE_PTR(gshadow);
87✔
943
                *ret_tmpfile_path = TAKE_PTR(gshadow_tmp);
87✔
944
        }
945
#endif
946
        return 0;
947
}
948

949
static int write_files(Context *c) {
113✔
950
        _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;
339✔
951
        _cleanup_(unlink_and_freep) char *passwd_tmp = NULL, *group_tmp = NULL, *shadow_tmp = NULL, *gshadow_tmp = NULL;
113✔
952
        int r;
113✔
953

954
        _cleanup_free_ char *passwd_path = path_join(arg_root, "/etc/passwd");
226✔
955
        if (!passwd_path)
113✔
956
                return log_oom();
×
957

958
        _cleanup_free_ char *shadow_path = path_join(arg_root, "/etc/shadow");
226✔
959
        if (!shadow_path)
113✔
960
                return log_oom();
×
961

962
        _cleanup_free_ char *group_path = path_join(arg_root, "/etc/group");
226✔
963
        if (!group_path)
113✔
964
                return log_oom();
×
965

966
        _cleanup_free_ char *gshadow_path = path_join(arg_root, "/etc/gshadow");
226✔
967
        if (!gshadow_path)
113✔
968
                return log_oom();
×
969

970
        assert(c);
113✔
971

972
        r = write_temporary_group(c, group_path, &group, &group_tmp);
113✔
973
        if (r < 0)
113✔
974
                return r;
975

976
        r = write_temporary_gshadow(c, gshadow_path, &gshadow, &gshadow_tmp);
113✔
977
        if (r < 0)
113✔
978
                return r;
979

980
        r = write_temporary_passwd(c, passwd_path, &passwd, &passwd_tmp);
113✔
981
        if (r < 0)
113✔
982
                return r;
983

984
        r = write_temporary_shadow(c, shadow_path, &shadow, &shadow_tmp);
113✔
985
        if (r < 0)
113✔
986
                return r;
987

988
        /* Make a backup of the old files */
989
        if (group) {
113✔
990
                r = make_backup("/etc/group", group_path);
87✔
991
                if (r < 0)
87✔
992
                        return log_error_errno(r, "Failed to backup %s: %m", group_path);
×
993
        }
994
        if (gshadow) {
113✔
995
                r = make_backup("/etc/gshadow", gshadow_path);
87✔
996
                if (r < 0)
87✔
997
                        return log_error_errno(r, "Failed to backup %s: %m", gshadow_path);
×
998
        }
999

1000
        if (passwd) {
113✔
1001
                r = make_backup("/etc/passwd", passwd_path);
87✔
1002
                if (r < 0)
87✔
1003
                        return log_error_errno(r, "Failed to backup %s: %m", passwd_path);
×
1004
        }
1005
        if (shadow) {
113✔
1006
                r = make_backup("/etc/shadow", shadow_path);
87✔
1007
                if (r < 0)
87✔
1008
                        return log_error_errno(r, "Failed to backup %s: %m", shadow_path);
×
1009
        }
1010

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

1027
                gshadow_tmp = mfree(gshadow_tmp);
87✔
1028
        }
1029

1030
        if (passwd) {
113✔
1031
                r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
87✔
1032
                if (r < 0)
87✔
1033
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1034
                                               passwd_tmp, passwd_path);
1035

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

1046
                shadow_tmp = mfree(shadow_tmp);
87✔
1047
        }
1048

1049
        return 0;
1050
}
1051

1052
static int uid_is_ok(
288✔
1053
                Context *c,
1054
                uid_t uid,
1055
                const char *name,
1056
                bool check_with_gid) {
1057

1058
        int r;
288✔
1059
        assert(c);
288✔
1060

1061
        /* Let's see if we already have assigned the UID a second time */
1062
        if (ordered_hashmap_get(c->todo_uids, UID_TO_PTR(uid)))
288✔
1063
                return 0;
1064

1065
        /* Try to avoid using uids that are already used by a group
1066
         * that doesn't have the same name as our new user. */
1067
        if (check_with_gid) {
283✔
1068
                Item *i;
203✔
1069

1070
                i = ordered_hashmap_get(c->todo_gids, GID_TO_PTR(uid));
203✔
1071
                if (i && !streq(i->name, name))
203✔
1072
                        return 0;
1073
        }
1074

1075
        /* Let's check the files directly */
1076
        if (hashmap_contains(c->database_by_uid, UID_TO_PTR(uid)))
273✔
1077
                return 0;
1078

1079
        if (check_with_gid) {
273✔
1080
                const char *n;
193✔
1081

1082
                n = hashmap_get(c->database_by_gid, GID_TO_PTR(uid));
193✔
1083
                if (n && !streq(n, name))
193✔
1084
                        return 0;
1085
        }
1086

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

1091
                r = getpwuid_malloc(uid, /* ret= */ NULL);
5✔
1092
                if (r >= 0)
5✔
1093
                        return 0;
1094
                if (r != -ESRCH)
5✔
1095
                        log_warning_errno(r, "Unexpected failure while looking up UID '" UID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
×
1096

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

1107
        return 1;
1108
}
1109

1110
static int root_stat(const char *p, struct stat *ret_st) {
×
1111
        return chase_and_stat(p, arg_root, CHASE_PREFIX_ROOT, /* ret_path= */ NULL, ret_st);
×
1112
}
1113

1114
static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
70✔
1115
        struct stat st;
70✔
1116
        bool found_uid = false, found_gid = false;
70✔
1117
        uid_t uid = 0;
70✔
1118
        gid_t gid = 0;
70✔
1119

1120
        assert(i);
70✔
1121

1122
        /* First, try to get the GID directly */
1123
        if (ret_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
70✔
1124
                gid = st.st_gid;
×
1125
                found_gid = true;
×
1126
        }
1127

1128
        /* Then, try to get the UID directly */
1129
        if ((ret_uid || (ret_gid && !found_gid))
70✔
1130
            && i->uid_path
70✔
1131
            && root_stat(i->uid_path, &st) >= 0) {
×
1132

1133
                uid = st.st_uid;
×
1134
                found_uid = true;
×
1135

1136
                /* If we need the gid, but had no success yet, also derive it from the UID path */
1137
                if (ret_gid && !found_gid) {
×
1138
                        gid = st.st_gid;
×
1139
                        found_gid = true;
×
1140
                }
1141
        }
1142

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

1146
                if (found_gid) {
×
1147
                        uid = (uid_t) gid;
1148
                        found_uid = true;
1149
                } else if (root_stat(i->gid_path, &st) >= 0) {
×
1150
                        uid = (uid_t) st.st_gid;
×
1151
                        found_uid = true;
×
1152
                }
1153
        }
1154

1155
        if (ret_uid) {
70✔
1156
                if (!found_uid)
40✔
1157
                        return 0;
70✔
1158

1159
                *ret_uid = uid;
×
1160
        }
1161

1162
        if (ret_gid) {
30✔
1163
                if (!found_gid)
30✔
1164
                        return 0;
1165

1166
                *ret_gid = gid;
×
1167
        }
1168

1169
        return 1;
1170
}
1171

1172
static int add_user(Context *c, Item *i) {
297✔
1173
        void *z;
297✔
1174
        int r;
297✔
1175

1176
        assert(c);
297✔
1177
        assert(i);
297✔
1178

1179
        /* Check the database directly */
1180
        z = hashmap_get(c->database_by_username, i->name);
297✔
1181
        if (z) {
297✔
1182
                log_debug("User %s already exists.", i->name);
29✔
1183
                i->uid = PTR_TO_UID(z);
29✔
1184
                i->uid_set = true;
29✔
1185
                return 0;
29✔
1186
        }
1187

1188
        if (!arg_root) {
268✔
1189
                _cleanup_free_ struct passwd *p = NULL;
5✔
1190

1191
                /* Also check NSS */
1192
                r = getpwnam_malloc(i->name, &p);
5✔
1193
                if (r >= 0) {
5✔
1194
                        log_debug("User %s already exists.", i->name);
×
1195
                        i->uid = p->pw_uid;
×
1196
                        i->uid_set = true;
×
1197

1198
                        r = free_and_strdup(&i->description, p->pw_gecos);
×
1199
                        if (r < 0)
×
1200
                                return log_oom();
×
1201

1202
                        return 0;
1203
                }
1204
                if (r != -ESRCH)
5✔
1205
                        log_warning_errno(r, "Unexpected failure while looking up user '%s' via NSS, assuming it doesn't exist: %m", i->name);
5✔
1206
        }
1207

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

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

1223
                if (read_id_from_file(i, &candidate, NULL) > 0) {
40✔
1224

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

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

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

1255
                for (;;) {
15✔
1256
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
15✔
1257
                        if (r < 0)
15✔
1258
                                return log_error_errno(r, "No free user ID available for %s.", i->name);
×
1259

1260
                        r = uid_is_ok(c, c->search_uid, i->name, true);
15✔
1261
                        if (r < 0)
15✔
1262
                                return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1263
                        else if (r > 0)
15✔
1264
                                break;
1265
                }
1266

1267
                i->uid_set = true;
15✔
1268
                i->uid = c->search_uid;
15✔
1269
        }
1270

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

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

1285
        return 0;
1286
}
1287

1288
static int gid_is_ok(
720✔
1289
                Context *c,
1290
                gid_t gid,
1291
                const char *groupname,
1292
                bool check_with_uid) {
1293

1294
        Item *user;
720✔
1295
        char *username;
720✔
1296
        int r;
720✔
1297

1298
        assert(c);
720✔
1299
        assert(groupname);
720✔
1300

1301
        if (ordered_hashmap_get(c->todo_gids, GID_TO_PTR(gid)))
720✔
1302
                return 0;
1303

1304
        /* Avoid reusing gids that are already used by a different user */
1305
        if (check_with_uid) {
655✔
1306
                user = ordered_hashmap_get(c->todo_uids, UID_TO_PTR(gid));
321✔
1307
                if (user && !streq(user->name, groupname))
321✔
1308
                        return 0;
1309
        }
1310

1311
        if (hashmap_contains(c->database_by_gid, GID_TO_PTR(gid)))
655✔
1312
                return 0;
1313

1314
        if (check_with_uid) {
517✔
1315
                username = hashmap_get(c->database_by_uid, UID_TO_PTR(gid));
183✔
1316
                if (username && !streq(username, groupname))
183✔
1317
                        return 0;
1318
        }
1319

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

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

1336
        return 1;
1337
}
1338

1339
static int get_gid_by_name(
645✔
1340
                Context *c,
1341
                const char *name,
1342
                gid_t *ret_gid) {
1343

1344
        void *z;
645✔
1345
        int r;
645✔
1346

1347
        assert(c);
645✔
1348
        assert(ret_gid);
645✔
1349

1350
        /* Check the database directly */
1351
        z = hashmap_get(c->database_by_groupname, name);
645✔
1352
        if (z) {
645✔
1353
                *ret_gid = PTR_TO_GID(z);
67✔
1354
                return 0;
67✔
1355
        }
1356

1357
        /* Also check NSS */
1358
        if (!arg_root) {
578✔
1359
                _cleanup_free_ struct group *g = NULL;
5✔
1360

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

1370
        return -ENOENT;
1371
}
1372

1373
static int add_group(Context *c, Item *i) {
639✔
1374
        int r;
639✔
1375

1376
        assert(c);
639✔
1377
        assert(i);
639✔
1378

1379
        r = get_gid_by_name(c, i->name, &i->gid);
639✔
1380
        if (r != -ENOENT) {
639✔
1381
                if (r < 0)
62✔
1382
                        return r;
1383
                log_debug("Group %s already exists.", i->name);
62✔
1384
                i->gid_set = true;
62✔
1385
                return 0;
62✔
1386
        }
1387

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

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

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

1426
                if (read_id_from_file(i, NULL, &candidate) > 0) {
30✔
1427

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

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

1447
                for (;;) {
168✔
1448
                        /* We look for new GIDs in the UID pool! */
1449
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
168✔
1450
                        if (r < 0)
168✔
1451
                                return log_error_errno(r, "No free group ID available for %s.", i->name);
×
1452

1453
                        r = gid_is_ok(c, c->search_uid, i->name, true);
168✔
1454
                        if (r < 0)
168✔
1455
                                return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1456
                        else if (r > 0)
168✔
1457
                                break;
1458
                }
1459

1460
                i->gid_set = true;
30✔
1461
                i->gid = c->search_uid;
30✔
1462
        }
1463

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

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

1475
        return 0;
1476
}
1477

1478
static int process_item(Context *c, Item *i) {
675✔
1479
        int r;
675✔
1480

1481
        assert(c);
675✔
1482
        assert(i);
675✔
1483

1484
        switch (i->type) {
675✔
1485

1486
        case ADD_USER: {
299✔
1487
                Item *j = NULL;
299✔
1488

1489
                if (!i->gid_set) {
299✔
1490
                        j = ordered_hashmap_get(c->groups, i->group_name ?: i->name);
235✔
1491

1492
                        /* If that's not a match, also check if the group name
1493
                         * matches a user name in the queue. */
1494
                        if (!j && i->group_name)
235✔
1495
                                j = ordered_hashmap_get(c->users, i->group_name);
11✔
1496
                }
1497

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

1519
                return add_user(c, i);
297✔
1520
        }
1521

1522
        case ADD_GROUP:
376✔
1523
                return add_group(c, i);
376✔
1524

1525
        default:
×
1526
                assert_not_reached();
×
1527
        }
1528
}
1529

1530
static Item* item_free(Item *i) {
677✔
1531
        if (!i)
677✔
1532
                return NULL;
1533

1534
        free(i->name);
677✔
1535
        free(i->group_name);
677✔
1536
        free(i->uid_path);
677✔
1537
        free(i->gid_path);
677✔
1538
        free(i->description);
677✔
1539
        free(i->home);
677✔
1540
        free(i->shell);
677✔
1541
        free(i->filename);
677✔
1542
        return mfree(i);
677✔
1543
}
1544

1545
DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1,364✔
1546
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
675✔
1547

1548
static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
677✔
1549
        assert(name);
677✔
1550
        assert(!!filename == (line > 0));
677✔
1551

1552
        _cleanup_(item_freep) Item *new = new(Item, 1);
1,354✔
1553
        if (!new)
677✔
1554
                return NULL;
1555

1556
        *new = (Item) {
677✔
1557
                .type = type,
1558
                .line = line,
1559
        };
1560

1561
        if (free_and_strdup(&new->name, name) < 0 ||
1,354✔
1562
            free_and_strdup(&new->filename, filename) < 0)
677✔
1563
                return NULL;
×
1564

1565
        return TAKE_PTR(new);
677✔
1566
}
1567

1568
static int add_implicit(Context *c) {
113✔
1569
        char *g, **l;
113✔
1570
        int r;
113✔
1571

1572
        assert(c);
113✔
1573

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

1583
                                r = ordered_hashmap_ensure_put(&c->users, &item_hash_ops, j->name, j);
5✔
1584
                                if (r == -ENOMEM)
5✔
1585
                                        return log_oom();
×
1586
                                if (r < 0)
5✔
1587
                                        return log_error_errno(r, "Failed to add implicit user '%s': %m", j->name);
×
1588

1589
                                log_debug("Adding implicit user '%s' due to m line", j->name);
5✔
1590
                                TAKE_PTR(j);
5✔
1591
                        }
1592

1593
                if (!(ordered_hashmap_get(c->users, g) ||
10✔
1594
                      ordered_hashmap_get(c->groups, g))) {
2✔
1595
                        _cleanup_(item_freep) Item *j =
×
1596
                                item_new(ADD_GROUP, g, /* filename= */ NULL, /* line= */ 0);
×
1597
                        if (!j)
×
1598
                                return log_oom();
×
1599

1600
                        r = ordered_hashmap_ensure_put(&c->groups, &item_hash_ops, j->name, j);
×
1601
                        if (r == -ENOMEM)
×
1602
                                return log_oom();
×
1603
                        if (r < 0)
×
1604
                                return log_error_errno(r, "Failed to add implicit group '%s': %m", j->name);
×
1605

1606
                        log_debug("Adding implicit group '%s' due to m line", j->name);
×
1607
                        TAKE_PTR(j);
×
1608
                }
1609
        }
1610

1611
        return 0;
113✔
1612
}
1613

1614
static int item_equivalent(Item *a, Item *b) {
1✔
1615
        int r;
1✔
1616

1617
        assert(a);
1✔
1618
        assert(b);
1✔
1619

1620
        if (a->type != b->type) {
1✔
1621
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1622
                           "Item not equivalent because types differ");
1623
                return false;
×
1624
        }
1625

1626
        if (!streq_ptr(a->name, b->name)) {
1✔
1627
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1628
                           "Item not equivalent because names differ ('%s' vs. '%s')",
1629
                           a->name, b->name);
1630
                return false;
×
1631
        }
1632

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

1641
        if (!streq_ptr(a->gid_path, b->gid_path)) {
1✔
1642
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1643
                           "Item not equivalent because GID paths differ (%s vs. %s)",
1644
                           a->gid_path ?: "(unset)", b->gid_path ?: "(unset)");
1645
                return false;
×
1646
        }
1647

1648
        if (!streq_ptr(a->description, b->description))  {
1✔
1649
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1650
                           "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1651
                           strempty(a->description), strempty(b->description));
1652
                return false;
×
1653
        }
1654

1655
        if ((a->uid_set != b->uid_set) ||
1✔
1656
            (a->uid_set && a->uid != b->uid)) {
×
1657
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1658
                           "Item not equivalent because UIDs differ (%s vs. %s)",
1659
                           a->uid_set ? FORMAT_UID(a->uid) : "(unset)",
1660
                           b->uid_set ? FORMAT_UID(b->uid) : "(unset)");
1661
                return false;
×
1662
        }
1663

1664
        if ((a->gid_set != b->gid_set) ||
1✔
1665
            (a->gid_set && a->gid != b->gid)) {
1✔
1666
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1667
                           "Item not equivalent because GIDs differ (%s vs. %s)",
1668
                           a->gid_set ? FORMAT_GID(a->gid) : "(unset)",
1669
                           b->gid_set ? FORMAT_GID(b->gid) : "(unset)");
1670
                return false;
×
1671
        }
1672

1673
        if (!streq_ptr(a->home, b->home)) {
1✔
1674
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1675
                           "Item not equivalent because home directories differ ('%s' vs. '%s')",
1676
                           strempty(a->description), strempty(b->description));
1677
                return false;
×
1678
        }
1679

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

1687
        const char *a_shell = pick_shell(a),
1✔
1688
                   *b_shell = pick_shell(b);
1✔
1689
        if (!path_equal(a_shell, b_shell) &&
1✔
1690
            !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
×
1691
                _cleanup_free_ char *pa = NULL, *pb = NULL;
×
1692

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

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

1709
                if (!path_equal(pa, pb)) {
×
1710
                        log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1711
                                   "Item not equivalent because shells differ ('%s' vs. '%s')",
1712
                                   pa, pb);
1713
                        return false;
×
1714
                }
1715
        }
1716

1717
        return true;
1718
}
1719

1720
static int parse_line(
682✔
1721
                const char *fname,
1722
                unsigned line,
1723
                const char *buffer,
1724
                bool *invalid_config,
1725
                void *context) {
1726

1727
        Context *c = ASSERT_PTR(context);
682✔
1728
        _cleanup_free_ char *action = NULL,
1,364✔
1729
                *name = NULL, *resolved_name = NULL,
×
1730
                *id = NULL, *resolved_id = NULL,
×
1731
                *description = NULL, *resolved_description = NULL,
×
1732
                *home = NULL, *resolved_home = NULL,
×
1733
                *shell = NULL, *resolved_shell = NULL;
682✔
1734
        _cleanup_(item_freep) Item *i = NULL;
682✔
1735
        Item *existing;
682✔
1736
        OrderedHashmap *h;
682✔
1737
        int r;
682✔
1738
        const char *p;
682✔
1739

1740
        assert(fname);
682✔
1741
        assert(line >= 1);
682✔
1742
        assert(buffer);
682✔
1743
        assert(!invalid_config); /* We don't support invalid_config yet. */
682✔
1744

1745
        /* Parse columns */
1746
        p = buffer;
682✔
1747
        r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
682✔
1748
                               &action, &name, &id, &description, &home, &shell);
1749
        if (r < 0)
682✔
1750
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Syntax error.");
×
1751
        if (r < 2)
682✔
1752
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1753
                                  "Missing action and name columns.");
1754
        if (!isempty(p))
682✔
1755
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1756
                                  "Trailing garbage.");
1757

1758
        if (isempty(action))
682✔
1759
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1760
                                  "Empty command specification.");
1761

1762
        bool locked = false;
1763
        for (int pos = 1; action[pos]; pos++)
694✔
1764
                if (action[pos] == '!' && !locked)
12✔
1765
                        locked = true;
12✔
1766
                else
1767
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1768
                                          "Unknown modifiers in command '%s'.", action);
1769

1770
        if (!IN_SET(action[0], ADD_USER, ADD_GROUP, ADD_MEMBER, ADD_RANGE))
682✔
1771
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1772
                                  "Unknown command type '%c'.", action[0]);
1773

1774
        /* Verify name */
1775
        if (empty_or_dash(name))
682✔
1776
                name = mfree(name);
×
1777

1778
        if (name) {
682✔
1779
                r = specifier_printf(name, NAME_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_name);
682✔
1780
                if (r < 0)
682✔
1781
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", name);
×
1782

1783
                if (!valid_user_group_name(resolved_name, 0))
682✔
1784
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1785
                                          "'%s' is not a valid user or group name.", resolved_name);
1786
        }
1787

1788
        /* Verify id */
1789
        if (empty_or_dash(id))
682✔
1790
                id = mfree(id);
55✔
1791

1792
        if (id) {
682✔
1793
                r = specifier_printf(id, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_id);
627✔
1794
                if (r < 0)
627✔
1795
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1796
                                          "Failed to replace specifiers in '%s': %m", name);
1797
        }
1798

1799
        /* Verify description */
1800
        if (empty_or_dash(description))
682✔
1801
                description = mfree(description);
631✔
1802

1803
        if (description) {
682✔
1804
                r = specifier_printf(description, LONG_LINE_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_description);
51✔
1805
                if (r < 0)
51✔
1806
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1807
                                          "Failed to replace specifiers in '%s': %m", description);
1808

1809
                if (!valid_gecos(resolved_description))
51✔
1810
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1811
                                          "'%s' is not a valid GECOS field.", resolved_description);
1812
        }
1813

1814
        /* Verify home */
1815
        if (empty_or_dash(home))
682✔
1816
                home = mfree(home);
542✔
1817

1818
        if (home) {
682✔
1819
                r = specifier_printf(home, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_home);
140✔
1820
                if (r < 0)
140✔
1821
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1822
                                          "Failed to replace specifiers in '%s': %m", home);
1823

1824
                path_simplify(resolved_home);
140✔
1825

1826
                if (!valid_home(resolved_home))
140✔
1827
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1828
                                          "'%s' is not a valid home directory field.", resolved_home);
1829
        }
1830

1831
        /* Verify shell */
1832
        if (empty_or_dash(shell))
682✔
1833
                shell = mfree(shell);
661✔
1834

1835
        if (shell) {
682✔
1836
                r = specifier_printf(shell, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_shell);
21✔
1837
                if (r < 0)
21✔
1838
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1839
                                          "Failed to replace specifiers in '%s': %m", shell);
1840

1841
                path_simplify(resolved_shell);
21✔
1842

1843
                if (!valid_shell(resolved_shell))
21✔
1844
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1845
                                          "'%s' is not a valid login shell field.", resolved_shell);
1846
        }
1847

1848
        switch (action[0]) {
682✔
1849

1850
        case ADD_RANGE:
×
1851
                if (locked)
×
1852
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1853
                                          "Flag '!' not permitted on lines of type 'r'.");
1854

1855
                if (resolved_name)
×
1856
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1857
                                          "Lines of type 'r' don't take a name field.");
1858

1859
                if (!resolved_id)
×
1860
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1861
                                          "Lines of type 'r' require an ID range in the third field.");
1862

1863
                if (description || home || shell)
×
1864
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1865
                                          "Lines of type '%c' don't take a %s field.",
1866
                                          action[0],
1867
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1868

1869
                r = uid_range_add_str(&c->uid_range, resolved_id);
×
1870
                if (r < 0)
×
1871
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1872
                                          "Invalid UID range %s.", resolved_id);
1873

1874
                return 0;
1875

1876
        case ADD_MEMBER: {
10✔
1877
                /* Try to extend an existing member or group item */
1878
                if (!name)
10✔
1879
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1880
                                          "Lines of type 'm' require a user name in the second field.");
1881

1882
                if (locked)
10✔
1883
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1884
                                          "Flag '!' not permitted on lines of type 'm'.");
1885

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

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

1894
                if (description || home || shell)
10✔
1895
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1896
                                          "Lines of type '%c' don't take a %s field.",
1897
                                          action[0],
1898
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1899

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

1904
                return 0;
1905
        }
1906

1907
        case ADD_USER:
295✔
1908
                if (!name)
295✔
1909
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1910
                                          "Lines of type 'u' require a user name in the second field.");
1911

1912
                r = ordered_hashmap_ensure_allocated(&c->users, &item_hash_ops);
295✔
1913
                if (r < 0)
295✔
1914
                        return log_oom();
×
1915

1916
                i = item_new(ADD_USER, resolved_name, fname, line);
295✔
1917
                if (!i)
295✔
1918
                        return log_oom();
×
1919

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

1949
                i->description = TAKE_PTR(resolved_description);
294✔
1950
                i->home = TAKE_PTR(resolved_home);
294✔
1951
                i->shell = TAKE_PTR(resolved_shell);
294✔
1952
                i->locked = locked;
294✔
1953

1954
                h = c->users;
294✔
1955
                break;
294✔
1956

1957
        case ADD_GROUP:
377✔
1958
                if (!name)
377✔
1959
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1960
                                          "Lines of type 'g' require a user name in the second field.");
1961

1962
                if (locked)
377✔
1963
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1964
                                          "Flag '!' not permitted on lines of type 'g'.");
1965

1966
                if (description || home || shell)
377✔
1967
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1968
                                          "Lines of type '%c' don't take a %s field.",
1969
                                          action[0],
1970
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1971

1972
                r = ordered_hashmap_ensure_allocated(&c->groups, &item_hash_ops);
377✔
1973
                if (r < 0)
377✔
1974
                        return log_oom();
×
1975

1976
                i = item_new(ADD_GROUP, resolved_name, fname, line);
377✔
1977
                if (!i)
377✔
1978
                        return log_oom();
×
1979

1980
                if (resolved_id) {
377✔
1981
                        if (path_is_absolute(resolved_id))
351✔
1982
                                i->gid_path = path_simplify(TAKE_PTR(resolved_id));
×
1983
                        else {
1984
                                r = parse_gid(resolved_id, &i->gid);
351✔
1985
                                if (r < 0)
351✔
1986
                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1987
                                                          "Failed to parse GID: '%s': %m", id);
1988

1989
                                i->gid_set = true;
351✔
1990
                        }
1991
                }
1992

1993
                h = c->groups;
377✔
1994
                break;
377✔
1995

1996
        default:
×
1997
                assert_not_reached();
×
1998
        }
1999

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

2020
                return 0;
1✔
2021
        }
2022

2023
        r = ordered_hashmap_put(h, i->name, i);
670✔
2024
        if (r < 0)
670✔
2025
                return log_oom();
×
2026

2027
        i = NULL;
670✔
2028
        return 0;
670✔
2029
}
2030

2031
static int read_config_file(Context *c, const char *fn, bool ignore_enoent) {
132✔
2032
        return conf_file_read(
396✔
2033
                        arg_root,
2034
                        (const char**) CONF_PATHS_STRV("sysusers.d"),
132✔
2035
                        ASSERT_PTR(fn),
132✔
2036
                        parse_line,
2037
                        ASSERT_PTR(c),
132✔
2038
                        ignore_enoent,
2039
                        /* invalid_config= */ NULL);
2040
}
2041

2042
static int cat_config(void) {
×
2043
        _cleanup_strv_free_ char **files = NULL;
×
2044
        int r;
×
2045

2046
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
×
2047
        if (r < 0)
×
2048
                return r;
2049

2050
        pager_open(arg_pager_flags);
×
2051

2052
        return cat_files(NULL, files, arg_cat_flags);
×
2053
}
2054

2055
static int help(void) {
×
2056
        _cleanup_free_ char *link = NULL;
×
2057
        int r;
×
2058

2059
        r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
×
2060
        if (r < 0)
×
2061
                return log_oom();
×
2062

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

2085
        return 0;
2086
}
2087

2088
static int parse_argv(int argc, char *argv[]) {
113✔
2089

2090
        enum {
113✔
2091
                ARG_VERSION = 0x100,
2092
                ARG_CAT_CONFIG,
2093
                ARG_TLDR,
2094
                ARG_ROOT,
2095
                ARG_IMAGE,
2096
                ARG_IMAGE_POLICY,
2097
                ARG_REPLACE,
2098
                ARG_DRY_RUN,
2099
                ARG_INLINE,
2100
                ARG_NO_PAGER,
2101
        };
2102

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

2118
        int c, r;
113✔
2119

2120
        assert(argc >= 0);
113✔
2121
        assert(argv);
113✔
2122

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

2125
                switch (c) {
147✔
2126

2127
                case 'h':
×
2128
                        return help();
×
2129

2130
                case ARG_VERSION:
×
2131
                        return version();
×
2132

2133
                case ARG_CAT_CONFIG:
×
2134
                        arg_cat_flags = CAT_CONFIG_ON;
×
2135
                        break;
×
2136

2137
                case ARG_TLDR:
×
2138
                        arg_cat_flags = CAT_TLDR;
×
2139
                        break;
×
2140

2141
                case ARG_ROOT:
108✔
2142
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
108✔
2143
                        if (r < 0)
108✔
2144
                                return r;
2145
                        break;
2146

2147
                case ARG_IMAGE:
×
2148
#ifdef STANDALONE
2149
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2150
                                               "This systemd-sysusers version is compiled without support for --image=.");
2151
#else
2152
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
2153
                        if (r < 0)
×
2154
                                return r;
2155
                        break;
2156
#endif
2157

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

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

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

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

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

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

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

2190
                default:
×
2191
                        assert_not_reached();
×
2192
                }
2193

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

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

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

2206
        return 1;
2207
}
2208

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

2213
        assert(c);
41✔
2214

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

2224
                pos++;
44✔
2225
        }
2226

2227
        return 0;
2228
}
2229

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

2235
        assert(c);
90✔
2236

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

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

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

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

2255
        return 0;
2256
}
2257

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

2263
        assert(c);
113✔
2264

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

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

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

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

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

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

2297
        log_setup();
113✔
2298

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

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

2305
        umask(0022);
113✔
2306

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

2311
#ifndef STANDALONE
2312
        if (arg_image) {
113✔
2313
                assert(!arg_root);
×
2314

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

2331
                arg_root = strdup(mounted_dir);
×
2332
                if (!arg_root)
×
2333
                        return log_oom();
×
2334
        }
2335
#else
2336
        assert(!arg_image);
2337
#endif
2338

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

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

2354
        r = read_credential_lines(&c);
113✔
2355
        if (r < 0)
113✔
2356
                return r;
2357

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

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

2373
                c.login_defs_need_warning = true;
113✔
2374

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

2388
        r = add_implicit(&c);
113✔
2389
        if (r < 0)
113✔
2390
                return r;
2391

2392
        if (!arg_dry_run) {
113✔
2393
                lock = take_etc_passwd_lock(arg_root);
113✔
2394
                if (lock < 0)
113✔
2395
                        return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
×
2396
        }
2397

2398
        r = load_user_database(&c);
113✔
2399
        if (r < 0)
113✔
2400
                return log_error_errno(r, "Failed to load user database: %m");
×
2401

2402
        r = load_group_database(&c);
113✔
2403
        if (r < 0)
113✔
2404
                return log_error_errno(r, "Failed to read group database: %m");
×
2405

2406
        ORDERED_HASHMAP_FOREACH(i, c.groups)
489✔
2407
                (void) process_item(&c, i);
376✔
2408

2409
        ORDERED_HASHMAP_FOREACH(i, c.users)
412✔
2410
                (void) process_item(&c, i);
299✔
2411

2412
        return write_files(&c);
113✔
2413
}
2414

2415
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