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