1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
13 #include "sd-messages.h"
15 #include "alloc-util.h"
17 #include "errno-util.h"
20 #include "format-util.h"
21 #include "lock-util.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "path-util.h"
27 #include "random-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));
56 /* We are very strict when parsing UIDs, and prohibit +/- as prefix, leading zero as prefix, and
57 * whitespace. We do this, since this call is often used in a context where we parse things as UID
58 * first, and if that doesn't work we fall back to NSS. Thus we really want to make sure that UIDs
59 * are parsed as UIDs only if they really really look like UIDs. */
60 r
= safe_atou32_full(s
, 10
61 | SAFE_ATO_REFUSE_PLUS_MINUS
62 | SAFE_ATO_REFUSE_LEADING_ZERO
63 | SAFE_ATO_REFUSE_LEADING_WHITESPACE
, &uid
);
67 if (!uid_is_valid(uid
))
68 return -ENXIO
; /* we return ENXIO instead of EINVAL
69 * here, to make it easy to distinguish
70 * invalid numeric uids from invalid
79 int parse_uid_range(const char *s
, uid_t
*ret_lower
, uid_t
*ret_upper
) {
80 _cleanup_free_
char *word
= NULL
;
88 r
= extract_first_word(&s
, &word
, "-", EXTRACT_DONT_COALESCE_SEPARATORS
);
94 r
= parse_uid(word
, &l
);
98 /* Check for the upper bound and extract it if needed */
100 /* Single number with no dash. */
103 /* Trailing dash is an error. */
106 r
= parse_uid(s
, &u
);
119 char* getlogname_malloc(void) {
123 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
128 return uid_to_name(uid
);
131 char *getusername_malloc(void) {
134 e
= secure_getenv("USER");
138 return uid_to_name(getuid());
141 bool is_nologin_shell(const char *shell
) {
142 return PATH_IN_SET(shell
,
143 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
144 * message and exits. Different distributions place the binary at different places though,
145 * hence let's list them all. */
150 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
151 * any message printing. Different distributions place the binary at various places but at
152 * least not in the 'sbin' directory. */
159 const char* default_root_shell_at(int rfd
) {
160 /* We want to use the preferred shell, i.e. DEFAULT_USER_SHELL, which usually
161 * will be /bin/bash. Fall back to /bin/sh if DEFAULT_USER_SHELL is not found,
162 * or any access errors. */
164 assert(rfd
>= 0 || rfd
== AT_FDCWD
);
166 int r
= chaseat(rfd
, DEFAULT_USER_SHELL
, CHASE_AT_RESOLVE_IN_ROOT
, NULL
, NULL
);
167 if (r
< 0 && r
!= -ENOENT
)
168 log_debug_errno(r
, "Failed to look up shell '%s': %m", DEFAULT_USER_SHELL
);
170 return DEFAULT_USER_SHELL
;
175 const char *default_root_shell(const char *root
) {
176 _cleanup_close_
int rfd
= -EBADF
;
178 rfd
= open(empty_to_root(root
), O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
182 return default_root_shell_at(rfd
);
185 static int synthesize_user_creds(
186 const char **username
,
187 uid_t
*uid
, gid_t
*gid
,
190 UserCredsFlags flags
) {
192 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
193 * their user record data. */
195 if (STR_IN_SET(*username
, "root", "0")) {
207 *shell
= default_root_shell(NULL
);
212 if (STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534") &&
213 synthesize_nobody()) {
214 *username
= NOBODY_USER_NAME
;
222 *home
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/";
225 *shell
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: NOLOGIN
;
234 const char **username
,
235 uid_t
*uid
, gid_t
*gid
,
238 UserCredsFlags flags
) {
240 uid_t u
= UID_INVALID
;
247 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
250 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
251 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
252 * user database will override the synthetic records instead — except if the user is only interested in
253 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
254 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
255 * Simply because there are valid usecase where the user might change the home directory or the shell
256 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
259 r
= synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
);
262 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
266 if (parse_uid(*username
, &u
) >= 0) {
270 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
271 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
272 * then let's pick the real username from /etc/passwd. */
274 *username
= p
->pw_name
;
275 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !gid
&& !home
&& !shell
) {
277 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
278 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then just return that
279 * and don't complain. */
288 p
= getpwnam(*username
);
291 r
= errno_or_else(ESRCH
);
293 /* If the user requested that we only synthesize as fallback, do so now */
294 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
)) {
295 if (synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
) >= 0)
303 if (!uid_is_valid(p
->pw_uid
))
310 if (!gid_is_valid(p
->pw_gid
))
317 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
318 (empty_or_root(p
->pw_dir
) ||
319 !path_is_valid(p
->pw_dir
) ||
320 !path_is_absolute(p
->pw_dir
)))
321 *home
= NULL
; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
327 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
328 (isempty(p
->pw_shell
) ||
329 !path_is_valid(p
->pw_dir
) ||
330 !path_is_absolute(p
->pw_shell
) ||
331 is_nologin_shell(p
->pw_shell
)))
334 *shell
= p
->pw_shell
;
340 int get_group_creds(const char **groupname
, gid_t
*gid
, UserCredsFlags flags
) {
346 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
348 if (STR_IN_SET(*groupname
, "root", "0")) {
357 if (STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534") &&
358 synthesize_nobody()) {
359 *groupname
= NOBODY_GROUP_NAME
;
367 if (parse_gid(*groupname
, &id
) >= 0) {
372 *groupname
= g
->gr_name
;
373 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
381 g
= getgrnam(*groupname
);
385 return errno_or_else(ESRCH
);
388 if (!gid_is_valid(g
->gr_gid
))
397 char* uid_to_name(uid_t uid
) {
401 /* Shortcut things to avoid NSS lookups */
403 return strdup("root");
404 if (uid
== UID_NOBODY
&& synthesize_nobody())
405 return strdup(NOBODY_USER_NAME
);
407 if (uid_is_valid(uid
)) {
410 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
415 struct passwd pwbuf
, *pw
= NULL
;
416 _cleanup_free_
char *buf
= NULL
;
418 buf
= malloc(bufsize
);
422 r
= getpwuid_r(uid
, &pwbuf
, buf
, (size_t) bufsize
, &pw
);
424 return strdup(pw
->pw_name
);
428 if (bufsize
> LONG_MAX
/2) /* overflow check */
435 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
441 char* gid_to_name(gid_t gid
) {
446 return strdup("root");
447 if (gid
== GID_NOBODY
&& synthesize_nobody())
448 return strdup(NOBODY_GROUP_NAME
);
450 if (gid_is_valid(gid
)) {
453 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
458 struct group grbuf
, *gr
= NULL
;
459 _cleanup_free_
char *buf
= NULL
;
461 buf
= malloc(bufsize
);
465 r
= getgrgid_r(gid
, &grbuf
, buf
, (size_t) bufsize
, &gr
);
467 return strdup(gr
->gr_name
);
471 if (bufsize
> LONG_MAX
/2) /* overflow check */
478 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
484 static bool gid_list_has(const gid_t
*list
, size_t size
, gid_t val
) {
485 for (size_t i
= 0; i
< size
; i
++)
491 int in_gid(gid_t gid
) {
492 _cleanup_free_ gid_t
*gids
= NULL
;
498 if (getegid() == gid
)
501 if (!gid_is_valid(gid
))
504 ngroups
= getgroups_alloc(&gids
);
508 return gid_list_has(gids
, ngroups
, gid
);
511 int in_group(const char *name
) {
515 r
= get_group_creds(&name
, &gid
, 0);
522 int merge_gid_lists(const gid_t
*list1
, size_t size1
, const gid_t
*list2
, size_t size2
, gid_t
**ret
) {
526 if (size2
> INT_MAX
- size1
)
529 gid_t
*buf
= new(gid_t
, size1
+ size2
);
533 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
534 for (size_t i
= 0; i
< size1
; i
++)
535 if (!gid_list_has(buf
, nresult
, list1
[i
]))
536 buf
[nresult
++] = list1
[i
];
537 for (size_t i
= 0; i
< size2
; i
++)
538 if (!gid_list_has(buf
, nresult
, list2
[i
]))
539 buf
[nresult
++] = list2
[i
];
544 int getgroups_alloc(gid_t
** gids
) {
546 _cleanup_free_ gid_t
*p
= NULL
;
548 unsigned attempt
= 0;
550 allocated
= new(gid_t
, ngroups
);
556 ngroups
= getgroups(ngroups
, p
);
562 /* Give up eventually */
566 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
567 * to use (in multi-threaded programs), hence let's call this in a loop. */
568 ngroups
= getgroups(0, NULL
);
576 p
= allocated
= new(gid_t
, ngroups
);
585 int get_home_dir(char **ret
) {
593 /* Take the user specified one */
594 e
= secure_getenv("HOME");
595 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
598 /* Hardcode home directory for root and nobody to avoid NSS */
605 if (u
== UID_NOBODY
&& synthesize_nobody()) {
610 /* Check the database... */
614 return errno_or_else(ESRCH
);
617 if (!path_is_valid(e
) || !path_is_absolute(e
))
625 *ret
= path_simplify(h
);
629 int get_shell(char **ret
) {
637 /* Take the user specified one */
638 e
= secure_getenv("SHELL");
639 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
642 /* Hardcode shell for root and nobody to avoid NSS */
645 e
= default_root_shell(NULL
);
648 if (u
== UID_NOBODY
&& synthesize_nobody()) {
653 /* Check the database... */
657 return errno_or_else(ESRCH
);
660 if (!path_is_valid(e
) || !path_is_absolute(e
))
668 *ret
= path_simplify(s
);
672 int reset_uid_gid(void) {
675 r
= maybe_setgroups(0, NULL
);
679 if (setresgid(0, 0, 0) < 0)
682 return RET_NERRNO(setresuid(0, 0, 0));
685 int take_etc_passwd_lock(const char *root
) {
688 /* This is roughly the same as lckpwdf(), but not as awful. We don't want to use alarm() and signals,
689 * hence we implement our own trivial version of this.
691 * Note that shadow-utils also takes per-database locks in addition to lckpwdf(). However, we don't,
692 * given that they are redundant: they invoke lckpwdf() first and keep it during everything they do.
693 * The per-database locks are awfully racy, and thus we just won't do them. */
695 _cleanup_free_
char *path
= path_join(root
, ETC_PASSWD_LOCK_PATH
);
697 return log_oom_debug();
699 (void) mkdir_parents(path
, 0755);
701 _cleanup_close_
int fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
703 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
705 r
= unposix_lock(fd
, LOCK_EX
);
707 return log_debug_errno(r
, "Locking %s failed: %m", path
);
712 bool valid_user_group_name(const char *u
, ValidUserFlags flags
) {
715 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
716 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
717 * pretty much everything except the really worst offending names.
719 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
720 * created by other stuff, let's be more liberal. */
722 if (isempty(u
)) /* An empty user name is never valid */
725 if (parse_uid(u
, NULL
) >= 0) /* Something that parses as numeric UID string is valid exactly when the
726 * flag for it is set */
727 return FLAGS_SET(flags
, VALID_USER_ALLOW_NUMERIC
);
729 if (FLAGS_SET(flags
, VALID_USER_RELAX
)) {
731 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
732 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
733 * is bound to cause problems for example when used with an MTA), hence only filter the most
734 * obvious cases, or where things would result in an invalid entry if such a user name would
735 * show up in /etc/passwd (or equivalent getent output).
737 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
738 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
739 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
742 if (startswith(u
, " ") || endswith(u
, " ")) /* At least expect whitespace padding is removed
743 * at front and back (accept in the middle, since
744 * that's apparently a thing on Windows). Note
745 * that this also blocks usernames consisting of
746 * whitespace only. */
749 if (!utf8_is_valid(u
)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
752 if (string_has_cc(u
, NULL
)) /* CC characters are just dangerous (and \n in particular is the
753 * record separator in /etc/passwd), so we can't allow that. */
756 if (strpbrk(u
, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
757 * that. Slashes are special to file systems paths and user names
758 * typically show up in the file system as home directories, hence
759 * don't allow slashes. */
762 if (in_charset(u
, "0123456789")) /* Don't allow fully numeric strings, they might be confused
763 * with UIDs (note that this test is more broad than
764 * the parse_uid() test above, as it will cover more than
765 * the 32bit range, and it will detect 65535 (which is in
766 * invalid UID, even though in the unsigned 32 bit range) */
769 if (u
[0] == '-' && in_charset(u
+ 1, "0123456789")) /* Don't allow negative fully numeric
770 * strings either. After all some people
771 * write 65535 as -1 (even though that's
772 * not even true on 32bit uid_t
776 if (dot_or_dot_dot(u
)) /* User names typically become home directory names, and these two are
777 * special in that context, don't allow that. */
780 /* Compare with strict result and warn if result doesn't match */
781 if (FLAGS_SET(flags
, VALID_USER_WARN
) && !valid_user_group_name(u
, 0))
782 log_struct(LOG_NOTICE
,
783 LOG_MESSAGE("Accepting user/group name '%s', which does not match strict user/group name rules.", u
),
784 "USER_GROUP_NAME=%s", u
,
785 "MESSAGE_ID=" SD_MESSAGE_UNSAFE_USER_NAME_STR
);
787 /* Note that we make no restrictions on the length in relaxed mode! */
792 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
793 * however. Specifically we deviate from POSIX rules:
795 * - We don't allow empty user names (see above)
796 * - We require that names fit into the appropriate utmp field
797 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
798 * - We don't allow dashes or digit as the first character
800 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
803 if (!ascii_isalpha(u
[0]) &&
807 for (i
= u
+1; *i
; i
++)
808 if (!ascii_isalpha(*i
) &&
809 !ascii_isdigit(*i
) &&
810 !IN_SET(*i
, '_', '-'))
815 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
820 if (l
> NAME_MAX
) /* must fit in a filename */
822 if (l
> UT_NAMESIZE
- 1)
829 bool valid_gecos(const char *d
) {
834 if (!utf8_is_valid(d
))
837 if (string_has_cc(d
, NULL
))
840 /* Colons are used as field separators, and hence not OK */
847 char *mangle_gecos(const char *d
) {
850 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
851 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
858 for (char *i
= mangled
; *i
; i
++) {
861 if ((uint8_t) *i
< (uint8_t) ' ' || *i
== ':') {
866 len
= utf8_encoded_valid_unichar(i
, SIZE_MAX
);
878 bool valid_home(const char *p
) {
879 /* Note that this function is also called by valid_shell(), any
880 * changes must account for that. */
885 if (!utf8_is_valid(p
))
888 if (string_has_cc(p
, NULL
))
891 if (!path_is_absolute(p
))
894 if (!path_is_normalized(p
))
897 /* Colons are used as field separators, and hence not OK */
904 int maybe_setgroups(size_t size
, const gid_t
*list
) {
907 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
908 if (size
== 0) { /* Dropping all aux groups? */
909 _cleanup_free_
char *setgroups_content
= NULL
;
912 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
914 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
915 can_setgroups
= true;
919 can_setgroups
= streq(setgroups_content
, "allow");
921 if (!can_setgroups
) {
922 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
927 return RET_NERRNO(setgroups(size
, list
));
930 bool synthesize_nobody(void) {
931 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
932 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
933 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
935 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
936 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
937 * shouldn't matter as each initialization should come to the same result. */
938 static int cache
= -1;
941 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
946 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
951 if (putpwent(pw
, stream
) != 0)
952 return errno_or_else(EIO
);
957 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
962 if (putspent(sp
, stream
) != 0)
963 return errno_or_else(EIO
);
968 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
973 if (putgrent(gr
, stream
) != 0)
974 return errno_or_else(EIO
);
980 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
985 if (putsgent(sg
, stream
) != 0)
986 return errno_or_else(EIO
);
992 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
997 struct passwd
*p
= fgetpwent(stream
);
998 if (!p
&& errno
!= ENOENT
)
999 return errno_or_else(EIO
);
1005 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
1010 struct spwd
*s
= fgetspent(stream
);
1011 if (!s
&& errno
!= ENOENT
)
1012 return errno_or_else(EIO
);
1018 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
1023 struct group
*g
= fgetgrent(stream
);
1024 if (!g
&& errno
!= ENOENT
)
1025 return errno_or_else(EIO
);
1032 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
1037 struct sgrp
*s
= fgetsgent(stream
);
1038 if (!s
&& errno
!= ENOENT
)
1039 return errno_or_else(EIO
);
1046 int is_this_me(const char *username
) {
1050 /* Checks if the specified username is our current one. Passed string might be a UID or a user name. */
1052 r
= get_user_creds(&username
, &uid
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
1056 return uid
== getuid();
1059 const char *get_home_root(void) {
1062 /* For debug purposes allow overriding where we look for home dirs */
1063 e
= secure_getenv("SYSTEMD_HOME_ROOT");
1064 if (e
&& path_is_absolute(e
) && path_is_normalized(e
))