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 "random-util.h"
27 #include "string-util.h"
29 #include "user-util.h"
32 bool uid_is_valid(uid_t uid
) {
34 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
36 /* Some libc APIs use UID_INVALID as special placeholder */
37 if (uid
== (uid_t
) UINT32_C(0xFFFFFFFF))
40 /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
41 if (uid
== (uid_t
) UINT32_C(0xFFFF))
47 int parse_uid(const char *s
, uid_t
*ret
) {
53 assert_cc(sizeof(uid_t
) == sizeof(uint32_t));
55 /* We are very strict when parsing UIDs, and prohibit +/- as prefix, leading zero as prefix, and
56 * whitespace. We do this, since this call is often used in a context where we parse things as UID
57 * first, and if that doesn't work we fall back to NSS. Thus we really want to make sure that UIDs
58 * are parsed as UIDs only if they really really look like UIDs. */
59 r
= safe_atou32_full(s
, 10
60 | SAFE_ATO_REFUSE_PLUS_MINUS
61 | SAFE_ATO_REFUSE_LEADING_ZERO
62 | SAFE_ATO_REFUSE_LEADING_WHITESPACE
, &uid
);
66 if (!uid_is_valid(uid
))
67 return -ENXIO
; /* we return ENXIO instead of EINVAL
68 * here, to make it easy to distinguish
69 * invalid numeric uids from invalid
78 int parse_uid_range(const char *s
, uid_t
*ret_lower
, uid_t
*ret_upper
) {
79 _cleanup_free_
char *word
= NULL
;
87 r
= extract_first_word(&s
, &word
, "-", EXTRACT_DONT_COALESCE_SEPARATORS
);
93 r
= parse_uid(word
, &l
);
97 /* Check for the upper bound and extract it if needed */
99 /* Single number with no dash. */
102 /* Trailing dash is an error. */
105 r
= parse_uid(s
, &u
);
118 char* getlogname_malloc(void) {
122 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
127 return uid_to_name(uid
);
130 char* getusername_malloc(void) {
133 e
= secure_getenv("USER");
137 return uid_to_name(getuid());
140 bool is_nologin_shell(const char *shell
) {
141 return PATH_IN_SET(shell
,
142 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
143 * message and exits. Different distributions place the binary at different places though,
144 * hence let's list them all. */
149 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
150 * any message printing. Different distributions place the binary at various places but at
151 * least not in the 'sbin' directory. */
158 const char* default_root_shell_at(int rfd
) {
159 /* We want to use the preferred shell, i.e. DEFAULT_USER_SHELL, which usually
160 * will be /bin/bash. Fall back to /bin/sh if DEFAULT_USER_SHELL is not found,
161 * or any access errors. */
163 assert(rfd
>= 0 || rfd
== AT_FDCWD
);
165 int r
= chaseat(rfd
, DEFAULT_USER_SHELL
, CHASE_AT_RESOLVE_IN_ROOT
, NULL
, NULL
);
166 if (r
< 0 && r
!= -ENOENT
)
167 log_debug_errno(r
, "Failed to look up shell '%s': %m", DEFAULT_USER_SHELL
);
169 return DEFAULT_USER_SHELL
;
174 const char* default_root_shell(const char *root
) {
175 _cleanup_close_
int rfd
= -EBADF
;
177 rfd
= open(empty_to_root(root
), O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
181 return default_root_shell_at(rfd
);
184 static int synthesize_user_creds(
185 const char **username
,
186 uid_t
*uid
, gid_t
*gid
,
189 UserCredsFlags flags
) {
191 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
192 * their user record data. */
194 if (STR_IN_SET(*username
, "root", "0")) {
206 *shell
= default_root_shell(NULL
);
211 if (STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534") &&
212 synthesize_nobody()) {
213 *username
= NOBODY_USER_NAME
;
221 *home
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/";
224 *shell
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: NOLOGIN
;
233 const char **username
,
234 uid_t
*uid
, gid_t
*gid
,
237 UserCredsFlags flags
) {
239 uid_t u
= UID_INVALID
;
246 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
249 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
250 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
251 * user database will override the synthetic records instead — except if the user is only interested in
252 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
253 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
254 * Simply because there are valid usecase where the user might change the home directory or the shell
255 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
258 r
= synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
);
261 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
265 if (parse_uid(*username
, &u
) >= 0) {
269 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
270 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
271 * then let's pick the real username from /etc/passwd. */
273 *username
= p
->pw_name
;
274 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !gid
&& !home
&& !shell
) {
276 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
277 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then just return that
278 * and don't complain. */
287 p
= getpwnam(*username
);
290 /* getpwnam() may fail with ENOENT if /etc/passwd is missing.
291 * For us that is equivalent to the name not being defined. */
292 r
= IN_SET(errno
, 0, ENOENT
) ? -ESRCH
: -errno
;
294 /* If the user requested that we only synthesize as fallback, do so now */
295 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
)) {
296 if (synthesize_user_creds(username
, uid
, gid
, home
, shell
, flags
) >= 0)
304 if (!uid_is_valid(p
->pw_uid
))
311 if (!gid_is_valid(p
->pw_gid
))
318 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
319 (empty_or_root(p
->pw_dir
) ||
320 !path_is_valid(p
->pw_dir
) ||
321 !path_is_absolute(p
->pw_dir
)))
322 *home
= NULL
; /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
328 if (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
329 (isempty(p
->pw_shell
) ||
330 !path_is_valid(p
->pw_dir
) ||
331 !path_is_absolute(p
->pw_shell
) ||
332 is_nologin_shell(p
->pw_shell
)))
335 *shell
= p
->pw_shell
;
341 int get_group_creds(const char **groupname
, gid_t
*gid
, UserCredsFlags flags
) {
347 /* We enforce some special rules for gid=0: in order to avoid NSS lookups for root we hardcode its data. */
349 if (STR_IN_SET(*groupname
, "root", "0")) {
358 if (STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534") &&
359 synthesize_nobody()) {
360 *groupname
= NOBODY_GROUP_NAME
;
368 if (parse_gid(*groupname
, &id
) >= 0) {
373 *groupname
= g
->gr_name
;
374 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
382 g
= getgrnam(*groupname
);
386 /* getgrnam() may fail with ENOENT if /etc/group is missing.
387 * For us that is equivalent to the name not being defined. */
388 return IN_SET(errno
, 0, ENOENT
) ? -ESRCH
: -errno
;
391 if (!gid_is_valid(g
->gr_gid
))
400 char* uid_to_name(uid_t uid
) {
404 /* Shortcut things to avoid NSS lookups */
406 return strdup("root");
407 if (uid
== UID_NOBODY
&& synthesize_nobody())
408 return strdup(NOBODY_USER_NAME
);
410 if (uid_is_valid(uid
)) {
413 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
418 struct passwd pwbuf
, *pw
= NULL
;
419 _cleanup_free_
char *buf
= NULL
;
421 buf
= malloc(bufsize
);
425 r
= getpwuid_r(uid
, &pwbuf
, buf
, (size_t) bufsize
, &pw
);
427 return strdup(pw
->pw_name
);
431 if (bufsize
> LONG_MAX
/2) /* overflow check */
438 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
444 char* gid_to_name(gid_t gid
) {
449 return strdup("root");
450 if (gid
== GID_NOBODY
&& synthesize_nobody())
451 return strdup(NOBODY_GROUP_NAME
);
453 if (gid_is_valid(gid
)) {
456 bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
461 struct group grbuf
, *gr
= NULL
;
462 _cleanup_free_
char *buf
= NULL
;
464 buf
= malloc(bufsize
);
468 r
= getgrgid_r(gid
, &grbuf
, buf
, (size_t) bufsize
, &gr
);
470 return strdup(gr
->gr_name
);
474 if (bufsize
> LONG_MAX
/2) /* overflow check */
481 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
487 static bool gid_list_has(const gid_t
*list
, size_t size
, gid_t val
) {
488 for (size_t i
= 0; i
< size
; i
++)
494 int in_gid(gid_t gid
) {
495 _cleanup_free_ gid_t
*gids
= NULL
;
501 if (getegid() == gid
)
504 if (!gid_is_valid(gid
))
507 ngroups
= getgroups_alloc(&gids
);
511 return gid_list_has(gids
, ngroups
, gid
);
514 int in_group(const char *name
) {
518 r
= get_group_creds(&name
, &gid
, 0);
525 int merge_gid_lists(const gid_t
*list1
, size_t size1
, const gid_t
*list2
, size_t size2
, gid_t
**ret
) {
529 if (size2
> INT_MAX
- size1
)
532 gid_t
*buf
= new(gid_t
, size1
+ size2
);
536 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
537 for (size_t i
= 0; i
< size1
; i
++)
538 if (!gid_list_has(buf
, nresult
, list1
[i
]))
539 buf
[nresult
++] = list1
[i
];
540 for (size_t i
= 0; i
< size2
; i
++)
541 if (!gid_list_has(buf
, nresult
, list2
[i
]))
542 buf
[nresult
++] = list2
[i
];
547 int getgroups_alloc(gid_t
** gids
) {
549 _cleanup_free_ gid_t
*p
= NULL
;
551 unsigned attempt
= 0;
553 allocated
= new(gid_t
, ngroups
);
559 ngroups
= getgroups(ngroups
, p
);
565 /* Give up eventually */
569 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
570 * to use (in multi-threaded programs), hence let's call this in a loop. */
571 ngroups
= getgroups(0, NULL
);
579 p
= allocated
= new(gid_t
, ngroups
);
588 int get_home_dir(char **ret
) {
596 /* Take the user specified one */
597 e
= secure_getenv("HOME");
598 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
601 /* Hardcode home directory for root and nobody to avoid NSS */
608 if (u
== UID_NOBODY
&& synthesize_nobody()) {
613 /* Check the database... */
617 return errno_or_else(ESRCH
);
620 if (!path_is_valid(e
) || !path_is_absolute(e
))
628 *ret
= path_simplify(h
);
632 int get_shell(char **ret
) {
640 /* Take the user specified one */
641 e
= secure_getenv("SHELL");
642 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
645 /* Hardcode shell for root and nobody to avoid NSS */
648 e
= default_root_shell(NULL
);
651 if (u
== UID_NOBODY
&& synthesize_nobody()) {
656 /* Check the database... */
660 return errno_or_else(ESRCH
);
663 if (!path_is_valid(e
) || !path_is_absolute(e
))
671 *ret
= path_simplify(s
);
675 int reset_uid_gid(void) {
678 r
= maybe_setgroups(0, NULL
);
682 if (setresgid(0, 0, 0) < 0)
685 return RET_NERRNO(setresuid(0, 0, 0));
688 int take_etc_passwd_lock(const char *root
) {
691 /* This is roughly the same as lckpwdf(), but not as awful. We don't want to use alarm() and signals,
692 * hence we implement our own trivial version of this.
694 * Note that shadow-utils also takes per-database locks in addition to lckpwdf(). However, we don't,
695 * given that they are redundant: they invoke lckpwdf() first and keep it during everything they do.
696 * The per-database locks are awfully racy, and thus we just won't do them. */
698 _cleanup_free_
char *path
= path_join(root
, ETC_PASSWD_LOCK_PATH
);
700 return log_oom_debug();
702 (void) mkdir_parents(path
, 0755);
704 _cleanup_close_
int fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
706 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
708 r
= unposix_lock(fd
, LOCK_EX
);
710 return log_debug_errno(r
, "Locking %s failed: %m", path
);
715 bool valid_user_group_name(const char *u
, ValidUserFlags flags
) {
718 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
719 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
720 * pretty much everything except the really worst offending names.
722 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
723 * created by other stuff, let's be more liberal. */
725 if (isempty(u
)) /* An empty user name is never valid */
728 if (parse_uid(u
, NULL
) >= 0) /* Something that parses as numeric UID string is valid exactly when the
729 * flag for it is set */
730 return FLAGS_SET(flags
, VALID_USER_ALLOW_NUMERIC
);
732 if (FLAGS_SET(flags
, VALID_USER_RELAX
)) {
734 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
735 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
736 * is bound to cause problems for example when used with an MTA), hence only filter the most
737 * obvious cases, or where things would result in an invalid entry if such a user name would
738 * show up in /etc/passwd (or equivalent getent output).
740 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
741 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
742 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
745 if (startswith(u
, " ") || endswith(u
, " ")) /* At least expect whitespace padding is removed
746 * at front and back (accept in the middle, since
747 * that's apparently a thing on Windows). Note
748 * that this also blocks usernames consisting of
749 * whitespace only. */
752 if (!utf8_is_valid(u
)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
755 if (string_has_cc(u
, NULL
)) /* CC characters are just dangerous (and \n in particular is the
756 * record separator in /etc/passwd), so we can't allow that. */
759 if (strpbrk(u
, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
760 * that. Slashes are special to file systems paths and user names
761 * typically show up in the file system as home directories, hence
762 * don't allow slashes. */
765 if (in_charset(u
, "0123456789")) /* Don't allow fully numeric strings, they might be confused
766 * with UIDs (note that this test is more broad than
767 * the parse_uid() test above, as it will cover more than
768 * the 32bit range, and it will detect 65535 (which is in
769 * invalid UID, even though in the unsigned 32 bit range) */
772 if (u
[0] == '-' && in_charset(u
+ 1, "0123456789")) /* Don't allow negative fully numeric
773 * strings either. After all some people
774 * write 65535 as -1 (even though that's
775 * not even true on 32bit uid_t
779 if (dot_or_dot_dot(u
)) /* User names typically become home directory names, and these two are
780 * special in that context, don't allow that. */
783 /* Compare with strict result and warn if result doesn't match */
784 if (FLAGS_SET(flags
, VALID_USER_WARN
) && !valid_user_group_name(u
, 0))
785 log_struct(LOG_NOTICE
,
786 LOG_MESSAGE("Accepting user/group name '%s', which does not match strict user/group name rules.", u
),
787 "USER_GROUP_NAME=%s", u
,
788 "MESSAGE_ID=" SD_MESSAGE_UNSAFE_USER_NAME_STR
);
790 /* Note that we make no restrictions on the length in relaxed mode! */
795 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
796 * however. Specifically we deviate from POSIX rules:
798 * - We don't allow empty user names (see above)
799 * - We require that names fit into the appropriate utmp field
800 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
801 * - We don't allow dashes or digit as the first character
803 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
806 if (!ascii_isalpha(u
[0]) &&
810 for (i
= u
+1; *i
; i
++)
811 if (!ascii_isalpha(*i
) &&
812 !ascii_isdigit(*i
) &&
813 !IN_SET(*i
, '_', '-'))
818 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
823 if (l
> NAME_MAX
) /* must fit in a filename */
825 if (l
> UT_NAMESIZE
- 1)
832 bool valid_gecos(const char *d
) {
837 if (!utf8_is_valid(d
))
840 if (string_has_cc(d
, NULL
))
843 /* Colons are used as field separators, and hence not OK */
850 char* mangle_gecos(const char *d
) {
853 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
854 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
861 for (char *i
= mangled
; *i
; i
++) {
864 if ((uint8_t) *i
< (uint8_t) ' ' || *i
== ':') {
869 len
= utf8_encoded_valid_unichar(i
, SIZE_MAX
);
881 bool valid_home(const char *p
) {
882 /* Note that this function is also called by valid_shell(), any
883 * changes must account for that. */
888 if (!utf8_is_valid(p
))
891 if (string_has_cc(p
, NULL
))
894 if (!path_is_absolute(p
))
897 if (!path_is_normalized(p
))
900 /* Colons are used as field separators, and hence not OK */
907 int maybe_setgroups(size_t size
, const gid_t
*list
) {
910 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
911 if (size
== 0) { /* Dropping all aux groups? */
912 _cleanup_free_
char *setgroups_content
= NULL
;
915 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
917 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
918 can_setgroups
= true;
922 can_setgroups
= streq(setgroups_content
, "allow");
924 if (!can_setgroups
) {
925 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
930 return RET_NERRNO(setgroups(size
, list
));
933 bool synthesize_nobody(void) {
934 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
935 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
936 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
938 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
939 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
940 * shouldn't matter as each initialization should come to the same result. */
941 static int cache
= -1;
944 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
949 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
954 if (putpwent(pw
, stream
) != 0)
955 return errno_or_else(EIO
);
960 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
965 if (putspent(sp
, stream
) != 0)
966 return errno_or_else(EIO
);
971 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
976 if (putgrent(gr
, stream
) != 0)
977 return errno_or_else(EIO
);
983 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
988 if (putsgent(sg
, stream
) != 0)
989 return errno_or_else(EIO
);
995 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
1000 struct passwd
*p
= fgetpwent(stream
);
1001 if (!p
&& errno
!= ENOENT
)
1002 return errno_or_else(EIO
);
1008 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
1013 struct spwd
*s
= fgetspent(stream
);
1014 if (!s
&& errno
!= ENOENT
)
1015 return errno_or_else(EIO
);
1021 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
1026 struct group
*g
= fgetgrent(stream
);
1027 if (!g
&& errno
!= ENOENT
)
1028 return errno_or_else(EIO
);
1035 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
1040 struct sgrp
*s
= fgetsgent(stream
);
1041 if (!s
&& errno
!= ENOENT
)
1042 return errno_or_else(EIO
);
1049 int is_this_me(const char *username
) {
1053 /* Checks if the specified username is our current one. Passed string might be a UID or a user name. */
1055 r
= get_user_creds(&username
, &uid
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
1059 return uid
== getuid();
1062 const char* get_home_root(void) {
1065 /* For debug purposes allow overriding where we look for home dirs */
1066 e
= secure_getenv("SYSTEMD_HOME_ROOT");
1067 if (e
&& path_is_absolute(e
) && path_is_normalized(e
))