]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/user-util.c
user-util: add get{pw,gr}{uid,gid,name}_malloc() helpers
[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/file.h>
10 #include <sys/stat.h>
11 #include <unistd.h>
12 #include <utmp.h>
13
14 #include "sd-messages.h"
15
16 #include "alloc-util.h"
17 #include "chase.h"
18 #include "errno-util.h"
19 #include "fd-util.h"
20 #include "fileio.h"
21 #include "format-util.h"
22 #include "lock-util.h"
23 #include "macro.h"
24 #include "mkdir.h"
25 #include "parse-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 16 bit, hence explicitly avoid the 16-bit -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 *ret_uid, gid_t *ret_gid,
188 const char **ret_home,
189 const char **ret_shell,
190 UserCredsFlags flags) {
191
192 assert(username);
193 assert(*username);
194
195 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
196 * their user record data. */
197
198 if (STR_IN_SET(*username, "root", "0")) {
199 *username = "root";
200
201 if (ret_uid)
202 *ret_uid = 0;
203 if (ret_gid)
204 *ret_gid = 0;
205 if (ret_home)
206 *ret_home = "/root";
207 if (ret_shell)
208 *ret_shell = default_root_shell(NULL);
209
210 return 0;
211 }
212
213 if (STR_IN_SET(*username, NOBODY_USER_NAME, "65534") &&
214 synthesize_nobody()) {
215 *username = NOBODY_USER_NAME;
216
217 if (ret_uid)
218 *ret_uid = UID_NOBODY;
219 if (ret_gid)
220 *ret_gid = GID_NOBODY;
221 if (ret_home)
222 *ret_home = FLAGS_SET(flags, USER_CREDS_CLEAN) ? NULL : "/";
223 if (ret_shell)
224 *ret_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 *ret_uid, gid_t *ret_gid,
235 const char **ret_home,
236 const char **ret_shell,
237 UserCredsFlags flags) {
238
239 bool patch_username = false;
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 (!ret_home && !ret_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, ret_uid, ret_gid, ret_home, ret_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 patch_username = true;
275 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING) && !ret_gid && !ret_home && !ret_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 (ret_uid)
282 *ret_uid = u;
283
284 return 0;
285 }
286 } else {
287 errno = 0;
288 p = getpwnam(*username);
289 }
290 if (!p) {
291 /* getpwnam() may fail with ENOENT if /etc/passwd is missing.
292 * For us that is equivalent to the name not being defined. */
293 r = IN_SET(errno, 0, ENOENT) ? -ESRCH : -errno;
294
295 /* If the user requested that we only synthesize as fallback, do so now */
296 if (FLAGS_SET(flags, USER_CREDS_PREFER_NSS))
297 if (synthesize_user_creds(username, ret_uid, ret_gid, ret_home, ret_shell, flags) >= 0)
298 return 0;
299
300 return r;
301 }
302
303 if (ret_uid && !uid_is_valid(p->pw_uid))
304 return -EBADMSG;
305
306 if (ret_gid && !gid_is_valid(p->pw_gid))
307 return -EBADMSG;
308
309 if (ret_uid)
310 *ret_uid = p->pw_uid;
311
312 if (ret_gid)
313 *ret_gid = p->pw_gid;
314
315 if (ret_home)
316 /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
317 *ret_home = (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))) ? NULL : p->pw_dir;
321
322 if (ret_shell)
323 *ret_shell = (FLAGS_SET(flags, USER_CREDS_CLEAN) &&
324 (isempty(p->pw_shell) ||
325 !path_is_valid(p->pw_shell) ||
326 !path_is_absolute(p->pw_shell) ||
327 is_nologin_shell(p->pw_shell))) ? NULL : p->pw_shell;
328
329 if (patch_username)
330 *username = p->pw_name;
331
332 return 0;
333 }
334
335 static int synthesize_group_creds(
336 const char **groupname,
337 gid_t *ret_gid) {
338
339 assert(groupname);
340 assert(*groupname);
341
342 if (STR_IN_SET(*groupname, "root", "0")) {
343 *groupname = "root";
344
345 if (ret_gid)
346 *ret_gid = 0;
347
348 return 0;
349 }
350
351 if (STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534") &&
352 synthesize_nobody()) {
353 *groupname = NOBODY_GROUP_NAME;
354
355 if (ret_gid)
356 *ret_gid = GID_NOBODY;
357
358 return 0;
359 }
360
361 return -ENOMEDIUM;
362 }
363
364 int get_group_creds(const char **groupname, gid_t *ret_gid, UserCredsFlags flags) {
365 bool patch_groupname = false;
366 struct group *g;
367 gid_t id;
368 int r;
369
370 assert(groupname);
371 assert(*groupname);
372
373 if (!FLAGS_SET(flags, USER_CREDS_PREFER_NSS)) {
374 r = synthesize_group_creds(groupname, ret_gid);
375 if (r >= 0)
376 return 0;
377 if (r != -ENOMEDIUM) /* not a groupname we can synthesize */
378 return r;
379 }
380
381 if (parse_gid(*groupname, &id) >= 0) {
382 errno = 0;
383 g = getgrgid(id);
384
385 if (g)
386 patch_groupname = true;
387 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING)) {
388 if (ret_gid)
389 *ret_gid = id;
390
391 return 0;
392 }
393 } else {
394 errno = 0;
395 g = getgrnam(*groupname);
396 }
397
398 if (!g) {
399 /* getgrnam() may fail with ENOENT if /etc/group is missing.
400 * For us that is equivalent to the name not being defined. */
401 r = IN_SET(errno, 0, ENOENT) ? -ESRCH : -errno;
402
403 if (FLAGS_SET(flags, USER_CREDS_PREFER_NSS))
404 if (synthesize_group_creds(groupname, ret_gid) >= 0)
405 return 0;
406
407 return r;
408 }
409
410 if (ret_gid) {
411 if (!gid_is_valid(g->gr_gid))
412 return -EBADMSG;
413
414 *ret_gid = g->gr_gid;
415 }
416
417 if (patch_groupname)
418 *groupname = g->gr_name;
419
420 return 0;
421 }
422
423 char* uid_to_name(uid_t uid) {
424 char *ret;
425 int r;
426
427 /* Shortcut things to avoid NSS lookups */
428 if (uid == 0)
429 return strdup("root");
430 if (uid == UID_NOBODY && synthesize_nobody())
431 return strdup(NOBODY_USER_NAME);
432
433 if (uid_is_valid(uid)) {
434 _cleanup_free_ struct passwd *pw = NULL;
435
436 r = getpwuid_malloc(uid, &pw);
437 if (r >= 0)
438 return strdup(pw->pw_name);
439 }
440
441 if (asprintf(&ret, UID_FMT, uid) < 0)
442 return NULL;
443
444 return ret;
445 }
446
447 char* gid_to_name(gid_t gid) {
448 char *ret;
449 int r;
450
451 if (gid == 0)
452 return strdup("root");
453 if (gid == GID_NOBODY && synthesize_nobody())
454 return strdup(NOBODY_GROUP_NAME);
455
456 if (gid_is_valid(gid)) {
457 _cleanup_free_ struct group *gr = NULL;
458
459 r = getgrgid_malloc(gid, &gr);
460 if (r >= 0)
461 return strdup(gr->gr_name);
462 }
463
464 if (asprintf(&ret, GID_FMT, gid) < 0)
465 return NULL;
466
467 return ret;
468 }
469
470 static bool gid_list_has(const gid_t *list, size_t size, gid_t val) {
471 for (size_t i = 0; i < size; i++)
472 if (list[i] == val)
473 return true;
474 return false;
475 }
476
477 int in_gid(gid_t gid) {
478 _cleanup_free_ gid_t *gids = NULL;
479 int ngroups;
480
481 if (getgid() == gid)
482 return 1;
483
484 if (getegid() == gid)
485 return 1;
486
487 if (!gid_is_valid(gid))
488 return -EINVAL;
489
490 ngroups = getgroups_alloc(&gids);
491 if (ngroups < 0)
492 return ngroups;
493
494 return gid_list_has(gids, ngroups, gid);
495 }
496
497 int in_group(const char *name) {
498 int r;
499 gid_t gid;
500
501 r = get_group_creds(&name, &gid, 0);
502 if (r < 0)
503 return r;
504
505 return in_gid(gid);
506 }
507
508 int merge_gid_lists(const gid_t *list1, size_t size1, const gid_t *list2, size_t size2, gid_t **ret) {
509 size_t nresult = 0;
510 assert(ret);
511
512 if (size2 > INT_MAX - size1)
513 return -ENOBUFS;
514
515 gid_t *buf = new(gid_t, size1 + size2);
516 if (!buf)
517 return -ENOMEM;
518
519 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
520 for (size_t i = 0; i < size1; i++)
521 if (!gid_list_has(buf, nresult, list1[i]))
522 buf[nresult++] = list1[i];
523 for (size_t i = 0; i < size2; i++)
524 if (!gid_list_has(buf, nresult, list2[i]))
525 buf[nresult++] = list2[i];
526 *ret = buf;
527 return (int)nresult;
528 }
529
530 int getgroups_alloc(gid_t** gids) {
531 gid_t *allocated;
532 _cleanup_free_ gid_t *p = NULL;
533 int ngroups = 8;
534 unsigned attempt = 0;
535
536 allocated = new(gid_t, ngroups);
537 if (!allocated)
538 return -ENOMEM;
539 p = allocated;
540
541 for (;;) {
542 ngroups = getgroups(ngroups, p);
543 if (ngroups >= 0)
544 break;
545 if (errno != EINVAL)
546 return -errno;
547
548 /* Give up eventually */
549 if (attempt++ > 10)
550 return -EINVAL;
551
552 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
553 * to use (in multi-threaded programs), hence let's call this in a loop. */
554 ngroups = getgroups(0, NULL);
555 if (ngroups < 0)
556 return -errno;
557 if (ngroups == 0)
558 return false;
559
560 free(allocated);
561
562 p = allocated = new(gid_t, ngroups);
563 if (!allocated)
564 return -ENOMEM;
565 }
566
567 *gids = TAKE_PTR(p);
568 return ngroups;
569 }
570
571 int get_home_dir(char **ret) {
572 _cleanup_free_ struct passwd *p = NULL;
573 const char *e;
574 uid_t u;
575 int r;
576
577 assert(ret);
578
579 /* Take the user specified one */
580 e = secure_getenv("HOME");
581 if (e && path_is_valid(e) && path_is_absolute(e))
582 goto found;
583
584 /* Hardcode home directory for root and nobody to avoid NSS */
585 u = getuid();
586 if (u == 0) {
587 e = "/root";
588 goto found;
589 }
590 if (u == UID_NOBODY && synthesize_nobody()) {
591 e = "/";
592 goto found;
593 }
594
595 /* Check the database... */
596 r = getpwuid_malloc(u, &p);
597 if (r < 0)
598 return r;
599
600 e = p->pw_dir;
601 if (!path_is_valid(e) || !path_is_absolute(e))
602 return -EINVAL;
603
604 found:
605 return path_simplify_alloc(e, ret);
606 }
607
608 int get_shell(char **ret) {
609 _cleanup_free_ struct passwd *p = NULL;
610 const char *e;
611 uid_t u;
612 int r;
613
614 assert(ret);
615
616 /* Take the user specified one */
617 e = secure_getenv("SHELL");
618 if (e && path_is_valid(e) && path_is_absolute(e))
619 goto found;
620
621 /* Hardcode shell for root and nobody to avoid NSS */
622 u = getuid();
623 if (u == 0) {
624 e = default_root_shell(NULL);
625 goto found;
626 }
627 if (u == UID_NOBODY && synthesize_nobody()) {
628 e = NOLOGIN;
629 goto found;
630 }
631
632 /* Check the database... */
633 r = getpwuid_malloc(u, &p);
634 if (r < 0)
635 return r;
636
637 e = p->pw_shell;
638 if (!path_is_valid(e) || !path_is_absolute(e))
639 return -EINVAL;
640
641 found:
642 return path_simplify_alloc(e, ret);
643 }
644
645 int fully_set_uid_gid(uid_t uid, gid_t gid, const gid_t supplementary_gids[], size_t n_supplementary_gids) {
646 int r;
647
648 assert(supplementary_gids || n_supplementary_gids == 0);
649
650 /* Sets all UIDs and all GIDs to the specified ones. Drops all auxiliary GIDs */
651
652 r = maybe_setgroups(n_supplementary_gids, supplementary_gids);
653 if (r < 0)
654 return r;
655
656 if (gid_is_valid(gid))
657 if (setresgid(gid, gid, gid) < 0)
658 return -errno;
659
660 if (uid_is_valid(uid))
661 if (setresuid(uid, uid, uid) < 0)
662 return -errno;
663
664 return 0;
665 }
666
667 int take_etc_passwd_lock(const char *root) {
668 int r;
669
670 /* This is roughly the same as lckpwdf(), but not as awful. We don't want to use alarm() and signals,
671 * hence we implement our own trivial version of this.
672 *
673 * Note that shadow-utils also takes per-database locks in addition to lckpwdf(). However, we don't,
674 * given that they are redundant: they invoke lckpwdf() first and keep it during everything they do.
675 * The per-database locks are awfully racy, and thus we just won't do them. */
676
677 _cleanup_free_ char *path = path_join(root, ETC_PASSWD_LOCK_PATH);
678 if (!path)
679 return log_oom_debug();
680
681 (void) mkdir_parents(path, 0755);
682
683 _cleanup_close_ int fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
684 if (fd < 0)
685 return log_debug_errno(errno, "Cannot open %s: %m", path);
686
687 r = unposix_lock(fd, LOCK_EX);
688 if (r < 0)
689 return log_debug_errno(r, "Locking %s failed: %m", path);
690
691 return TAKE_FD(fd);
692 }
693
694 bool valid_user_group_name(const char *u, ValidUserFlags flags) {
695 const char *i;
696
697 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
698 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
699 * pretty much everything except the really worst offending names.
700 *
701 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
702 * created by other stuff, let's be more liberal. */
703
704 if (isempty(u)) /* An empty user name is never valid */
705 return false;
706
707 if (parse_uid(u, NULL) >= 0) /* Something that parses as numeric UID string is valid exactly when the
708 * flag for it is set */
709 return FLAGS_SET(flags, VALID_USER_ALLOW_NUMERIC);
710
711 if (FLAGS_SET(flags, VALID_USER_RELAX)) {
712
713 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
714 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
715 * is bound to cause problems for example when used with an MTA), hence only filter the most
716 * obvious cases, or where things would result in an invalid entry if such a user name would
717 * show up in /etc/passwd (or equivalent getent output).
718 *
719 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
720 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
721 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
722 * have...) */
723
724 if (startswith(u, " ") || endswith(u, " ")) /* At least expect whitespace padding is removed
725 * at front and back (accept in the middle, since
726 * that's apparently a thing on Windows). Note
727 * that this also blocks usernames consisting of
728 * whitespace only. */
729 return false;
730
731 if (!utf8_is_valid(u)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
732 return false;
733
734 if (string_has_cc(u, NULL)) /* CC characters are just dangerous (and \n in particular is the
735 * record separator in /etc/passwd), so we can't allow that. */
736 return false;
737
738 if (strpbrk(u, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
739 * that. Slashes are special to file systems paths and user names
740 * typically show up in the file system as home directories, hence
741 * don't allow slashes. */
742 return false;
743
744 if (in_charset(u, "0123456789")) /* Don't allow fully numeric strings, they might be confused
745 * with UIDs (note that this test is more broad than
746 * the parse_uid() test above, as it will cover more than
747 * the 32-bit range, and it will detect 65535 (which is in
748 * invalid UID, even though in the unsigned 32 bit range) */
749 return false;
750
751 if (u[0] == '-' && in_charset(u + 1, "0123456789")) /* Don't allow negative fully numeric
752 * strings either. After all some people
753 * write 65535 as -1 (even though that's
754 * not even true on 32-bit uid_t
755 * anyway) */
756 return false;
757
758 if (dot_or_dot_dot(u)) /* User names typically become home directory names, and these two are
759 * special in that context, don't allow that. */
760 return false;
761
762 /* Compare with strict result and warn if result doesn't match */
763 if (FLAGS_SET(flags, VALID_USER_WARN) && !valid_user_group_name(u, 0))
764 log_struct(LOG_NOTICE,
765 LOG_MESSAGE("Accepting user/group name '%s', which does not match strict user/group name rules.", u),
766 "USER_GROUP_NAME=%s", u,
767 "MESSAGE_ID=" SD_MESSAGE_UNSAFE_USER_NAME_STR);
768
769 /* Note that we make no restrictions on the length in relaxed mode! */
770 } else {
771 long sz;
772 size_t l;
773
774 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
775 * however. Specifically we deviate from POSIX rules:
776 *
777 * - We don't allow empty user names (see above)
778 * - We require that names fit into the appropriate utmp field
779 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
780 * - We don't allow dashes or digit as the first character
781 *
782 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
783 */
784
785 if (!ascii_isalpha(u[0]) &&
786 u[0] != '_')
787 return false;
788
789 for (i = u+1; *i; i++)
790 if (!ascii_isalpha(*i) &&
791 !ascii_isdigit(*i) &&
792 !IN_SET(*i, '_', '-'))
793 return false;
794
795 l = i - u;
796
797 sz = sysconf(_SC_LOGIN_NAME_MAX);
798 assert_se(sz > 0);
799
800 if (l > (size_t) sz)
801 return false;
802 if (l > NAME_MAX) /* must fit in a filename */
803 return false;
804 if (l > UT_NAMESIZE - 1)
805 return false;
806 }
807
808 return true;
809 }
810
811 bool valid_gecos(const char *d) {
812
813 if (!d)
814 return false;
815
816 if (!utf8_is_valid(d))
817 return false;
818
819 if (string_has_cc(d, NULL))
820 return false;
821
822 /* Colons are used as field separators, and hence not OK */
823 if (strchr(d, ':'))
824 return false;
825
826 return true;
827 }
828
829 char* mangle_gecos(const char *d) {
830 char *mangled;
831
832 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
833 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
834 * UTF-8 */
835
836 mangled = strdup(d);
837 if (!mangled)
838 return NULL;
839
840 for (char *i = mangled; *i; i++) {
841 int len;
842
843 if ((uint8_t) *i < (uint8_t) ' ' || *i == ':') {
844 *i = ' ';
845 continue;
846 }
847
848 len = utf8_encoded_valid_unichar(i, SIZE_MAX);
849 if (len < 0) {
850 *i = ' ';
851 continue;
852 }
853
854 i += len - 1;
855 }
856
857 return mangled;
858 }
859
860 bool valid_home(const char *p) {
861 /* Note that this function is also called by valid_shell(), any
862 * changes must account for that. */
863
864 if (isempty(p))
865 return false;
866
867 if (!utf8_is_valid(p))
868 return false;
869
870 if (string_has_cc(p, NULL))
871 return false;
872
873 if (!path_is_absolute(p))
874 return false;
875
876 if (!path_is_normalized(p))
877 return false;
878
879 /* Colons are used as field separators, and hence not OK */
880 if (strchr(p, ':'))
881 return false;
882
883 return true;
884 }
885
886 int maybe_setgroups(size_t size, const gid_t *list) {
887 int r;
888
889 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
890 if (size == 0) { /* Dropping all aux groups? */
891 _cleanup_free_ char *setgroups_content = NULL;
892 bool can_setgroups;
893
894 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
895 if (r == -ENOENT)
896 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
897 can_setgroups = true;
898 else if (r < 0)
899 return r;
900 else
901 can_setgroups = streq(setgroups_content, "allow");
902
903 if (!can_setgroups) {
904 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
905 return 0;
906 }
907 }
908
909 return RET_NERRNO(setgroups(size, list));
910 }
911
912 bool synthesize_nobody(void) {
913 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
914 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
915 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
916 *
917 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
918 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
919 * shouldn't matter as each initialization should come to the same result. */
920 static int cache = -1;
921
922 if (cache < 0)
923 cache = access("/etc/systemd/dont-synthesize-nobody", F_OK) < 0;
924
925 return cache;
926 }
927
928 int putpwent_sane(const struct passwd *pw, FILE *stream) {
929 assert(pw);
930 assert(stream);
931
932 errno = 0;
933 if (putpwent(pw, stream) != 0)
934 return errno_or_else(EIO);
935
936 return 0;
937 }
938
939 int putspent_sane(const struct spwd *sp, FILE *stream) {
940 assert(sp);
941 assert(stream);
942
943 errno = 0;
944 if (putspent(sp, stream) != 0)
945 return errno_or_else(EIO);
946
947 return 0;
948 }
949
950 int putgrent_sane(const struct group *gr, FILE *stream) {
951 assert(gr);
952 assert(stream);
953
954 errno = 0;
955 if (putgrent(gr, stream) != 0)
956 return errno_or_else(EIO);
957
958 return 0;
959 }
960
961 #if ENABLE_GSHADOW
962 int putsgent_sane(const struct sgrp *sg, FILE *stream) {
963 assert(sg);
964 assert(stream);
965
966 errno = 0;
967 if (putsgent(sg, stream) != 0)
968 return errno_or_else(EIO);
969
970 return 0;
971 }
972 #endif
973
974 int fgetpwent_sane(FILE *stream, struct passwd **pw) {
975 assert(stream);
976 assert(pw);
977
978 errno = 0;
979 struct passwd *p = fgetpwent(stream);
980 if (!p && errno != ENOENT)
981 return errno_or_else(EIO);
982
983 *pw = p;
984 return !!p;
985 }
986
987 int fgetspent_sane(FILE *stream, struct spwd **sp) {
988 assert(stream);
989 assert(sp);
990
991 errno = 0;
992 struct spwd *s = fgetspent(stream);
993 if (!s && errno != ENOENT)
994 return errno_or_else(EIO);
995
996 *sp = s;
997 return !!s;
998 }
999
1000 int fgetgrent_sane(FILE *stream, struct group **gr) {
1001 assert(stream);
1002 assert(gr);
1003
1004 errno = 0;
1005 struct group *g = fgetgrent(stream);
1006 if (!g && errno != ENOENT)
1007 return errno_or_else(EIO);
1008
1009 *gr = g;
1010 return !!g;
1011 }
1012
1013 #if ENABLE_GSHADOW
1014 int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
1015 assert(stream);
1016 assert(sg);
1017
1018 errno = 0;
1019 struct sgrp *s = fgetsgent(stream);
1020 if (!s && errno != ENOENT)
1021 return errno_or_else(EIO);
1022
1023 *sg = s;
1024 return !!s;
1025 }
1026 #endif
1027
1028 int is_this_me(const char *username) {
1029 uid_t uid;
1030 int r;
1031
1032 /* Checks if the specified username is our current one. Passed string might be a UID or a user name. */
1033
1034 r = get_user_creds(&username, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
1035 if (r < 0)
1036 return r;
1037
1038 return uid == getuid();
1039 }
1040
1041 const char* get_home_root(void) {
1042 const char *e;
1043
1044 /* For debug purposes allow overriding where we look for home dirs */
1045 e = secure_getenv("SYSTEMD_HOME_ROOT");
1046 if (e && path_is_absolute(e) && path_is_normalized(e))
1047 return e;
1048
1049 return "/home";
1050 }
1051
1052 static size_t getpw_buffer_size(void) {
1053 long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1054 return bufsize <= 0 ? 4096U : (size_t) bufsize;
1055 }
1056
1057 static bool errno_is_user_doesnt_exist(int error) {
1058 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
1059 * not found. */
1060 return IN_SET(abs(error), ENOENT, ESRCH, EBADF, EPERM);
1061 }
1062
1063 int getpwnam_malloc(const char *name, struct passwd **ret) {
1064 size_t bufsize = getpw_buffer_size();
1065 int r;
1066
1067 /* A wrapper around getpwnam_r() that allocates the necessary buffer on the heap. The caller must
1068 * free() the returned sructured! */
1069
1070 if (isempty(name))
1071 return -EINVAL;
1072
1073 for (;;) {
1074 _cleanup_free_ void *buf = NULL;
1075
1076 buf = malloc(ALIGN(sizeof(struct passwd)) + bufsize);
1077 if (!buf)
1078 return -ENOMEM;
1079
1080 struct passwd *pw = NULL;
1081 r = getpwnam_r(name, buf, (char*) buf + ALIGN(sizeof(struct passwd)), (size_t) bufsize, &pw);
1082 if (r == 0) {
1083 if (pw) {
1084 if (ret)
1085 *ret = TAKE_PTR(buf);
1086 return 0;
1087 }
1088
1089 return -ESRCH;
1090 }
1091
1092 assert(r > 0);
1093
1094 /* getpwnam() may fail with ENOENT if /etc/passwd is missing. For us that is equivalent to
1095 * the name not being defined. */
1096 if (errno_is_user_doesnt_exist(r))
1097 return -ESRCH;
1098 if (r != ERANGE)
1099 return -r;
1100
1101 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct passwd)))
1102 return -ENOMEM;
1103 bufsize *= 2;
1104 }
1105 }
1106
1107 int getpwuid_malloc(uid_t uid, struct passwd **ret) {
1108 size_t bufsize = getpw_buffer_size();
1109 int r;
1110
1111 if (!uid_is_valid(uid))
1112 return -EINVAL;
1113
1114 for (;;) {
1115 _cleanup_free_ void *buf = NULL;
1116
1117 buf = malloc(ALIGN(sizeof(struct passwd)) + bufsize);
1118 if (!buf)
1119 return -ENOMEM;
1120
1121 struct passwd *pw = NULL;
1122 r = getpwuid_r(uid, buf, (char*) buf + ALIGN(sizeof(struct passwd)), (size_t) bufsize, &pw);
1123 if (r == 0) {
1124 if (pw) {
1125 if (ret)
1126 *ret = TAKE_PTR(buf);
1127 return 0;
1128 }
1129
1130 return -ESRCH;
1131 }
1132
1133 assert(r > 0);
1134
1135 if (errno_is_user_doesnt_exist(r))
1136 return -ESRCH;
1137 if (r != ERANGE)
1138 return -r;
1139
1140 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct passwd)))
1141 return -ENOMEM;
1142 bufsize *= 2;
1143 }
1144 }
1145
1146 static size_t getgr_buffer_size(void) {
1147 long bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1148 return bufsize <= 0 ? 4096U : (size_t) bufsize;
1149 }
1150
1151 int getgrnam_malloc(const char *name, struct group **ret) {
1152 size_t bufsize = getgr_buffer_size();
1153 int r;
1154
1155 if (isempty(name))
1156 return -EINVAL;
1157
1158 for (;;) {
1159 _cleanup_free_ void *buf = NULL;
1160
1161 buf = malloc(ALIGN(sizeof(struct group)) + bufsize);
1162 if (!buf)
1163 return -ENOMEM;
1164
1165 struct group *gr = NULL;
1166 r = getgrnam_r(name, buf, (char*) buf + ALIGN(sizeof(struct group)), (size_t) bufsize, &gr);
1167 if (r == 0) {
1168 if (gr) {
1169 if (ret)
1170 *ret = TAKE_PTR(buf);
1171 return 0;
1172 }
1173
1174 return -ESRCH;
1175 }
1176
1177 assert(r > 0);
1178
1179 if (errno_is_user_doesnt_exist(r))
1180 return -ESRCH;
1181 if (r != ERANGE)
1182 return -r;
1183
1184 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct group)))
1185 return -ENOMEM;
1186 bufsize *= 2;
1187 }
1188 }
1189
1190 int getgrgid_malloc(gid_t gid, struct group **ret) {
1191 size_t bufsize = getgr_buffer_size();
1192 int r;
1193
1194 if (!gid_is_valid(gid))
1195 return -EINVAL;
1196
1197 for (;;) {
1198 _cleanup_free_ void *buf = NULL;
1199
1200 buf = malloc(ALIGN(sizeof(struct group)) + bufsize);
1201 if (!buf)
1202 return -ENOMEM;
1203
1204 struct group *gr = NULL;
1205 r = getgrgid_r(gid, buf, (char*) buf + ALIGN(sizeof(struct group)), (size_t) bufsize, &gr);
1206 if (r == 0) {
1207 if (gr) {
1208 if (ret)
1209 *ret = TAKE_PTR(buf);
1210 return 0;
1211 }
1212
1213 return -ESRCH;
1214 }
1215
1216 assert(r > 0);
1217
1218 if (errno_is_user_doesnt_exist(r))
1219 return -ESRCH;
1220 if (r != ERANGE)
1221 return -r;
1222
1223 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct group)))
1224 return -ENOMEM;
1225 bufsize *= 2;
1226 }
1227 }