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