]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/sysusers/sysusers.c
Merge pull request #13084 from ddstreet/log_time
[thirdparty/systemd.git] / src / sysusers / sysusers.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <getopt.h>
4 #include <utmp.h>
5
6 #include "alloc-util.h"
7 #include "conf-files.h"
8 #include "copy.h"
9 #include "def.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "format-util.h"
13 #include "fs-util.h"
14 #include "hashmap.h"
15 #include "main-func.h"
16 #include "pager.h"
17 #include "path-util.h"
18 #include "pretty-print.h"
19 #include "set.h"
20 #include "selinux-util.h"
21 #include "smack-util.h"
22 #include "specifier.h"
23 #include "string-util.h"
24 #include "strv.h"
25 #include "tmpfile-util-label.h"
26 #include "uid-range.h"
27 #include "user-util.h"
28 #include "utf8.h"
29 #include "util.h"
30
31 typedef enum ItemType {
32 ADD_USER = 'u',
33 ADD_GROUP = 'g',
34 ADD_MEMBER = 'm',
35 ADD_RANGE = 'r',
36 } ItemType;
37
38 typedef struct Item {
39 ItemType type;
40
41 char *name;
42 char *group_name;
43 char *uid_path;
44 char *gid_path;
45 char *description;
46 char *home;
47 char *shell;
48
49 gid_t gid;
50 uid_t uid;
51
52 bool gid_set:1;
53
54 /* When set the group with the specified gid must exist
55 * and the check if a uid clashes with the gid is skipped.
56 */
57 bool id_set_strict:1;
58
59 bool uid_set:1;
60
61 bool todo_user:1;
62 bool todo_group:1;
63 } Item;
64
65 static char *arg_root = NULL;
66 static bool arg_cat_config = false;
67 static const char *arg_replace = NULL;
68 static bool arg_inline = false;
69 static PagerFlags arg_pager_flags = 0;
70
71 static OrderedHashmap *users = NULL, *groups = NULL;
72 static OrderedHashmap *todo_uids = NULL, *todo_gids = NULL;
73 static OrderedHashmap *members = NULL;
74
75 static Hashmap *database_by_uid = NULL, *database_by_username = NULL;
76 static Hashmap *database_by_gid = NULL, *database_by_groupname = NULL;
77 static Set *database_users = NULL, *database_groups = NULL;
78
79 static uid_t search_uid = UID_INVALID;
80 static UidRange *uid_range = NULL;
81 static unsigned n_uid_range = 0;
82
83 STATIC_DESTRUCTOR_REGISTER(groups, ordered_hashmap_freep);
84 STATIC_DESTRUCTOR_REGISTER(users, ordered_hashmap_freep);
85 STATIC_DESTRUCTOR_REGISTER(members, ordered_hashmap_freep);
86 STATIC_DESTRUCTOR_REGISTER(todo_uids, ordered_hashmap_freep);
87 STATIC_DESTRUCTOR_REGISTER(todo_gids, ordered_hashmap_freep);
88 STATIC_DESTRUCTOR_REGISTER(database_by_uid, hashmap_freep);
89 STATIC_DESTRUCTOR_REGISTER(database_by_username, hashmap_freep);
90 STATIC_DESTRUCTOR_REGISTER(database_users, set_free_freep);
91 STATIC_DESTRUCTOR_REGISTER(database_by_gid, hashmap_freep);
92 STATIC_DESTRUCTOR_REGISTER(database_by_groupname, hashmap_freep);
93 STATIC_DESTRUCTOR_REGISTER(database_groups, set_free_freep);
94 STATIC_DESTRUCTOR_REGISTER(uid_range, freep);
95 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
96
97 static int errno_is_not_exists(int code) {
98 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
99 * not found. */
100 return IN_SET(code, 0, ENOENT, ESRCH, EBADF, EPERM);
101 }
102
103 static int load_user_database(void) {
104 _cleanup_fclose_ FILE *f = NULL;
105 const char *passwd_path;
106 struct passwd *pw;
107 int r;
108
109 passwd_path = prefix_roota(arg_root, "/etc/passwd");
110 f = fopen(passwd_path, "re");
111 if (!f)
112 return errno == ENOENT ? 0 : -errno;
113
114 r = hashmap_ensure_allocated(&database_by_username, &string_hash_ops);
115 if (r < 0)
116 return r;
117
118 r = hashmap_ensure_allocated(&database_by_uid, NULL);
119 if (r < 0)
120 return r;
121
122 r = set_ensure_allocated(&database_users, NULL);
123 if (r < 0)
124 return r;
125
126 while ((r = fgetpwent_sane(f, &pw)) > 0) {
127 char *n;
128 int k, q;
129
130 n = strdup(pw->pw_name);
131 if (!n)
132 return -ENOMEM;
133
134 k = set_put(database_users, n);
135 if (k < 0) {
136 free(n);
137 return k;
138 }
139
140 k = hashmap_put(database_by_username, n, UID_TO_PTR(pw->pw_uid));
141 if (k < 0 && k != -EEXIST)
142 return k;
143
144 q = hashmap_put(database_by_uid, UID_TO_PTR(pw->pw_uid), n);
145 if (q < 0 && q != -EEXIST)
146 return q;
147 }
148 return r;
149 }
150
151 static int load_group_database(void) {
152 _cleanup_fclose_ FILE *f = NULL;
153 const char *group_path;
154 struct group *gr;
155 int r;
156
157 group_path = prefix_roota(arg_root, "/etc/group");
158 f = fopen(group_path, "re");
159 if (!f)
160 return errno == ENOENT ? 0 : -errno;
161
162 r = hashmap_ensure_allocated(&database_by_groupname, &string_hash_ops);
163 if (r < 0)
164 return r;
165
166 r = hashmap_ensure_allocated(&database_by_gid, NULL);
167 if (r < 0)
168 return r;
169
170 r = set_ensure_allocated(&database_groups, NULL);
171 if (r < 0)
172 return r;
173
174 while ((r = fgetgrent_sane(f, &gr)) > 0) {
175 char *n;
176 int k, q;
177
178 n = strdup(gr->gr_name);
179 if (!n)
180 return -ENOMEM;
181
182 k = set_put(database_groups, n);
183 if (k < 0) {
184 free(n);
185 return k;
186 }
187
188 k = hashmap_put(database_by_groupname, n, GID_TO_PTR(gr->gr_gid));
189 if (k < 0 && k != -EEXIST)
190 return k;
191
192 q = hashmap_put(database_by_gid, GID_TO_PTR(gr->gr_gid), n);
193 if (q < 0 && q != -EEXIST)
194 return q;
195 }
196 return r;
197 }
198
199 static int make_backup(const char *target, const char *x) {
200 _cleanup_close_ int src = -1;
201 _cleanup_fclose_ FILE *dst = NULL;
202 _cleanup_free_ char *dst_tmp = NULL;
203 char *backup;
204 struct timespec ts[2];
205 struct stat st;
206 int r;
207
208 src = open(x, O_RDONLY|O_CLOEXEC|O_NOCTTY);
209 if (src < 0) {
210 if (errno == ENOENT) /* No backup necessary... */
211 return 0;
212
213 return -errno;
214 }
215
216 if (fstat(src, &st) < 0)
217 return -errno;
218
219 r = fopen_temporary_label(target, x, &dst, &dst_tmp);
220 if (r < 0)
221 return r;
222
223 r = copy_bytes(src, fileno(dst), (uint64_t) -1, COPY_REFLINK);
224 if (r < 0)
225 goto fail;
226
227 /* Don't fail on chmod() or chown(). If it stays owned by us
228 * and/or unreadable by others, then it isn't too bad... */
229
230 backup = strjoina(x, "-");
231
232 /* Copy over the access mask */
233 r = chmod_and_chown_unsafe(dst_tmp, st.st_mode & 07777, st.st_uid, st.st_gid);
234 if (r < 0)
235 log_warning_errno(r, "Failed to change access mode or ownership of %s: %m", backup);
236
237 ts[0] = st.st_atim;
238 ts[1] = st.st_mtim;
239 if (futimens(fileno(dst), ts) < 0)
240 log_warning_errno(errno, "Failed to fix access and modification time of %s: %m", backup);
241
242 r = fflush_sync_and_check(dst);
243 if (r < 0)
244 goto fail;
245
246 if (rename(dst_tmp, backup) < 0) {
247 r = -errno;
248 goto fail;
249 }
250
251 return 0;
252
253 fail:
254 (void) unlink(dst_tmp);
255 return r;
256 }
257
258 static int putgrent_with_members(const struct group *gr, FILE *group) {
259 char **a;
260
261 assert(gr);
262 assert(group);
263
264 a = ordered_hashmap_get(members, gr->gr_name);
265 if (a) {
266 _cleanup_strv_free_ char **l = NULL;
267 bool added = false;
268 char **i;
269
270 l = strv_copy(gr->gr_mem);
271 if (!l)
272 return -ENOMEM;
273
274 STRV_FOREACH(i, a) {
275 if (strv_find(l, *i))
276 continue;
277
278 if (strv_extend(&l, *i) < 0)
279 return -ENOMEM;
280
281 added = true;
282 }
283
284 if (added) {
285 struct group t;
286 int r;
287
288 strv_uniq(l);
289 strv_sort(l);
290
291 t = *gr;
292 t.gr_mem = l;
293
294 r = putgrent_sane(&t, group);
295 return r < 0 ? r : 1;
296 }
297 }
298
299 return putgrent_sane(gr, group);
300 }
301
302 #if ENABLE_GSHADOW
303 static int putsgent_with_members(const struct sgrp *sg, FILE *gshadow) {
304 char **a;
305
306 assert(sg);
307 assert(gshadow);
308
309 a = ordered_hashmap_get(members, sg->sg_namp);
310 if (a) {
311 _cleanup_strv_free_ char **l = NULL;
312 bool added = false;
313 char **i;
314
315 l = strv_copy(sg->sg_mem);
316 if (!l)
317 return -ENOMEM;
318
319 STRV_FOREACH(i, a) {
320 if (strv_find(l, *i))
321 continue;
322
323 if (strv_extend(&l, *i) < 0)
324 return -ENOMEM;
325
326 added = true;
327 }
328
329 if (added) {
330 struct sgrp t;
331 int r;
332
333 strv_uniq(l);
334 strv_sort(l);
335
336 t = *sg;
337 t.sg_mem = l;
338
339 r = putsgent_sane(&t, gshadow);
340 return r < 0 ? r : 1;
341 }
342 }
343
344 return putsgent_sane(sg, gshadow);
345 }
346 #endif
347
348 static int sync_rights(FILE *from, const char *to) {
349 struct stat st;
350
351 if (fstat(fileno(from), &st) < 0)
352 return -errno;
353
354 return chmod_and_chown_unsafe(to, st.st_mode & 07777, st.st_uid, st.st_gid);
355 }
356
357 static int rename_and_apply_smack(const char *temp_path, const char *dest_path) {
358 int r = 0;
359 if (rename(temp_path, dest_path) < 0)
360 return -errno;
361
362 #ifdef SMACK_RUN_LABEL
363 r = mac_smack_apply(dest_path, SMACK_ATTR_ACCESS, SMACK_FLOOR_LABEL);
364 if (r < 0)
365 return r;
366 #endif
367 return r;
368 }
369
370 static const char* default_shell(uid_t uid) {
371 return uid == 0 ? "/bin/sh" : NOLOGIN;
372 }
373
374 static int write_temporary_passwd(const char *passwd_path, FILE **tmpfile, char **tmpfile_path) {
375 _cleanup_fclose_ FILE *original = NULL, *passwd = NULL;
376 _cleanup_(unlink_and_freep) char *passwd_tmp = NULL;
377 struct passwd *pw = NULL;
378 Iterator iterator;
379 Item *i;
380 int r;
381
382 if (ordered_hashmap_size(todo_uids) == 0)
383 return 0;
384
385 r = fopen_temporary_label("/etc/passwd", passwd_path, &passwd, &passwd_tmp);
386 if (r < 0)
387 return r;
388
389 original = fopen(passwd_path, "re");
390 if (original) {
391
392 r = sync_rights(original, passwd_tmp);
393 if (r < 0)
394 return r;
395
396 while ((r = fgetpwent_sane(original, &pw)) > 0) {
397
398 i = ordered_hashmap_get(users, pw->pw_name);
399 if (i && i->todo_user)
400 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
401 "%s: User \"%s\" already exists.",
402 passwd_path, pw->pw_name);
403
404 if (ordered_hashmap_contains(todo_uids, UID_TO_PTR(pw->pw_uid)))
405 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
406 "%s: Detected collision for UID " UID_FMT ".",
407 passwd_path, pw->pw_uid);
408
409 /* Make sure we keep the NIS entries (if any) at the end. */
410 if (IN_SET(pw->pw_name[0], '+', '-'))
411 break;
412
413 r = putpwent_sane(pw, passwd);
414 if (r < 0)
415 return r;
416 }
417 if (r < 0)
418 return r;
419
420 } else {
421 if (errno != ENOENT)
422 return -errno;
423 if (fchmod(fileno(passwd), 0644) < 0)
424 return -errno;
425 }
426
427 ORDERED_HASHMAP_FOREACH(i, todo_uids, iterator) {
428 struct passwd n = {
429 .pw_name = i->name,
430 .pw_uid = i->uid,
431 .pw_gid = i->gid,
432 .pw_gecos = i->description,
433
434 /* "x" means the password is stored in the shadow file */
435 .pw_passwd = (char*) "x",
436
437 /* We default to the root directory as home */
438 .pw_dir = i->home ?: (char*) "/",
439
440 /* Initialize the shell to nologin, with one exception:
441 * for root we patch in something special */
442 .pw_shell = i->shell ?: (char*) default_shell(i->uid),
443 };
444
445 r = putpwent_sane(&n, passwd);
446 if (r < 0)
447 return r;
448 }
449
450 /* Append the remaining NIS entries if any */
451 while (pw) {
452 r = putpwent_sane(pw, passwd);
453 if (r < 0)
454 return r;
455
456 r = fgetpwent_sane(original, &pw);
457 if (r < 0)
458 return r;
459 if (r == 0)
460 break;
461 }
462
463 r = fflush_and_check(passwd);
464 if (r < 0)
465 return r;
466
467 *tmpfile = TAKE_PTR(passwd);
468 *tmpfile_path = TAKE_PTR(passwd_tmp);
469
470 return 0;
471 }
472
473 static int write_temporary_shadow(const char *shadow_path, FILE **tmpfile, char **tmpfile_path) {
474 _cleanup_fclose_ FILE *original = NULL, *shadow = NULL;
475 _cleanup_(unlink_and_freep) char *shadow_tmp = NULL;
476 struct spwd *sp = NULL;
477 Iterator iterator;
478 long lstchg;
479 Item *i;
480 int r;
481
482 if (ordered_hashmap_size(todo_uids) == 0)
483 return 0;
484
485 r = fopen_temporary_label("/etc/shadow", shadow_path, &shadow, &shadow_tmp);
486 if (r < 0)
487 return r;
488
489 lstchg = (long) (now(CLOCK_REALTIME) / USEC_PER_DAY);
490
491 original = fopen(shadow_path, "re");
492 if (original) {
493
494 r = sync_rights(original, shadow_tmp);
495 if (r < 0)
496 return r;
497
498 while ((r = fgetspent_sane(original, &sp)) > 0) {
499
500 i = ordered_hashmap_get(users, sp->sp_namp);
501 if (i && i->todo_user) {
502 /* we will update the existing entry */
503 sp->sp_lstchg = lstchg;
504
505 /* only the /etc/shadow stage is left, so we can
506 * safely remove the item from the todo set */
507 i->todo_user = false;
508 ordered_hashmap_remove(todo_uids, UID_TO_PTR(i->uid));
509 }
510
511 /* Make sure we keep the NIS entries (if any) at the end. */
512 if (IN_SET(sp->sp_namp[0], '+', '-'))
513 break;
514
515 r = putspent_sane(sp, shadow);
516 if (r < 0)
517 return r;
518 }
519 if (r < 0)
520 return r;
521
522 } else {
523 if (errno != ENOENT)
524 return -errno;
525 if (fchmod(fileno(shadow), 0000) < 0)
526 return -errno;
527 }
528
529 ORDERED_HASHMAP_FOREACH(i, todo_uids, iterator) {
530 struct spwd n = {
531 .sp_namp = i->name,
532 .sp_pwdp = (char*) "!!", /* lock this password, and make it invalid */
533 .sp_lstchg = lstchg,
534 .sp_min = -1,
535 .sp_max = -1,
536 .sp_warn = -1,
537 .sp_inact = -1,
538 .sp_expire = -1,
539 .sp_flag = (unsigned long) -1, /* this appears to be what everybody does ... */
540 };
541
542 r = putspent_sane(&n, shadow);
543 if (r < 0)
544 return r;
545 }
546
547 /* Append the remaining NIS entries if any */
548 while (sp) {
549 r = putspent_sane(sp, shadow);
550 if (r < 0)
551 return r;
552
553 r = fgetspent_sane(original, &sp);
554 if (r < 0)
555 return r;
556 if (r == 0)
557 break;
558 }
559 if (!IN_SET(errno, 0, ENOENT))
560 return -errno;
561
562 r = fflush_sync_and_check(shadow);
563 if (r < 0)
564 return r;
565
566 *tmpfile = TAKE_PTR(shadow);
567 *tmpfile_path = TAKE_PTR(shadow_tmp);
568
569 return 0;
570 }
571
572 static int write_temporary_group(const char *group_path, FILE **tmpfile, char **tmpfile_path) {
573 _cleanup_fclose_ FILE *original = NULL, *group = NULL;
574 _cleanup_(unlink_and_freep) char *group_tmp = NULL;
575 bool group_changed = false;
576 struct group *gr = NULL;
577 Iterator iterator;
578 Item *i;
579 int r;
580
581 if (ordered_hashmap_size(todo_gids) == 0 && ordered_hashmap_size(members) == 0)
582 return 0;
583
584 r = fopen_temporary_label("/etc/group", group_path, &group, &group_tmp);
585 if (r < 0)
586 return r;
587
588 original = fopen(group_path, "re");
589 if (original) {
590
591 r = sync_rights(original, group_tmp);
592 if (r < 0)
593 return r;
594
595 while ((r = fgetgrent_sane(original, &gr)) > 0) {
596 /* Safety checks against name and GID collisions. Normally,
597 * this should be unnecessary, but given that we look at the
598 * entries anyway here, let's make an extra verification
599 * step that we don't generate duplicate entries. */
600
601 i = ordered_hashmap_get(groups, gr->gr_name);
602 if (i && i->todo_group)
603 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
604 "%s: Group \"%s\" already exists.",
605 group_path, gr->gr_name);
606
607 if (ordered_hashmap_contains(todo_gids, GID_TO_PTR(gr->gr_gid)))
608 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
609 "%s: Detected collision for GID " GID_FMT ".",
610 group_path, gr->gr_gid);
611
612 /* Make sure we keep the NIS entries (if any) at the end. */
613 if (IN_SET(gr->gr_name[0], '+', '-'))
614 break;
615
616 r = putgrent_with_members(gr, group);
617 if (r < 0)
618 return r;
619 if (r > 0)
620 group_changed = true;
621 }
622 if (r < 0)
623 return r;
624
625 } else {
626 if (errno != ENOENT)
627 return -errno;
628 if (fchmod(fileno(group), 0644) < 0)
629 return -errno;
630 }
631
632 ORDERED_HASHMAP_FOREACH(i, todo_gids, iterator) {
633 struct group n = {
634 .gr_name = i->name,
635 .gr_gid = i->gid,
636 .gr_passwd = (char*) "x",
637 };
638
639 r = putgrent_with_members(&n, group);
640 if (r < 0)
641 return r;
642
643 group_changed = true;
644 }
645
646 /* Append the remaining NIS entries if any */
647 while (gr) {
648 r = putgrent_sane(gr, group);
649 if (r < 0)
650 return r;
651
652 r = fgetgrent_sane(original, &gr);
653 if (r < 0)
654 return r;
655 if (r == 0)
656 break;
657 }
658
659 r = fflush_sync_and_check(group);
660 if (r < 0)
661 return r;
662
663 if (group_changed) {
664 *tmpfile = TAKE_PTR(group);
665 *tmpfile_path = TAKE_PTR(group_tmp);
666 }
667 return 0;
668 }
669
670 static int write_temporary_gshadow(const char * gshadow_path, FILE **tmpfile, char **tmpfile_path) {
671 #if ENABLE_GSHADOW
672 _cleanup_fclose_ FILE *original = NULL, *gshadow = NULL;
673 _cleanup_(unlink_and_freep) char *gshadow_tmp = NULL;
674 bool group_changed = false;
675 Iterator iterator;
676 Item *i;
677 int r;
678
679 if (ordered_hashmap_size(todo_gids) == 0 && ordered_hashmap_size(members) == 0)
680 return 0;
681
682 r = fopen_temporary_label("/etc/gshadow", gshadow_path, &gshadow, &gshadow_tmp);
683 if (r < 0)
684 return r;
685
686 original = fopen(gshadow_path, "re");
687 if (original) {
688 struct sgrp *sg;
689
690 r = sync_rights(original, gshadow_tmp);
691 if (r < 0)
692 return r;
693
694 while ((r = fgetsgent_sane(original, &sg)) > 0) {
695
696 i = ordered_hashmap_get(groups, sg->sg_namp);
697 if (i && i->todo_group)
698 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
699 "%s: Group \"%s\" already exists.",
700 gshadow_path, sg->sg_namp);
701
702 r = putsgent_with_members(sg, gshadow);
703 if (r < 0)
704 return r;
705 if (r > 0)
706 group_changed = true;
707 }
708 if (r < 0)
709 return r;
710
711 } else {
712 if (errno != ENOENT)
713 return -errno;
714 if (fchmod(fileno(gshadow), 0000) < 0)
715 return -errno;
716 }
717
718 ORDERED_HASHMAP_FOREACH(i, todo_gids, iterator) {
719 struct sgrp n = {
720 .sg_namp = i->name,
721 .sg_passwd = (char*) "!!",
722 };
723
724 r = putsgent_with_members(&n, gshadow);
725 if (r < 0)
726 return r;
727
728 group_changed = true;
729 }
730
731 r = fflush_sync_and_check(gshadow);
732 if (r < 0)
733 return r;
734
735 if (group_changed) {
736 *tmpfile = TAKE_PTR(gshadow);
737 *tmpfile_path = TAKE_PTR(gshadow_tmp);
738 }
739 return 0;
740 #else
741 return 0;
742 #endif
743 }
744
745 static int write_files(void) {
746 _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;
747 _cleanup_(unlink_and_freep) char *passwd_tmp = NULL, *group_tmp = NULL, *shadow_tmp = NULL, *gshadow_tmp = NULL;
748 const char *passwd_path = NULL, *group_path = NULL, *shadow_path = NULL, *gshadow_path = NULL;
749 int r;
750
751 passwd_path = prefix_roota(arg_root, "/etc/passwd");
752 shadow_path = prefix_roota(arg_root, "/etc/shadow");
753 group_path = prefix_roota(arg_root, "/etc/group");
754 gshadow_path = prefix_roota(arg_root, "/etc/gshadow");
755
756 r = write_temporary_group(group_path, &group, &group_tmp);
757 if (r < 0)
758 return r;
759
760 r = write_temporary_gshadow(gshadow_path, &gshadow, &gshadow_tmp);
761 if (r < 0)
762 return r;
763
764 r = write_temporary_passwd(passwd_path, &passwd, &passwd_tmp);
765 if (r < 0)
766 return r;
767
768 r = write_temporary_shadow(shadow_path, &shadow, &shadow_tmp);
769 if (r < 0)
770 return r;
771
772 /* Make a backup of the old files */
773 if (group) {
774 r = make_backup("/etc/group", group_path);
775 if (r < 0)
776 return r;
777 }
778 if (gshadow) {
779 r = make_backup("/etc/gshadow", gshadow_path);
780 if (r < 0)
781 return r;
782 }
783
784 if (passwd) {
785 r = make_backup("/etc/passwd", passwd_path);
786 if (r < 0)
787 return r;
788 }
789 if (shadow) {
790 r = make_backup("/etc/shadow", shadow_path);
791 if (r < 0)
792 return r;
793 }
794
795 /* And make the new files count */
796 if (group) {
797 r = rename_and_apply_smack(group_tmp, group_path);
798 if (r < 0)
799 return r;
800
801 group_tmp = mfree(group_tmp);
802 }
803 if (gshadow) {
804 r = rename_and_apply_smack(gshadow_tmp, gshadow_path);
805 if (r < 0)
806 return r;
807
808 gshadow_tmp = mfree(gshadow_tmp);
809 }
810
811 if (passwd) {
812 r = rename_and_apply_smack(passwd_tmp, passwd_path);
813 if (r < 0)
814 return r;
815
816 passwd_tmp = mfree(passwd_tmp);
817 }
818 if (shadow) {
819 r = rename_and_apply_smack(shadow_tmp, shadow_path);
820 if (r < 0)
821 return r;
822
823 shadow_tmp = mfree(shadow_tmp);
824 }
825
826 return 0;
827 }
828
829 static int uid_is_ok(uid_t uid, const char *name, bool check_with_gid) {
830 struct passwd *p;
831 struct group *g;
832 const char *n;
833 Item *i;
834
835 /* Let's see if we already have assigned the UID a second time */
836 if (ordered_hashmap_get(todo_uids, UID_TO_PTR(uid)))
837 return 0;
838
839 /* Try to avoid using uids that are already used by a group
840 * that doesn't have the same name as our new user. */
841 if (check_with_gid) {
842 i = ordered_hashmap_get(todo_gids, GID_TO_PTR(uid));
843 if (i && !streq(i->name, name))
844 return 0;
845 }
846
847 /* Let's check the files directly */
848 if (hashmap_contains(database_by_uid, UID_TO_PTR(uid)))
849 return 0;
850
851 if (check_with_gid) {
852 n = hashmap_get(database_by_gid, GID_TO_PTR(uid));
853 if (n && !streq(n, name))
854 return 0;
855 }
856
857 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
858 if (!arg_root) {
859 errno = 0;
860 p = getpwuid(uid);
861 if (p)
862 return 0;
863 if (!IN_SET(errno, 0, ENOENT))
864 return -errno;
865
866 if (check_with_gid) {
867 errno = 0;
868 g = getgrgid((gid_t) uid);
869 if (g) {
870 if (!streq(g->gr_name, name))
871 return 0;
872 } else if (!IN_SET(errno, 0, ENOENT))
873 return -errno;
874 }
875 }
876
877 return 1;
878 }
879
880 static int root_stat(const char *p, struct stat *st) {
881 const char *fix;
882
883 fix = prefix_roota(arg_root, p);
884 if (stat(fix, st) < 0)
885 return -errno;
886
887 return 0;
888 }
889
890 static int read_id_from_file(Item *i, uid_t *_uid, gid_t *_gid) {
891 struct stat st;
892 bool found_uid = false, found_gid = false;
893 uid_t uid = 0;
894 gid_t gid = 0;
895
896 assert(i);
897
898 /* First, try to get the gid directly */
899 if (_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
900 gid = st.st_gid;
901 found_gid = true;
902 }
903
904 /* Then, try to get the uid directly */
905 if ((_uid || (_gid && !found_gid))
906 && i->uid_path
907 && root_stat(i->uid_path, &st) >= 0) {
908
909 uid = st.st_uid;
910 found_uid = true;
911
912 /* If we need the gid, but had no success yet, also derive it from the uid path */
913 if (_gid && !found_gid) {
914 gid = st.st_gid;
915 found_gid = true;
916 }
917 }
918
919 /* If that didn't work yet, then let's reuse the gid as uid */
920 if (_uid && !found_uid && i->gid_path) {
921
922 if (found_gid) {
923 uid = (uid_t) gid;
924 found_uid = true;
925 } else if (root_stat(i->gid_path, &st) >= 0) {
926 uid = (uid_t) st.st_gid;
927 found_uid = true;
928 }
929 }
930
931 if (_uid) {
932 if (!found_uid)
933 return 0;
934
935 *_uid = uid;
936 }
937
938 if (_gid) {
939 if (!found_gid)
940 return 0;
941
942 *_gid = gid;
943 }
944
945 return 1;
946 }
947
948 static int add_user(Item *i) {
949 void *z;
950 int r;
951
952 assert(i);
953
954 /* Check the database directly */
955 z = hashmap_get(database_by_username, i->name);
956 if (z) {
957 log_debug("User %s already exists.", i->name);
958 i->uid = PTR_TO_UID(z);
959 i->uid_set = true;
960 return 0;
961 }
962
963 if (!arg_root) {
964 struct passwd *p;
965
966 /* Also check NSS */
967 errno = 0;
968 p = getpwnam(i->name);
969 if (p) {
970 log_debug("User %s already exists.", i->name);
971 i->uid = p->pw_uid;
972 i->uid_set = true;
973
974 r = free_and_strdup(&i->description, p->pw_gecos);
975 if (r < 0)
976 return log_oom();
977
978 return 0;
979 }
980 if (!errno_is_not_exists(errno))
981 return log_error_errno(errno, "Failed to check if user %s already exists: %m", i->name);
982 }
983
984 /* Try to use the suggested numeric uid */
985 if (i->uid_set) {
986 r = uid_is_ok(i->uid, i->name, !i->id_set_strict);
987 if (r < 0)
988 return log_error_errno(r, "Failed to verify uid " UID_FMT ": %m", i->uid);
989 if (r == 0) {
990 log_debug("Suggested user ID " UID_FMT " for %s already used.", i->uid, i->name);
991 i->uid_set = false;
992 }
993 }
994
995 /* If that didn't work, try to read it from the specified path */
996 if (!i->uid_set) {
997 uid_t c;
998
999 if (read_id_from_file(i, &c, NULL) > 0) {
1000
1001 if (c <= 0 || !uid_range_contains(uid_range, n_uid_range, c))
1002 log_debug("User ID " UID_FMT " of file not suitable for %s.", c, i->name);
1003 else {
1004 r = uid_is_ok(c, i->name, true);
1005 if (r < 0)
1006 return log_error_errno(r, "Failed to verify uid " UID_FMT ": %m", i->uid);
1007 else if (r > 0) {
1008 i->uid = c;
1009 i->uid_set = true;
1010 } else
1011 log_debug("User ID " UID_FMT " of file for %s is already used.", c, i->name);
1012 }
1013 }
1014 }
1015
1016 /* Otherwise, try to reuse the group ID */
1017 if (!i->uid_set && i->gid_set) {
1018 r = uid_is_ok((uid_t) i->gid, i->name, true);
1019 if (r < 0)
1020 return log_error_errno(r, "Failed to verify uid " UID_FMT ": %m", i->uid);
1021 if (r > 0) {
1022 i->uid = (uid_t) i->gid;
1023 i->uid_set = true;
1024 }
1025 }
1026
1027 /* And if that didn't work either, let's try to find a free one */
1028 if (!i->uid_set) {
1029 for (;;) {
1030 r = uid_range_next_lower(uid_range, n_uid_range, &search_uid);
1031 if (r < 0)
1032 return log_error_errno(r, "No free user ID available for %s.", i->name);
1033
1034 r = uid_is_ok(search_uid, i->name, true);
1035 if (r < 0)
1036 return log_error_errno(r, "Failed to verify uid " UID_FMT ": %m", i->uid);
1037 else if (r > 0)
1038 break;
1039 }
1040
1041 i->uid_set = true;
1042 i->uid = search_uid;
1043 }
1044
1045 r = ordered_hashmap_ensure_allocated(&todo_uids, NULL);
1046 if (r < 0)
1047 return log_oom();
1048
1049 r = ordered_hashmap_put(todo_uids, UID_TO_PTR(i->uid), i);
1050 if (r < 0)
1051 return log_oom();
1052
1053 i->todo_user = true;
1054 log_info("Creating user %s (%s) with uid " UID_FMT " and gid " GID_FMT ".", i->name, strna(i->description), i->uid, i->gid);
1055
1056 return 0;
1057 }
1058
1059 static int gid_is_ok(gid_t gid) {
1060 struct group *g;
1061 struct passwd *p;
1062
1063 if (ordered_hashmap_get(todo_gids, GID_TO_PTR(gid)))
1064 return 0;
1065
1066 /* Avoid reusing gids that are already used by a different user */
1067 if (ordered_hashmap_get(todo_uids, UID_TO_PTR(gid)))
1068 return 0;
1069
1070 if (hashmap_contains(database_by_gid, GID_TO_PTR(gid)))
1071 return 0;
1072
1073 if (hashmap_contains(database_by_uid, UID_TO_PTR(gid)))
1074 return 0;
1075
1076 if (!arg_root) {
1077 errno = 0;
1078 g = getgrgid(gid);
1079 if (g)
1080 return 0;
1081 if (!IN_SET(errno, 0, ENOENT))
1082 return -errno;
1083
1084 errno = 0;
1085 p = getpwuid((uid_t) gid);
1086 if (p)
1087 return 0;
1088 if (!IN_SET(errno, 0, ENOENT))
1089 return -errno;
1090 }
1091
1092 return 1;
1093 }
1094
1095 static int get_gid_by_name(const char *name, gid_t *gid) {
1096 void *z;
1097
1098 assert(gid);
1099
1100 /* Check the database directly */
1101 z = hashmap_get(database_by_groupname, name);
1102 if (z) {
1103 *gid = PTR_TO_GID(z);
1104 return 0;
1105 }
1106
1107 /* Also check NSS */
1108 if (!arg_root) {
1109 struct group *g;
1110
1111 errno = 0;
1112 g = getgrnam(name);
1113 if (g) {
1114 *gid = g->gr_gid;
1115 return 0;
1116 }
1117 if (!errno_is_not_exists(errno))
1118 return log_error_errno(errno, "Failed to check if group %s already exists: %m", name);
1119 }
1120
1121 return -ENOENT;
1122 }
1123
1124 static int add_group(Item *i) {
1125 int r;
1126
1127 assert(i);
1128
1129 r = get_gid_by_name(i->name, &i->gid);
1130 if (r != -ENOENT) {
1131 if (r < 0)
1132 return r;
1133 log_debug("Group %s already exists.", i->name);
1134 i->gid_set = true;
1135 return 0;
1136 }
1137
1138 /* Try to use the suggested numeric gid */
1139 if (i->gid_set) {
1140 r = gid_is_ok(i->gid);
1141 if (r < 0)
1142 return log_error_errno(r, "Failed to verify gid " GID_FMT ": %m", i->gid);
1143 if (i->id_set_strict) {
1144 /* If we require the gid to already exist we can return here:
1145 * r > 0: means the gid does not exist -> fail
1146 * r == 0: means the gid exists -> nothing more to do.
1147 */
1148 if (r > 0)
1149 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1150 "Failed to create %s: please create GID %d",
1151 i->name, i->gid);
1152 if (r == 0)
1153 return 0;
1154 }
1155 if (r == 0) {
1156 log_debug("Suggested group ID " GID_FMT " for %s already used.", i->gid, i->name);
1157 i->gid_set = false;
1158 }
1159 }
1160
1161 /* Try to reuse the numeric uid, if there's one */
1162 if (!i->gid_set && i->uid_set) {
1163 r = gid_is_ok((gid_t) i->uid);
1164 if (r < 0)
1165 return log_error_errno(r, "Failed to verify gid " GID_FMT ": %m", i->gid);
1166 if (r > 0) {
1167 i->gid = (gid_t) i->uid;
1168 i->gid_set = true;
1169 }
1170 }
1171
1172 /* If that didn't work, try to read it from the specified path */
1173 if (!i->gid_set) {
1174 gid_t c;
1175
1176 if (read_id_from_file(i, NULL, &c) > 0) {
1177
1178 if (c <= 0 || !uid_range_contains(uid_range, n_uid_range, c))
1179 log_debug("Group ID " GID_FMT " of file not suitable for %s.", c, i->name);
1180 else {
1181 r = gid_is_ok(c);
1182 if (r < 0)
1183 return log_error_errno(r, "Failed to verify gid " GID_FMT ": %m", i->gid);
1184 else if (r > 0) {
1185 i->gid = c;
1186 i->gid_set = true;
1187 } else
1188 log_debug("Group ID " GID_FMT " of file for %s already used.", c, i->name);
1189 }
1190 }
1191 }
1192
1193 /* And if that didn't work either, let's try to find a free one */
1194 if (!i->gid_set) {
1195 for (;;) {
1196 /* We look for new GIDs in the UID pool! */
1197 r = uid_range_next_lower(uid_range, n_uid_range, &search_uid);
1198 if (r < 0)
1199 return log_error_errno(r, "No free group ID available for %s.", i->name);
1200
1201 r = gid_is_ok(search_uid);
1202 if (r < 0)
1203 return log_error_errno(r, "Failed to verify gid " GID_FMT ": %m", i->gid);
1204 else if (r > 0)
1205 break;
1206 }
1207
1208 i->gid_set = true;
1209 i->gid = search_uid;
1210 }
1211
1212 r = ordered_hashmap_ensure_allocated(&todo_gids, NULL);
1213 if (r < 0)
1214 return log_oom();
1215
1216 r = ordered_hashmap_put(todo_gids, GID_TO_PTR(i->gid), i);
1217 if (r < 0)
1218 return log_oom();
1219
1220 i->todo_group = true;
1221 log_info("Creating group %s with gid " GID_FMT ".", i->name, i->gid);
1222
1223 return 0;
1224 }
1225
1226 static int process_item(Item *i) {
1227 int r;
1228
1229 assert(i);
1230
1231 switch (i->type) {
1232
1233 case ADD_USER: {
1234 Item *j;
1235
1236 j = ordered_hashmap_get(groups, i->group_name ?: i->name);
1237 if (j && j->todo_group) {
1238 /* When a group with the target name is already in queue,
1239 * use the information about the group and do not create
1240 * duplicated group entry. */
1241 i->gid_set = j->gid_set;
1242 i->gid = j->gid;
1243 i->id_set_strict = true;
1244 } else if (i->group_name) {
1245 /* When a group name was given instead of a GID and it's
1246 * not in queue, then it must already exist. */
1247 r = get_gid_by_name(i->group_name, &i->gid);
1248 if (r < 0)
1249 return log_error_errno(r, "Group %s not found.", i->group_name);
1250 i->gid_set = true;
1251 i->id_set_strict = true;
1252 } else {
1253 r = add_group(i);
1254 if (r < 0)
1255 return r;
1256 }
1257
1258 return add_user(i);
1259 }
1260
1261 case ADD_GROUP:
1262 return add_group(i);
1263
1264 default:
1265 assert_not_reached("Unknown item type");
1266 }
1267 }
1268
1269 static Item* item_free(Item *i) {
1270 if (!i)
1271 return NULL;
1272
1273 free(i->name);
1274 free(i->group_name);
1275 free(i->uid_path);
1276 free(i->gid_path);
1277 free(i->description);
1278 free(i->home);
1279 free(i->shell);
1280 return mfree(i);
1281 }
1282
1283 DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1284 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
1285
1286 static int add_implicit(void) {
1287 char *g, **l;
1288 Iterator iterator;
1289 int r;
1290
1291 /* Implicitly create additional users and groups, if they were listed in "m" lines */
1292 ORDERED_HASHMAP_FOREACH_KEY(l, g, members, iterator) {
1293 char **m;
1294
1295 STRV_FOREACH(m, l)
1296 if (!ordered_hashmap_get(users, *m)) {
1297 _cleanup_(item_freep) Item *j = NULL;
1298
1299 r = ordered_hashmap_ensure_allocated(&users, &item_hash_ops);
1300 if (r < 0)
1301 return log_oom();
1302
1303 j = new0(Item, 1);
1304 if (!j)
1305 return log_oom();
1306
1307 j->type = ADD_USER;
1308 j->name = strdup(*m);
1309 if (!j->name)
1310 return log_oom();
1311
1312 r = ordered_hashmap_put(users, j->name, j);
1313 if (r < 0)
1314 return log_oom();
1315
1316 log_debug("Adding implicit user '%s' due to m line", j->name);
1317 j = NULL;
1318 }
1319
1320 if (!(ordered_hashmap_get(users, g) ||
1321 ordered_hashmap_get(groups, g))) {
1322 _cleanup_(item_freep) Item *j = NULL;
1323
1324 r = ordered_hashmap_ensure_allocated(&groups, &item_hash_ops);
1325 if (r < 0)
1326 return log_oom();
1327
1328 j = new0(Item, 1);
1329 if (!j)
1330 return log_oom();
1331
1332 j->type = ADD_GROUP;
1333 j->name = strdup(g);
1334 if (!j->name)
1335 return log_oom();
1336
1337 r = ordered_hashmap_put(groups, j->name, j);
1338 if (r < 0)
1339 return log_oom();
1340
1341 log_debug("Adding implicit group '%s' due to m line", j->name);
1342 j = NULL;
1343 }
1344 }
1345
1346 return 0;
1347 }
1348
1349 static bool item_equal(Item *a, Item *b) {
1350 assert(a);
1351 assert(b);
1352
1353 if (a->type != b->type)
1354 return false;
1355
1356 if (!streq_ptr(a->name, b->name))
1357 return false;
1358
1359 if (!streq_ptr(a->uid_path, b->uid_path))
1360 return false;
1361
1362 if (!streq_ptr(a->gid_path, b->gid_path))
1363 return false;
1364
1365 if (!streq_ptr(a->description, b->description))
1366 return false;
1367
1368 if (a->uid_set != b->uid_set)
1369 return false;
1370
1371 if (a->uid_set && a->uid != b->uid)
1372 return false;
1373
1374 if (a->gid_set != b->gid_set)
1375 return false;
1376
1377 if (a->gid_set && a->gid != b->gid)
1378 return false;
1379
1380 if (!streq_ptr(a->home, b->home))
1381 return false;
1382
1383 if (!streq_ptr(a->shell, b->shell))
1384 return false;
1385
1386 return true;
1387 }
1388
1389 static int parse_line(const char *fname, unsigned line, const char *buffer) {
1390
1391 static const Specifier specifier_table[] = {
1392 { 'm', specifier_machine_id, NULL },
1393 { 'b', specifier_boot_id, NULL },
1394 { 'H', specifier_host_name, NULL },
1395 { 'v', specifier_kernel_release, NULL },
1396 { 'T', specifier_tmp_dir, NULL },
1397 { 'V', specifier_var_tmp_dir, NULL },
1398 {}
1399 };
1400
1401 _cleanup_free_ char *action = NULL,
1402 *name = NULL, *resolved_name = NULL,
1403 *id = NULL, *resolved_id = NULL,
1404 *description = NULL, *resolved_description = NULL,
1405 *home = NULL, *resolved_home = NULL,
1406 *shell = NULL, *resolved_shell = NULL;
1407 _cleanup_(item_freep) Item *i = NULL;
1408 Item *existing;
1409 OrderedHashmap *h;
1410 int r;
1411 const char *p;
1412
1413 assert(fname);
1414 assert(line >= 1);
1415 assert(buffer);
1416
1417 /* Parse columns */
1418 p = buffer;
1419 r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
1420 &action, &name, &id, &description, &home, &shell, NULL);
1421 if (r < 0)
1422 return log_error_errno(r, "[%s:%u] Syntax error.", fname, line);
1423 if (r < 2)
1424 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1425 "[%s:%u] Missing action and name columns.", fname, line);
1426 if (!isempty(p))
1427 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1428 "[%s:%u] Trailing garbage.", fname, line);
1429
1430 /* Verify action */
1431 if (strlen(action) != 1)
1432 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1433 "[%s:%u] Unknown modifier '%s'", fname, line, action);
1434
1435 if (!IN_SET(action[0], ADD_USER, ADD_GROUP, ADD_MEMBER, ADD_RANGE))
1436 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
1437 "[%s:%u] Unknown command type '%c'.", fname, line, action[0]);
1438
1439 /* Verify name */
1440 if (empty_or_dash(name))
1441 name = mfree(name);
1442
1443 if (name) {
1444 r = specifier_printf(name, specifier_table, NULL, &resolved_name);
1445 if (r < 0)
1446 log_error_errno(r, "[%s:%u] Failed to replace specifiers: %s", fname, line, name);
1447
1448 if (!valid_user_group_name(resolved_name))
1449 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1450 "[%s:%u] '%s' is not a valid user or group name.",
1451 fname, line, resolved_name);
1452 }
1453
1454 /* Verify id */
1455 if (empty_or_dash(id))
1456 id = mfree(id);
1457
1458 if (id) {
1459 r = specifier_printf(id, specifier_table, NULL, &resolved_id);
1460 if (r < 0)
1461 return log_error_errno(r, "[%s:%u] Failed to replace specifiers: %s",
1462 fname, line, name);
1463 }
1464
1465 /* Verify description */
1466 if (empty_or_dash(description))
1467 description = mfree(description);
1468
1469 if (description) {
1470 r = specifier_printf(description, specifier_table, NULL, &resolved_description);
1471 if (r < 0)
1472 return log_error_errno(r, "[%s:%u] Failed to replace specifiers: %s",
1473 fname, line, description);
1474
1475 if (!valid_gecos(resolved_description))
1476 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1477 "[%s:%u] '%s' is not a valid GECOS field.",
1478 fname, line, resolved_description);
1479 }
1480
1481 /* Verify home */
1482 if (empty_or_dash(home))
1483 home = mfree(home);
1484
1485 if (home) {
1486 r = specifier_printf(home, specifier_table, NULL, &resolved_home);
1487 if (r < 0)
1488 return log_error_errno(r, "[%s:%u] Failed to replace specifiers: %s",
1489 fname, line, home);
1490
1491 if (!valid_home(resolved_home))
1492 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1493 "[%s:%u] '%s' is not a valid home directory field.",
1494 fname, line, resolved_home);
1495 }
1496
1497 /* Verify shell */
1498 if (empty_or_dash(shell))
1499 shell = mfree(shell);
1500
1501 if (shell) {
1502 r = specifier_printf(shell, specifier_table, NULL, &resolved_shell);
1503 if (r < 0)
1504 return log_error_errno(r, "[%s:%u] Failed to replace specifiers: %s",
1505 fname, line, shell);
1506
1507 if (!valid_shell(resolved_shell))
1508 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1509 "[%s:%u] '%s' is not a valid login shell field.",
1510 fname, line, resolved_shell);
1511 }
1512
1513 switch (action[0]) {
1514
1515 case ADD_RANGE:
1516 if (resolved_name)
1517 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1518 "[%s:%u] Lines of type 'r' don't take a name field.",
1519 fname, line);
1520
1521 if (!resolved_id)
1522 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1523 "[%s:%u] Lines of type 'r' require a ID range in the third field.",
1524 fname, line);
1525
1526 if (description || home || shell)
1527 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1528 "[%s:%u] Lines of type '%c' don't take a %s field.",
1529 fname, line, action[0],
1530 description ? "GECOS" : home ? "home directory" : "login shell");
1531
1532 r = uid_range_add_str(&uid_range, &n_uid_range, resolved_id);
1533 if (r < 0)
1534 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1535 "[%s:%u] Invalid UID range %s.", fname, line, resolved_id);
1536
1537 return 0;
1538
1539 case ADD_MEMBER: {
1540 /* Try to extend an existing member or group item */
1541 if (!name)
1542 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1543 "[%s:%u] Lines of type 'm' require a user name in the second field.",
1544 fname, line);
1545
1546 if (!resolved_id)
1547 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1548 "[%s:%u] Lines of type 'm' require a group name in the third field.",
1549 fname, line);
1550
1551 if (!valid_user_group_name(resolved_id))
1552 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1553 "[%s:%u] '%s' is not a valid user or group name.",
1554 fname, line, resolved_id);
1555
1556 if (description || home || shell)
1557 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1558 "[%s:%u] Lines of type '%c' don't take a %s field.",
1559 fname, line, action[0],
1560 description ? "GECOS" : home ? "home directory" : "login shell");
1561
1562 r = string_strv_ordered_hashmap_put(&members, resolved_id, resolved_name);
1563 if (r < 0)
1564 return log_error_errno(r, "Failed to store mapping for %s: %m", resolved_id);
1565
1566 return 0;
1567 }
1568
1569 case ADD_USER:
1570 if (!name)
1571 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1572 "[%s:%u] Lines of type 'u' require a user name in the second field.",
1573 fname, line);
1574
1575 r = ordered_hashmap_ensure_allocated(&users, &item_hash_ops);
1576 if (r < 0)
1577 return log_oom();
1578
1579 i = new0(Item, 1);
1580 if (!i)
1581 return log_oom();
1582
1583 if (resolved_id) {
1584 if (path_is_absolute(resolved_id)) {
1585 i->uid_path = TAKE_PTR(resolved_id);
1586 path_simplify(i->uid_path, false);
1587 } else {
1588 _cleanup_free_ char *uid = NULL, *gid = NULL;
1589 if (split_pair(resolved_id, ":", &uid, &gid) == 0) {
1590 r = parse_gid(gid, &i->gid);
1591 if (r < 0) {
1592 if (valid_user_group_name(gid))
1593 i->group_name = TAKE_PTR(gid);
1594 else
1595 return log_error_errno(r, "Failed to parse GID: '%s': %m", id);
1596 } else {
1597 i->gid_set = true;
1598 i->id_set_strict = true;
1599 }
1600 free_and_replace(resolved_id, uid);
1601 }
1602 if (!streq(resolved_id, "-")) {
1603 r = parse_uid(resolved_id, &i->uid);
1604 if (r < 0)
1605 return log_error_errno(r, "Failed to parse UID: '%s': %m", id);
1606 i->uid_set = true;
1607 }
1608 }
1609 }
1610
1611 i->description = TAKE_PTR(resolved_description);
1612 i->home = TAKE_PTR(resolved_home);
1613 i->shell = TAKE_PTR(resolved_shell);
1614
1615 h = users;
1616 break;
1617
1618 case ADD_GROUP:
1619 if (!name)
1620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1621 "[%s:%u] Lines of type 'g' require a user name in the second field.",
1622 fname, line);
1623
1624 if (description || home || shell)
1625 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1626 "[%s:%u] Lines of type '%c' don't take a %s field.",
1627 fname, line, action[0],
1628 description ? "GECOS" : home ? "home directory" : "login shell");
1629
1630 r = ordered_hashmap_ensure_allocated(&groups, &item_hash_ops);
1631 if (r < 0)
1632 return log_oom();
1633
1634 i = new0(Item, 1);
1635 if (!i)
1636 return log_oom();
1637
1638 if (resolved_id) {
1639 if (path_is_absolute(resolved_id)) {
1640 i->gid_path = TAKE_PTR(resolved_id);
1641 path_simplify(i->gid_path, false);
1642 } else {
1643 r = parse_gid(resolved_id, &i->gid);
1644 if (r < 0)
1645 return log_error_errno(r, "Failed to parse GID: '%s': %m", id);
1646
1647 i->gid_set = true;
1648 }
1649 }
1650
1651 h = groups;
1652 break;
1653
1654 default:
1655 return -EBADMSG;
1656 }
1657
1658 i->type = action[0];
1659 i->name = TAKE_PTR(resolved_name);
1660
1661 existing = ordered_hashmap_get(h, i->name);
1662 if (existing) {
1663 /* Two identical items are fine */
1664 if (!item_equal(existing, i))
1665 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->name);
1666
1667 return 0;
1668 }
1669
1670 r = ordered_hashmap_put(h, i->name, i);
1671 if (r < 0)
1672 return log_oom();
1673
1674 i = NULL;
1675 return 0;
1676 }
1677
1678 static int read_config_file(const char *fn, bool ignore_enoent) {
1679 _cleanup_fclose_ FILE *rf = NULL;
1680 FILE *f = NULL;
1681 unsigned v = 0;
1682 int r = 0;
1683
1684 assert(fn);
1685
1686 if (streq(fn, "-"))
1687 f = stdin;
1688 else {
1689 r = search_and_fopen(fn, "re", arg_root, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf);
1690 if (r < 0) {
1691 if (ignore_enoent && r == -ENOENT)
1692 return 0;
1693
1694 return log_error_errno(r, "Failed to open '%s', ignoring: %m", fn);
1695 }
1696
1697 f = rf;
1698 }
1699
1700 for (;;) {
1701 _cleanup_free_ char *line = NULL;
1702 char *l;
1703 int k;
1704
1705 k = read_line(f, LONG_LINE_MAX, &line);
1706 if (k < 0)
1707 return log_error_errno(k, "Failed to read '%s': %m", fn);
1708 if (k == 0)
1709 break;
1710
1711 v++;
1712
1713 l = strstrip(line);
1714 if (IN_SET(*l, 0, '#'))
1715 continue;
1716
1717 k = parse_line(fn, v, l);
1718 if (k < 0 && r == 0)
1719 r = k;
1720 }
1721
1722 if (ferror(f)) {
1723 log_error_errno(errno, "Failed to read from file %s: %m", fn);
1724 if (r == 0)
1725 r = -EIO;
1726 }
1727
1728 return r;
1729 }
1730
1731 static int cat_config(void) {
1732 _cleanup_strv_free_ char **files = NULL;
1733 int r;
1734
1735 r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
1736 if (r < 0)
1737 return r;
1738
1739 (void) pager_open(arg_pager_flags);
1740
1741 return cat_files(NULL, files, 0);
1742 }
1743
1744 static int help(void) {
1745 _cleanup_free_ char *link = NULL;
1746 int r;
1747
1748 r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
1749 if (r < 0)
1750 return log_oom();
1751
1752 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1753 "Creates system user accounts.\n\n"
1754 " -h --help Show this help\n"
1755 " --version Show package version\n"
1756 " --cat-config Show configuration files\n"
1757 " --root=PATH Operate on an alternate filesystem root\n"
1758 " --replace=PATH Treat arguments as replacement for PATH\n"
1759 " --inline Treat arguments as configuration lines\n"
1760 " --no-pager Do not pipe output into a pager\n"
1761 "\nSee the %s for details.\n"
1762 , program_invocation_short_name
1763 , link
1764 );
1765
1766 return 0;
1767 }
1768
1769 static int parse_argv(int argc, char *argv[]) {
1770
1771 enum {
1772 ARG_VERSION = 0x100,
1773 ARG_CAT_CONFIG,
1774 ARG_ROOT,
1775 ARG_REPLACE,
1776 ARG_INLINE,
1777 ARG_NO_PAGER,
1778 };
1779
1780 static const struct option options[] = {
1781 { "help", no_argument, NULL, 'h' },
1782 { "version", no_argument, NULL, ARG_VERSION },
1783 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
1784 { "root", required_argument, NULL, ARG_ROOT },
1785 { "replace", required_argument, NULL, ARG_REPLACE },
1786 { "inline", no_argument, NULL, ARG_INLINE },
1787 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1788 {}
1789 };
1790
1791 int c, r;
1792
1793 assert(argc >= 0);
1794 assert(argv);
1795
1796 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
1797
1798 switch (c) {
1799
1800 case 'h':
1801 return help();
1802
1803 case ARG_VERSION:
1804 return version();
1805
1806 case ARG_CAT_CONFIG:
1807 arg_cat_config = true;
1808 break;
1809
1810 case ARG_ROOT:
1811 r = parse_path_argument_and_warn(optarg, true, &arg_root);
1812 if (r < 0)
1813 return r;
1814 break;
1815
1816 case ARG_REPLACE:
1817 if (!path_is_absolute(optarg) ||
1818 !endswith(optarg, ".conf"))
1819 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1820 "The argument to --replace= must an absolute path to a config file");
1821
1822 arg_replace = optarg;
1823 break;
1824
1825 case ARG_INLINE:
1826 arg_inline = true;
1827 break;
1828
1829 case ARG_NO_PAGER:
1830 arg_pager_flags |= PAGER_DISABLE;
1831 break;
1832
1833 case '?':
1834 return -EINVAL;
1835
1836 default:
1837 assert_not_reached("Unhandled option");
1838 }
1839
1840 if (arg_replace && arg_cat_config)
1841 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1842 "Option --replace= is not supported with --cat-config");
1843
1844 if (arg_replace && optind >= argc)
1845 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1846 "When --replace= is given, some configuration items must be specified");
1847
1848 return 1;
1849 }
1850
1851 static int parse_arguments(char **args) {
1852 char **arg;
1853 unsigned pos = 1;
1854 int r;
1855
1856 STRV_FOREACH(arg, args) {
1857 if (arg_inline)
1858 /* Use (argument):n, where n==1 for the first positional arg */
1859 r = parse_line("(argument)", pos, *arg);
1860 else
1861 r = read_config_file(*arg, false);
1862 if (r < 0)
1863 return r;
1864
1865 pos++;
1866 }
1867
1868 return 0;
1869 }
1870
1871 static int read_config_files(char **args) {
1872 _cleanup_strv_free_ char **files = NULL;
1873 _cleanup_free_ char *p = NULL;
1874 char **f;
1875 int r;
1876
1877 r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
1878 if (r < 0)
1879 return r;
1880
1881 STRV_FOREACH(f, files)
1882 if (p && path_equal(*f, p)) {
1883 log_debug("Parsing arguments at position \"%s\"…", *f);
1884
1885 r = parse_arguments(args);
1886 if (r < 0)
1887 return r;
1888 } else {
1889 log_debug("Reading config file \"%s\"…", *f);
1890
1891 /* Just warn, ignore result otherwise */
1892 (void) read_config_file(*f, true);
1893 }
1894
1895 return 0;
1896 }
1897
1898 static int run(int argc, char *argv[]) {
1899 _cleanup_close_ int lock = -1;
1900 Iterator iterator;
1901 Item *i;
1902 int r;
1903
1904 r = parse_argv(argc, argv);
1905 if (r <= 0)
1906 return r;
1907
1908 log_setup_service();
1909
1910 if (arg_cat_config)
1911 return cat_config();
1912
1913 umask(0022);
1914
1915 r = mac_selinux_init();
1916 if (r < 0)
1917 return log_error_errno(r, "SELinux setup failed: %m");
1918
1919 /* If command line arguments are specified along with --replace, read all
1920 * configuration files and insert the positional arguments at the specified
1921 * place. Otherwise, if command line arguments are specified, execute just
1922 * them, and finally, without --replace= or any positional arguments, just
1923 * read configuration and execute it.
1924 */
1925 if (arg_replace || optind >= argc)
1926 r = read_config_files(argv + optind);
1927 else
1928 r = parse_arguments(argv + optind);
1929 if (r < 0)
1930 return r;
1931
1932 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our detection
1933 * whether the names or UID/GID area already used otherwise doesn't get confused. After all, even though
1934 * nss-systemd synthesizes these users/groups, they should still appear in /etc/passwd and /etc/group, as the
1935 * synthesizing logic is merely supposed to be fallback for cases where we run with a completely unpopulated
1936 * /etc. */
1937 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
1938 return log_error_errno(errno, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
1939
1940 if (!uid_range) {
1941 /* Default to default range of 1..SYSTEM_UID_MAX */
1942 r = uid_range_add(&uid_range, &n_uid_range, 1, SYSTEM_UID_MAX);
1943 if (r < 0)
1944 return log_oom();
1945 }
1946
1947 r = add_implicit();
1948 if (r < 0)
1949 return r;
1950
1951 lock = take_etc_passwd_lock(arg_root);
1952 if (lock < 0)
1953 return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
1954
1955 r = load_user_database();
1956 if (r < 0)
1957 return log_error_errno(r, "Failed to load user database: %m");
1958
1959 r = load_group_database();
1960 if (r < 0)
1961 return log_error_errno(r, "Failed to read group database: %m");
1962
1963 ORDERED_HASHMAP_FOREACH(i, groups, iterator)
1964 (void) process_item(i);
1965
1966 ORDERED_HASHMAP_FOREACH(i, users, iterator)
1967 (void) process_item(i);
1968
1969 r = write_files();
1970 if (r < 0)
1971 return log_error_errno(r, "Failed to write files: %m");
1972
1973 return 0;
1974 }
1975
1976 DEFINE_MAIN_FUNCTION(run);