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