chiark / gitweb /
796e00f694e348c336d32742a837f561bf4a1ba0
[elogind.git] / src / basic / user-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <alloca.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <grp.h>
12 #include <pwd.h>
13 #include <stddef.h>
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/stat.h>
19 #include <unistd.h>
20 #include <utmp.h>
21
22 #include "alloc-util.h"
23 #include "fd-util.h"
24 #include "fileio.h"
25 #include "format-util.h"
26 #include "macro.h"
27 #include "missing.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "string-util.h"
31 #include "strv.h"
32 #include "user-util.h"
33 #include "utf8.h"
34
35 bool uid_is_valid(uid_t uid) {
36
37         /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
38
39         /* Some libc APIs use UID_INVALID as special placeholder */
40         if (uid == (uid_t) UINT32_C(0xFFFFFFFF))
41                 return false;
42
43         /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
44         if (uid == (uid_t) UINT32_C(0xFFFF))
45                 return false;
46
47         return true;
48 }
49
50 int parse_uid(const char *s, uid_t *ret) {
51         uint32_t uid = 0;
52         int r;
53
54         assert(s);
55
56         assert_cc(sizeof(uid_t) == sizeof(uint32_t));
57         r = safe_atou32(s, &uid);
58         if (r < 0)
59                 return r;
60
61         if (!uid_is_valid(uid))
62                 return -ENXIO; /* we return ENXIO instead of EINVAL
63                                 * here, to make it easy to distuingish
64                                 * invalid numeric uids from invalid
65                                 * strings. */
66
67         if (ret)
68                 *ret = uid;
69
70         return 0;
71 }
72
73 char* getlogname_malloc(void) {
74         uid_t uid;
75         struct stat st;
76
77         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
78                 uid = st.st_uid;
79         else
80                 uid = getuid();
81
82         return uid_to_name(uid);
83 }
84
85 #if 0 /// UNNEEDED by elogind
86 char *getusername_malloc(void) {
87         const char *e;
88
89         e = getenv("USER");
90         if (e)
91                 return strdup(e);
92
93         return uid_to_name(getuid());
94 }
95 #endif // 0
96
97 int get_user_creds(
98                 const char **username,
99                 uid_t *uid, gid_t *gid,
100                 const char **home,
101                 const char **shell) {
102
103         struct passwd *p;
104         uid_t u;
105
106         assert(username);
107         assert(*username);
108
109         /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
110          * their user record data. */
111
112         if (STR_IN_SET(*username, "root", "0")) {
113                 *username = "root";
114
115                 if (uid)
116                         *uid = 0;
117                 if (gid)
118                         *gid = 0;
119
120                 if (home)
121                         *home = "/root";
122
123                 if (shell)
124                         *shell = "/bin/sh";
125
126                 return 0;
127         }
128
129         if (synthesize_nobody() &&
130             STR_IN_SET(*username, NOBODY_USER_NAME, "65534")) {
131                 *username = NOBODY_USER_NAME;
132
133                 if (uid)
134                         *uid = UID_NOBODY;
135                 if (gid)
136                         *gid = GID_NOBODY;
137
138                 if (home)
139                         *home = "/";
140
141                 if (shell)
142                         *shell = "/sbin/nologin";
143
144                 return 0;
145         }
146
147         if (parse_uid(*username, &u) >= 0) {
148                 errno = 0;
149                 p = getpwuid(u);
150
151                 /* If there are multiple users with the same id, make
152                  * sure to leave $USER to the configured value instead
153                  * of the first occurrence in the database. However if
154                  * the uid was configured by a numeric uid, then let's
155                  * pick the real username from /etc/passwd. */
156                 if (p)
157                         *username = p->pw_name;
158         } else {
159                 errno = 0;
160                 p = getpwnam(*username);
161         }
162
163         if (!p)
164                 return errno > 0 ? -errno : -ESRCH;
165
166         if (uid) {
167                 if (!uid_is_valid(p->pw_uid))
168                         return -EBADMSG;
169
170                 *uid = p->pw_uid;
171         }
172
173         if (gid) {
174                 if (!gid_is_valid(p->pw_gid))
175                         return -EBADMSG;
176
177                 *gid = p->pw_gid;
178         }
179
180         if (home)
181                 *home = p->pw_dir;
182
183         if (shell)
184                 *shell = p->pw_shell;
185
186         return 0;
187 }
188
189 static inline bool is_nologin_shell(const char *shell) {
190
191         return PATH_IN_SET(shell,
192                            /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
193                             * message and exits. Different distributions place the binary at different places though,
194                             * hence let's list them all. */
195                            "/bin/nologin",
196                            "/sbin/nologin",
197                            "/usr/bin/nologin",
198                            "/usr/sbin/nologin",
199                            /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
200                             * any message printing. Different distributions place the binary at various places but at
201                             * least not in the 'sbin' directory. */
202                            "/bin/false",
203                            "/usr/bin/false",
204                            "/bin/true",
205                            "/usr/bin/true");
206 }
207
208 #if 0 /// UNNEEDED by elogind
209 int get_user_creds_clean(
210                 const char **username,
211                 uid_t *uid, gid_t *gid,
212                 const char **home,
213                 const char **shell) {
214
215         int r;
216
217         /* Like get_user_creds(), but resets home/shell to NULL if they don't contain anything relevant. */
218
219         r = get_user_creds(username, uid, gid, home, shell);
220         if (r < 0)
221                 return r;
222
223         if (shell &&
224             (isempty(*shell) || is_nologin_shell(*shell)))
225                 *shell = NULL;
226
227         if (home && empty_or_root(*home))
228                 *home = NULL;
229
230         return 0;
231 }
232
233 int get_group_creds(const char **groupname, gid_t *gid) {
234         struct group *g;
235         gid_t id;
236
237         assert(groupname);
238
239         /* We enforce some special rules for gid=0: in order to avoid
240          * NSS lookups for root we hardcode its data. */
241
242         if (STR_IN_SET(*groupname, "root", "0")) {
243                 *groupname = "root";
244
245                 if (gid)
246                         *gid = 0;
247
248                 return 0;
249         }
250
251         if (synthesize_nobody() &&
252             STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534")) {
253                 *groupname = NOBODY_GROUP_NAME;
254
255                 if (gid)
256                         *gid = GID_NOBODY;
257
258                 return 0;
259         }
260
261         if (parse_gid(*groupname, &id) >= 0) {
262                 errno = 0;
263                 g = getgrgid(id);
264
265                 if (g)
266                         *groupname = g->gr_name;
267         } else {
268                 errno = 0;
269                 g = getgrnam(*groupname);
270         }
271
272         if (!g)
273                 return errno > 0 ? -errno : -ESRCH;
274
275         if (gid) {
276                 if (!gid_is_valid(g->gr_gid))
277                         return -EBADMSG;
278
279                 *gid = g->gr_gid;
280         }
281
282         return 0;
283 }
284 #endif // 0
285
286 char* uid_to_name(uid_t uid) {
287         char *ret;
288         int r;
289
290         /* Shortcut things to avoid NSS lookups */
291         if (uid == 0)
292                 return strdup("root");
293         if (synthesize_nobody() &&
294             uid == UID_NOBODY)
295                 return strdup(NOBODY_USER_NAME);
296
297         if (uid_is_valid(uid)) {
298                 long bufsize;
299
300                 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
301                 if (bufsize <= 0)
302                         bufsize = 4096;
303
304                 for (;;) {
305                         struct passwd pwbuf, *pw = NULL;
306                         _cleanup_free_ char *buf = NULL;
307
308                         buf = malloc(bufsize);
309                         if (!buf)
310                                 return NULL;
311
312                         r = getpwuid_r(uid, &pwbuf, buf, (size_t) bufsize, &pw);
313                         if (r == 0 && pw)
314                                 return strdup(pw->pw_name);
315                         if (r != ERANGE)
316                                 break;
317
318                         bufsize *= 2;
319                 }
320         }
321
322         if (asprintf(&ret, UID_FMT, uid) < 0)
323                 return NULL;
324
325         return ret;
326 }
327
328 char* gid_to_name(gid_t gid) {
329         char *ret;
330         int r;
331
332         if (gid == 0)
333                 return strdup("root");
334         if (synthesize_nobody() &&
335             gid == GID_NOBODY)
336                 return strdup(NOBODY_GROUP_NAME);
337
338         if (gid_is_valid(gid)) {
339                 long bufsize;
340
341                 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
342                 if (bufsize <= 0)
343                         bufsize = 4096;
344
345                 for (;;) {
346                         struct group grbuf, *gr = NULL;
347                         _cleanup_free_ char *buf = NULL;
348
349                         buf = malloc(bufsize);
350                         if (!buf)
351                                 return NULL;
352
353                         r = getgrgid_r(gid, &grbuf, buf, (size_t) bufsize, &gr);
354                         if (r == 0 && gr)
355                                 return strdup(gr->gr_name);
356                         if (r != ERANGE)
357                                 break;
358
359                         bufsize *= 2;
360                 }
361         }
362
363         if (asprintf(&ret, GID_FMT, gid) < 0)
364                 return NULL;
365
366         return ret;
367 }
368
369 #if 0 /// UNNEEDED by elogind
370 int in_gid(gid_t gid) {
371         long ngroups_max;
372         gid_t *gids;
373         int r, i;
374
375         if (getgid() == gid)
376                 return 1;
377
378         if (getegid() == gid)
379                 return 1;
380
381         if (!gid_is_valid(gid))
382                 return -EINVAL;
383
384         ngroups_max = sysconf(_SC_NGROUPS_MAX);
385         assert(ngroups_max > 0);
386
387         gids = newa(gid_t, ngroups_max);
388
389         r = getgroups(ngroups_max, gids);
390         if (r < 0)
391                 return -errno;
392
393         for (i = 0; i < r; i++)
394                 if (gids[i] == gid)
395                         return 1;
396
397         return 0;
398 }
399
400 int in_group(const char *name) {
401         int r;
402         gid_t gid;
403
404         r = get_group_creds(&name, &gid);
405         if (r < 0)
406                 return r;
407
408         return in_gid(gid);
409 }
410
411 int get_home_dir(char **_h) {
412         struct passwd *p;
413         const char *e;
414         char *h;
415         uid_t u;
416
417         assert(_h);
418
419         /* Take the user specified one */
420         e = secure_getenv("HOME");
421         if (e && path_is_absolute(e)) {
422                 h = strdup(e);
423                 if (!h)
424                         return -ENOMEM;
425
426                 *_h = h;
427                 return 0;
428         }
429
430         /* Hardcode home directory for root and nobody to avoid NSS */
431         u = getuid();
432         if (u == 0) {
433                 h = strdup("/root");
434                 if (!h)
435                         return -ENOMEM;
436
437                 *_h = h;
438                 return 0;
439         }
440         if (synthesize_nobody() &&
441             u == UID_NOBODY) {
442                 h = strdup("/");
443                 if (!h)
444                         return -ENOMEM;
445
446                 *_h = h;
447                 return 0;
448         }
449
450         /* Check the database... */
451         errno = 0;
452         p = getpwuid(u);
453         if (!p)
454                 return errno > 0 ? -errno : -ESRCH;
455
456         if (!path_is_absolute(p->pw_dir))
457                 return -EINVAL;
458
459         h = strdup(p->pw_dir);
460         if (!h)
461                 return -ENOMEM;
462
463         *_h = h;
464         return 0;
465 }
466
467 int get_shell(char **_s) {
468         struct passwd *p;
469         const char *e;
470         char *s;
471         uid_t u;
472
473         assert(_s);
474
475         /* Take the user specified one */
476         e = getenv("SHELL");
477         if (e) {
478                 s = strdup(e);
479                 if (!s)
480                         return -ENOMEM;
481
482                 *_s = s;
483                 return 0;
484         }
485
486         /* Hardcode shell for root and nobody to avoid NSS */
487         u = getuid();
488         if (u == 0) {
489                 s = strdup("/bin/sh");
490                 if (!s)
491                         return -ENOMEM;
492
493                 *_s = s;
494                 return 0;
495         }
496         if (synthesize_nobody() &&
497             u == UID_NOBODY) {
498                 s = strdup("/sbin/nologin");
499                 if (!s)
500                         return -ENOMEM;
501
502                 *_s = s;
503                 return 0;
504         }
505
506         /* Check the database... */
507         errno = 0;
508         p = getpwuid(u);
509         if (!p)
510                 return errno > 0 ? -errno : -ESRCH;
511
512         if (!path_is_absolute(p->pw_shell))
513                 return -EINVAL;
514
515         s = strdup(p->pw_shell);
516         if (!s)
517                 return -ENOMEM;
518
519         *_s = s;
520         return 0;
521 }
522 #endif // 0
523
524 int reset_uid_gid(void) {
525         int r;
526
527         r = maybe_setgroups(0, NULL);
528         if (r < 0)
529                 return r;
530
531         if (setresgid(0, 0, 0) < 0)
532                 return -errno;
533
534         if (setresuid(0, 0, 0) < 0)
535                 return -errno;
536
537         return 0;
538 }
539
540 #if 0 /// UNNEEDED by elogind
541 int take_etc_passwd_lock(const char *root) {
542
543         struct flock flock = {
544                 .l_type = F_WRLCK,
545                 .l_whence = SEEK_SET,
546                 .l_start = 0,
547                 .l_len = 0,
548         };
549
550         const char *path;
551         int fd, r;
552
553         /* This is roughly the same as lckpwdf(), but not as awful. We
554          * don't want to use alarm() and signals, hence we implement
555          * our own trivial version of this.
556          *
557          * Note that shadow-utils also takes per-database locks in
558          * addition to lckpwdf(). However, we don't given that they
559          * are redundant as they invoke lckpwdf() first and keep
560          * it during everything they do. The per-database locks are
561          * awfully racy, and thus we just won't do them. */
562
563         if (root)
564                 path = prefix_roota(root, ETC_PASSWD_LOCK_PATH);
565         else
566                 path = ETC_PASSWD_LOCK_PATH;
567
568         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
569         if (fd < 0)
570                 return log_debug_errno(errno, "Cannot open %s: %m", path);
571
572         r = fcntl(fd, F_SETLKW, &flock);
573         if (r < 0) {
574                 safe_close(fd);
575                 return log_debug_errno(errno, "Locking %s failed: %m", path);
576         }
577
578         return fd;
579 }
580 #endif // 0
581
582 bool valid_user_group_name(const char *u) {
583         const char *i;
584         long sz;
585
586         /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
587          * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
588          *
589          * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
590          * - We require that names fit into the appropriate utmp field
591          * - We don't allow empty user names
592          *
593          * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
594          */
595
596         if (isempty(u))
597                 return false;
598
599         if (!(u[0] >= 'a' && u[0] <= 'z') &&
600             !(u[0] >= 'A' && u[0] <= 'Z') &&
601             u[0] != '_')
602                 return false;
603
604         for (i = u+1; *i; i++) {
605                 if (!(*i >= 'a' && *i <= 'z') &&
606                     !(*i >= 'A' && *i <= 'Z') &&
607                     !(*i >= '0' && *i <= '9') &&
608                     !IN_SET(*i, '_', '-'))
609                         return false;
610         }
611
612         sz = sysconf(_SC_LOGIN_NAME_MAX);
613         assert_se(sz > 0);
614
615         if ((size_t) (i-u) > (size_t) sz)
616                 return false;
617
618         if ((size_t) (i-u) > UT_NAMESIZE - 1)
619                 return false;
620
621         return true;
622 }
623
624 bool valid_user_group_name_or_id(const char *u) {
625
626         /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
627          * range, and not the invalid user ids. */
628
629         if (isempty(u))
630                 return false;
631
632         if (valid_user_group_name(u))
633                 return true;
634
635         return parse_uid(u, NULL) >= 0;
636 }
637
638 bool valid_gecos(const char *d) {
639
640         if (!d)
641                 return false;
642
643         if (!utf8_is_valid(d))
644                 return false;
645
646         if (string_has_cc(d, NULL))
647                 return false;
648
649         /* Colons are used as field separators, and hence not OK */
650         if (strchr(d, ':'))
651                 return false;
652
653         return true;
654 }
655
656 bool valid_home(const char *p) {
657         /* Note that this function is also called by valid_shell(), any
658          * changes must account for that. */
659
660         if (isempty(p))
661                 return false;
662
663         if (!utf8_is_valid(p))
664                 return false;
665
666         if (string_has_cc(p, NULL))
667                 return false;
668
669         if (!path_is_absolute(p))
670                 return false;
671
672         if (!path_is_normalized(p))
673                 return false;
674
675         /* Colons are used as field separators, and hence not OK */
676         if (strchr(p, ':'))
677                 return false;
678
679         return true;
680 }
681
682 int maybe_setgroups(size_t size, const gid_t *list) {
683         int r;
684
685         /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
686         if (size == 0) { /* Dropping all aux groups? */
687                 _cleanup_free_ char *setgroups_content = NULL;
688                 bool can_setgroups;
689
690                 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
691                 if (r == -ENOENT)
692                         /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
693                         can_setgroups = true;
694                 else if (r < 0)
695                         return r;
696                 else
697                         can_setgroups = streq(setgroups_content, "allow");
698
699                 if (!can_setgroups) {
700                         log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
701                         return 0;
702                 }
703         }
704
705         if (setgroups(size, list) < 0)
706                 return -errno;
707
708         return 0;
709 }
710
711 bool synthesize_nobody(void) {
712
713 #ifdef NOLEGACY
714         return true;
715 #else
716         /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
717          * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
718          * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
719          *
720          * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
721          * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
722          * shouldn't matter as each initialization should come to the same result. */
723         static int cache = -1;
724
725         if (cache < 0)
726                 cache = access("/etc/elogind/dont-synthesize-nobody", F_OK) < 0;
727
728         return cache;
729 #endif
730 }
731
732 int putpwent_sane(const struct passwd *pw, FILE *stream) {
733         assert(pw);
734         assert(stream);
735
736         errno = 0;
737         if (putpwent(pw, stream) != 0)
738                 return errno > 0 ? -errno : -EIO;
739
740         return 0;
741 }
742
743 int putspent_sane(const struct spwd *sp, FILE *stream) {
744         assert(sp);
745         assert(stream);
746
747         errno = 0;
748         if (putspent(sp, stream) != 0)
749                 return errno > 0 ? -errno : -EIO;
750
751         return 0;
752 }
753
754 int putgrent_sane(const struct group *gr, FILE *stream) {
755         assert(gr);
756         assert(stream);
757
758         errno = 0;
759         if (putgrent(gr, stream) != 0)
760                 return errno > 0 ? -errno : -EIO;
761
762         return 0;
763 }
764
765 #if ENABLE_GSHADOW
766 int putsgent_sane(const struct sgrp *sg, FILE *stream) {
767         assert(sg);
768         assert(stream);
769
770         errno = 0;
771         if (putsgent(sg, stream) != 0)
772                 return errno > 0 ? -errno : -EIO;
773
774         return 0;
775 }
776 #endif
777
778 int fgetpwent_sane(FILE *stream, struct passwd **pw) {
779         struct passwd *p;
780
781         assert(pw);
782         assert(stream);
783
784         errno = 0;
785         p = fgetpwent(stream);
786         if (!p && errno != ENOENT)
787                 return errno > 0 ? -errno : -EIO;
788
789         *pw = p;
790         return !!p;
791 }
792
793 int fgetspent_sane(FILE *stream, struct spwd **sp) {
794         struct spwd *s;
795
796         assert(sp);
797         assert(stream);
798
799         errno = 0;
800         s = fgetspent(stream);
801         if (!s && errno != ENOENT)
802                 return errno > 0 ? -errno : -EIO;
803
804         *sp = s;
805         return !!s;
806 }
807
808 int fgetgrent_sane(FILE *stream, struct group **gr) {
809         struct group *g;
810
811         assert(gr);
812         assert(stream);
813
814         errno = 0;
815         g = fgetgrent(stream);
816         if (!g && errno != ENOENT)
817                 return errno > 0 ? -errno : -EIO;
818
819         *gr = g;
820         return !!g;
821 }
822
823 #if ENABLE_GSHADOW
824 int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
825         struct sgrp *s;
826
827         assert(sg);
828         assert(stream);
829
830         errno = 0;
831         s = fgetsgent(stream);
832         if (!s && errno != ENOENT)
833                 return errno > 0 ? -errno : -EIO;
834
835         *sg = s;
836         return !!s;
837 }
838 #endif