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