]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/user-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
15 #include "alloc-util.h"
16 #include "errno-util.h"
19 #include "format-util.h"
21 #include "parse-util.h"
22 #include "path-util.h"
23 #include "random-util.h"
24 #include "string-util.h"
26 #include "user-util.h"
29 bool uid_is_valid(uid_t uid
) {
31 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
33 /* Some libc APIs use UID_INVALID as special placeholder */
34 if (uid
== (uid_t
) UINT32_C(0xFFFFFFFF))
37 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
38 if (uid
== (uid_t
) UINT32_C(0xFFFF))
44 int parse_uid(const char *s
, uid_t
*ret
) {
50 assert_cc(sizeof(uid_t
) == sizeof(uint32_t));
51 r
= safe_atou32(s
, &uid
);
55 if (!uid_is_valid(uid
))
56 return -ENXIO
; /* we return ENXIO instead of EINVAL
57 * here, to make it easy to distinguish
58 * invalid numeric uids from invalid
67 char* getlogname_malloc(void) {
71 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
76 return uid_to_name(uid
);
79 char *getusername_malloc(void) {
82 e
= secure_getenv("USER");
86 return uid_to_name(getuid());
89 static bool is_nologin_shell(const char *shell
) {
91 return PATH_IN_SET(shell
,
92 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
93 * message and exits. Different distributions place the binary at different places though,
94 * hence let's list them all. */
99 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
100 * any message printing. Different distributions place the binary at various places but at
101 * least not in the 'sbin' directory. */
108 static int synthesize_user_creds(
109 const char **username
,
110 uid_t
*uid
, gid_t
*gid
,
113 UserCredsFlags flags
) {
115 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
116 * their user record data. */
118 if (STR_IN_SET(*username
, "root", "0")) {
135 if (synthesize_nobody() &&
136 STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534")) {
137 *username
= NOBODY_USER_NAME
;
145 *home
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/";
148 *shell
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: NOLOGIN
;
157 const char **username
,
158 uid_t
*uid
, gid_t
*gid
,
161 UserCredsFlags flags
) {
163 uid_t u
= UID_INVALID
;
170 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
173 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
174 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
175 * user database will override the synthetic records instead — except if the user is only interested in
176 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
177 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
178 * Simply because there are valid usecase where the user might change the home directory or the shell
179 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
182 r
= synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
);
185 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
189 if (parse_uid(*username
, &u
) >= 0) {
193 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
194 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
195 * then let's pick the real username from /etc/passwd. */
197 *username
= p
->pw_name
;
198 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !gid
&& !home
&& !shell
) {
200 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
201 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then juts return that
202 * and don't complain. */
211 p
= getpwnam(*username
);
214 r
= errno_or_else(ESRCH
);
216 /* If the user requested that we only synthesize as fallback, do so now */
217 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
)) {
218 if (synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
) >= 0)
226 if (!uid_is_valid(p
->pw_uid
))
233 if (!gid_is_valid(p
->pw_gid
))
240 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
241 (empty_or_root(p
->pw_dir
) ||
242 !path_is_valid(p
->pw_dir
) ||
243 !path_is_absolute(p
->pw_dir
)))
244 *home
= NULL
; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
250 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
251 (isempty(p
->pw_shell
) ||
252 !path_is_valid(p
->pw_dir
) ||
253 !path_is_absolute(p
->pw_shell
) ||
254 is_nologin_shell(p
->pw_shell
)))
257 *shell
= p
->pw_shell
;
263 int get_group_creds(const char **groupname
, gid_t
*gid
, UserCredsFlags flags
) {
269 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
271 if (STR_IN_SET(*groupname
, "root", "0")) {
280 if (synthesize_nobody() &&
281 STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534")) {
282 *groupname
= NOBODY_GROUP_NAME
;
290 if (parse_gid(*groupname
, &id
) >= 0) {
295 *groupname
= g
->gr_name
;
296 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
304 g
= getgrnam(*groupname
);
308 return errno_or_else(ESRCH
);
311 if (!gid_is_valid(g
->gr_gid
))
320 char* uid_to_name(uid_t uid
) {
324 /* Shortcut things to avoid NSS lookups */
326 return strdup("root");
327 if (synthesize_nobody() &&
329 return strdup(NOBODY_USER_NAME
);
331 if (uid_is_valid(uid
)) {
334 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
339 struct passwd pwbuf
, *pw
= NULL
;
340 _cleanup_free_
char *buf
= NULL
;
342 buf
= malloc(bufsize
);
346 r
= getpwuid_r(uid
, &pwbuf
, buf
, (size_t) bufsize
, &pw
);
348 return strdup(pw
->pw_name
);
352 if (bufsize
> LONG_MAX
/2) /* overflow check */
359 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
365 char* gid_to_name(gid_t gid
) {
370 return strdup("root");
371 if (synthesize_nobody() &&
373 return strdup(NOBODY_GROUP_NAME
);
375 if (gid_is_valid(gid
)) {
378 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
383 struct group grbuf
, *gr
= NULL
;
384 _cleanup_free_
char *buf
= NULL
;
386 buf
= malloc(bufsize
);
390 r
= getgrgid_r(gid
, &grbuf
, buf
, (size_t) bufsize
, &gr
);
392 return strdup(gr
->gr_name
);
396 if (bufsize
> LONG_MAX
/2) /* overflow check */
403 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
409 int in_gid(gid_t gid
) {
410 _cleanup_free_ gid_t
*allocated
= NULL
;
411 gid_t local
[16], *p
= local
;
412 int ngroups
= ELEMENTSOF(local
);
413 unsigned attempt
= 0;
418 if (getegid() == gid
)
421 if (!gid_is_valid(gid
))
425 ngroups
= getgroups(ngroups
, p
);
431 /* Give up eventually */
435 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
436 * to use (in multi-threaded programs), hence let's call this in a loop. */
437 ngroups
= getgroups(0, NULL
);
445 allocated
= new(gid_t
, ngroups
);
452 for (int i
= 0; i
< ngroups
; i
++)
459 int in_group(const char *name
) {
463 r
= get_group_creds(&name
, &gid
, 0);
470 int get_home_dir(char **_h
) {
478 /* Take the user specified one */
479 e
= secure_getenv("HOME");
480 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
485 *_h
= path_simplify(h
, true);
489 /* Hardcode home directory for root and nobody to avoid NSS */
499 if (synthesize_nobody() &&
509 /* Check the database... */
513 return errno_or_else(ESRCH
);
515 if (!path_is_valid(p
->pw_dir
) ||
516 !path_is_absolute(p
->pw_dir
))
519 h
= strdup(p
->pw_dir
);
523 *_h
= path_simplify(h
, true);
527 int get_shell(char **_s
) {
535 /* Take the user specified one */
536 e
= secure_getenv("SHELL");
537 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
542 *_s
= path_simplify(s
, true);
546 /* Hardcode shell for root and nobody to avoid NSS */
549 s
= strdup("/bin/sh");
556 if (synthesize_nobody() &&
566 /* Check the database... */
570 return errno_or_else(ESRCH
);
572 if (!path_is_valid(p
->pw_shell
) ||
573 !path_is_absolute(p
->pw_shell
))
576 s
= strdup(p
->pw_shell
);
580 *_s
= path_simplify(s
, true);
584 int reset_uid_gid(void) {
587 r
= maybe_setgroups(0, NULL
);
591 if (setresgid(0, 0, 0) < 0)
594 if (setresuid(0, 0, 0) < 0)
600 int take_etc_passwd_lock(const char *root
) {
602 struct flock flock
= {
604 .l_whence
= SEEK_SET
,
612 /* This is roughly the same as lckpwdf(), but not as awful. We
613 * don't want to use alarm() and signals, hence we implement
614 * our own trivial version of this.
616 * Note that shadow-utils also takes per-database locks in
617 * addition to lckpwdf(). However, we don't given that they
618 * are redundant as they invoke lckpwdf() first and keep
619 * it during everything they do. The per-database locks are
620 * awfully racy, and thus we just won't do them. */
623 path
= prefix_roota(root
, ETC_PASSWD_LOCK_PATH
);
625 path
= ETC_PASSWD_LOCK_PATH
;
627 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
629 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
631 r
= fcntl(fd
, F_SETLKW
, &flock
);
634 return log_debug_errno(errno
, "Locking %s failed: %m", path
);
640 bool valid_user_group_name_full(const char *u
, bool strict
) {
644 /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
645 * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
647 * - We require that names fit into the appropriate utmp field
648 * - We don't allow empty user names
649 * - No dots or digits in the first character
651 * If strict==true, additionally:
652 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
654 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
660 if (!(u
[0] >= 'a' && u
[0] <= 'z') &&
661 !(u
[0] >= 'A' && u
[0] <= 'Z') &&
667 for (i
= u
+1; *i
; i
++) {
668 if (((*i
>= 'a' && *i
<= 'z') ||
669 (*i
>= 'A' && *i
<= 'Z') ||
670 (*i
>= '0' && *i
<= '9') ||
671 IN_SET(*i
, '_', '-')))
674 if (*i
== '.' && !strict
) {
676 log_warning("Bad user or group name \"%s\", accepting for compatibility.", u
);
686 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
689 if ((size_t) (i
-u
) > (size_t) sz
)
692 if ((size_t) (i
-u
) > UT_NAMESIZE
- 1)
698 bool valid_user_group_name_or_id_full(const char *u
, bool strict
) {
700 /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the
701 * right range, and not the invalid user ids. */
706 if (valid_user_group_name_full(u
, strict
))
709 return parse_uid(u
, NULL
) >= 0;
712 bool valid_gecos(const char *d
) {
717 if (!utf8_is_valid(d
))
720 if (string_has_cc(d
, NULL
))
723 /* Colons are used as field separators, and hence not OK */
730 bool valid_home(const char *p
) {
731 /* Note that this function is also called by valid_shell(), any
732 * changes must account for that. */
737 if (!utf8_is_valid(p
))
740 if (string_has_cc(p
, NULL
))
743 if (!path_is_absolute(p
))
746 if (!path_is_normalized(p
))
749 /* Colons are used as field separators, and hence not OK */
756 int maybe_setgroups(size_t size
, const gid_t
*list
) {
759 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
760 if (size
== 0) { /* Dropping all aux groups? */
761 _cleanup_free_
char *setgroups_content
= NULL
;
764 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
766 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
767 can_setgroups
= true;
771 can_setgroups
= streq(setgroups_content
, "allow");
773 if (!can_setgroups
) {
774 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
779 if (setgroups(size
, list
) < 0)
785 bool synthesize_nobody(void) {
786 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
787 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
788 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
790 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
791 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
792 * shouldn't matter as each initialization should come to the same result. */
793 static int cache
= -1;
796 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
801 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
806 if (putpwent(pw
, stream
) != 0)
807 return errno_or_else(EIO
);
812 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
817 if (putspent(sp
, stream
) != 0)
818 return errno_or_else(EIO
);
823 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
828 if (putgrent(gr
, stream
) != 0)
829 return errno_or_else(EIO
);
835 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
840 if (putsgent(sg
, stream
) != 0)
841 return errno_or_else(EIO
);
847 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
854 p
= fgetpwent(stream
);
855 if (!p
&& errno
!= ENOENT
)
856 return errno_or_else(EIO
);
862 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
869 s
= fgetspent(stream
);
870 if (!s
&& errno
!= ENOENT
)
871 return errno_or_else(EIO
);
877 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
884 g
= fgetgrent(stream
);
885 if (!g
&& errno
!= ENOENT
)
886 return errno_or_else(EIO
);
893 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
900 s
= fgetsgent(stream
);
901 if (!s
&& errno
!= ENOENT
)
902 return errno_or_else(EIO
);
909 int make_salt(char **ret
) {
910 static const char table
[] =
911 "abcdefghijklmnopqrstuvwxyz"
912 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
921 /* This is a bit like crypt_gensalt_ra(), but doesn't require libcrypt, and doesn't do anything but
922 * SHA512, i.e. is legacy-free and minimizes our deps. */
924 assert_cc(sizeof(table
) == 64U + 1U);
926 /* Insist on the best randomness by setting RANDOM_BLOCK, this is about keeping passwords secret after all. */
927 r
= genuine_random_bytes(raw
, sizeof(raw
), RANDOM_BLOCK
);
931 salt
= new(char, 3+sizeof(raw
)+1+1);
935 /* We only bother with SHA512 hashed passwords, the rest is legacy, and we don't do legacy. */
936 j
= stpcpy(salt
, "$6$");
937 for (i
= 0; i
< sizeof(raw
); i
++)
938 j
[i
] = table
[raw
[i
] & 63];