]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/user-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
17 #include "alloc-util.h"
20 #include "format-util.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "string-util.h"
27 #include "user-util.h"
30 bool uid_is_valid(uid_t uid
) {
32 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
34 /* Some libc APIs use UID_INVALID as special placeholder */
35 if (uid
== (uid_t
) UINT32_C(0xFFFFFFFF))
38 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
39 if (uid
== (uid_t
) UINT32_C(0xFFFF))
45 int parse_uid(const char *s
, uid_t
*ret
) {
51 assert_cc(sizeof(uid_t
) == sizeof(uint32_t));
52 r
= safe_atou32(s
, &uid
);
56 if (!uid_is_valid(uid
))
57 return -ENXIO
; /* we return ENXIO instead of EINVAL
58 * here, to make it easy to distuingish
59 * invalid numeric uids from invalid
68 char* getlogname_malloc(void) {
72 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
77 return uid_to_name(uid
);
80 char *getusername_malloc(void) {
87 return uid_to_name(getuid());
90 static inline bool is_nologin_shell(const char *shell
) {
92 return PATH_IN_SET(shell
,
93 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
94 * message and exits. Different distributions place the binary at different places though,
95 * hence let's list them all. */
100 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
101 * any message printing. Different distributions place the binary at various places but at
102 * least not in the 'sbin' directory. */
109 static int synthesize_user_creds(
110 const char **username
,
111 uid_t
*uid
, gid_t
*gid
,
114 UserCredsFlags flags
) {
116 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
117 * their user record data. */
119 if (STR_IN_SET(*username
, "root", "0")) {
136 if (synthesize_nobody() &&
137 STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534")) {
138 *username
= NOBODY_USER_NAME
;
146 *home
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/";
149 *shell
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/sbin/nologin";
158 const char **username
,
159 uid_t
*uid
, gid_t
*gid
,
162 UserCredsFlags flags
) {
164 uid_t u
= UID_INVALID
;
171 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
174 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
175 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
176 * user database will override the synthetic records instead — except if the user is only interested in
177 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
178 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
179 * Simply because there are valid usecase where the user might change the home directory or the shell
180 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
183 r
= synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
);
186 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
190 if (parse_uid(*username
, &u
) >= 0) {
194 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
195 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
196 * then let's pick the real username from /etc/passwd. */
198 *username
= p
->pw_name
;
199 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !gid
&& !home
&& !shell
) {
201 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
202 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then juts return that
203 * and don't complain. */
212 p
= getpwnam(*username
);
215 r
= errno
> 0 ? -errno
: -ESRCH
;
217 /* If the user requested that we only synthesize as fallback, do so now */
218 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
)) {
219 if (synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
) >= 0)
227 if (!uid_is_valid(p
->pw_uid
))
234 if (!gid_is_valid(p
->pw_gid
))
241 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) && empty_or_root(p
->pw_dir
))
248 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) && (isempty(p
->pw_shell
) || is_nologin_shell(p
->pw_shell
)))
251 *shell
= p
->pw_shell
;
257 int get_group_creds(const char **groupname
, gid_t
*gid
, UserCredsFlags flags
) {
263 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
265 if (STR_IN_SET(*groupname
, "root", "0")) {
274 if (synthesize_nobody() &&
275 STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534")) {
276 *groupname
= NOBODY_GROUP_NAME
;
284 if (parse_gid(*groupname
, &id
) >= 0) {
289 *groupname
= g
->gr_name
;
290 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
298 g
= getgrnam(*groupname
);
302 return errno
> 0 ? -errno
: -ESRCH
;
305 if (!gid_is_valid(g
->gr_gid
))
314 char* uid_to_name(uid_t uid
) {
318 /* Shortcut things to avoid NSS lookups */
320 return strdup("root");
321 if (synthesize_nobody() &&
323 return strdup(NOBODY_USER_NAME
);
325 if (uid_is_valid(uid
)) {
328 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
333 struct passwd pwbuf
, *pw
= NULL
;
334 _cleanup_free_
char *buf
= NULL
;
336 buf
= malloc(bufsize
);
340 r
= getpwuid_r(uid
, &pwbuf
, buf
, (size_t) bufsize
, &pw
);
342 return strdup(pw
->pw_name
);
350 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
356 char* gid_to_name(gid_t gid
) {
361 return strdup("root");
362 if (synthesize_nobody() &&
364 return strdup(NOBODY_GROUP_NAME
);
366 if (gid_is_valid(gid
)) {
369 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
374 struct group grbuf
, *gr
= NULL
;
375 _cleanup_free_
char *buf
= NULL
;
377 buf
= malloc(bufsize
);
381 r
= getgrgid_r(gid
, &grbuf
, buf
, (size_t) bufsize
, &gr
);
383 return strdup(gr
->gr_name
);
391 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
397 int in_gid(gid_t gid
) {
405 if (getegid() == gid
)
408 if (!gid_is_valid(gid
))
411 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
412 assert(ngroups_max
> 0);
414 gids
= newa(gid_t
, ngroups_max
);
416 r
= getgroups(ngroups_max
, gids
);
420 for (i
= 0; i
< r
; i
++)
427 int in_group(const char *name
) {
431 r
= get_group_creds(&name
, &gid
, 0);
438 int get_home_dir(char **_h
) {
446 /* Take the user specified one */
447 e
= secure_getenv("HOME");
448 if (e
&& path_is_absolute(e
)) {
457 /* Hardcode home directory for root and nobody to avoid NSS */
467 if (synthesize_nobody() &&
477 /* Check the database... */
481 return errno
> 0 ? -errno
: -ESRCH
;
483 if (!path_is_absolute(p
->pw_dir
))
486 h
= strdup(p
->pw_dir
);
494 int get_shell(char **_s
) {
502 /* Take the user specified one */
513 /* Hardcode shell for root and nobody to avoid NSS */
516 s
= strdup("/bin/sh");
523 if (synthesize_nobody() &&
525 s
= strdup("/sbin/nologin");
533 /* Check the database... */
537 return errno
> 0 ? -errno
: -ESRCH
;
539 if (!path_is_absolute(p
->pw_shell
))
542 s
= strdup(p
->pw_shell
);
550 int reset_uid_gid(void) {
553 r
= maybe_setgroups(0, NULL
);
557 if (setresgid(0, 0, 0) < 0)
560 if (setresuid(0, 0, 0) < 0)
566 int take_etc_passwd_lock(const char *root
) {
568 struct flock flock
= {
570 .l_whence
= SEEK_SET
,
578 /* This is roughly the same as lckpwdf(), but not as awful. We
579 * don't want to use alarm() and signals, hence we implement
580 * our own trivial version of this.
582 * Note that shadow-utils also takes per-database locks in
583 * addition to lckpwdf(). However, we don't given that they
584 * are redundant as they invoke lckpwdf() first and keep
585 * it during everything they do. The per-database locks are
586 * awfully racy, and thus we just won't do them. */
589 path
= prefix_roota(root
, ETC_PASSWD_LOCK_PATH
);
591 path
= ETC_PASSWD_LOCK_PATH
;
593 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
595 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
597 r
= fcntl(fd
, F_SETLKW
, &flock
);
600 return log_debug_errno(errno
, "Locking %s failed: %m", path
);
606 bool valid_user_group_name(const char *u
) {
610 /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
611 * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
613 * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
614 * - We require that names fit into the appropriate utmp field
615 * - We don't allow empty user names
617 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
623 if (!(u
[0] >= 'a' && u
[0] <= 'z') &&
624 !(u
[0] >= 'A' && u
[0] <= 'Z') &&
628 for (i
= u
+1; *i
; i
++) {
629 if (!(*i
>= 'a' && *i
<= 'z') &&
630 !(*i
>= 'A' && *i
<= 'Z') &&
631 !(*i
>= '0' && *i
<= '9') &&
632 !IN_SET(*i
, '_', '-'))
636 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
639 if ((size_t) (i
-u
) > (size_t) sz
)
642 if ((size_t) (i
-u
) > UT_NAMESIZE
- 1)
648 bool valid_user_group_name_or_id(const char *u
) {
650 /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
651 * range, and not the invalid user ids. */
656 if (valid_user_group_name(u
))
659 return parse_uid(u
, NULL
) >= 0;
662 bool valid_gecos(const char *d
) {
667 if (!utf8_is_valid(d
))
670 if (string_has_cc(d
, NULL
))
673 /* Colons are used as field separators, and hence not OK */
680 bool valid_home(const char *p
) {
681 /* Note that this function is also called by valid_shell(), any
682 * changes must account for that. */
687 if (!utf8_is_valid(p
))
690 if (string_has_cc(p
, NULL
))
693 if (!path_is_absolute(p
))
696 if (!path_is_normalized(p
))
699 /* Colons are used as field separators, and hence not OK */
706 int maybe_setgroups(size_t size
, const gid_t
*list
) {
709 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
710 if (size
== 0) { /* Dropping all aux groups? */
711 _cleanup_free_
char *setgroups_content
= NULL
;
714 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
716 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
717 can_setgroups
= true;
721 can_setgroups
= streq(setgroups_content
, "allow");
723 if (!can_setgroups
) {
724 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
729 if (setgroups(size
, list
) < 0)
735 bool synthesize_nobody(void) {
740 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
741 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
742 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
744 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
745 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
746 * shouldn't matter as each initialization should come to the same result. */
747 static int cache
= -1;
750 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
756 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
761 if (putpwent(pw
, stream
) != 0)
762 return errno
> 0 ? -errno
: -EIO
;
767 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
772 if (putspent(sp
, stream
) != 0)
773 return errno
> 0 ? -errno
: -EIO
;
778 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
783 if (putgrent(gr
, stream
) != 0)
784 return errno
> 0 ? -errno
: -EIO
;
790 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
795 if (putsgent(sg
, stream
) != 0)
796 return errno
> 0 ? -errno
: -EIO
;
802 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
809 p
= fgetpwent(stream
);
810 if (!p
&& errno
!= ENOENT
)
811 return errno
> 0 ? -errno
: -EIO
;
817 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
824 s
= fgetspent(stream
);
825 if (!s
&& errno
!= ENOENT
)
826 return errno
> 0 ? -errno
: -EIO
;
832 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
839 g
= fgetgrent(stream
);
840 if (!g
&& errno
!= ENOENT
)
841 return errno
> 0 ? -errno
: -EIO
;
848 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
855 s
= fgetsgent(stream
);
856 if (!s
&& errno
!= ENOENT
)
857 return errno
> 0 ? -errno
: -EIO
;