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