1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
22 #include "alloc-util.h"
25 #include "format-util.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "string-util.h"
32 #include "user-util.h"
35 bool uid_is_valid(uid_t uid) {
37 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
39 /* Some libc APIs use UID_INVALID as special placeholder */
40 if (uid == (uid_t) UINT32_C(0xFFFFFFFF))
43 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
44 if (uid == (uid_t) UINT32_C(0xFFFF))
50 int parse_uid(const char *s, uid_t *ret) {
56 assert_cc(sizeof(uid_t) == sizeof(uint32_t));
57 r = safe_atou32(s, &uid);
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
73 char* getlogname_malloc(void) {
77 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
82 return uid_to_name(uid);
85 #if 0 /// UNNEEDED by elogind
86 char *getusername_malloc(void) {
93 return uid_to_name(getuid());
98 const char **username,
99 uid_t *uid, gid_t *gid,
101 const char **shell) {
109 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
110 * their user record data. */
112 if (STR_IN_SET(*username, "root", "0")) {
129 if (synthesize_nobody() &&
130 STR_IN_SET(*username, NOBODY_USER_NAME, "65534")) {
131 *username = NOBODY_USER_NAME;
142 *shell = "/sbin/nologin";
147 if (parse_uid(*username, &u) >= 0) {
151 /* If there are multiple users with the same id, make
152 * sure to leave $USER to the configured value instead
153 * of the first occurrence in the database. However if
154 * the uid was configured by a numeric uid, then let's
155 * pick the real username from /etc/passwd. */
157 *username = p->pw_name;
160 p = getpwnam(*username);
164 return errno > 0 ? -errno : -ESRCH;
167 if (!uid_is_valid(p->pw_uid))
174 if (!gid_is_valid(p->pw_gid))
184 *shell = p->pw_shell;
189 static inline bool is_nologin_shell(const char *shell) {
191 return PATH_IN_SET(shell,
192 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
193 * message and exits. Different distributions place the binary at different places though,
194 * hence let's list them all. */
199 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
200 * any message printing. Different distributions place the binary at various places but at
201 * least not in the 'sbin' directory. */
208 #if 0 /// UNNEEDED by elogind
209 int get_user_creds_clean(
210 const char **username,
211 uid_t *uid, gid_t *gid,
213 const char **shell) {
217 /* Like get_user_creds(), but resets home/shell to NULL if they don't contain anything relevant. */
219 r = get_user_creds(username, uid, gid, home, shell);
224 (isempty(*shell) || is_nologin_shell(*shell)))
227 if (home && empty_or_root(*home))
233 int get_group_creds(const char **groupname, gid_t *gid) {
239 /* We enforce some special rules for gid=0: in order to avoid
240 * NSS lookups for root we hardcode its data. */
242 if (STR_IN_SET(*groupname, "root", "0")) {
251 if (synthesize_nobody() &&
252 STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534")) {
253 *groupname = NOBODY_GROUP_NAME;
261 if (parse_gid(*groupname, &id) >= 0) {
266 *groupname = g->gr_name;
269 g = getgrnam(*groupname);
273 return errno > 0 ? -errno : -ESRCH;
276 if (!gid_is_valid(g->gr_gid))
286 char* uid_to_name(uid_t uid) {
290 /* Shortcut things to avoid NSS lookups */
292 return strdup("root");
293 if (synthesize_nobody() &&
295 return strdup(NOBODY_USER_NAME);
297 if (uid_is_valid(uid)) {
300 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
305 struct passwd pwbuf, *pw = NULL;
306 _cleanup_free_ char *buf = NULL;
308 buf = malloc(bufsize);
312 r = getpwuid_r(uid, &pwbuf, buf, (size_t) bufsize, &pw);
314 return strdup(pw->pw_name);
322 if (asprintf(&ret, UID_FMT, uid) < 0)
328 char* gid_to_name(gid_t gid) {
333 return strdup("root");
334 if (synthesize_nobody() &&
336 return strdup(NOBODY_GROUP_NAME);
338 if (gid_is_valid(gid)) {
341 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
346 struct group grbuf, *gr = NULL;
347 _cleanup_free_ char *buf = NULL;
349 buf = malloc(bufsize);
353 r = getgrgid_r(gid, &grbuf, buf, (size_t) bufsize, &gr);
355 return strdup(gr->gr_name);
363 if (asprintf(&ret, GID_FMT, gid) < 0)
369 #if 0 /// UNNEEDED by elogind
370 int in_gid(gid_t gid) {
378 if (getegid() == gid)
381 if (!gid_is_valid(gid))
384 ngroups_max = sysconf(_SC_NGROUPS_MAX);
385 assert(ngroups_max > 0);
387 gids = newa(gid_t, ngroups_max);
389 r = getgroups(ngroups_max, gids);
393 for (i = 0; i < r; i++)
400 int in_group(const char *name) {
404 r = get_group_creds(&name, &gid);
411 int get_home_dir(char **_h) {
419 /* Take the user specified one */
420 e = secure_getenv("HOME");
421 if (e && path_is_absolute(e)) {
430 /* Hardcode home directory for root and nobody to avoid NSS */
440 if (synthesize_nobody() &&
450 /* Check the database... */
454 return errno > 0 ? -errno : -ESRCH;
456 if (!path_is_absolute(p->pw_dir))
459 h = strdup(p->pw_dir);
467 int get_shell(char **_s) {
475 /* Take the user specified one */
486 /* Hardcode shell for root and nobody to avoid NSS */
489 s = strdup("/bin/sh");
496 if (synthesize_nobody() &&
498 s = strdup("/sbin/nologin");
506 /* Check the database... */
510 return errno > 0 ? -errno : -ESRCH;
512 if (!path_is_absolute(p->pw_shell))
515 s = strdup(p->pw_shell);
524 int reset_uid_gid(void) {
527 r = maybe_setgroups(0, NULL);
531 if (setresgid(0, 0, 0) < 0)
534 if (setresuid(0, 0, 0) < 0)
540 #if 0 /// UNNEEDED by elogind
541 int take_etc_passwd_lock(const char *root) {
543 struct flock flock = {
545 .l_whence = SEEK_SET,
553 /* This is roughly the same as lckpwdf(), but not as awful. We
554 * don't want to use alarm() and signals, hence we implement
555 * our own trivial version of this.
557 * Note that shadow-utils also takes per-database locks in
558 * addition to lckpwdf(). However, we don't given that they
559 * are redundant as they invoke lckpwdf() first and keep
560 * it during everything they do. The per-database locks are
561 * awfully racy, and thus we just won't do them. */
564 path = prefix_roota(root, ETC_PASSWD_LOCK_PATH);
566 path = ETC_PASSWD_LOCK_PATH;
568 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
570 return log_debug_errno(errno, "Cannot open %s: %m", path);
572 r = fcntl(fd, F_SETLKW, &flock);
575 return log_debug_errno(errno, "Locking %s failed: %m", path);
582 bool valid_user_group_name(const char *u) {
586 /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
587 * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
589 * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
590 * - We require that names fit into the appropriate utmp field
591 * - We don't allow empty user names
593 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
599 if (!(u[0] >= 'a' && u[0] <= 'z') &&
600 !(u[0] >= 'A' && u[0] <= 'Z') &&
604 for (i = u+1; *i; i++) {
605 if (!(*i >= 'a' && *i <= 'z') &&
606 !(*i >= 'A' && *i <= 'Z') &&
607 !(*i >= '0' && *i <= '9') &&
608 !IN_SET(*i, '_', '-'))
612 sz = sysconf(_SC_LOGIN_NAME_MAX);
615 if ((size_t) (i-u) > (size_t) sz)
618 if ((size_t) (i-u) > UT_NAMESIZE - 1)
624 bool valid_user_group_name_or_id(const char *u) {
626 /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
627 * range, and not the invalid user ids. */
632 if (valid_user_group_name(u))
635 return parse_uid(u, NULL) >= 0;
638 bool valid_gecos(const char *d) {
643 if (!utf8_is_valid(d))
646 if (string_has_cc(d, NULL))
649 /* Colons are used as field separators, and hence not OK */
656 bool valid_home(const char *p) {
657 /* Note that this function is also called by valid_shell(), any
658 * changes must account for that. */
663 if (!utf8_is_valid(p))
666 if (string_has_cc(p, NULL))
669 if (!path_is_absolute(p))
672 if (!path_is_normalized(p))
675 /* Colons are used as field separators, and hence not OK */
682 int maybe_setgroups(size_t size, const gid_t *list) {
685 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
686 if (size == 0) { /* Dropping all aux groups? */
687 _cleanup_free_ char *setgroups_content = NULL;
690 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
692 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
693 can_setgroups = true;
697 can_setgroups = streq(setgroups_content, "allow");
699 if (!can_setgroups) {
700 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
705 if (setgroups(size, list) < 0)
711 bool synthesize_nobody(void) {
716 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
717 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
718 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
720 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
721 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
722 * shouldn't matter as each initialization should come to the same result. */
723 static int cache = -1;
726 cache = access("/etc/elogind/dont-synthesize-nobody", F_OK) < 0;
732 int putpwent_sane(const struct passwd *pw, FILE *stream) {
737 if (putpwent(pw, stream) != 0)
738 return errno > 0 ? -errno : -EIO;
743 int putspent_sane(const struct spwd *sp, FILE *stream) {
748 if (putspent(sp, stream) != 0)
749 return errno > 0 ? -errno : -EIO;
754 int putgrent_sane(const struct group *gr, FILE *stream) {
759 if (putgrent(gr, stream) != 0)
760 return errno > 0 ? -errno : -EIO;
766 int putsgent_sane(const struct sgrp *sg, FILE *stream) {
771 if (putsgent(sg, stream) != 0)
772 return errno > 0 ? -errno : -EIO;
778 int fgetpwent_sane(FILE *stream, struct passwd **pw) {
785 p = fgetpwent(stream);
786 if (!p && errno != ENOENT)
787 return errno > 0 ? -errno : -EIO;
793 int fgetspent_sane(FILE *stream, struct spwd **sp) {
800 s = fgetspent(stream);
801 if (!s && errno != ENOENT)
802 return errno > 0 ? -errno : -EIO;
808 int fgetgrent_sane(FILE *stream, struct group **gr) {
815 g = fgetgrent(stream);
816 if (!g && errno != ENOENT)
817 return errno > 0 ? -errno : -EIO;
824 int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
831 s = fgetsgent(stream);
832 if (!s && errno != ENOENT)
833 return errno > 0 ? -errno : -EIO;