]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/user-util.c
Fixes for vscode/intellisense parsing (#38040)
[thirdparty/systemd.git] / src / basic / user-util.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
b1d4f8e1 2
11c3a366 3#include <fcntl.h>
11c3a366
TA
4#include <stdio.h>
5#include <stdlib.h>
213ddf2d 6#include <sys/file.h>
11c3a366
TA
7#include <sys/stat.h>
8#include <unistd.h>
f3389fff 9#include <utmpx.h>
b1d4f8e1 10
7a8867ab
LP
11#include "sd-messages.h"
12
b5efdb8a 13#include "alloc-util.h"
f461a28d 14#include "chase.h"
66855de7 15#include "errno-util.h"
6553db60 16#include "extract-word.h"
e929bee0 17#include "fd-util.h"
36d85478 18#include "fileio.h"
f97b34a6 19#include "format-util.h"
460accdf 20#include "lock-util.h"
93a1f792 21#include "log.h"
d173d556 22#include "mkdir.h"
6bedfcbb 23#include "parse-util.h"
b1d4f8e1 24#include "path-util.h"
6bedfcbb 25#include "string-util.h"
be39ccf3 26#include "strv.h"
300b7e76 27#include "terminal-util.h"
6bedfcbb 28#include "user-util.h"
e4631b48 29#include "utf8.h"
b1d4f8e1
LP
30
31bool uid_is_valid(uid_t uid) {
32
1429dfe5
LP
33 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
34
b1d4f8e1 35 /* Some libc APIs use UID_INVALID as special placeholder */
b1d52773 36 if (uid == (uid_t) UINT32_C(0xFFFFFFFF))
b1d4f8e1
LP
37 return false;
38
da890466 39 /* A long time ago UIDs where 16 bit, hence explicitly avoid the 16-bit -1 too */
b1d52773 40 if (uid == (uid_t) UINT32_C(0xFFFF))
b1d4f8e1
LP
41 return false;
42
43 return true;
44}
45
b1d52773
LP
46int parse_uid(const char *s, uid_t *ret) {
47 uint32_t uid = 0;
b1d4f8e1
LP
48 int r;
49
50 assert(s);
51
b1d52773 52 assert_cc(sizeof(uid_t) == sizeof(uint32_t));
f5979b63
LP
53
54 /* We are very strict when parsing UIDs, and prohibit +/- as prefix, leading zero as prefix, and
55 * whitespace. We do this, since this call is often used in a context where we parse things as UID
56 * first, and if that doesn't work we fall back to NSS. Thus we really want to make sure that UIDs
57 * are parsed as UIDs only if they really really look like UIDs. */
58 r = safe_atou32_full(s, 10
59 | SAFE_ATO_REFUSE_PLUS_MINUS
60 | SAFE_ATO_REFUSE_LEADING_ZERO
61 | SAFE_ATO_REFUSE_LEADING_WHITESPACE, &uid);
b1d4f8e1
LP
62 if (r < 0)
63 return r;
64
b1d4f8e1
LP
65 if (!uid_is_valid(uid))
66 return -ENXIO; /* we return ENXIO instead of EINVAL
5238e957 67 * here, to make it easy to distinguish
ba60af86 68 * invalid numeric uids from invalid
b1d4f8e1
LP
69 * strings. */
70
b1d52773
LP
71 if (ret)
72 *ret = uid;
b1d4f8e1
LP
73
74 return 0;
75}
76
03de302a 77int parse_uid_range(const char *s, uid_t *ret_lower, uid_t *ret_upper) {
60eb1f07
LP
78 _cleanup_free_ char *word = NULL;
79 uid_t l, u;
03de302a
YW
80 int r;
81
82 assert(s);
83 assert(ret_lower);
84 assert(ret_upper);
85
60eb1f07 86 r = extract_first_word(&s, &word, "-", EXTRACT_DONT_COALESCE_SEPARATORS);
03de302a
YW
87 if (r < 0)
88 return r;
60eb1f07 89 if (r == 0)
03de302a
YW
90 return -EINVAL;
91
60eb1f07
LP
92 r = parse_uid(word, &l);
93 if (r < 0)
94 return r;
95
96 /* Check for the upper bound and extract it if needed */
97 if (!s)
98 /* Single number with no dash. */
99 u = l;
100 else if (!*s)
101 /* Trailing dash is an error. */
102 return -EINVAL;
103 else {
104 r = parse_uid(s, &u);
105 if (r < 0)
106 return r;
107
108 if (l > u)
109 return -EINVAL;
110 }
03de302a
YW
111
112 *ret_lower = l;
113 *ret_upper = u;
114 return 0;
115}
116
b1d4f8e1
LP
117char* getlogname_malloc(void) {
118 uid_t uid;
119 struct stat st;
120
300b7e76 121 if (isatty_safe(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
b1d4f8e1
LP
122 uid = st.st_uid;
123 else
124 uid = getuid();
125
d0260817 126 return uid_to_name(uid);
b1d4f8e1
LP
127}
128
78435d62 129char* getusername_malloc(void) {
b1d4f8e1
LP
130 const char *e;
131
b2a3953f 132 e = secure_getenv("USER");
b1d4f8e1
LP
133 if (e)
134 return strdup(e);
135
d0260817 136 return uid_to_name(getuid());
b1d4f8e1
LP
137}
138
6093b2bb 139bool is_nologin_shell(const char *shell) {
fafff8f1
LP
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. */
144 "/bin/nologin",
145 "/sbin/nologin",
146 "/usr/bin/nologin",
147 "/usr/sbin/nologin",
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. */
151 "/bin/false",
152 "/usr/bin/false",
153 "/bin/true",
154 "/usr/bin/true");
155}
156
0c15577a
DDM
157bool shell_is_placeholder(const char *shell) {
158 return isempty(shell) || is_nologin_shell(shell);
159}
160
bd595c10 161const char* default_root_shell_at(int rfd) {
8a7adccb
ZJS
162 /* We want to use the preferred shell, i.e. DEFAULT_USER_SHELL, which usually
163 * will be /bin/bash. Fall back to /bin/sh if DEFAULT_USER_SHELL is not found,
164 * or any access errors. */
165
bd595c10
DDM
166 assert(rfd >= 0 || rfd == AT_FDCWD);
167
168 int r = chaseat(rfd, DEFAULT_USER_SHELL, CHASE_AT_RESOLVE_IN_ROOT, NULL, NULL);
8a7adccb 169 if (r < 0 && r != -ENOENT)
bd595c10 170 log_debug_errno(r, "Failed to look up shell '%s': %m", DEFAULT_USER_SHELL);
8a7adccb
ZJS
171 if (r > 0)
172 return DEFAULT_USER_SHELL;
173
174 return "/bin/sh";
175}
176
78435d62 177const char* default_root_shell(const char *root) {
bd595c10
DDM
178 _cleanup_close_ int rfd = -EBADF;
179
180 rfd = open(empty_to_root(root), O_CLOEXEC | O_DIRECTORY | O_PATH);
181 if (rfd < 0)
182 return "/bin/sh";
183
184 return default_root_shell_at(rfd);
185}
186
fafff8f1 187static int synthesize_user_creds(
b1d4f8e1 188 const char **username,
83e9b584
LP
189 uid_t *ret_uid, gid_t *ret_gid,
190 const char **ret_home,
191 const char **ret_shell,
fafff8f1 192 UserCredsFlags flags) {
b1d4f8e1 193
83e9b584
LP
194 assert(username);
195 assert(*username);
196
7e61fd02
LP
197 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
198 * their user record data. */
b1d4f8e1 199
7e61fd02 200 if (STR_IN_SET(*username, "root", "0")) {
b1d4f8e1
LP
201 *username = "root";
202
83e9b584
LP
203 if (ret_uid)
204 *ret_uid = 0;
205 if (ret_gid)
206 *ret_gid = 0;
207 if (ret_home)
208 *ret_home = "/root";
209 if (ret_shell)
210 *ret_shell = default_root_shell(NULL);
b1d4f8e1
LP
211
212 return 0;
213 }
214
36bac2dc
ZJS
215 if (STR_IN_SET(*username, NOBODY_USER_NAME, "65534") &&
216 synthesize_nobody()) {
7e61fd02
LP
217 *username = NOBODY_USER_NAME;
218
83e9b584
LP
219 if (ret_uid)
220 *ret_uid = UID_NOBODY;
221 if (ret_gid)
222 *ret_gid = GID_NOBODY;
223 if (ret_home)
eea9d3eb 224 *ret_home = FLAGS_SET(flags, USER_CREDS_SUPPRESS_PLACEHOLDER) ? NULL : "/";
83e9b584 225 if (ret_shell)
eea9d3eb 226 *ret_shell = FLAGS_SET(flags, USER_CREDS_SUPPRESS_PLACEHOLDER) ? NULL : NOLOGIN;
7e61fd02
LP
227
228 return 0;
229 }
230
fafff8f1
LP
231 return -ENOMEDIUM;
232}
233
234int get_user_creds(
235 const char **username,
83e9b584
LP
236 uid_t *ret_uid, gid_t *ret_gid,
237 const char **ret_home,
238 const char **ret_shell,
fafff8f1
LP
239 UserCredsFlags flags) {
240
83e9b584 241 bool patch_username = false;
fafff8f1
LP
242 uid_t u = UID_INVALID;
243 struct passwd *p;
244 int r;
245
246 assert(username);
247 assert(*username);
eea9d3eb 248 assert((ret_home || ret_shell) || !(flags & (USER_CREDS_SUPPRESS_PLACEHOLDER|USER_CREDS_CLEAN)));
fafff8f1 249
43ad3ad7 250 if (!FLAGS_SET(flags, USER_CREDS_PREFER_NSS) ||
83e9b584 251 (!ret_home && !ret_shell)) {
fafff8f1
LP
252
253 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
43ad3ad7 254 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
fafff8f1
LP
255 * user database will override the synthetic records instead — except if the user is only interested in
256 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
43ad3ad7 257 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
fafff8f1
LP
258 * Simply because there are valid usecase where the user might change the home directory or the shell
259 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
260 * support. */
261
83e9b584 262 r = synthesize_user_creds(username, ret_uid, ret_gid, ret_home, ret_shell, flags);
fafff8f1
LP
263 if (r >= 0)
264 return 0;
265 if (r != -ENOMEDIUM) /* not a username we can synthesize */
266 return r;
267 }
268
b1d4f8e1
LP
269 if (parse_uid(*username, &u) >= 0) {
270 errno = 0;
271 p = getpwuid(u);
272
fafff8f1
LP
273 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
274 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
275 * then let's pick the real username from /etc/passwd. */
b1d4f8e1 276 if (p)
83e9b584
LP
277 patch_username = true;
278 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING) && !ret_gid && !ret_home && !ret_shell) {
fafff8f1
LP
279
280 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
0017be9d 281 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then just return that
fafff8f1
LP
282 * and don't complain. */
283
83e9b584
LP
284 if (ret_uid)
285 *ret_uid = u;
fafff8f1
LP
286
287 return 0;
288 }
b1d4f8e1
LP
289 } else {
290 errno = 0;
291 p = getpwnam(*username);
292 }
fafff8f1 293 if (!p) {
c42bac6a
ZJS
294 /* getpwnam() may fail with ENOENT if /etc/passwd is missing.
295 * For us that is equivalent to the name not being defined. */
296 r = IN_SET(errno, 0, ENOENT) ? -ESRCH : -errno;
b1d4f8e1 297
fafff8f1 298 /* If the user requested that we only synthesize as fallback, do so now */
83e9b584
LP
299 if (FLAGS_SET(flags, USER_CREDS_PREFER_NSS))
300 if (synthesize_user_creds(username, ret_uid, ret_gid, ret_home, ret_shell, flags) >= 0)
fafff8f1 301 return 0;
fafff8f1
LP
302
303 return r;
304 }
b1d4f8e1 305
83e9b584
LP
306 if (ret_uid && !uid_is_valid(p->pw_uid))
307 return -EBADMSG;
67c7c892 308
83e9b584
LP
309 if (ret_gid && !gid_is_valid(p->pw_gid))
310 return -EBADMSG;
67c7c892 311
83e9b584
LP
312 if (ret_uid)
313 *ret_uid = p->pw_uid;
b1d4f8e1 314
83e9b584
LP
315 if (ret_gid)
316 *ret_gid = p->pw_gid;
b1d4f8e1 317
83e9b584
LP
318 if (ret_home)
319 /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
eea9d3eb
MY
320 *ret_home = (FLAGS_SET(flags, USER_CREDS_SUPPRESS_PLACEHOLDER) && empty_or_root(p->pw_dir)) ||
321 (FLAGS_SET(flags, USER_CREDS_CLEAN) && (!path_is_valid(p->pw_dir) || !path_is_absolute(p->pw_dir)))
322 ? NULL : p->pw_dir;
be39ccf3 323
83e9b584 324 if (ret_shell)
eea9d3eb
MY
325 *ret_shell = (FLAGS_SET(flags, USER_CREDS_SUPPRESS_PLACEHOLDER) && shell_is_placeholder(p->pw_shell)) ||
326 (FLAGS_SET(flags, USER_CREDS_CLEAN) && (!path_is_valid(p->pw_shell) || !path_is_absolute(p->pw_shell)))
327 ? NULL : p->pw_shell;
83e9b584
LP
328
329 if (patch_username)
330 *username = p->pw_name;
be39ccf3
LP
331
332 return 0;
333}
334
e9c974fd
LP
335static int synthesize_group_creds(
336 const char **groupname,
337 gid_t *ret_gid) {
b1d4f8e1
LP
338
339 assert(groupname);
83e9b584 340 assert(*groupname);
b1d4f8e1 341
7e61fd02 342 if (STR_IN_SET(*groupname, "root", "0")) {
b1d4f8e1
LP
343 *groupname = "root";
344
83e9b584
LP
345 if (ret_gid)
346 *ret_gid = 0;
b1d4f8e1
LP
347
348 return 0;
349 }
350
36bac2dc
ZJS
351 if (STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534") &&
352 synthesize_nobody()) {
7e61fd02
LP
353 *groupname = NOBODY_GROUP_NAME;
354
83e9b584
LP
355 if (ret_gid)
356 *ret_gid = GID_NOBODY;
7e61fd02
LP
357
358 return 0;
359 }
360
e9c974fd
LP
361 return -ENOMEDIUM;
362}
363
364int get_group_creds(const char **groupname, gid_t *ret_gid, UserCredsFlags flags) {
365 bool patch_groupname = false;
366 struct group *g;
367 gid_t id;
368 int r;
369
370 assert(groupname);
371 assert(*groupname);
372
373 if (!FLAGS_SET(flags, USER_CREDS_PREFER_NSS)) {
374 r = synthesize_group_creds(groupname, ret_gid);
375 if (r >= 0)
376 return 0;
377 if (r != -ENOMEDIUM) /* not a groupname we can synthesize */
378 return r;
379 }
380
b1d4f8e1
LP
381 if (parse_gid(*groupname, &id) >= 0) {
382 errno = 0;
383 g = getgrgid(id);
384
385 if (g)
83e9b584 386 patch_groupname = true;
fafff8f1 387 else if (FLAGS_SET(flags, USER_CREDS_ALLOW_MISSING)) {
83e9b584
LP
388 if (ret_gid)
389 *ret_gid = id;
fafff8f1
LP
390
391 return 0;
392 }
b1d4f8e1
LP
393 } else {
394 errno = 0;
395 g = getgrnam(*groupname);
396 }
397
e9c974fd 398 if (!g) {
c42bac6a
ZJS
399 /* getgrnam() may fail with ENOENT if /etc/group is missing.
400 * For us that is equivalent to the name not being defined. */
e9c974fd
LP
401 r = IN_SET(errno, 0, ENOENT) ? -ESRCH : -errno;
402
403 if (FLAGS_SET(flags, USER_CREDS_PREFER_NSS))
404 if (synthesize_group_creds(groupname, ret_gid) >= 0)
405 return 0;
406
407 return r;
408 }
b1d4f8e1 409
83e9b584 410 if (ret_gid) {
67c7c892
LP
411 if (!gid_is_valid(g->gr_gid))
412 return -EBADMSG;
413
83e9b584 414 *ret_gid = g->gr_gid;
67c7c892 415 }
b1d4f8e1 416
83e9b584
LP
417 if (patch_groupname)
418 *groupname = g->gr_name;
419
b1d4f8e1
LP
420 return 0;
421}
422
423char* uid_to_name(uid_t uid) {
d0260817
LP
424 char *ret;
425 int r;
b1d4f8e1 426
d0260817 427 /* Shortcut things to avoid NSS lookups */
b1d4f8e1
LP
428 if (uid == 0)
429 return strdup("root");
36bac2dc 430 if (uid == UID_NOBODY && synthesize_nobody())
7e61fd02 431 return strdup(NOBODY_USER_NAME);
b1d4f8e1 432
d0260817 433 if (uid_is_valid(uid)) {
75673cd8 434 _cleanup_free_ struct passwd *pw = NULL;
d0260817 435
75673cd8
LP
436 r = getpwuid_malloc(uid, &pw);
437 if (r >= 0)
438 return strdup(pw->pw_name);
d0260817 439 }
b1d4f8e1 440
d0260817 441 if (asprintf(&ret, UID_FMT, uid) < 0)
b1d4f8e1
LP
442 return NULL;
443
d0260817 444 return ret;
b1d4f8e1
LP
445}
446
447char* gid_to_name(gid_t gid) {
d0260817
LP
448 char *ret;
449 int r;
b1d4f8e1
LP
450
451 if (gid == 0)
452 return strdup("root");
36bac2dc 453 if (gid == GID_NOBODY && synthesize_nobody())
7e61fd02 454 return strdup(NOBODY_GROUP_NAME);
b1d4f8e1 455
d0260817 456 if (gid_is_valid(gid)) {
75673cd8 457 _cleanup_free_ struct group *gr = NULL;
d0260817 458
75673cd8
LP
459 r = getgrgid_malloc(gid, &gr);
460 if (r >= 0)
461 return strdup(gr->gr_name);
d0260817 462 }
b1d4f8e1 463
d0260817 464 if (asprintf(&ret, GID_FMT, gid) < 0)
b1d4f8e1
LP
465 return NULL;
466
d0260817 467 return ret;
b1d4f8e1
LP
468}
469
0c5d6679 470static bool gid_list_has(const gid_t *list, size_t size, gid_t val) {
8112df6b
MY
471 assert(list || size == 0);
472
473 FOREACH_ARRAY(i, list, size)
474 if (*i == val)
0c5d6679 475 return true;
8112df6b 476
0c5d6679
DG
477 return false;
478}
479
b1d4f8e1 480int in_gid(gid_t gid) {
0c5d6679
DG
481 _cleanup_free_ gid_t *gids = NULL;
482 int ngroups;
b1d4f8e1
LP
483
484 if (getgid() == gid)
485 return 1;
486
487 if (getegid() == gid)
488 return 1;
489
67c7c892
LP
490 if (!gid_is_valid(gid))
491 return -EINVAL;
492
0c5d6679
DG
493 ngroups = getgroups_alloc(&gids);
494 if (ngroups < 0)
495 return ngroups;
496
497 return gid_list_has(gids, ngroups, gid);
498}
499
500int in_group(const char *name) {
501 int r;
502 gid_t gid;
503
504 r = get_group_creds(&name, &gid, 0);
505 if (r < 0)
506 return r;
507
508 return in_gid(gid);
509}
510
511int merge_gid_lists(const gid_t *list1, size_t size1, const gid_t *list2, size_t size2, gid_t **ret) {
512 size_t nresult = 0;
513 assert(ret);
514
515 if (size2 > INT_MAX - size1)
516 return -ENOBUFS;
517
518 gid_t *buf = new(gid_t, size1 + size2);
519 if (!buf)
520 return -ENOMEM;
521
522 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
523 for (size_t i = 0; i < size1; i++)
524 if (!gid_list_has(buf, nresult, list1[i]))
525 buf[nresult++] = list1[i];
526 for (size_t i = 0; i < size2; i++)
527 if (!gid_list_has(buf, nresult, list2[i]))
528 buf[nresult++] = list2[i];
529 *ret = buf;
530 return (int)nresult;
531}
532
f0e8db76 533int getgroups_alloc(gid_t **ret) {
0c5d6679 534 int ngroups = 8;
0c5d6679 535
f0e8db76
MY
536 assert(ret);
537
538 for (unsigned attempt = 0;;) {
539 _cleanup_free_ gid_t *p = NULL;
540
541 p = new(gid_t, ngroups);
542 if (!p)
543 return -ENOMEM;
0c5d6679 544
6e0a3888 545 ngroups = getgroups(ngroups, p);
f0e8db76
MY
546 if (ngroups > 0) {
547 *ret = TAKE_PTR(p);
548 return ngroups;
549 }
550 if (ngroups == 0)
6e0a3888
LP
551 break;
552 if (errno != EINVAL)
553 return -errno;
554
555 /* Give up eventually */
556 if (attempt++ > 10)
557 return -EINVAL;
558
559 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
560 * to use (in multi-threaded programs), hence let's call this in a loop. */
561 ngroups = getgroups(0, NULL);
562 if (ngroups < 0)
563 return -errno;
564 if (ngroups == 0)
f0e8db76 565 break;
6e0a3888 566 }
b1d4f8e1 567
f0e8db76
MY
568 *ret = NULL;
569 return 0;
b1d4f8e1
LP
570}
571
8795d9ba 572int get_home_dir(char **ret) {
75673cd8 573 _cleanup_free_ struct passwd *p = NULL;
b1d4f8e1 574 const char *e;
b1d4f8e1 575 uid_t u;
75673cd8 576 int r;
b1d4f8e1 577
8795d9ba 578 assert(ret);
b1d4f8e1
LP
579
580 /* Take the user specified one */
581 e = secure_getenv("HOME");
8795d9ba
ZJS
582 if (e && path_is_valid(e) && path_is_absolute(e))
583 goto found;
b1d4f8e1 584
7e61fd02 585 /* Hardcode home directory for root and nobody to avoid NSS */
b1d4f8e1
LP
586 u = getuid();
587 if (u == 0) {
8795d9ba
ZJS
588 e = "/root";
589 goto found;
b1d4f8e1 590 }
36bac2dc 591 if (u == UID_NOBODY && synthesize_nobody()) {
8795d9ba
ZJS
592 e = "/";
593 goto found;
7e61fd02 594 }
b1d4f8e1
LP
595
596 /* Check the database... */
75673cd8
LP
597 r = getpwuid_malloc(u, &p);
598 if (r < 0)
599 return r;
b1d4f8e1 600
75673cd8 601 e = p->pw_dir;
8795d9ba 602 if (!path_is_valid(e) || !path_is_absolute(e))
b1d4f8e1
LP
603 return -EINVAL;
604
8795d9ba 605 found:
660087dc 606 return path_simplify_alloc(e, ret);
b1d4f8e1
LP
607}
608
8795d9ba 609int get_shell(char **ret) {
75673cd8 610 _cleanup_free_ struct passwd *p = NULL;
b1d4f8e1 611 const char *e;
b1d4f8e1 612 uid_t u;
75673cd8 613 int r;
b1d4f8e1 614
8795d9ba 615 assert(ret);
b1d4f8e1
LP
616
617 /* Take the user specified one */
b2a3953f 618 e = secure_getenv("SHELL");
8795d9ba
ZJS
619 if (e && path_is_valid(e) && path_is_absolute(e))
620 goto found;
b1d4f8e1 621
7e61fd02 622 /* Hardcode shell for root and nobody to avoid NSS */
b1d4f8e1
LP
623 u = getuid();
624 if (u == 0) {
8795d9ba
ZJS
625 e = default_root_shell(NULL);
626 goto found;
b1d4f8e1 627 }
36bac2dc 628 if (u == UID_NOBODY && synthesize_nobody()) {
8795d9ba
ZJS
629 e = NOLOGIN;
630 goto found;
7e61fd02 631 }
b1d4f8e1
LP
632
633 /* Check the database... */
75673cd8
LP
634 r = getpwuid_malloc(u, &p);
635 if (r < 0)
636 return r;
b1d4f8e1 637
75673cd8 638 e = p->pw_shell;
8795d9ba 639 if (!path_is_valid(e) || !path_is_absolute(e))
b1d4f8e1
LP
640 return -EINVAL;
641
8795d9ba 642 found:
660087dc 643 return path_simplify_alloc(e, ret);
b1d4f8e1
LP
644}
645
6498a0c2 646int fully_set_uid_gid(uid_t uid, gid_t gid, const gid_t supplementary_gids[], size_t n_supplementary_gids) {
97f0e76f 647 int r;
b1d4f8e1 648
6498a0c2
LP
649 assert(supplementary_gids || n_supplementary_gids == 0);
650
651 /* Sets all UIDs and all GIDs to the specified ones. Drops all auxiliary GIDs */
652
653 r = maybe_setgroups(n_supplementary_gids, supplementary_gids);
97f0e76f
LP
654 if (r < 0)
655 return r;
b1d4f8e1 656
6498a0c2
LP
657 if (gid_is_valid(gid))
658 if (setresgid(gid, gid, gid) < 0)
659 return -errno;
660
661 if (uid_is_valid(uid))
662 if (setresuid(uid, uid, uid) < 0)
663 return -errno;
b1d4f8e1 664
6498a0c2 665 return 0;
b1d4f8e1 666}
e929bee0
LP
667
668int take_etc_passwd_lock(const char *root) {
460accdf 669 int r;
e929bee0 670
fddb524d
ZJS
671 /* This is roughly the same as lckpwdf(), but not as awful. We don't want to use alarm() and signals,
672 * hence we implement our own trivial version of this.
e929bee0 673 *
fddb524d
ZJS
674 * Note that shadow-utils also takes per-database locks in addition to lckpwdf(). However, we don't,
675 * given that they are redundant: they invoke lckpwdf() first and keep it during everything they do.
676 * The per-database locks are awfully racy, and thus we just won't do them. */
e929bee0 677
e5b30f72
ZJS
678 _cleanup_free_ char *path = path_join(root, ETC_PASSWD_LOCK_PATH);
679 if (!path)
680 return log_oom_debug();
e929bee0 681
d173d556
ZJS
682 (void) mkdir_parents(path, 0755);
683
e5b30f72 684 _cleanup_close_ int fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
e929bee0 685 if (fd < 0)
d1e4b8fd 686 return log_debug_errno(errno, "Cannot open %s: %m", path);
e929bee0 687
460accdf
DDM
688 r = unposix_lock(fd, LOCK_EX);
689 if (r < 0)
690 return log_debug_errno(r, "Locking %s failed: %m", path);
e929bee0 691
e5b30f72 692 return TAKE_FD(fd);
e929bee0 693}
e4631b48 694
7a8867ab 695bool valid_user_group_name(const char *u, ValidUserFlags flags) {
e4631b48 696 const char *i;
e4631b48 697
7a8867ab
LP
698 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
699 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
700 * pretty much everything except the really worst offending names.
1429dfe5 701 *
7a8867ab
LP
702 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
703 * created by other stuff, let's be more liberal. */
e4631b48 704
7a8867ab 705 if (isempty(u)) /* An empty user name is never valid */
e4631b48
LP
706 return false;
707
7a8867ab
LP
708 if (parse_uid(u, NULL) >= 0) /* Something that parses as numeric UID string is valid exactly when the
709 * flag for it is set */
710 return FLAGS_SET(flags, VALID_USER_ALLOW_NUMERIC);
711
712 if (FLAGS_SET(flags, VALID_USER_RELAX)) {
713
714 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
715 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
716 * is bound to cause problems for example when used with an MTA), hence only filter the most
717 * obvious cases, or where things would result in an invalid entry if such a user name would
718 * show up in /etc/passwd (or equivalent getent output).
719 *
720 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
721 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
722 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
723 * have...) */
724
725 if (startswith(u, " ") || endswith(u, " ")) /* At least expect whitespace padding is removed
726 * at front and back (accept in the middle, since
727 * that's apparently a thing on Windows). Note
728 * that this also blocks usernames consisting of
729 * whitespace only. */
730 return false;
93c23c92 731
7a8867ab
LP
732 if (!utf8_is_valid(u)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
733 return false;
88e2ed0b 734
7a8867ab
LP
735 if (string_has_cc(u, NULL)) /* CC characters are just dangerous (and \n in particular is the
736 * record separator in /etc/passwd), so we can't allow that. */
737 return false;
88e2ed0b 738
7a8867ab
LP
739 if (strpbrk(u, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
740 * that. Slashes are special to file systems paths and user names
741 * typically show up in the file system as home directories, hence
742 * don't allow slashes. */
743 return false;
e4631b48 744
7a8867ab 745 if (in_charset(u, "0123456789")) /* Don't allow fully numeric strings, they might be confused
e9dd6984 746 * with UIDs (note that this test is more broad than
7a8867ab 747 * the parse_uid() test above, as it will cover more than
da890466 748 * the 32-bit range, and it will detect 65535 (which is in
7a8867ab
LP
749 * invalid UID, even though in the unsigned 32 bit range) */
750 return false;
93c23c92 751
7a8867ab
LP
752 if (u[0] == '-' && in_charset(u + 1, "0123456789")) /* Don't allow negative fully numeric
753 * strings either. After all some people
754 * write 65535 as -1 (even though that's
da890466 755 * not even true on 32-bit uid_t
7a8867ab
LP
756 * anyway) */
757 return false;
e4631b48 758
7a8867ab
LP
759 if (dot_or_dot_dot(u)) /* User names typically become home directory names, and these two are
760 * special in that context, don't allow that. */
761 return false;
e4631b48 762
7a8867ab
LP
763 /* Compare with strict result and warn if result doesn't match */
764 if (FLAGS_SET(flags, VALID_USER_WARN) && !valid_user_group_name(u, 0))
765 log_struct(LOG_NOTICE,
92663a5e 766 LOG_MESSAGE("Accepting user/group name '%s', which does not match strict user/group name rules.", u),
3cf6a3a3
YW
767 LOG_ITEM("USER_GROUP_NAME=%s", u),
768 LOG_MESSAGE_ID(SD_MESSAGE_UNSAFE_USER_NAME_STR));
e4631b48 769
7a8867ab
LP
770 /* Note that we make no restrictions on the length in relaxed mode! */
771 } else {
772 long sz;
773 size_t l;
774
775 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
776 * however. Specifically we deviate from POSIX rules:
777 *
778 * - We don't allow empty user names (see above)
779 * - We require that names fit into the appropriate utmp field
780 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
781 * - We don't allow dashes or digit as the first character
782 *
783 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
784 */
785
ff25d338 786 if (!ascii_isalpha(u[0]) &&
7a8867ab
LP
787 u[0] != '_')
788 return false;
e4631b48 789
7a8867ab 790 for (i = u+1; *i; i++)
ff25d338
LP
791 if (!ascii_isalpha(*i) &&
792 !ascii_isdigit(*i) &&
7a8867ab
LP
793 !IN_SET(*i, '_', '-'))
794 return false;
e4631b48 795
7a8867ab 796 l = i - u;
e4631b48 797
7a8867ab
LP
798 sz = sysconf(_SC_LOGIN_NAME_MAX);
799 assert_se(sz > 0);
e4631b48 800
b009782b 801 if (l > (size_t) sz) /* glibc: 256 */
7a8867ab 802 return false;
b009782b 803 if (l > NAME_MAX) /* must fit in a filename: 255 */
7a8867ab 804 return false;
f3389fff 805 if (l > sizeof_field(struct utmpx, ut_user) - 1) /* must fit in utmp: 31 */
7a8867ab
LP
806 return false;
807 }
e4631b48 808
7a8867ab 809 return true;
e4631b48
LP
810}
811
812bool valid_gecos(const char *d) {
813
814 if (!d)
815 return false;
816
817 if (!utf8_is_valid(d))
818 return false;
819
820 if (string_has_cc(d, NULL))
821 return false;
822
823 /* Colons are used as field separators, and hence not OK */
824 if (strchr(d, ':'))
825 return false;
826
827 return true;
828}
829
78435d62 830char* mangle_gecos(const char *d) {
b10fd796
LP
831 char *mangled;
832
833 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
834 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
835 * UTF-8 */
836
837 mangled = strdup(d);
838 if (!mangled)
839 return NULL;
840
841 for (char *i = mangled; *i; i++) {
842 int len;
843
844 if ((uint8_t) *i < (uint8_t) ' ' || *i == ':') {
845 *i = ' ';
846 continue;
847 }
848
f5fbe71d 849 len = utf8_encoded_valid_unichar(i, SIZE_MAX);
b10fd796
LP
850 if (len < 0) {
851 *i = ' ';
852 continue;
853 }
854
855 i += len - 1;
856 }
857
858 return mangled;
859}
860
e4631b48 861bool valid_home(const char *p) {
7b1aaf66
ZJS
862 /* Note that this function is also called by valid_shell(), any
863 * changes must account for that. */
e4631b48
LP
864
865 if (isempty(p))
866 return false;
867
868 if (!utf8_is_valid(p))
869 return false;
870
871 if (string_has_cc(p, NULL))
872 return false;
873
874 if (!path_is_absolute(p))
875 return false;
876
99be45a4 877 if (!path_is_normalized(p))
e4631b48
LP
878 return false;
879
880 /* Colons are used as field separators, and hence not OK */
881 if (strchr(p, ':'))
882 return false;
883
884 return true;
885}
36d85478 886
4167e9e2
LP
887bool valid_shell(const char *p) {
888 /* We have the same requirements, so just piggy-back on the home check.
889 *
890 * Let's ignore /etc/shells because this is only applicable to real and not system users. It is also
891 * incompatible with the idea of empty /etc/. */
892 if (!valid_home(p))
893 return false;
894
895 return !endswith(p, "/"); /* one additional restriction: shells may not be dirs */
896}
897
36d85478 898int maybe_setgroups(size_t size, const gid_t *list) {
97f0e76f
LP
899 int r;
900
901 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
902 if (size == 0) { /* Dropping all aux groups? */
903 _cleanup_free_ char *setgroups_content = NULL;
904 bool can_setgroups;
905
906 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
907 if (r == -ENOENT)
908 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
909 can_setgroups = true;
910 else if (r < 0)
911 return r;
912 else
913 can_setgroups = streq(setgroups_content, "allow");
914
915 if (!can_setgroups) {
916 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
36d85478 917 return 0;
97f0e76f 918 }
36d85478 919 }
97f0e76f 920
7c248223 921 return RET_NERRNO(setgroups(size, list));
36d85478 922}
24eccc34
LP
923
924bool synthesize_nobody(void) {
24eccc34
LP
925 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
926 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
927 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
928 *
929 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
930 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
931 * shouldn't matter as each initialization should come to the same result. */
932 static int cache = -1;
933
934 if (cache < 0)
935 cache = access("/etc/systemd/dont-synthesize-nobody", F_OK) < 0;
936
937 return cache;
24eccc34 938}
100d5f6e
FB
939
940int putpwent_sane(const struct passwd *pw, FILE *stream) {
941 assert(pw);
942 assert(stream);
943
944 errno = 0;
945 if (putpwent(pw, stream) != 0)
66855de7 946 return errno_or_else(EIO);
100d5f6e
FB
947
948 return 0;
949}
950
951int putspent_sane(const struct spwd *sp, FILE *stream) {
952 assert(sp);
953 assert(stream);
954
955 errno = 0;
956 if (putspent(sp, stream) != 0)
66855de7 957 return errno_or_else(EIO);
100d5f6e
FB
958
959 return 0;
960}
961
962int putgrent_sane(const struct group *gr, FILE *stream) {
963 assert(gr);
964 assert(stream);
965
966 errno = 0;
967 if (putgrent(gr, stream) != 0)
66855de7 968 return errno_or_else(EIO);
100d5f6e
FB
969
970 return 0;
971}
972
973#if ENABLE_GSHADOW
974int putsgent_sane(const struct sgrp *sg, FILE *stream) {
975 assert(sg);
976 assert(stream);
977
978 errno = 0;
979 if (putsgent(sg, stream) != 0)
66855de7 980 return errno_or_else(EIO);
100d5f6e
FB
981
982 return 0;
983}
984#endif
985
986int fgetpwent_sane(FILE *stream, struct passwd **pw) {
100d5f6e 987 assert(stream);
67f047a6 988 assert(pw);
100d5f6e
FB
989
990 errno = 0;
67f047a6 991 struct passwd *p = fgetpwent(stream);
953c60e2
MG
992 if (!p && !IN_SET(errno, 0, ENOENT))
993 return -errno;
100d5f6e
FB
994
995 *pw = p;
ad80c6a6 996 return !!p;
100d5f6e
FB
997}
998
999int fgetspent_sane(FILE *stream, struct spwd **sp) {
100d5f6e 1000 assert(stream);
67f047a6 1001 assert(sp);
100d5f6e
FB
1002
1003 errno = 0;
67f047a6 1004 struct spwd *s = fgetspent(stream);
953c60e2
MG
1005 if (!s && !IN_SET(errno, 0, ENOENT))
1006 return -errno;
100d5f6e
FB
1007
1008 *sp = s;
ad80c6a6 1009 return !!s;
100d5f6e
FB
1010}
1011
1012int fgetgrent_sane(FILE *stream, struct group **gr) {
100d5f6e 1013 assert(stream);
67f047a6 1014 assert(gr);
100d5f6e
FB
1015
1016 errno = 0;
67f047a6 1017 struct group *g = fgetgrent(stream);
953c60e2
MG
1018 if (!g && !IN_SET(errno, 0, ENOENT))
1019 return -errno;
100d5f6e
FB
1020
1021 *gr = g;
ad80c6a6 1022 return !!g;
100d5f6e
FB
1023}
1024
1025#if ENABLE_GSHADOW
1026int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
100d5f6e 1027 assert(stream);
67f047a6 1028 assert(sg);
100d5f6e
FB
1029
1030 errno = 0;
67f047a6 1031 struct sgrp *s = fgetsgent(stream);
953c60e2
MG
1032 if (!s && !IN_SET(errno, 0, ENOENT))
1033 return -errno;
100d5f6e
FB
1034
1035 *sg = s;
ad80c6a6 1036 return !!s;
100d5f6e
FB
1037}
1038#endif
7bdbafc2
LP
1039
1040int is_this_me(const char *username) {
1041 uid_t uid;
1042 int r;
1043
1044 /* Checks if the specified username is our current one. Passed string might be a UID or a user name. */
1045
1046 r = get_user_creds(&username, &uid, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
1047 if (r < 0)
1048 return r;
1049
1050 return uid == getuid();
1051}
2700fecd 1052
78435d62 1053const char* get_home_root(void) {
2700fecd
LP
1054 const char *e;
1055
1056 /* For debug purposes allow overriding where we look for home dirs */
1057 e = secure_getenv("SYSTEMD_HOME_ROOT");
1058 if (e && path_is_absolute(e) && path_is_normalized(e))
1059 return e;
1060
1061 return "/home";
1062}
75673cd8
LP
1063
1064static size_t getpw_buffer_size(void) {
1065 long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1066 return bufsize <= 0 ? 4096U : (size_t) bufsize;
1067}
1068
1069static bool errno_is_user_doesnt_exist(int error) {
1070 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
1071 * not found. */
1072 return IN_SET(abs(error), ENOENT, ESRCH, EBADF, EPERM);
1073}
1074
1075int getpwnam_malloc(const char *name, struct passwd **ret) {
1076 size_t bufsize = getpw_buffer_size();
1077 int r;
1078
1079 /* A wrapper around getpwnam_r() that allocates the necessary buffer on the heap. The caller must
a4f1a308 1080 * free() the returned structures! */
75673cd8
LP
1081
1082 if (isempty(name))
1083 return -EINVAL;
1084
1085 for (;;) {
1086 _cleanup_free_ void *buf = NULL;
1087
64fc712f 1088 buf = malloc0(ALIGN(sizeof(struct passwd)) + bufsize);
75673cd8
LP
1089 if (!buf)
1090 return -ENOMEM;
1091
1092 struct passwd *pw = NULL;
1093 r = getpwnam_r(name, buf, (char*) buf + ALIGN(sizeof(struct passwd)), (size_t) bufsize, &pw);
1094 if (r == 0) {
1095 if (pw) {
1096 if (ret)
1097 *ret = TAKE_PTR(buf);
1098 return 0;
1099 }
1100
1101 return -ESRCH;
1102 }
1103
1104 assert(r > 0);
1105
1106 /* getpwnam() may fail with ENOENT if /etc/passwd is missing. For us that is equivalent to
1107 * the name not being defined. */
1108 if (errno_is_user_doesnt_exist(r))
1109 return -ESRCH;
1110 if (r != ERANGE)
1111 return -r;
1112
1113 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct passwd)))
1114 return -ENOMEM;
1115 bufsize *= 2;
1116 }
1117}
1118
1119int getpwuid_malloc(uid_t uid, struct passwd **ret) {
1120 size_t bufsize = getpw_buffer_size();
1121 int r;
1122
1123 if (!uid_is_valid(uid))
1124 return -EINVAL;
1125
1126 for (;;) {
1127 _cleanup_free_ void *buf = NULL;
1128
64fc712f 1129 buf = malloc0(ALIGN(sizeof(struct passwd)) + bufsize);
75673cd8
LP
1130 if (!buf)
1131 return -ENOMEM;
1132
1133 struct passwd *pw = NULL;
1134 r = getpwuid_r(uid, buf, (char*) buf + ALIGN(sizeof(struct passwd)), (size_t) bufsize, &pw);
1135 if (r == 0) {
1136 if (pw) {
1137 if (ret)
1138 *ret = TAKE_PTR(buf);
1139 return 0;
1140 }
1141
1142 return -ESRCH;
1143 }
1144
1145 assert(r > 0);
1146
1147 if (errno_is_user_doesnt_exist(r))
1148 return -ESRCH;
1149 if (r != ERANGE)
1150 return -r;
1151
1152 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct passwd)))
1153 return -ENOMEM;
1154 bufsize *= 2;
1155 }
1156}
1157
1158static size_t getgr_buffer_size(void) {
1159 long bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
1160 return bufsize <= 0 ? 4096U : (size_t) bufsize;
1161}
1162
1163int getgrnam_malloc(const char *name, struct group **ret) {
1164 size_t bufsize = getgr_buffer_size();
1165 int r;
1166
1167 if (isempty(name))
1168 return -EINVAL;
1169
1170 for (;;) {
1171 _cleanup_free_ void *buf = NULL;
1172
64fc712f 1173 buf = malloc0(ALIGN(sizeof(struct group)) + bufsize);
75673cd8
LP
1174 if (!buf)
1175 return -ENOMEM;
1176
1177 struct group *gr = NULL;
1178 r = getgrnam_r(name, buf, (char*) buf + ALIGN(sizeof(struct group)), (size_t) bufsize, &gr);
1179 if (r == 0) {
1180 if (gr) {
1181 if (ret)
1182 *ret = TAKE_PTR(buf);
1183 return 0;
1184 }
1185
1186 return -ESRCH;
1187 }
1188
1189 assert(r > 0);
1190
1191 if (errno_is_user_doesnt_exist(r))
1192 return -ESRCH;
1193 if (r != ERANGE)
1194 return -r;
1195
1196 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct group)))
1197 return -ENOMEM;
1198 bufsize *= 2;
1199 }
1200}
1201
1202int getgrgid_malloc(gid_t gid, struct group **ret) {
1203 size_t bufsize = getgr_buffer_size();
1204 int r;
1205
1206 if (!gid_is_valid(gid))
1207 return -EINVAL;
1208
1209 for (;;) {
1210 _cleanup_free_ void *buf = NULL;
1211
64fc712f 1212 buf = malloc0(ALIGN(sizeof(struct group)) + bufsize);
75673cd8
LP
1213 if (!buf)
1214 return -ENOMEM;
1215
1216 struct group *gr = NULL;
1217 r = getgrgid_r(gid, buf, (char*) buf + ALIGN(sizeof(struct group)), (size_t) bufsize, &gr);
1218 if (r == 0) {
1219 if (gr) {
1220 if (ret)
1221 *ret = TAKE_PTR(buf);
1222 return 0;
1223 }
1224
1225 return -ESRCH;
1226 }
1227
1228 assert(r > 0);
1229
1230 if (errno_is_user_doesnt_exist(r))
1231 return -ESRCH;
1232 if (r != ERANGE)
1233 return -r;
1234
1235 if (bufsize > SIZE_MAX/2 - ALIGN(sizeof(struct group)))
1236 return -ENOMEM;
1237 bufsize *= 2;
1238 }
1239}