1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
13 #include "sd-messages.h"
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 "path-util.h"
24 #include "random-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));
53 /* We are very strict when parsing UIDs, and prohibit +/- as prefix, leading zero as prefix, and
54 * whitespace. We do this, since this call is often used in a context where we parse things as UID
55 * first, and if that doesn't work we fall back to NSS. Thus we really want to make sure that UIDs
56 * are parsed as UIDs only if they really really look like UIDs. */
57 r
= safe_atou32_full(s
, 10
58 | SAFE_ATO_REFUSE_PLUS_MINUS
59 | SAFE_ATO_REFUSE_LEADING_ZERO
60 | SAFE_ATO_REFUSE_LEADING_WHITESPACE
, &uid
);
64 if (!uid_is_valid(uid
))
65 return -ENXIO
; /* we return ENXIO instead of EINVAL
66 * here, to make it easy to distinguish
67 * invalid numeric uids from invalid
76 int parse_uid_range(const char *s
, uid_t
*ret_lower
, uid_t
*ret_upper
) {
77 _cleanup_free_
char *word
= NULL
;
85 r
= extract_first_word(&s
, &word
, "-", EXTRACT_DONT_COALESCE_SEPARATORS
);
91 r
= parse_uid(word
, &l
);
95 /* Check for the upper bound and extract it if needed */
97 /* Single number with no dash. */
100 /* Trailing dash is an error. */
103 r
= parse_uid(s
, &u
);
116 char* getlogname_malloc(void) {
120 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
125 return uid_to_name(uid
);
128 char *getusername_malloc(void) {
131 e
= secure_getenv("USER");
135 return uid_to_name(getuid());
138 bool is_nologin_shell(const char *shell
) {
140 return PATH_IN_SET(shell
,
141 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
142 * message and exits. Different distributions place the binary at different places though,
143 * hence let's list them all. */
148 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
149 * any message printing. Different distributions place the binary at various places but at
150 * least not in the 'sbin' directory. */
157 static int synthesize_user_creds(
158 const char **username
,
159 uid_t
*uid
, gid_t
*gid
,
162 UserCredsFlags flags
) {
164 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
165 * their user record data. */
167 if (STR_IN_SET(*username
, "root", "0")) {
184 if (synthesize_nobody() &&
185 STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534")) {
186 *username
= NOBODY_USER_NAME
;
194 *home
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/";
197 *shell
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: NOLOGIN
;
206 const char **username
,
207 uid_t
*uid
, gid_t
*gid
,
210 UserCredsFlags flags
) {
212 uid_t u
= UID_INVALID
;
219 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
222 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
223 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
224 * user database will override the synthetic records instead — except if the user is only interested in
225 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
226 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
227 * Simply because there are valid usecase where the user might change the home directory or the shell
228 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
231 r
= synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
);
234 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
238 if (parse_uid(*username
, &u
) >= 0) {
242 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
243 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
244 * then let's pick the real username from /etc/passwd. */
246 *username
= p
->pw_name
;
247 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !gid
&& !home
&& !shell
) {
249 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
250 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then juts return that
251 * and don't complain. */
260 p
= getpwnam(*username
);
263 r
= errno_or_else(ESRCH
);
265 /* If the user requested that we only synthesize as fallback, do so now */
266 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
)) {
267 if (synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
) >= 0)
275 if (!uid_is_valid(p
->pw_uid
))
282 if (!gid_is_valid(p
->pw_gid
))
289 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
290 (empty_or_root(p
->pw_dir
) ||
291 !path_is_valid(p
->pw_dir
) ||
292 !path_is_absolute(p
->pw_dir
)))
293 *home
= NULL
; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
299 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
300 (isempty(p
->pw_shell
) ||
301 !path_is_valid(p
->pw_dir
) ||
302 !path_is_absolute(p
->pw_shell
) ||
303 is_nologin_shell(p
->pw_shell
)))
306 *shell
= p
->pw_shell
;
312 int get_group_creds(const char **groupname
, gid_t
*gid
, UserCredsFlags flags
) {
318 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
320 if (STR_IN_SET(*groupname
, "root", "0")) {
329 if (synthesize_nobody() &&
330 STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534")) {
331 *groupname
= NOBODY_GROUP_NAME
;
339 if (parse_gid(*groupname
, &id
) >= 0) {
344 *groupname
= g
->gr_name
;
345 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
353 g
= getgrnam(*groupname
);
357 return errno_or_else(ESRCH
);
360 if (!gid_is_valid(g
->gr_gid
))
369 char* uid_to_name(uid_t uid
) {
373 /* Shortcut things to avoid NSS lookups */
375 return strdup("root");
376 if (synthesize_nobody() &&
378 return strdup(NOBODY_USER_NAME
);
380 if (uid_is_valid(uid
)) {
383 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
388 struct passwd pwbuf
, *pw
= NULL
;
389 _cleanup_free_
char *buf
= NULL
;
391 buf
= malloc(bufsize
);
395 r
= getpwuid_r(uid
, &pwbuf
, buf
, (size_t) bufsize
, &pw
);
397 return strdup(pw
->pw_name
);
401 if (bufsize
> LONG_MAX
/2) /* overflow check */
408 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
414 char* gid_to_name(gid_t gid
) {
419 return strdup("root");
420 if (synthesize_nobody() &&
422 return strdup(NOBODY_GROUP_NAME
);
424 if (gid_is_valid(gid
)) {
427 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
432 struct group grbuf
, *gr
= NULL
;
433 _cleanup_free_
char *buf
= NULL
;
435 buf
= malloc(bufsize
);
439 r
= getgrgid_r(gid
, &grbuf
, buf
, (size_t) bufsize
, &gr
);
441 return strdup(gr
->gr_name
);
445 if (bufsize
> LONG_MAX
/2) /* overflow check */
452 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
458 static bool gid_list_has(const gid_t
*list
, size_t size
, gid_t val
) {
459 for (size_t i
= 0; i
< size
; i
++)
465 int in_gid(gid_t gid
) {
466 _cleanup_free_ gid_t
*gids
= NULL
;
472 if (getegid() == gid
)
475 if (!gid_is_valid(gid
))
478 ngroups
= getgroups_alloc(&gids
);
482 return gid_list_has(gids
, ngroups
, gid
);
485 int in_group(const char *name
) {
489 r
= get_group_creds(&name
, &gid
, 0);
496 int merge_gid_lists(const gid_t
*list1
, size_t size1
, const gid_t
*list2
, size_t size2
, gid_t
**ret
) {
500 if (size2
> INT_MAX
- size1
)
503 gid_t
*buf
= new(gid_t
, size1
+ size2
);
507 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
508 for (size_t i
= 0; i
< size1
; i
++)
509 if (!gid_list_has(buf
, nresult
, list1
[i
]))
510 buf
[nresult
++] = list1
[i
];
511 for (size_t i
= 0; i
< size2
; i
++)
512 if (!gid_list_has(buf
, nresult
, list2
[i
]))
513 buf
[nresult
++] = list2
[i
];
518 int getgroups_alloc(gid_t
** gids
) {
520 _cleanup_free_ gid_t
*p
= NULL
;
522 unsigned attempt
= 0;
524 allocated
= new(gid_t
, ngroups
);
530 ngroups
= getgroups(ngroups
, p
);
536 /* Give up eventually */
540 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
541 * to use (in multi-threaded programs), hence let's call this in a loop. */
542 ngroups
= getgroups(0, NULL
);
550 p
= allocated
= new(gid_t
, ngroups
);
559 int get_home_dir(char **_h
) {
567 /* Take the user specified one */
568 e
= secure_getenv("HOME");
569 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
574 *_h
= path_simplify(h
, true);
578 /* Hardcode home directory for root and nobody to avoid NSS */
588 if (synthesize_nobody() &&
598 /* Check the database... */
602 return errno_or_else(ESRCH
);
604 if (!path_is_valid(p
->pw_dir
) ||
605 !path_is_absolute(p
->pw_dir
))
608 h
= strdup(p
->pw_dir
);
612 *_h
= path_simplify(h
, true);
616 int get_shell(char **_s
) {
624 /* Take the user specified one */
625 e
= secure_getenv("SHELL");
626 if (e
&& path_is_valid(e
) && path_is_absolute(e
)) {
631 *_s
= path_simplify(s
, true);
635 /* Hardcode shell for root and nobody to avoid NSS */
638 s
= strdup("/bin/sh");
645 if (synthesize_nobody() &&
655 /* Check the database... */
659 return errno_or_else(ESRCH
);
661 if (!path_is_valid(p
->pw_shell
) ||
662 !path_is_absolute(p
->pw_shell
))
665 s
= strdup(p
->pw_shell
);
669 *_s
= path_simplify(s
, true);
673 int reset_uid_gid(void) {
676 r
= maybe_setgroups(0, NULL
);
680 if (setresgid(0, 0, 0) < 0)
683 if (setresuid(0, 0, 0) < 0)
689 int take_etc_passwd_lock(const char *root
) {
691 struct flock flock
= {
693 .l_whence
= SEEK_SET
,
701 /* This is roughly the same as lckpwdf(), but not as awful. We
702 * don't want to use alarm() and signals, hence we implement
703 * our own trivial version of this.
705 * Note that shadow-utils also takes per-database locks in
706 * addition to lckpwdf(). However, we don't given that they
707 * are redundant as they invoke lckpwdf() first and keep
708 * it during everything they do. The per-database locks are
709 * awfully racy, and thus we just won't do them. */
712 path
= prefix_roota(root
, ETC_PASSWD_LOCK_PATH
);
714 path
= ETC_PASSWD_LOCK_PATH
;
716 fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
718 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
720 r
= fcntl(fd
, F_SETLKW
, &flock
);
723 return log_debug_errno(errno
, "Locking %s failed: %m", path
);
729 bool valid_user_group_name(const char *u
, ValidUserFlags flags
) {
732 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
733 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
734 * pretty much everything except the really worst offending names.
736 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
737 * created by other stuff, let's be more liberal. */
739 if (isempty(u
)) /* An empty user name is never valid */
742 if (parse_uid(u
, NULL
) >= 0) /* Something that parses as numeric UID string is valid exactly when the
743 * flag for it is set */
744 return FLAGS_SET(flags
, VALID_USER_ALLOW_NUMERIC
);
746 if (FLAGS_SET(flags
, VALID_USER_RELAX
)) {
748 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
749 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
750 * is bound to cause problems for example when used with an MTA), hence only filter the most
751 * obvious cases, or where things would result in an invalid entry if such a user name would
752 * show up in /etc/passwd (or equivalent getent output).
754 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
755 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
756 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
759 if (startswith(u
, " ") || endswith(u
, " ")) /* At least expect whitespace padding is removed
760 * at front and back (accept in the middle, since
761 * that's apparently a thing on Windows). Note
762 * that this also blocks usernames consisting of
763 * whitespace only. */
766 if (!utf8_is_valid(u
)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
769 if (string_has_cc(u
, NULL
)) /* CC characters are just dangerous (and \n in particular is the
770 * record separator in /etc/passwd), so we can't allow that. */
773 if (strpbrk(u
, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
774 * that. Slashes are special to file systems paths and user names
775 * typically show up in the file system as home directories, hence
776 * don't allow slashes. */
779 if (in_charset(u
, "0123456789")) /* Don't allow fully numeric strings, they might be confused
780 * with UIDs (note that this test is more broad than
781 * the parse_uid() test above, as it will cover more than
782 * the 32bit range, and it will detect 65535 (which is in
783 * invalid UID, even though in the unsigned 32 bit range) */
786 if (u
[0] == '-' && in_charset(u
+ 1, "0123456789")) /* Don't allow negative fully numeric
787 * strings either. After all some people
788 * write 65535 as -1 (even though that's
789 * not even true on 32bit uid_t
793 if (dot_or_dot_dot(u
)) /* User names typically become home directory names, and these two are
794 * special in that context, don't allow that. */
797 /* Compare with strict result and warn if result doesn't match */
798 if (FLAGS_SET(flags
, VALID_USER_WARN
) && !valid_user_group_name(u
, 0))
799 log_struct(LOG_NOTICE
,
800 "MESSAGE=Accepting user/group name '%s', which does not match strict user/group name rules.", u
,
801 "USER_GROUP_NAME=%s", u
,
802 "MESSAGE_ID=" SD_MESSAGE_UNSAFE_USER_NAME_STR
);
804 /* Note that we make no restrictions on the length in relaxed mode! */
809 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
810 * however. Specifically we deviate from POSIX rules:
812 * - We don't allow empty user names (see above)
813 * - We require that names fit into the appropriate utmp field
814 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
815 * - We don't allow dashes or digit as the first character
817 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
820 if (!(u
[0] >= 'a' && u
[0] <= 'z') &&
821 !(u
[0] >= 'A' && u
[0] <= 'Z') &&
825 for (i
= u
+1; *i
; i
++)
826 if (!(*i
>= 'a' && *i
<= 'z') &&
827 !(*i
>= 'A' && *i
<= 'Z') &&
828 !(*i
>= '0' && *i
<= '9') &&
829 !IN_SET(*i
, '_', '-'))
834 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
839 if (l
> FILENAME_MAX
)
841 if (l
> UT_NAMESIZE
- 1)
848 bool valid_gecos(const char *d
) {
853 if (!utf8_is_valid(d
))
856 if (string_has_cc(d
, NULL
))
859 /* Colons are used as field separators, and hence not OK */
866 char *mangle_gecos(const char *d
) {
869 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
870 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
877 for (char *i
= mangled
; *i
; i
++) {
880 if ((uint8_t) *i
< (uint8_t) ' ' || *i
== ':') {
885 len
= utf8_encoded_valid_unichar(i
, (size_t) -1);
897 bool valid_home(const char *p
) {
898 /* Note that this function is also called by valid_shell(), any
899 * changes must account for that. */
904 if (!utf8_is_valid(p
))
907 if (string_has_cc(p
, NULL
))
910 if (!path_is_absolute(p
))
913 if (!path_is_normalized(p
))
916 /* Colons are used as field separators, and hence not OK */
923 int maybe_setgroups(size_t size
, const gid_t
*list
) {
926 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
927 if (size
== 0) { /* Dropping all aux groups? */
928 _cleanup_free_
char *setgroups_content
= NULL
;
931 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
933 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
934 can_setgroups
= true;
938 can_setgroups
= streq(setgroups_content
, "allow");
940 if (!can_setgroups
) {
941 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
946 if (setgroups(size
, list
) < 0)
952 bool synthesize_nobody(void) {
953 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
954 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
955 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
957 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
958 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
959 * shouldn't matter as each initialization should come to the same result. */
960 static int cache
= -1;
963 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
968 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
973 if (putpwent(pw
, stream
) != 0)
974 return errno_or_else(EIO
);
979 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
984 if (putspent(sp
, stream
) != 0)
985 return errno_or_else(EIO
);
990 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
995 if (putgrent(gr
, stream
) != 0)
996 return errno_or_else(EIO
);
1002 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
1007 if (putsgent(sg
, stream
) != 0)
1008 return errno_or_else(EIO
);
1014 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
1021 p
= fgetpwent(stream
);
1022 if (!p
&& errno
!= ENOENT
)
1023 return errno_or_else(EIO
);
1029 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
1036 s
= fgetspent(stream
);
1037 if (!s
&& errno
!= ENOENT
)
1038 return errno_or_else(EIO
);
1044 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
1051 g
= fgetgrent(stream
);
1052 if (!g
&& errno
!= ENOENT
)
1053 return errno_or_else(EIO
);
1060 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
1067 s
= fgetsgent(stream
);
1068 if (!s
&& errno
!= ENOENT
)
1069 return errno_or_else(EIO
);