]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/user-util.c
socket-util.h: include string.h
[thirdparty/systemd.git] / src / basic / user-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <alloca.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <grp.h>
7 #include <pwd.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/stat.h>
14 #include <unistd.h>
15 #include <utmp.h>
16
17 #include "alloc-util.h"
18 #include "fd-util.h"
19 #include "fileio.h"
20 #include "format-util.h"
21 #include "macro.h"
22 #include "missing.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "string-util.h"
26 #include "strv.h"
27 #include "user-util.h"
28 #include "utf8.h"
29
30 bool uid_is_valid(uid_t uid) {
31
32 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
33
34 /* Some libc APIs use UID_INVALID as special placeholder */
35 if (uid == (uid_t) UINT32_C(0xFFFFFFFF))
36 return false;
37
38 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
39 if (uid == (uid_t) UINT32_C(0xFFFF))
40 return false;
41
42 return true;
43 }
44
45 int parse_uid(const char *s, uid_t *ret) {
46 uint32_t uid = 0;
47 int r;
48
49 assert(s);
50
51 assert_cc(sizeof(uid_t) == sizeof(uint32_t));
52 r = safe_atou32(s, &uid);
53 if (r < 0)
54 return r;
55
56 if (!uid_is_valid(uid))
57 return -ENXIO; /* we return ENXIO instead of EINVAL
58 * here, to make it easy to distinguish
59 * invalid numeric uids from invalid
60 * strings. */
61
62 if (ret)
63 *ret = uid;
64
65 return 0;
66 }
67
68 char* getlogname_malloc(void) {
69 uid_t uid;
70 struct stat st;
71
72 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
73 uid = st.st_uid;
74 else
75 uid = getuid();
76
77 return uid_to_name(uid);
78 }
79
80 char *getusername_malloc(void) {
81 const char *e;
82
83 e = secure_getenv("USER");
84 if (e)
85 return strdup(e);
86
87 return uid_to_name(getuid());
88 }
89
90 static bool is_nologin_shell(const char *shell) {
91
92 return PATH_IN_SET(shell,
93 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
94 * message and exits. Different distributions place the binary at different places though,
95 * hence let's list them all. */
96 "/bin/nologin",
97 "/sbin/nologin",
98 "/usr/bin/nologin",
99 "/usr/sbin/nologin",
100 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
101 * any message printing. Different distributions place the binary at various places but at
102 * least not in the 'sbin' directory. */
103 "/bin/false",
104 "/usr/bin/false",
105 "/bin/true",
106 "/usr/bin/true");
107 }
108
109 static int synthesize_user_creds(
110 const char **username,
111 uid_t *uid, gid_t *gid,
112 const char **home,
113 const char **shell,
114 UserCredsFlags flags) {
115
116 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
117 * their user record data. */
118
119 if (STR_IN_SET(*username, "root", "0")) {
120 *username = "root";
121
122 if (uid)
123 *uid = 0;
124 if (gid)
125 *gid = 0;
126
127 if (home)
128 *home = "/root";
129
130 if (shell)
131 *shell = "/bin/sh";
132
133 return 0;
134 }
135
136 if (synthesize_nobody() &&
137 STR_IN_SET(*username, NOBODY_USER_NAME, "65534")) {
138 *username = NOBODY_USER_NAME;
139
140 if (uid)
141 *uid = UID_NOBODY;
142 if (gid)
143 *gid = GID_NOBODY;
144
145 if (home)
146 *home = FLAGS_SET(flags, USER_CREDS_CLEAN) ? NULL : "/";
147
148 if (shell)
149 *shell = FLAGS_SET(flags, USER_CREDS_CLEAN) ? NULL : "/sbin/nologin";
150
151 return 0;
152 }
153
154 return -ENOMEDIUM;
155 }
156
157 int get_user_creds(
158 const char **username,
159 uid_t *uid, gid_t *gid,
160 const char **home,
161 const char **shell,
162 UserCredsFlags flags) {
163
164 uid_t u = UID_INVALID;
165 struct passwd *p;
166 int r;
167
168 assert(username);
169 assert(*username);
170
171 if (!FLAGS_SET(flags, USER_CREDS_PREFER_NSS) ||
172 (!home && !shell)) {
173
174 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
175 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
176 * user database will override the synthetic records instead — except if the user is only interested in
177 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
178 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
179 * Simply because there are valid usecase where the user might change the home directory or the shell
180 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
181 * support. */
182
183 r = synthesize_user_creds(username, uid, gid, home, shell, flags);
184 if (r >= 0)
185 return 0;
186 if (r != -ENOMEDIUM) /* not a username we can synthesize */
187 return r;
188 }
189
190 if (parse_uid(*username, &u) >= 0) {
191 errno = 0;
192 p = getpwuid(u);
193
194 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
195 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
196 * then let's pick the real username from /etc/passwd. */
197 if (p)
198 *username = p->pw_name;
199 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING) && !gid && !home && !shell) {
200
201 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
202 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then juts return that
203 * and don't complain. */
204
205 if (uid)
206 *uid = u;
207
208 return 0;
209 }
210 } else {
211 errno = 0;
212 p = getpwnam(*username);
213 }
214 if (!p) {
215 r = errno > 0 ? -errno : -ESRCH;
216
217 /* If the user requested that we only synthesize as fallback, do so now */
218 if (FLAGS_SET(flags, USER_CREDS_PREFER_NSS)) {
219 if (synthesize_user_creds(username, uid, gid, home, shell, flags) >= 0)
220 return 0;
221 }
222
223 return r;
224 }
225
226 if (uid) {
227 if (!uid_is_valid(p->pw_uid))
228 return -EBADMSG;
229
230 *uid = p->pw_uid;
231 }
232
233 if (gid) {
234 if (!gid_is_valid(p->pw_gid))
235 return -EBADMSG;
236
237 *gid = p->pw_gid;
238 }
239
240 if (home) {
241 if (FLAGS_SET(flags, USER_CREDS_CLEAN) &&
242 (empty_or_root(p->pw_dir) ||
243 !path_is_valid(p->pw_dir) ||
244 !path_is_absolute(p->pw_dir)))
245 *home = NULL; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
246 else
247 *home = p->pw_dir;
248 }
249
250 if (shell) {
251 if (FLAGS_SET(flags, USER_CREDS_CLEAN) &&
252 (isempty(p->pw_shell) ||
253 !path_is_valid(p->pw_dir) ||
254 !path_is_absolute(p->pw_shell) ||
255 is_nologin_shell(p->pw_shell)))
256 *shell = NULL;
257 else
258 *shell = p->pw_shell;
259 }
260
261 return 0;
262 }
263
264 int get_group_creds(const char **groupname, gid_t *gid, UserCredsFlags flags) {
265 struct group *g;
266 gid_t id;
267
268 assert(groupname);
269
270 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
271
272 if (STR_IN_SET(*groupname, "root", "0")) {
273 *groupname = "root";
274
275 if (gid)
276 *gid = 0;
277
278 return 0;
279 }
280
281 if (synthesize_nobody() &&
282 STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534")) {
283 *groupname = NOBODY_GROUP_NAME;
284
285 if (gid)
286 *gid = GID_NOBODY;
287
288 return 0;
289 }
290
291 if (parse_gid(*groupname, &id) >= 0) {
292 errno = 0;
293 g = getgrgid(id);
294
295 if (g)
296 *groupname = g->gr_name;
297 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING)) {
298 if (gid)
299 *gid = id;
300
301 return 0;
302 }
303 } else {
304 errno = 0;
305 g = getgrnam(*groupname);
306 }
307
308 if (!g)
309 return errno > 0 ? -errno : -ESRCH;
310
311 if (gid) {
312 if (!gid_is_valid(g->gr_gid))
313 return -EBADMSG;
314
315 *gid = g->gr_gid;
316 }
317
318 return 0;
319 }
320
321 char* uid_to_name(uid_t uid) {
322 char *ret;
323 int r;
324
325 /* Shortcut things to avoid NSS lookups */
326 if (uid == 0)
327 return strdup("root");
328 if (synthesize_nobody() &&
329 uid == UID_NOBODY)
330 return strdup(NOBODY_USER_NAME);
331
332 if (uid_is_valid(uid)) {
333 long bufsize;
334
335 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
336 if (bufsize <= 0)
337 bufsize = 4096;
338
339 for (;;) {
340 struct passwd pwbuf, *pw = NULL;
341 _cleanup_free_ char *buf = NULL;
342
343 buf = malloc(bufsize);
344 if (!buf)
345 return NULL;
346
347 r = getpwuid_r(uid, &pwbuf, buf, (size_t) bufsize, &pw);
348 if (r == 0 && pw)
349 return strdup(pw->pw_name);
350 if (r != ERANGE)
351 break;
352
353 if (bufsize > LONG_MAX/2) /* overflow check */
354 return NULL;
355
356 bufsize *= 2;
357 }
358 }
359
360 if (asprintf(&ret, UID_FMT, uid) < 0)
361 return NULL;
362
363 return ret;
364 }
365
366 char* gid_to_name(gid_t gid) {
367 char *ret;
368 int r;
369
370 if (gid == 0)
371 return strdup("root");
372 if (synthesize_nobody() &&
373 gid == GID_NOBODY)
374 return strdup(NOBODY_GROUP_NAME);
375
376 if (gid_is_valid(gid)) {
377 long bufsize;
378
379 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
380 if (bufsize <= 0)
381 bufsize = 4096;
382
383 for (;;) {
384 struct group grbuf, *gr = NULL;
385 _cleanup_free_ char *buf = NULL;
386
387 buf = malloc(bufsize);
388 if (!buf)
389 return NULL;
390
391 r = getgrgid_r(gid, &grbuf, buf, (size_t) bufsize, &gr);
392 if (r == 0 && gr)
393 return strdup(gr->gr_name);
394 if (r != ERANGE)
395 break;
396
397 if (bufsize > LONG_MAX/2) /* overflow check */
398 return NULL;
399
400 bufsize *= 2;
401 }
402 }
403
404 if (asprintf(&ret, GID_FMT, gid) < 0)
405 return NULL;
406
407 return ret;
408 }
409
410 int in_gid(gid_t gid) {
411 long ngroups_max;
412 gid_t *gids;
413 int r, i;
414
415 if (getgid() == gid)
416 return 1;
417
418 if (getegid() == gid)
419 return 1;
420
421 if (!gid_is_valid(gid))
422 return -EINVAL;
423
424 ngroups_max = sysconf(_SC_NGROUPS_MAX);
425 assert(ngroups_max > 0);
426
427 gids = newa(gid_t, ngroups_max);
428
429 r = getgroups(ngroups_max, gids);
430 if (r < 0)
431 return -errno;
432
433 for (i = 0; i < r; i++)
434 if (gids[i] == gid)
435 return 1;
436
437 return 0;
438 }
439
440 int in_group(const char *name) {
441 int r;
442 gid_t gid;
443
444 r = get_group_creds(&name, &gid, 0);
445 if (r < 0)
446 return r;
447
448 return in_gid(gid);
449 }
450
451 int get_home_dir(char **_h) {
452 struct passwd *p;
453 const char *e;
454 char *h;
455 uid_t u;
456
457 assert(_h);
458
459 /* Take the user specified one */
460 e = secure_getenv("HOME");
461 if (e && path_is_valid(e) && path_is_absolute(e)) {
462 h = strdup(e);
463 if (!h)
464 return -ENOMEM;
465
466 *_h = path_simplify(h, true);
467 return 0;
468 }
469
470 /* Hardcode home directory for root and nobody to avoid NSS */
471 u = getuid();
472 if (u == 0) {
473 h = strdup("/root");
474 if (!h)
475 return -ENOMEM;
476
477 *_h = h;
478 return 0;
479 }
480 if (synthesize_nobody() &&
481 u == UID_NOBODY) {
482 h = strdup("/");
483 if (!h)
484 return -ENOMEM;
485
486 *_h = h;
487 return 0;
488 }
489
490 /* Check the database... */
491 errno = 0;
492 p = getpwuid(u);
493 if (!p)
494 return errno > 0 ? -errno : -ESRCH;
495
496 if (!path_is_valid(p->pw_dir) ||
497 !path_is_absolute(p->pw_dir))
498 return -EINVAL;
499
500 h = strdup(p->pw_dir);
501 if (!h)
502 return -ENOMEM;
503
504 *_h = path_simplify(h, true);
505 return 0;
506 }
507
508 int get_shell(char **_s) {
509 struct passwd *p;
510 const char *e;
511 char *s;
512 uid_t u;
513
514 assert(_s);
515
516 /* Take the user specified one */
517 e = secure_getenv("SHELL");
518 if (e && path_is_valid(e) && path_is_absolute(e)) {
519 s = strdup(e);
520 if (!s)
521 return -ENOMEM;
522
523 *_s = path_simplify(s, true);
524 return 0;
525 }
526
527 /* Hardcode shell for root and nobody to avoid NSS */
528 u = getuid();
529 if (u == 0) {
530 s = strdup("/bin/sh");
531 if (!s)
532 return -ENOMEM;
533
534 *_s = s;
535 return 0;
536 }
537 if (synthesize_nobody() &&
538 u == UID_NOBODY) {
539 s = strdup("/sbin/nologin");
540 if (!s)
541 return -ENOMEM;
542
543 *_s = s;
544 return 0;
545 }
546
547 /* Check the database... */
548 errno = 0;
549 p = getpwuid(u);
550 if (!p)
551 return errno > 0 ? -errno : -ESRCH;
552
553 if (!path_is_valid(p->pw_shell) ||
554 !path_is_absolute(p->pw_shell))
555 return -EINVAL;
556
557 s = strdup(p->pw_shell);
558 if (!s)
559 return -ENOMEM;
560
561 *_s = path_simplify(s, true);
562 return 0;
563 }
564
565 int reset_uid_gid(void) {
566 int r;
567
568 r = maybe_setgroups(0, NULL);
569 if (r < 0)
570 return r;
571
572 if (setresgid(0, 0, 0) < 0)
573 return -errno;
574
575 if (setresuid(0, 0, 0) < 0)
576 return -errno;
577
578 return 0;
579 }
580
581 int take_etc_passwd_lock(const char *root) {
582
583 struct flock flock = {
584 .l_type = F_WRLCK,
585 .l_whence = SEEK_SET,
586 .l_start = 0,
587 .l_len = 0,
588 };
589
590 const char *path;
591 int fd, r;
592
593 /* This is roughly the same as lckpwdf(), but not as awful. We
594 * don't want to use alarm() and signals, hence we implement
595 * our own trivial version of this.
596 *
597 * Note that shadow-utils also takes per-database locks in
598 * addition to lckpwdf(). However, we don't given that they
599 * are redundant as they invoke lckpwdf() first and keep
600 * it during everything they do. The per-database locks are
601 * awfully racy, and thus we just won't do them. */
602
603 if (root)
604 path = prefix_roota(root, ETC_PASSWD_LOCK_PATH);
605 else
606 path = ETC_PASSWD_LOCK_PATH;
607
608 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
609 if (fd < 0)
610 return log_debug_errno(errno, "Cannot open %s: %m", path);
611
612 r = fcntl(fd, F_SETLKW, &flock);
613 if (r < 0) {
614 safe_close(fd);
615 return log_debug_errno(errno, "Locking %s failed: %m", path);
616 }
617
618 return fd;
619 }
620
621 bool valid_user_group_name(const char *u) {
622 const char *i;
623 long sz;
624
625 /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
626 * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
627 *
628 * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
629 * - We require that names fit into the appropriate utmp field
630 * - We don't allow empty user names
631 *
632 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
633 */
634
635 if (isempty(u))
636 return false;
637
638 if (!(u[0] >= 'a' && u[0] <= 'z') &&
639 !(u[0] >= 'A' && u[0] <= 'Z') &&
640 u[0] != '_')
641 return false;
642
643 for (i = u+1; *i; i++) {
644 if (!(*i >= 'a' && *i <= 'z') &&
645 !(*i >= 'A' && *i <= 'Z') &&
646 !(*i >= '0' && *i <= '9') &&
647 !IN_SET(*i, '_', '-'))
648 return false;
649 }
650
651 sz = sysconf(_SC_LOGIN_NAME_MAX);
652 assert_se(sz > 0);
653
654 if ((size_t) (i-u) > (size_t) sz)
655 return false;
656
657 if ((size_t) (i-u) > UT_NAMESIZE - 1)
658 return false;
659
660 return true;
661 }
662
663 bool valid_user_group_name_or_id(const char *u) {
664
665 /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
666 * range, and not the invalid user ids. */
667
668 if (isempty(u))
669 return false;
670
671 if (valid_user_group_name(u))
672 return true;
673
674 return parse_uid(u, NULL) >= 0;
675 }
676
677 bool valid_gecos(const char *d) {
678
679 if (!d)
680 return false;
681
682 if (!utf8_is_valid(d))
683 return false;
684
685 if (string_has_cc(d, NULL))
686 return false;
687
688 /* Colons are used as field separators, and hence not OK */
689 if (strchr(d, ':'))
690 return false;
691
692 return true;
693 }
694
695 bool valid_home(const char *p) {
696 /* Note that this function is also called by valid_shell(), any
697 * changes must account for that. */
698
699 if (isempty(p))
700 return false;
701
702 if (!utf8_is_valid(p))
703 return false;
704
705 if (string_has_cc(p, NULL))
706 return false;
707
708 if (!path_is_absolute(p))
709 return false;
710
711 if (!path_is_normalized(p))
712 return false;
713
714 /* Colons are used as field separators, and hence not OK */
715 if (strchr(p, ':'))
716 return false;
717
718 return true;
719 }
720
721 int maybe_setgroups(size_t size, const gid_t *list) {
722 int r;
723
724 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
725 if (size == 0) { /* Dropping all aux groups? */
726 _cleanup_free_ char *setgroups_content = NULL;
727 bool can_setgroups;
728
729 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
730 if (r == -ENOENT)
731 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
732 can_setgroups = true;
733 else if (r < 0)
734 return r;
735 else
736 can_setgroups = streq(setgroups_content, "allow");
737
738 if (!can_setgroups) {
739 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
740 return 0;
741 }
742 }
743
744 if (setgroups(size, list) < 0)
745 return -errno;
746
747 return 0;
748 }
749
750 bool synthesize_nobody(void) {
751 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
752 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
753 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
754 *
755 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
756 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
757 * shouldn't matter as each initialization should come to the same result. */
758 static int cache = -1;
759
760 if (cache < 0)
761 cache = access("/etc/systemd/dont-synthesize-nobody", F_OK) < 0;
762
763 return cache;
764 }
765
766 int putpwent_sane(const struct passwd *pw, FILE *stream) {
767 assert(pw);
768 assert(stream);
769
770 errno = 0;
771 if (putpwent(pw, stream) != 0)
772 return errno > 0 ? -errno : -EIO;
773
774 return 0;
775 }
776
777 int putspent_sane(const struct spwd *sp, FILE *stream) {
778 assert(sp);
779 assert(stream);
780
781 errno = 0;
782 if (putspent(sp, stream) != 0)
783 return errno > 0 ? -errno : -EIO;
784
785 return 0;
786 }
787
788 int putgrent_sane(const struct group *gr, FILE *stream) {
789 assert(gr);
790 assert(stream);
791
792 errno = 0;
793 if (putgrent(gr, stream) != 0)
794 return errno > 0 ? -errno : -EIO;
795
796 return 0;
797 }
798
799 #if ENABLE_GSHADOW
800 int putsgent_sane(const struct sgrp *sg, FILE *stream) {
801 assert(sg);
802 assert(stream);
803
804 errno = 0;
805 if (putsgent(sg, stream) != 0)
806 return errno > 0 ? -errno : -EIO;
807
808 return 0;
809 }
810 #endif
811
812 int fgetpwent_sane(FILE *stream, struct passwd **pw) {
813 struct passwd *p;
814
815 assert(pw);
816 assert(stream);
817
818 errno = 0;
819 p = fgetpwent(stream);
820 if (!p && errno != ENOENT)
821 return errno > 0 ? -errno : -EIO;
822
823 *pw = p;
824 return !!p;
825 }
826
827 int fgetspent_sane(FILE *stream, struct spwd **sp) {
828 struct spwd *s;
829
830 assert(sp);
831 assert(stream);
832
833 errno = 0;
834 s = fgetspent(stream);
835 if (!s && errno != ENOENT)
836 return errno > 0 ? -errno : -EIO;
837
838 *sp = s;
839 return !!s;
840 }
841
842 int fgetgrent_sane(FILE *stream, struct group **gr) {
843 struct group *g;
844
845 assert(gr);
846 assert(stream);
847
848 errno = 0;
849 g = fgetgrent(stream);
850 if (!g && errno != ENOENT)
851 return errno > 0 ? -errno : -EIO;
852
853 *gr = g;
854 return !!g;
855 }
856
857 #if ENABLE_GSHADOW
858 int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
859 struct sgrp *s;
860
861 assert(sg);
862 assert(stream);
863
864 errno = 0;
865 s = fgetsgent(stream);
866 if (!s && errno != ENOENT)
867 return errno > 0 ? -errno : -EIO;
868
869 *sg = s;
870 return !!s;
871 }
872 #endif