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