]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/user-util.c
Merge pull request #25608 from poettering/dissect-moar
[thirdparty/systemd.git] / src / basic / user-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stddef.h>
6 #include <stdint.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #include <utmp.h>
12
13 #include "sd-messages.h"
14
15 #include "alloc-util.h"
16 #include "chase.h"
17 #include "errno-util.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 #include "format-util.h"
21 #include "lock-util.h"
22 #include "macro.h"
23 #include "mkdir.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "path-util.h"
27 #include "random-util.h"
28 #include "string-util.h"
29 #include "strv.h"
30 #include "user-util.h"
31 #include "utf8.h"
32
33 bool uid_is_valid(uid_t uid) {
34
35 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
36
37 /* Some libc APIs use UID_INVALID as special placeholder */
38 if (uid == (uid_t) UINT32_C(0xFFFFFFFF))
39 return false;
40
41 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
42 if (uid == (uid_t) UINT32_C(0xFFFF))
43 return false;
44
45 return true;
46 }
47
48 int parse_uid(const char *s, uid_t *ret) {
49 uint32_t uid = 0;
50 int r;
51
52 assert(s);
53
54 assert_cc(sizeof(uid_t) == sizeof(uint32_t));
55
56 /* We are very strict when parsing UIDs, and prohibit +/- as prefix, leading zero as prefix, and
57 * whitespace. We do this, since this call is often used in a context where we parse things as UID
58 * first, and if that doesn't work we fall back to NSS. Thus we really want to make sure that UIDs
59 * are parsed as UIDs only if they really really look like UIDs. */
60 r = safe_atou32_full(s, 10
61 | SAFE_ATO_REFUSE_PLUS_MINUS
62 | SAFE_ATO_REFUSE_LEADING_ZERO
63 | SAFE_ATO_REFUSE_LEADING_WHITESPACE, &uid);
64 if (r < 0)
65 return r;
66
67 if (!uid_is_valid(uid))
68 return -ENXIO; /* we return ENXIO instead of EINVAL
69 * here, to make it easy to distinguish
70 * invalid numeric uids from invalid
71 * strings. */
72
73 if (ret)
74 *ret = uid;
75
76 return 0;
77 }
78
79 int parse_uid_range(const char *s, uid_t *ret_lower, uid_t *ret_upper) {
80 _cleanup_free_ char *word = NULL;
81 uid_t l, u;
82 int r;
83
84 assert(s);
85 assert(ret_lower);
86 assert(ret_upper);
87
88 r = extract_first_word(&s, &word, "-", EXTRACT_DONT_COALESCE_SEPARATORS);
89 if (r < 0)
90 return r;
91 if (r == 0)
92 return -EINVAL;
93
94 r = parse_uid(word, &l);
95 if (r < 0)
96 return r;
97
98 /* Check for the upper bound and extract it if needed */
99 if (!s)
100 /* Single number with no dash. */
101 u = l;
102 else if (!*s)
103 /* Trailing dash is an error. */
104 return -EINVAL;
105 else {
106 r = parse_uid(s, &u);
107 if (r < 0)
108 return r;
109
110 if (l > u)
111 return -EINVAL;
112 }
113
114 *ret_lower = l;
115 *ret_upper = u;
116 return 0;
117 }
118
119 char* getlogname_malloc(void) {
120 uid_t uid;
121 struct stat st;
122
123 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
124 uid = st.st_uid;
125 else
126 uid = getuid();
127
128 return uid_to_name(uid);
129 }
130
131 char *getusername_malloc(void) {
132 const char *e;
133
134 e = secure_getenv("USER");
135 if (e)
136 return strdup(e);
137
138 return uid_to_name(getuid());
139 }
140
141 bool is_nologin_shell(const char *shell) {
142 return PATH_IN_SET(shell,
143 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
144 * message and exits. Different distributions place the binary at different places though,
145 * hence let's list them all. */
146 "/bin/nologin",
147 "/sbin/nologin",
148 "/usr/bin/nologin",
149 "/usr/sbin/nologin",
150 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
151 * any message printing. Different distributions place the binary at various places but at
152 * least not in the 'sbin' directory. */
153 "/bin/false",
154 "/usr/bin/false",
155 "/bin/true",
156 "/usr/bin/true");
157 }
158
159 const char* default_root_shell_at(int rfd) {
160 /* We want to use the preferred shell, i.e. DEFAULT_USER_SHELL, which usually
161 * will be /bin/bash. Fall back to /bin/sh if DEFAULT_USER_SHELL is not found,
162 * or any access errors. */
163
164 assert(rfd >= 0 || rfd == AT_FDCWD);
165
166 int r = chaseat(rfd, DEFAULT_USER_SHELL, CHASE_AT_RESOLVE_IN_ROOT, NULL, NULL);
167 if (r < 0 && r != -ENOENT)
168 log_debug_errno(r, "Failed to look up shell '%s': %m", DEFAULT_USER_SHELL);
169 if (r > 0)
170 return DEFAULT_USER_SHELL;
171
172 return "/bin/sh";
173 }
174
175 const char *default_root_shell(const char *root) {
176 _cleanup_close_ int rfd = -EBADF;
177
178 rfd = open(empty_to_root(root), O_CLOEXEC | O_DIRECTORY | O_PATH);
179 if (rfd < 0)
180 return "/bin/sh";
181
182 return default_root_shell_at(rfd);
183 }
184
185 static int synthesize_user_creds(
186 const char **username,
187 uid_t *uid, gid_t *gid,
188 const char **home,
189 const char **shell,
190 UserCredsFlags flags) {
191
192 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
193 * their user record data. */
194
195 if (STR_IN_SET(*username, "root", "0")) {
196 *username = "root";
197
198 if (uid)
199 *uid = 0;
200 if (gid)
201 *gid = 0;
202
203 if (home)
204 *home = "/root";
205
206 if (shell)
207 *shell = default_root_shell(NULL);
208
209 return 0;
210 }
211
212 if (STR_IN_SET(*username, NOBODY_USER_NAME, "65534") &&
213 synthesize_nobody()) {
214 *username = NOBODY_USER_NAME;
215
216 if (uid)
217 *uid = UID_NOBODY;
218 if (gid)
219 *gid = GID_NOBODY;
220
221 if (home)
222 *home = FLAGS_SET(flags, USER_CREDS_CLEAN) ? NULL : "/";
223
224 if (shell)
225 *shell = FLAGS_SET(flags, USER_CREDS_CLEAN) ? NULL : NOLOGIN;
226
227 return 0;
228 }
229
230 return -ENOMEDIUM;
231 }
232
233 int get_user_creds(
234 const char **username,
235 uid_t *uid, gid_t *gid,
236 const char **home,
237 const char **shell,
238 UserCredsFlags flags) {
239
240 uid_t u = UID_INVALID;
241 struct passwd *p;
242 int r;
243
244 assert(username);
245 assert(*username);
246
247 if (!FLAGS_SET(flags, USER_CREDS_PREFER_NSS) ||
248 (!home && !shell)) {
249
250 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
251 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
252 * user database will override the synthetic records instead — except if the user is only interested in
253 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
254 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
255 * Simply because there are valid usecase where the user might change the home directory or the shell
256 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
257 * support. */
258
259 r = synthesize_user_creds(username, uid, gid, home, shell, flags);
260 if (r >= 0)
261 return 0;
262 if (r != -ENOMEDIUM) /* not a username we can synthesize */
263 return r;
264 }
265
266 if (parse_uid(*username, &u) >= 0) {
267 errno = 0;
268 p = getpwuid(u);
269
270 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
271 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
272 * then let's pick the real username from /etc/passwd. */
273 if (p)
274 *username = p->pw_name;
275 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING) && !gid && !home && !shell) {
276
277 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
278 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then just return that
279 * and don't complain. */
280
281 if (uid)
282 *uid = u;
283
284 return 0;
285 }
286 } else {
287 errno = 0;
288 p = getpwnam(*username);
289 }
290 if (!p) {
291 r = errno_or_else(ESRCH);
292
293 /* If the user requested that we only synthesize as fallback, do so now */
294 if (FLAGS_SET(flags, USER_CREDS_PREFER_NSS)) {
295 if (synthesize_user_creds(username, uid, gid, home, shell, flags) >= 0)
296 return 0;
297 }
298
299 return r;
300 }
301
302 if (uid) {
303 if (!uid_is_valid(p->pw_uid))
304 return -EBADMSG;
305
306 *uid = p->pw_uid;
307 }
308
309 if (gid) {
310 if (!gid_is_valid(p->pw_gid))
311 return -EBADMSG;
312
313 *gid = p->pw_gid;
314 }
315
316 if (home) {
317 if (FLAGS_SET(flags, USER_CREDS_CLEAN) &&
318 (empty_or_root(p->pw_dir) ||
319 !path_is_valid(p->pw_dir) ||
320 !path_is_absolute(p->pw_dir)))
321 *home = NULL; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
322 else
323 *home = p->pw_dir;
324 }
325
326 if (shell) {
327 if (FLAGS_SET(flags, USER_CREDS_CLEAN) &&
328 (isempty(p->pw_shell) ||
329 !path_is_valid(p->pw_dir) ||
330 !path_is_absolute(p->pw_shell) ||
331 is_nologin_shell(p->pw_shell)))
332 *shell = NULL;
333 else
334 *shell = p->pw_shell;
335 }
336
337 return 0;
338 }
339
340 int get_group_creds(const char **groupname, gid_t *gid, UserCredsFlags flags) {
341 struct group *g;
342 gid_t id;
343
344 assert(groupname);
345
346 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
347
348 if (STR_IN_SET(*groupname, "root", "0")) {
349 *groupname = "root";
350
351 if (gid)
352 *gid = 0;
353
354 return 0;
355 }
356
357 if (STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534") &&
358 synthesize_nobody()) {
359 *groupname = NOBODY_GROUP_NAME;
360
361 if (gid)
362 *gid = GID_NOBODY;
363
364 return 0;
365 }
366
367 if (parse_gid(*groupname, &id) >= 0) {
368 errno = 0;
369 g = getgrgid(id);
370
371 if (g)
372 *groupname = g->gr_name;
373 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING)) {
374 if (gid)
375 *gid = id;
376
377 return 0;
378 }
379 } else {
380 errno = 0;
381 g = getgrnam(*groupname);
382 }
383
384 if (!g)
385 return errno_or_else(ESRCH);
386
387 if (gid) {
388 if (!gid_is_valid(g->gr_gid))
389 return -EBADMSG;
390
391 *gid = g->gr_gid;
392 }
393
394 return 0;
395 }
396
397 char* uid_to_name(uid_t uid) {
398 char *ret;
399 int r;
400
401 /* Shortcut things to avoid NSS lookups */
402 if (uid == 0)
403 return strdup("root");
404 if (uid == UID_NOBODY && synthesize_nobody())
405 return strdup(NOBODY_USER_NAME);
406
407 if (uid_is_valid(uid)) {
408 long bufsize;
409
410 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
411 if (bufsize <= 0)
412 bufsize = 4096;
413
414 for (;;) {
415 struct passwd pwbuf, *pw = NULL;
416 _cleanup_free_ char *buf = NULL;
417
418 buf = malloc(bufsize);
419 if (!buf)
420 return NULL;
421
422 r = getpwuid_r(uid, &pwbuf, buf, (size_t) bufsize, &pw);
423 if (r == 0 && pw)
424 return strdup(pw->pw_name);
425 if (r != ERANGE)
426 break;
427
428 if (bufsize > LONG_MAX/2) /* overflow check */
429 return NULL;
430
431 bufsize *= 2;
432 }
433 }
434
435 if (asprintf(&ret, UID_FMT, uid) < 0)
436 return NULL;
437
438 return ret;
439 }
440
441 char* gid_to_name(gid_t gid) {
442 char *ret;
443 int r;
444
445 if (gid == 0)
446 return strdup("root");
447 if (gid == GID_NOBODY && synthesize_nobody())
448 return strdup(NOBODY_GROUP_NAME);
449
450 if (gid_is_valid(gid)) {
451 long bufsize;
452
453 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
454 if (bufsize <= 0)
455 bufsize = 4096;
456
457 for (;;) {
458 struct group grbuf, *gr = NULL;
459 _cleanup_free_ char *buf = NULL;
460
461 buf = malloc(bufsize);
462 if (!buf)
463 return NULL;
464
465 r = getgrgid_r(gid, &grbuf, buf, (size_t) bufsize, &gr);
466 if (r == 0 && gr)
467 return strdup(gr->gr_name);
468 if (r != ERANGE)
469 break;
470
471 if (bufsize > LONG_MAX/2) /* overflow check */
472 return NULL;
473
474 bufsize *= 2;
475 }
476 }
477
478 if (asprintf(&ret, GID_FMT, gid) < 0)
479 return NULL;
480
481 return ret;
482 }
483
484 static bool gid_list_has(const gid_t *list, size_t size, gid_t val) {
485 for (size_t i = 0; i < size; i++)
486 if (list[i] == val)
487 return true;
488 return false;
489 }
490
491 int in_gid(gid_t gid) {
492 _cleanup_free_ gid_t *gids = NULL;
493 int ngroups;
494
495 if (getgid() == gid)
496 return 1;
497
498 if (getegid() == gid)
499 return 1;
500
501 if (!gid_is_valid(gid))
502 return -EINVAL;
503
504 ngroups = getgroups_alloc(&gids);
505 if (ngroups < 0)
506 return ngroups;
507
508 return gid_list_has(gids, ngroups, gid);
509 }
510
511 int in_group(const char *name) {
512 int r;
513 gid_t gid;
514
515 r = get_group_creds(&name, &gid, 0);
516 if (r < 0)
517 return r;
518
519 return in_gid(gid);
520 }
521
522 int merge_gid_lists(const gid_t *list1, size_t size1, const gid_t *list2, size_t size2, gid_t **ret) {
523 size_t nresult = 0;
524 assert(ret);
525
526 if (size2 > INT_MAX - size1)
527 return -ENOBUFS;
528
529 gid_t *buf = new(gid_t, size1 + size2);
530 if (!buf)
531 return -ENOMEM;
532
533 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
534 for (size_t i = 0; i < size1; i++)
535 if (!gid_list_has(buf, nresult, list1[i]))
536 buf[nresult++] = list1[i];
537 for (size_t i = 0; i < size2; i++)
538 if (!gid_list_has(buf, nresult, list2[i]))
539 buf[nresult++] = list2[i];
540 *ret = buf;
541 return (int)nresult;
542 }
543
544 int getgroups_alloc(gid_t** gids) {
545 gid_t *allocated;
546 _cleanup_free_ gid_t *p = NULL;
547 int ngroups = 8;
548 unsigned attempt = 0;
549
550 allocated = new(gid_t, ngroups);
551 if (!allocated)
552 return -ENOMEM;
553 p = allocated;
554
555 for (;;) {
556 ngroups = getgroups(ngroups, p);
557 if (ngroups >= 0)
558 break;
559 if (errno != EINVAL)
560 return -errno;
561
562 /* Give up eventually */
563 if (attempt++ > 10)
564 return -EINVAL;
565
566 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
567 * to use (in multi-threaded programs), hence let's call this in a loop. */
568 ngroups = getgroups(0, NULL);
569 if (ngroups < 0)
570 return -errno;
571 if (ngroups == 0)
572 return false;
573
574 free(allocated);
575
576 p = allocated = new(gid_t, ngroups);
577 if (!allocated)
578 return -ENOMEM;
579 }
580
581 *gids = TAKE_PTR(p);
582 return ngroups;
583 }
584
585 int get_home_dir(char **ret) {
586 struct passwd *p;
587 const char *e;
588 char *h;
589 uid_t u;
590
591 assert(ret);
592
593 /* Take the user specified one */
594 e = secure_getenv("HOME");
595 if (e && path_is_valid(e) && path_is_absolute(e))
596 goto found;
597
598 /* Hardcode home directory for root and nobody to avoid NSS */
599 u = getuid();
600 if (u == 0) {
601 e = "/root";
602 goto found;
603 }
604
605 if (u == UID_NOBODY && synthesize_nobody()) {
606 e = "/";
607 goto found;
608 }
609
610 /* Check the database... */
611 errno = 0;
612 p = getpwuid(u);
613 if (!p)
614 return errno_or_else(ESRCH);
615 e = p->pw_dir;
616
617 if (!path_is_valid(e) || !path_is_absolute(e))
618 return -EINVAL;
619
620 found:
621 h = strdup(e);
622 if (!h)
623 return -ENOMEM;
624
625 *ret = path_simplify(h);
626 return 0;
627 }
628
629 int get_shell(char **ret) {
630 struct passwd *p;
631 const char *e;
632 char *s;
633 uid_t u;
634
635 assert(ret);
636
637 /* Take the user specified one */
638 e = secure_getenv("SHELL");
639 if (e && path_is_valid(e) && path_is_absolute(e))
640 goto found;
641
642 /* Hardcode shell for root and nobody to avoid NSS */
643 u = getuid();
644 if (u == 0) {
645 e = default_root_shell(NULL);
646 goto found;
647 }
648 if (u == UID_NOBODY && synthesize_nobody()) {
649 e = NOLOGIN;
650 goto found;
651 }
652
653 /* Check the database... */
654 errno = 0;
655 p = getpwuid(u);
656 if (!p)
657 return errno_or_else(ESRCH);
658 e = p->pw_shell;
659
660 if (!path_is_valid(e) || !path_is_absolute(e))
661 return -EINVAL;
662
663 found:
664 s = strdup(e);
665 if (!s)
666 return -ENOMEM;
667
668 *ret = path_simplify(s);
669 return 0;
670 }
671
672 int reset_uid_gid(void) {
673 int r;
674
675 r = maybe_setgroups(0, NULL);
676 if (r < 0)
677 return r;
678
679 if (setresgid(0, 0, 0) < 0)
680 return -errno;
681
682 return RET_NERRNO(setresuid(0, 0, 0));
683 }
684
685 int take_etc_passwd_lock(const char *root) {
686 int r;
687
688 /* This is roughly the same as lckpwdf(), but not as awful. We don't want to use alarm() and signals,
689 * hence we implement our own trivial version of this.
690 *
691 * Note that shadow-utils also takes per-database locks in addition to lckpwdf(). However, we don't,
692 * given that they are redundant: they invoke lckpwdf() first and keep it during everything they do.
693 * The per-database locks are awfully racy, and thus we just won't do them. */
694
695 _cleanup_free_ char *path = path_join(root, ETC_PASSWD_LOCK_PATH);
696 if (!path)
697 return log_oom_debug();
698
699 (void) mkdir_parents(path, 0755);
700
701 _cleanup_close_ int fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
702 if (fd < 0)
703 return log_debug_errno(errno, "Cannot open %s: %m", path);
704
705 r = unposix_lock(fd, LOCK_EX);
706 if (r < 0)
707 return log_debug_errno(r, "Locking %s failed: %m", path);
708
709 return TAKE_FD(fd);
710 }
711
712 bool valid_user_group_name(const char *u, ValidUserFlags flags) {
713 const char *i;
714
715 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
716 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
717 * pretty much everything except the really worst offending names.
718 *
719 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
720 * created by other stuff, let's be more liberal. */
721
722 if (isempty(u)) /* An empty user name is never valid */
723 return false;
724
725 if (parse_uid(u, NULL) >= 0) /* Something that parses as numeric UID string is valid exactly when the
726 * flag for it is set */
727 return FLAGS_SET(flags, VALID_USER_ALLOW_NUMERIC);
728
729 if (FLAGS_SET(flags, VALID_USER_RELAX)) {
730
731 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
732 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
733 * is bound to cause problems for example when used with an MTA), hence only filter the most
734 * obvious cases, or where things would result in an invalid entry if such a user name would
735 * show up in /etc/passwd (or equivalent getent output).
736 *
737 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
738 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
739 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
740 * have...) */
741
742 if (startswith(u, " ") || endswith(u, " ")) /* At least expect whitespace padding is removed
743 * at front and back (accept in the middle, since
744 * that's apparently a thing on Windows). Note
745 * that this also blocks usernames consisting of
746 * whitespace only. */
747 return false;
748
749 if (!utf8_is_valid(u)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
750 return false;
751
752 if (string_has_cc(u, NULL)) /* CC characters are just dangerous (and \n in particular is the
753 * record separator in /etc/passwd), so we can't allow that. */
754 return false;
755
756 if (strpbrk(u, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
757 * that. Slashes are special to file systems paths and user names
758 * typically show up in the file system as home directories, hence
759 * don't allow slashes. */
760 return false;
761
762 if (in_charset(u, "0123456789")) /* Don't allow fully numeric strings, they might be confused
763 * with UIDs (note that this test is more broad than
764 * the parse_uid() test above, as it will cover more than
765 * the 32bit range, and it will detect 65535 (which is in
766 * invalid UID, even though in the unsigned 32 bit range) */
767 return false;
768
769 if (u[0] == '-' && in_charset(u + 1, "0123456789")) /* Don't allow negative fully numeric
770 * strings either. After all some people
771 * write 65535 as -1 (even though that's
772 * not even true on 32bit uid_t
773 * anyway) */
774 return false;
775
776 if (dot_or_dot_dot(u)) /* User names typically become home directory names, and these two are
777 * special in that context, don't allow that. */
778 return false;
779
780 /* Compare with strict result and warn if result doesn't match */
781 if (FLAGS_SET(flags, VALID_USER_WARN) && !valid_user_group_name(u, 0))
782 log_struct(LOG_NOTICE,
783 LOG_MESSAGE("Accepting user/group name '%s', which does not match strict user/group name rules.", u),
784 "USER_GROUP_NAME=%s", u,
785 "MESSAGE_ID=" SD_MESSAGE_UNSAFE_USER_NAME_STR);
786
787 /* Note that we make no restrictions on the length in relaxed mode! */
788 } else {
789 long sz;
790 size_t l;
791
792 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
793 * however. Specifically we deviate from POSIX rules:
794 *
795 * - We don't allow empty user names (see above)
796 * - We require that names fit into the appropriate utmp field
797 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
798 * - We don't allow dashes or digit as the first character
799 *
800 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
801 */
802
803 if (!ascii_isalpha(u[0]) &&
804 u[0] != '_')
805 return false;
806
807 for (i = u+1; *i; i++)
808 if (!ascii_isalpha(*i) &&
809 !ascii_isdigit(*i) &&
810 !IN_SET(*i, '_', '-'))
811 return false;
812
813 l = i - u;
814
815 sz = sysconf(_SC_LOGIN_NAME_MAX);
816 assert_se(sz > 0);
817
818 if (l > (size_t) sz)
819 return false;
820 if (l > NAME_MAX) /* must fit in a filename */
821 return false;
822 if (l > UT_NAMESIZE - 1)
823 return false;
824 }
825
826 return true;
827 }
828
829 bool valid_gecos(const char *d) {
830
831 if (!d)
832 return false;
833
834 if (!utf8_is_valid(d))
835 return false;
836
837 if (string_has_cc(d, NULL))
838 return false;
839
840 /* Colons are used as field separators, and hence not OK */
841 if (strchr(d, ':'))
842 return false;
843
844 return true;
845 }
846
847 char *mangle_gecos(const char *d) {
848 char *mangled;
849
850 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
851 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
852 * UTF-8 */
853
854 mangled = strdup(d);
855 if (!mangled)
856 return NULL;
857
858 for (char *i = mangled; *i; i++) {
859 int len;
860
861 if ((uint8_t) *i < (uint8_t) ' ' || *i == ':') {
862 *i = ' ';
863 continue;
864 }
865
866 len = utf8_encoded_valid_unichar(i, SIZE_MAX);
867 if (len < 0) {
868 *i = ' ';
869 continue;
870 }
871
872 i += len - 1;
873 }
874
875 return mangled;
876 }
877
878 bool valid_home(const char *p) {
879 /* Note that this function is also called by valid_shell(), any
880 * changes must account for that. */
881
882 if (isempty(p))
883 return false;
884
885 if (!utf8_is_valid(p))
886 return false;
887
888 if (string_has_cc(p, NULL))
889 return false;
890
891 if (!path_is_absolute(p))
892 return false;
893
894 if (!path_is_normalized(p))
895 return false;
896
897 /* Colons are used as field separators, and hence not OK */
898 if (strchr(p, ':'))
899 return false;
900
901 return true;
902 }
903
904 int maybe_setgroups(size_t size, const gid_t *list) {
905 int r;
906
907 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
908 if (size == 0) { /* Dropping all aux groups? */
909 _cleanup_free_ char *setgroups_content = NULL;
910 bool can_setgroups;
911
912 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
913 if (r == -ENOENT)
914 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
915 can_setgroups = true;
916 else if (r < 0)
917 return r;
918 else
919 can_setgroups = streq(setgroups_content, "allow");
920
921 if (!can_setgroups) {
922 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
923 return 0;
924 }
925 }
926
927 return RET_NERRNO(setgroups(size, list));
928 }
929
930 bool synthesize_nobody(void) {
931 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
932 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
933 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
934 *
935 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
936 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
937 * shouldn't matter as each initialization should come to the same result. */
938 static int cache = -1;
939
940 if (cache < 0)
941 cache = access("/etc/systemd/dont-synthesize-nobody", F_OK) < 0;
942
943 return cache;
944 }
945
946 int putpwent_sane(const struct passwd *pw, FILE *stream) {
947 assert(pw);
948 assert(stream);
949
950 errno = 0;
951 if (putpwent(pw, stream) != 0)
952 return errno_or_else(EIO);
953
954 return 0;
955 }
956
957 int putspent_sane(const struct spwd *sp, FILE *stream) {
958 assert(sp);
959 assert(stream);
960
961 errno = 0;
962 if (putspent(sp, stream) != 0)
963 return errno_or_else(EIO);
964
965 return 0;
966 }
967
968 int putgrent_sane(const struct group *gr, FILE *stream) {
969 assert(gr);
970 assert(stream);
971
972 errno = 0;
973 if (putgrent(gr, stream) != 0)
974 return errno_or_else(EIO);
975
976 return 0;
977 }
978
979 #if ENABLE_GSHADOW
980 int putsgent_sane(const struct sgrp *sg, FILE *stream) {
981 assert(sg);
982 assert(stream);
983
984 errno = 0;
985 if (putsgent(sg, stream) != 0)
986 return errno_or_else(EIO);
987
988 return 0;
989 }
990 #endif
991
992 int fgetpwent_sane(FILE *stream, struct passwd **pw) {
993 assert(stream);
994 assert(pw);
995
996 errno = 0;
997 struct passwd *p = fgetpwent(stream);
998 if (!p && errno != ENOENT)
999 return errno_or_else(EIO);
1000
1001 *pw = p;
1002 return !!p;
1003 }
1004
1005 int fgetspent_sane(FILE *stream, struct spwd **sp) {
1006 assert(stream);
1007 assert(sp);
1008
1009 errno = 0;
1010 struct spwd *s = fgetspent(stream);
1011 if (!s && errno != ENOENT)
1012 return errno_or_else(EIO);
1013
1014 *sp = s;
1015 return !!s;
1016 }
1017
1018 int fgetgrent_sane(FILE *stream, struct group **gr) {
1019 assert(stream);
1020 assert(gr);
1021
1022 errno = 0;
1023 struct group *g = fgetgrent(stream);
1024 if (!g && errno != ENOENT)
1025 return errno_or_else(EIO);
1026
1027 *gr = g;
1028 return !!g;
1029 }
1030
1031 #if ENABLE_GSHADOW
1032 int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
1033 assert(stream);
1034 assert(sg);
1035
1036 errno = 0;
1037 struct sgrp *s = fgetsgent(stream);
1038 if (!s && errno != ENOENT)
1039 return errno_or_else(EIO);
1040
1041 *sg = s;
1042 return !!s;
1043 }
1044 #endif
1045
1046 int is_this_me(const char *username) {
1047 uid_t uid;
1048 int r;
1049
1050 /* Checks if the specified username is our current one. Passed string might be a UID or a user name. */
1051
1052 r = get_user_creds(&username, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
1053 if (r < 0)
1054 return r;
1055
1056 return uid == getuid();
1057 }
1058
1059 const char *get_home_root(void) {
1060 const char *e;
1061
1062 /* For debug purposes allow overriding where we look for home dirs */
1063 e = secure_getenv("SYSTEMD_HOME_ROOT");
1064 if (e && path_is_absolute(e) && path_is_normalized(e))
1065 return e;
1066
1067 return "/home";
1068 }