]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/user-util.c
d127b0c107282562e6a6d41cb077eae45765a908
1 /* SPDX-License-Identifier: LGPL-2.1+ */
17 #include "alloc-util.h"
18 #include "errno-util.h"
21 #include "format-util.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "random-util.h"
27 #include "string-util.h"
29 #include "user-util.h"
32 bool uid_is_valid(uid_t uid
) {
34 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
36 /* Some libc APIs use UID_INVALID as special placeholder */
37 if (uid
== (uid_t
) UINT32_C(0xFFFFFFFF))
40 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
41 if (uid
== (uid_t
) UINT32_C(0xFFFF))
47 int parse_uid(const char *s
, uid_t
*ret
) {
53 assert_cc(sizeof(uid_t
) == sizeof(uint32_t));
54 r
= safe_atou32(s
, &uid
);
58 if (!uid_is_valid(uid
))
59 return -ENXIO
; /* we return ENXIO instead of EINVAL
60 * here, to make it easy to distinguish
61 * invalid numeric uids from invalid
70 char* getlogname_malloc(void) {
74 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
79 return uid_to_name(uid
);
82 char *getusername_malloc(void) {
85 e
= secure_getenv("USER");
89 return uid_to_name(getuid());
92 static bool is_nologin_shell(const char *shell
) {
94 return PATH_IN_SET(shell
,
95 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
96 * message and exits. Different distributions place the binary at different places though,
97 * hence let's list them all. */
102 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
103 * any message printing. Different distributions place the binary at various places but at
104 * least not in the 'sbin' directory. */
111 static int synthesize_user_creds(
112 const char **username
,
113 uid_t
*uid
, gid_t
*gid
,
116 UserCredsFlags flags
) {
118 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
119 * their user record data. */
121 if (STR_IN_SET(*username
, "root", "0")) {
138 if (synthesize_nobody() &&
139 STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534")) {
140 *username
= NOBODY_USER_NAME
;
148 *home
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/";
151 *shell
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: NOLOGIN
;
160 const char **username
,
161 uid_t
*uid
, gid_t
*gid
,
164 UserCredsFlags flags
) {
166 uid_t u
= UID_INVALID
;
173 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
176 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
177 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
178 * user database will override the synthetic records instead — except if the user is only interested in
179 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
180 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
181 * Simply because there are valid usecase where the user might change the home directory or the shell
182 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
185 r
= synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
);
188 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
192 if (parse_uid(*username
, &u
) >= 0) {
196 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
197 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
198 * then let's pick the real username from /etc/passwd. */
200 *username
= p
->pw_name
;
201 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !gid
&& !home
&& !shell
) {
203 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
204 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then juts return that
205 * and don't complain. */
214 p
= getpwnam(*username
);
217 r
= errno_or_else(ESRCH
);
219 /* If the user requested that we only synthesize as fallback, do so now */
220 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
)) {
221 if (synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
) >= 0)
229 if (!uid_is_valid(p
->pw_uid
))
236 if (!gid_is_valid(p
->pw_gid
))
243 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
244 (empty_or_root(p
->pw_dir
) ||
245 !path_is_valid(p
->pw_dir
) ||
246 !path_is_absolute(p
->pw_dir
)))
247 *home
= NULL
; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
253 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
254 (isempty(p
->pw_shell
) ||
255 !path_is_valid(p
->pw_dir
) ||
256 !path_is_absolute(p
->pw_shell
) ||
257 is_nologin_shell(p
->pw_shell
)))
260 *shell
= p
->pw_shell
;
266 int get_group_creds(const char **groupname
, gid_t
*gid
, UserCredsFlags flags
) {
272 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
274 if (STR_IN_SET(*groupname
, "root", "0")) {
283 if (synthesize_nobody() &&
284 STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534")) {
285 *groupname
= NOBODY_GROUP_NAME
;
293 if (parse_gid(*groupname
, &id
) >= 0) {
298 *groupname
= g
->gr_name
;
299 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
307 g
= getgrnam(*groupname
);
311 return errno_or_else(ESRCH
);
314 if (!gid_is_valid(g
->gr_gid
))
323 char* uid_to_name(uid_t uid
) {
327 /* Shortcut things to avoid NSS lookups */
329 return strdup("root");
330 if (synthesize_nobody() &&
332 return strdup(NOBODY_USER_NAME
);
334 if (uid_is_valid(uid
)) {
337 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
342 struct passwd pwbuf
, *pw
= NULL
;
343 _cleanup_free_
char *buf
= NULL
;
345 buf
= malloc(bufsize
);
349 r
= getpwuid_r(uid
, &pwbuf
, buf
, (size_t) bufsize
, &pw
);
351 return strdup(pw
->pw_name
);
355 if (bufsize
> LONG_MAX
/2) /* overflow check */
362 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
368 char* gid_to_name(gid_t gid
) {
373 return strdup("root");
374 if (synthesize_nobody() &&
376 return strdup(NOBODY_GROUP_NAME
);
378 if (gid_is_valid(gid
)) {
381 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
386 struct group grbuf
, *gr
= NULL
;
387 _cleanup_free_
char *buf
= NULL
;
389 buf
= malloc(bufsize
);
393 r
= getgrgid_r(gid
, &grbuf
, buf
, (size_t) bufsize
, &gr
);
395 return strdup(gr
->gr_name
);
399 if (bufsize
> LONG_MAX
/2) /* overflow check */
406 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
412 int in_gid(gid_t gid
) {
420 if (getegid() == gid
)
423 if (!gid_is_valid(gid
))
426 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
427 assert(ngroups_max
> 0);
429 gids
= newa(gid_t
, ngroups_max
);
431 r
= getgroups(ngroups_max
, gids
);
435 for (i
= 0; i
< r
; i
++)
442 int in_group(const char *name
) {
446 r
= get_group_creds(&name
, &gid
, 0);
453 int get_home_dir(char **_h
) {
461 /* Take the user specified one */
462 e
= secure_getenv("HOME");
463 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
468 *_h
= path_simplify(h
, true);
472 /* Hardcode home directory for root and nobody to avoid NSS */
482 if (synthesize_nobody() &&
492 /* Check the database... */
496 return errno_or_else(ESRCH
);
498 if (!path_is_valid(p
->pw_dir
) ||
499 !path_is_absolute(p
->pw_dir
))
502 h
= strdup(p
->pw_dir
);
506 *_h
= path_simplify(h
, true);
510 int get_shell(char **_s
) {
518 /* Take the user specified one */
519 e
= secure_getenv("SHELL");
520 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
525 *_s
= path_simplify(s
, true);
529 /* Hardcode shell for root and nobody to avoid NSS */
532 s
= strdup("/bin/sh");
539 if (synthesize_nobody() &&
549 /* Check the database... */
553 return errno_or_else(ESRCH
);
555 if (!path_is_valid(p
->pw_shell
) ||
556 !path_is_absolute(p
->pw_shell
))
559 s
= strdup(p
->pw_shell
);
563 *_s
= path_simplify(s
, true);
567 int reset_uid_gid(void) {
570 r
= maybe_setgroups(0, NULL
);
574 if (setresgid(0, 0, 0) < 0)
577 if (setresuid(0, 0, 0) < 0)
583 int take_etc_passwd_lock(const char *root
) {
585 struct flock flock
= {
587 .l_whence
= SEEK_SET
,
595 /* This is roughly the same as lckpwdf(), but not as awful. We
596 * don't want to use alarm() and signals, hence we implement
597 * our own trivial version of this.
599 * Note that shadow-utils also takes per-database locks in
600 * addition to lckpwdf(). However, we don't given that they
601 * are redundant as they invoke lckpwdf() first and keep
602 * it during everything they do. The per-database locks are
603 * awfully racy, and thus we just won't do them. */
606 path
= prefix_roota(root
, ETC_PASSWD_LOCK_PATH
);
608 path
= ETC_PASSWD_LOCK_PATH
;
610 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
612 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
614 r
= fcntl(fd
, F_SETLKW
, &flock
);
617 return log_debug_errno(errno
, "Locking %s failed: %m", path
);
623 bool valid_user_group_name(const char *u
) {
627 /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
628 * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
630 * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
631 * - We require that names fit into the appropriate utmp field
632 * - We don't allow empty user names
634 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
640 if (!(u
[0] >= 'a' && u
[0] <= 'z') &&
641 !(u
[0] >= 'A' && u
[0] <= 'Z') &&
645 for (i
= u
+1; *i
; i
++) {
646 if (!(*i
>= 'a' && *i
<= 'z') &&
647 !(*i
>= 'A' && *i
<= 'Z') &&
648 !(*i
>= '0' && *i
<= '9') &&
649 !IN_SET(*i
, '_', '-'))
653 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
656 if ((size_t) (i
-u
) > (size_t) sz
)
659 if ((size_t) (i
-u
) > UT_NAMESIZE
- 1)
665 bool valid_user_group_name_or_id(const char *u
) {
667 /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
668 * range, and not the invalid user ids. */
673 if (valid_user_group_name(u
))
676 return parse_uid(u
, NULL
) >= 0;
679 bool valid_gecos(const char *d
) {
684 if (!utf8_is_valid(d
))
687 if (string_has_cc(d
, NULL
))
690 /* Colons are used as field separators, and hence not OK */
697 bool valid_home(const char *p
) {
698 /* Note that this function is also called by valid_shell(), any
699 * changes must account for that. */
704 if (!utf8_is_valid(p
))
707 if (string_has_cc(p
, NULL
))
710 if (!path_is_absolute(p
))
713 if (!path_is_normalized(p
))
716 /* Colons are used as field separators, and hence not OK */
723 int maybe_setgroups(size_t size
, const gid_t
*list
) {
726 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
727 if (size
== 0) { /* Dropping all aux groups? */
728 _cleanup_free_
char *setgroups_content
= NULL
;
731 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
733 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
734 can_setgroups
= true;
738 can_setgroups
= streq(setgroups_content
, "allow");
740 if (!can_setgroups
) {
741 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
746 if (setgroups(size
, list
) < 0)
752 bool synthesize_nobody(void) {
753 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
754 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
755 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
757 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
758 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
759 * shouldn't matter as each initialization should come to the same result. */
760 static int cache
= -1;
763 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
768 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
773 if (putpwent(pw
, stream
) != 0)
774 return errno_or_else(EIO
);
779 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
784 if (putspent(sp
, stream
) != 0)
785 return errno_or_else(EIO
);
790 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
795 if (putgrent(gr
, stream
) != 0)
796 return errno_or_else(EIO
);
802 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
807 if (putsgent(sg
, stream
) != 0)
808 return errno_or_else(EIO
);
814 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
821 p
= fgetpwent(stream
);
822 if (!p
&& errno
!= ENOENT
)
823 return errno_or_else(EIO
);
829 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
836 s
= fgetspent(stream
);
837 if (!s
&& errno
!= ENOENT
)
838 return errno_or_else(EIO
);
844 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
851 g
= fgetgrent(stream
);
852 if (!g
&& errno
!= ENOENT
)
853 return errno_or_else(EIO
);
860 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
867 s
= fgetsgent(stream
);
868 if (!s
&& errno
!= ENOENT
)
869 return errno_or_else(EIO
);
876 int make_salt(char **ret
) {
877 static const char table
[] =
878 "abcdefghijklmnopqrstuvwxyz"
879 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
888 /* This is a bit like crypt_gensalt_ra(), but doesn't require libcrypt, and doesn't do anything but
889 * SHA512, i.e. is legacy-free and minimizes our deps. */
891 assert_cc(sizeof(table
) == 64U + 1U);
893 /* Insist on the best randomness by setting RANDOM_BLOCK, this is about keeping passwords secret after all. */
894 r
= genuine_random_bytes(raw
, sizeof(raw
), RANDOM_BLOCK
);
898 salt
= new(char, 3+sizeof(raw
)+1+1);
902 /* We only bother with SHA512 hashed passwords, the rest is legacy, and we don't do legacy. */
903 j
= stpcpy(salt
, "$6$");
904 for (i
= 0; i
< sizeof(raw
); i
++)
905 j
[i
] = table
[raw
[i
] & 63];