1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
20 #include "alloc-util.h"
23 #include "format-util.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "string-util.h"
30 #include "user-util.h"
33 bool uid_is_valid(uid_t uid) {
35 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
37 /* Some libc APIs use UID_INVALID as special placeholder */
38 if (uid == (uid_t) UINT32_C(0xFFFFFFFF))
41 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
42 if (uid == (uid_t) UINT32_C(0xFFFF))
48 int parse_uid(const char *s, uid_t *ret) {
54 assert_cc(sizeof(uid_t) == sizeof(uint32_t));
55 r = safe_atou32(s, &uid);
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
71 char* getlogname_malloc(void) {
75 if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
80 return uid_to_name(uid);
83 #if 0 /// UNNEEDED by elogind
84 char *getusername_malloc(void) {
91 return uid_to_name(getuid());
96 const char **username,
97 uid_t *uid, gid_t *gid,
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. */
110 if (STR_IN_SET(*username, "root", "0")) {
127 if (synthesize_nobody() &&
128 STR_IN_SET(*username, NOBODY_USER_NAME, "65534")) {
129 *username = NOBODY_USER_NAME;
140 *shell = "/sbin/nologin";
145 if (parse_uid(*username, &u) >= 0) {
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. */
155 *username = p->pw_name;
158 p = getpwnam(*username);
162 return errno > 0 ? -errno : -ESRCH;
165 if (!uid_is_valid(p->pw_uid))
172 if (!gid_is_valid(p->pw_gid))
182 *shell = p->pw_shell;
187 static inline bool is_nologin_shell(const char *shell) {
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. */
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. */
206 #if 0 /// UNNEEDED by elogind
207 int get_user_creds_clean(
208 const char **username,
209 uid_t *uid, gid_t *gid,
211 const char **shell) {
215 /* Like get_user_creds(), but resets home/shell to NULL if they don't contain anything relevant. */
217 r = get_user_creds(username, uid, gid, home, shell);
222 (isempty(*shell) || is_nologin_shell(*shell)))
225 if (home && empty_or_root(*home))
231 int get_group_creds(const char **groupname, gid_t *gid) {
237 /* We enforce some special rules for gid=0: in order to avoid
238 * NSS lookups for root we hardcode its data. */
240 if (STR_IN_SET(*groupname, "root", "0")) {
249 if (synthesize_nobody() &&
250 STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534")) {
251 *groupname = NOBODY_GROUP_NAME;
259 if (parse_gid(*groupname, &id) >= 0) {
264 *groupname = g->gr_name;
267 g = getgrnam(*groupname);
271 return errno > 0 ? -errno : -ESRCH;
274 if (!gid_is_valid(g->gr_gid))
284 char* uid_to_name(uid_t uid) {
288 /* Shortcut things to avoid NSS lookups */
290 return strdup("root");
291 if (synthesize_nobody() &&
293 return strdup(NOBODY_USER_NAME);
295 if (uid_is_valid(uid)) {
298 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
303 struct passwd pwbuf, *pw = NULL;
304 _cleanup_free_ char *buf = NULL;
306 buf = malloc(bufsize);
310 r = getpwuid_r(uid, &pwbuf, buf, (size_t) bufsize, &pw);
312 return strdup(pw->pw_name);
320 if (asprintf(&ret, UID_FMT, uid) < 0)
326 char* gid_to_name(gid_t gid) {
331 return strdup("root");
332 if (synthesize_nobody() &&
334 return strdup(NOBODY_GROUP_NAME);
336 if (gid_is_valid(gid)) {
339 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
344 struct group grbuf, *gr = NULL;
345 _cleanup_free_ char *buf = NULL;
347 buf = malloc(bufsize);
351 r = getgrgid_r(gid, &grbuf, buf, (size_t) bufsize, &gr);
353 return strdup(gr->gr_name);
361 if (asprintf(&ret, GID_FMT, gid) < 0)
367 #if 0 /// UNNEEDED by elogind
368 int in_gid(gid_t gid) {
376 if (getegid() == gid)
379 if (!gid_is_valid(gid))
382 ngroups_max = sysconf(_SC_NGROUPS_MAX);
383 assert(ngroups_max > 0);
385 gids = newa(gid_t, ngroups_max);
387 r = getgroups(ngroups_max, gids);
391 for (i = 0; i < r; i++)
398 int in_group(const char *name) {
402 r = get_group_creds(&name, &gid);
409 int get_home_dir(char **_h) {
417 /* Take the user specified one */
418 e = secure_getenv("HOME");
419 if (e && path_is_absolute(e)) {
428 /* Hardcode home directory for root and nobody to avoid NSS */
438 if (synthesize_nobody() &&
448 /* Check the database... */
452 return errno > 0 ? -errno : -ESRCH;
454 if (!path_is_absolute(p->pw_dir))
457 h = strdup(p->pw_dir);
465 int get_shell(char **_s) {
473 /* Take the user specified one */
484 /* Hardcode shell for root and nobody to avoid NSS */
487 s = strdup("/bin/sh");
494 if (synthesize_nobody() &&
496 s = strdup("/sbin/nologin");
504 /* Check the database... */
508 return errno > 0 ? -errno : -ESRCH;
510 if (!path_is_absolute(p->pw_shell))
513 s = strdup(p->pw_shell);
522 int reset_uid_gid(void) {
525 r = maybe_setgroups(0, NULL);
529 if (setresgid(0, 0, 0) < 0)
532 if (setresuid(0, 0, 0) < 0)
538 #if 0 /// UNNEEDED by elogind
539 int take_etc_passwd_lock(const char *root) {
541 struct flock flock = {
543 .l_whence = SEEK_SET,
551 /* This is roughly the same as lckpwdf(), but not as awful. We
552 * don't want to use alarm() and signals, hence we implement
553 * our own trivial version of this.
555 * Note that shadow-utils also takes per-database locks in
556 * addition to lckpwdf(). However, we don't given that they
557 * are redundant as they invoke lckpwdf() first and keep
558 * it during everything they do. The per-database locks are
559 * awfully racy, and thus we just won't do them. */
562 path = prefix_roota(root, ETC_PASSWD_LOCK_PATH);
564 path = ETC_PASSWD_LOCK_PATH;
566 fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
568 return log_debug_errno(errno, "Cannot open %s: %m", path);
570 r = fcntl(fd, F_SETLKW, &flock);
573 return log_debug_errno(errno, "Locking %s failed: %m", path);
580 bool valid_user_group_name(const char *u) {
584 /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
585 * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
587 * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
588 * - We require that names fit into the appropriate utmp field
589 * - We don't allow empty user names
591 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
597 if (!(u[0] >= 'a' && u[0] <= 'z') &&
598 !(u[0] >= 'A' && u[0] <= 'Z') &&
602 for (i = u+1; *i; i++) {
603 if (!(*i >= 'a' && *i <= 'z') &&
604 !(*i >= 'A' && *i <= 'Z') &&
605 !(*i >= '0' && *i <= '9') &&
606 !IN_SET(*i, '_', '-'))
610 sz = sysconf(_SC_LOGIN_NAME_MAX);
613 if ((size_t) (i-u) > (size_t) sz)
616 if ((size_t) (i-u) > UT_NAMESIZE - 1)
622 bool valid_user_group_name_or_id(const char *u) {
624 /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
625 * range, and not the invalid user ids. */
630 if (valid_user_group_name(u))
633 return parse_uid(u, NULL) >= 0;
636 bool valid_gecos(const char *d) {
641 if (!utf8_is_valid(d))
644 if (string_has_cc(d, NULL))
647 /* Colons are used as field separators, and hence not OK */
654 bool valid_home(const char *p) {
655 /* Note that this function is also called by valid_shell(), any
656 * changes must account for that. */
661 if (!utf8_is_valid(p))
664 if (string_has_cc(p, NULL))
667 if (!path_is_absolute(p))
670 if (!path_is_normalized(p))
673 /* Colons are used as field separators, and hence not OK */
680 int maybe_setgroups(size_t size, const gid_t *list) {
683 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
684 if (size == 0) { /* Dropping all aux groups? */
685 _cleanup_free_ char *setgroups_content = NULL;
688 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
690 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
691 can_setgroups = true;
695 can_setgroups = streq(setgroups_content, "allow");
697 if (!can_setgroups) {
698 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
703 if (setgroups(size, list) < 0)
709 bool synthesize_nobody(void) {
714 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
715 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
716 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
718 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
719 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
720 * shouldn't matter as each initialization should come to the same result. */
721 static int cache = -1;
724 cache = access("/etc/elogind/dont-synthesize-nobody", F_OK) < 0;
730 int putpwent_sane(const struct passwd *pw, FILE *stream) {
735 if (putpwent(pw, stream) != 0)
736 return errno > 0 ? -errno : -EIO;
741 int putspent_sane(const struct spwd *sp, FILE *stream) {
746 if (putspent(sp, stream) != 0)
747 return errno > 0 ? -errno : -EIO;
752 int putgrent_sane(const struct group *gr, FILE *stream) {
757 if (putgrent(gr, stream) != 0)
758 return errno > 0 ? -errno : -EIO;
764 int putsgent_sane(const struct sgrp *sg, FILE *stream) {
769 if (putsgent(sg, stream) != 0)
770 return errno > 0 ? -errno : -EIO;
776 int fgetpwent_sane(FILE *stream, struct passwd **pw) {
783 p = fgetpwent(stream);
784 if (!p && errno != ENOENT)
785 return errno > 0 ? -errno : -EIO;
791 int fgetspent_sane(FILE *stream, struct spwd **sp) {
798 s = fgetspent(stream);
799 if (!s && errno != ENOENT)
800 return errno > 0 ? -errno : -EIO;
806 int fgetgrent_sane(FILE *stream, struct group **gr) {
813 g = fgetgrent(stream);
814 if (!g && errno != ENOENT)
815 return errno > 0 ? -errno : -EIO;
822 int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
829 s = fgetsgent(stream);
830 if (!s && errno != ENOENT)
831 return errno > 0 ? -errno : -EIO;