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