]>
git.proxmox.com Git - 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) {
83 e
= secure_getenv("USER");
87 return uid_to_name(getuid());
90 static 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
) &&
242 (empty_or_root(p
->pw_dir
) ||
243 !path_is_valid(p
->pw_dir
) ||
244 !path_is_absolute(p
->pw_dir
)))
245 *home
= NULL
; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
251 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
252 (isempty(p
->pw_shell
) ||
253 !path_is_valid(p
->pw_dir
) ||
254 !path_is_absolute(p
->pw_shell
) ||
255 is_nologin_shell(p
->pw_shell
)))
258 *shell
= p
->pw_shell
;
264 int get_group_creds(const char **groupname
, gid_t
*gid
, UserCredsFlags flags
) {
270 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
272 if (STR_IN_SET(*groupname
, "root", "0")) {
281 if (synthesize_nobody() &&
282 STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534")) {
283 *groupname
= NOBODY_GROUP_NAME
;
291 if (parse_gid(*groupname
, &id
) >= 0) {
296 *groupname
= g
->gr_name
;
297 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
305 g
= getgrnam(*groupname
);
309 return errno
> 0 ? -errno
: -ESRCH
;
312 if (!gid_is_valid(g
->gr_gid
))
321 char* uid_to_name(uid_t uid
) {
325 /* Shortcut things to avoid NSS lookups */
327 return strdup("root");
328 if (synthesize_nobody() &&
330 return strdup(NOBODY_USER_NAME
);
332 if (uid_is_valid(uid
)) {
335 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
340 struct passwd pwbuf
, *pw
= NULL
;
341 _cleanup_free_
char *buf
= NULL
;
343 buf
= malloc(bufsize
);
347 r
= getpwuid_r(uid
, &pwbuf
, buf
, (size_t) bufsize
, &pw
);
349 return strdup(pw
->pw_name
);
353 if (bufsize
> LONG_MAX
/2) /* overflow check */
360 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
366 char* gid_to_name(gid_t gid
) {
371 return strdup("root");
372 if (synthesize_nobody() &&
374 return strdup(NOBODY_GROUP_NAME
);
376 if (gid_is_valid(gid
)) {
379 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
384 struct group grbuf
, *gr
= NULL
;
385 _cleanup_free_
char *buf
= NULL
;
387 buf
= malloc(bufsize
);
391 r
= getgrgid_r(gid
, &grbuf
, buf
, (size_t) bufsize
, &gr
);
393 return strdup(gr
->gr_name
);
397 if (bufsize
> LONG_MAX
/2) /* overflow check */
404 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
410 int in_gid(gid_t gid
) {
418 if (getegid() == gid
)
421 if (!gid_is_valid(gid
))
424 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
425 assert(ngroups_max
> 0);
427 gids
= newa(gid_t
, ngroups_max
);
429 r
= getgroups(ngroups_max
, gids
);
433 for (i
= 0; i
< r
; i
++)
440 int in_group(const char *name
) {
444 r
= get_group_creds(&name
, &gid
, 0);
451 int get_home_dir(char **_h
) {
459 /* Take the user specified one */
460 e
= secure_getenv("HOME");
461 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
466 *_h
= path_simplify(h
, true);
470 /* Hardcode home directory for root and nobody to avoid NSS */
480 if (synthesize_nobody() &&
490 /* Check the database... */
494 return errno
> 0 ? -errno
: -ESRCH
;
496 if (!path_is_valid(p
->pw_dir
) ||
497 !path_is_absolute(p
->pw_dir
))
500 h
= strdup(p
->pw_dir
);
504 *_h
= path_simplify(h
, true);
508 int get_shell(char **_s
) {
516 /* Take the user specified one */
517 e
= secure_getenv("SHELL");
518 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
523 *_s
= path_simplify(s
, true);
527 /* Hardcode shell for root and nobody to avoid NSS */
530 s
= strdup("/bin/sh");
537 if (synthesize_nobody() &&
539 s
= strdup("/sbin/nologin");
547 /* Check the database... */
551 return errno
> 0 ? -errno
: -ESRCH
;
553 if (!path_is_valid(p
->pw_shell
) ||
554 !path_is_absolute(p
->pw_shell
))
557 s
= strdup(p
->pw_shell
);
561 *_s
= path_simplify(s
, true);
565 int reset_uid_gid(void) {
568 r
= maybe_setgroups(0, NULL
);
572 if (setresgid(0, 0, 0) < 0)
575 if (setresuid(0, 0, 0) < 0)
581 int take_etc_passwd_lock(const char *root
) {
583 struct flock flock
= {
585 .l_whence
= SEEK_SET
,
593 /* This is roughly the same as lckpwdf(), but not as awful. We
594 * don't want to use alarm() and signals, hence we implement
595 * our own trivial version of this.
597 * Note that shadow-utils also takes per-database locks in
598 * addition to lckpwdf(). However, we don't given that they
599 * are redundant as they invoke lckpwdf() first and keep
600 * it during everything they do. The per-database locks are
601 * awfully racy, and thus we just won't do them. */
604 path
= prefix_roota(root
, ETC_PASSWD_LOCK_PATH
);
606 path
= ETC_PASSWD_LOCK_PATH
;
608 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
610 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
612 r
= fcntl(fd
, F_SETLKW
, &flock
);
615 return log_debug_errno(errno
, "Locking %s failed: %m", path
);
621 bool valid_user_group_name(const char *u
) {
625 /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
626 * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
628 * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
629 * - We require that names fit into the appropriate utmp field
630 * - We don't allow empty user names
632 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
638 if (!(u
[0] >= 'a' && u
[0] <= 'z') &&
639 !(u
[0] >= 'A' && u
[0] <= 'Z') &&
643 for (i
= u
+1; *i
; i
++) {
644 if (!(*i
>= 'a' && *i
<= 'z') &&
645 !(*i
>= 'A' && *i
<= 'Z') &&
646 !(*i
>= '0' && *i
<= '9') &&
647 !IN_SET(*i
, '_', '-'))
651 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
654 if ((size_t) (i
-u
) > (size_t) sz
)
657 if ((size_t) (i
-u
) > UT_NAMESIZE
- 1)
663 bool valid_user_group_name_or_id(const char *u
) {
665 /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
666 * range, and not the invalid user ids. */
671 if (valid_user_group_name(u
))
674 return parse_uid(u
, NULL
) >= 0;
677 bool valid_gecos(const char *d
) {
682 if (!utf8_is_valid(d
))
685 if (string_has_cc(d
, NULL
))
688 /* Colons are used as field separators, and hence not OK */
695 bool valid_home(const char *p
) {
696 /* Note that this function is also called by valid_shell(), any
697 * changes must account for that. */
702 if (!utf8_is_valid(p
))
705 if (string_has_cc(p
, NULL
))
708 if (!path_is_absolute(p
))
711 if (!path_is_normalized(p
))
714 /* Colons are used as field separators, and hence not OK */
721 int maybe_setgroups(size_t size
, const gid_t
*list
) {
724 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
725 if (size
== 0) { /* Dropping all aux groups? */
726 _cleanup_free_
char *setgroups_content
= NULL
;
729 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
731 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
732 can_setgroups
= true;
736 can_setgroups
= streq(setgroups_content
, "allow");
738 if (!can_setgroups
) {
739 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
744 if (setgroups(size
, list
) < 0)
750 bool synthesize_nobody(void) {
751 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
752 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
753 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
755 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
756 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
757 * shouldn't matter as each initialization should come to the same result. */
758 static int cache
= -1;
761 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
766 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
771 if (putpwent(pw
, stream
) != 0)
772 return errno
> 0 ? -errno
: -EIO
;
777 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
782 if (putspent(sp
, stream
) != 0)
783 return errno
> 0 ? -errno
: -EIO
;
788 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
793 if (putgrent(gr
, stream
) != 0)
794 return errno
> 0 ? -errno
: -EIO
;
800 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
805 if (putsgent(sg
, stream
) != 0)
806 return errno
> 0 ? -errno
: -EIO
;
812 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
819 p
= fgetpwent(stream
);
820 if (!p
&& errno
!= ENOENT
)
821 return errno
> 0 ? -errno
: -EIO
;
827 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
834 s
= fgetspent(stream
);
835 if (!s
&& errno
!= ENOENT
)
836 return errno
> 0 ? -errno
: -EIO
;
842 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
849 g
= fgetgrent(stream
);
850 if (!g
&& errno
!= ENOENT
)
851 return errno
> 0 ? -errno
: -EIO
;
858 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
865 s
= fgetsgent(stream
);
866 if (!s
&& errno
!= ENOENT
)
867 return errno
> 0 ? -errno
: -EIO
;