chiark / gitweb /
tree-wide: drop license boilerplate
[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 &&
228             (isempty(*home) || path_equal(*home, "/")))
229                 *home = NULL;
230
231         return 0;
232 }
233
234 int get_group_creds(const char **groupname, gid_t *gid) {
235         struct group *g;
236         gid_t id;
237
238         assert(groupname);
239
240         /* We enforce some special rules for gid=0: in order to avoid
241          * NSS lookups for root we hardcode its data. */
242
243         if (STR_IN_SET(*groupname, "root", "0")) {
244                 *groupname = "root";
245
246                 if (gid)
247                         *gid = 0;
248
249                 return 0;
250         }
251
252         if (synthesize_nobody() &&
253             STR_IN_SET(*groupname, NOBODY_GROUP_NAME, "65534")) {
254                 *groupname = NOBODY_GROUP_NAME;
255
256                 if (gid)
257                         *gid = GID_NOBODY;
258
259                 return 0;
260         }
261
262         if (parse_gid(*groupname, &id) >= 0) {
263                 errno = 0;
264                 g = getgrgid(id);
265
266                 if (g)
267                         *groupname = g->gr_name;
268         } else {
269                 errno = 0;
270                 g = getgrnam(*groupname);
271         }
272
273         if (!g)
274                 return errno > 0 ? -errno : -ESRCH;
275
276         if (gid) {
277                 if (!gid_is_valid(g->gr_gid))
278                         return -EBADMSG;
279
280                 *gid = g->gr_gid;
281         }
282
283         return 0;
284 }
285 #endif // 0
286
287 char* uid_to_name(uid_t uid) {
288         char *ret;
289         int r;
290
291         /* Shortcut things to avoid NSS lookups */
292         if (uid == 0)
293                 return strdup("root");
294         if (synthesize_nobody() &&
295             uid == UID_NOBODY)
296                 return strdup(NOBODY_USER_NAME);
297
298         if (uid_is_valid(uid)) {
299                 long bufsize;
300
301                 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
302                 if (bufsize <= 0)
303                         bufsize = 4096;
304
305                 for (;;) {
306                         struct passwd pwbuf, *pw = NULL;
307                         _cleanup_free_ char *buf = NULL;
308
309                         buf = malloc(bufsize);
310                         if (!buf)
311                                 return NULL;
312
313                         r = getpwuid_r(uid, &pwbuf, buf, (size_t) bufsize, &pw);
314                         if (r == 0 && pw)
315                                 return strdup(pw->pw_name);
316                         if (r != ERANGE)
317                                 break;
318
319                         bufsize *= 2;
320                 }
321         }
322
323         if (asprintf(&ret, UID_FMT, uid) < 0)
324                 return NULL;
325
326         return ret;
327 }
328
329 char* gid_to_name(gid_t gid) {
330         char *ret;
331         int r;
332
333         if (gid == 0)
334                 return strdup("root");
335         if (synthesize_nobody() &&
336             gid == GID_NOBODY)
337                 return strdup(NOBODY_GROUP_NAME);
338
339         if (gid_is_valid(gid)) {
340                 long bufsize;
341
342                 bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
343                 if (bufsize <= 0)
344                         bufsize = 4096;
345
346                 for (;;) {
347                         struct group grbuf, *gr = NULL;
348                         _cleanup_free_ char *buf = NULL;
349
350                         buf = malloc(bufsize);
351                         if (!buf)
352                                 return NULL;
353
354                         r = getgrgid_r(gid, &grbuf, buf, (size_t) bufsize, &gr);
355                         if (r == 0 && gr)
356                                 return strdup(gr->gr_name);
357                         if (r != ERANGE)
358                                 break;
359
360                         bufsize *= 2;
361                 }
362         }
363
364         if (asprintf(&ret, GID_FMT, gid) < 0)
365                 return NULL;
366
367         return ret;
368 }
369
370 #if 0 /// UNNEEDED by elogind
371 int in_gid(gid_t gid) {
372         long ngroups_max;
373         gid_t *gids;
374         int r, i;
375
376         if (getgid() == gid)
377                 return 1;
378
379         if (getegid() == gid)
380                 return 1;
381
382         if (!gid_is_valid(gid))
383                 return -EINVAL;
384
385         ngroups_max = sysconf(_SC_NGROUPS_MAX);
386         assert(ngroups_max > 0);
387
388         gids = newa(gid_t, ngroups_max);
389
390         r = getgroups(ngroups_max, gids);
391         if (r < 0)
392                 return -errno;
393
394         for (i = 0; i < r; i++)
395                 if (gids[i] == gid)
396                         return 1;
397
398         return 0;
399 }
400
401 int in_group(const char *name) {
402         int r;
403         gid_t gid;
404
405         r = get_group_creds(&name, &gid);
406         if (r < 0)
407                 return r;
408
409         return in_gid(gid);
410 }
411
412 int get_home_dir(char **_h) {
413         struct passwd *p;
414         const char *e;
415         char *h;
416         uid_t u;
417
418         assert(_h);
419
420         /* Take the user specified one */
421         e = secure_getenv("HOME");
422         if (e && path_is_absolute(e)) {
423                 h = strdup(e);
424                 if (!h)
425                         return -ENOMEM;
426
427                 *_h = h;
428                 return 0;
429         }
430
431         /* Hardcode home directory for root and nobody to avoid NSS */
432         u = getuid();
433         if (u == 0) {
434                 h = strdup("/root");
435                 if (!h)
436                         return -ENOMEM;
437
438                 *_h = h;
439                 return 0;
440         }
441         if (synthesize_nobody() &&
442             u == UID_NOBODY) {
443                 h = strdup("/");
444                 if (!h)
445                         return -ENOMEM;
446
447                 *_h = h;
448                 return 0;
449         }
450
451         /* Check the database... */
452         errno = 0;
453         p = getpwuid(u);
454         if (!p)
455                 return errno > 0 ? -errno : -ESRCH;
456
457         if (!path_is_absolute(p->pw_dir))
458                 return -EINVAL;
459
460         h = strdup(p->pw_dir);
461         if (!h)
462                 return -ENOMEM;
463
464         *_h = h;
465         return 0;
466 }
467
468 int get_shell(char **_s) {
469         struct passwd *p;
470         const char *e;
471         char *s;
472         uid_t u;
473
474         assert(_s);
475
476         /* Take the user specified one */
477         e = getenv("SHELL");
478         if (e) {
479                 s = strdup(e);
480                 if (!s)
481                         return -ENOMEM;
482
483                 *_s = s;
484                 return 0;
485         }
486
487         /* Hardcode shell for root and nobody to avoid NSS */
488         u = getuid();
489         if (u == 0) {
490                 s = strdup("/bin/sh");
491                 if (!s)
492                         return -ENOMEM;
493
494                 *_s = s;
495                 return 0;
496         }
497         if (synthesize_nobody() &&
498             u == UID_NOBODY) {
499                 s = strdup("/sbin/nologin");
500                 if (!s)
501                         return -ENOMEM;
502
503                 *_s = s;
504                 return 0;
505         }
506
507         /* Check the database... */
508         errno = 0;
509         p = getpwuid(u);
510         if (!p)
511                 return errno > 0 ? -errno : -ESRCH;
512
513         if (!path_is_absolute(p->pw_shell))
514                 return -EINVAL;
515
516         s = strdup(p->pw_shell);
517         if (!s)
518                 return -ENOMEM;
519
520         *_s = s;
521         return 0;
522 }
523 #endif // 0
524
525 int reset_uid_gid(void) {
526         int r;
527
528         r = maybe_setgroups(0, NULL);
529         if (r < 0)
530                 return r;
531
532         if (setresgid(0, 0, 0) < 0)
533                 return -errno;
534
535         if (setresuid(0, 0, 0) < 0)
536                 return -errno;
537
538         return 0;
539 }
540
541 #if 0 /// UNNEEDED by elogind
542 int take_etc_passwd_lock(const char *root) {
543
544         struct flock flock = {
545                 .l_type = F_WRLCK,
546                 .l_whence = SEEK_SET,
547                 .l_start = 0,
548                 .l_len = 0,
549         };
550
551         const char *path;
552         int fd, r;
553
554         /* This is roughly the same as lckpwdf(), but not as awful. We
555          * don't want to use alarm() and signals, hence we implement
556          * our own trivial version of this.
557          *
558          * Note that shadow-utils also takes per-database locks in
559          * addition to lckpwdf(). However, we don't given that they
560          * are redundant as they invoke lckpwdf() first and keep
561          * it during everything they do. The per-database locks are
562          * awfully racy, and thus we just won't do them. */
563
564         if (root)
565                 path = prefix_roota(root, ETC_PASSWD_LOCK_PATH);
566         else
567                 path = ETC_PASSWD_LOCK_PATH;
568
569         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
570         if (fd < 0)
571                 return log_debug_errno(errno, "Cannot open %s: %m", path);
572
573         r = fcntl(fd, F_SETLKW, &flock);
574         if (r < 0) {
575                 safe_close(fd);
576                 return log_debug_errno(errno, "Locking %s failed: %m", path);
577         }
578
579         return fd;
580 }
581 #endif // 0
582
583 bool valid_user_group_name(const char *u) {
584         const char *i;
585         long sz;
586
587         /* Checks if the specified name is a valid user/group name. Also see POSIX IEEE Std 1003.1-2008, 2016 Edition,
588          * 3.437. We are a bit stricter here however. Specifically we deviate from POSIX rules:
589          *
590          * - We don't allow any dots (this would break chown syntax which permits dots as user/group name separator)
591          * - We require that names fit into the appropriate utmp field
592          * - We don't allow empty user names
593          *
594          * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
595          */
596
597         if (isempty(u))
598                 return false;
599
600         if (!(u[0] >= 'a' && u[0] <= 'z') &&
601             !(u[0] >= 'A' && u[0] <= 'Z') &&
602             u[0] != '_')
603                 return false;
604
605         for (i = u+1; *i; i++) {
606                 if (!(*i >= 'a' && *i <= 'z') &&
607                     !(*i >= 'A' && *i <= 'Z') &&
608                     !(*i >= '0' && *i <= '9') &&
609                     !IN_SET(*i, '_', '-'))
610                         return false;
611         }
612
613         sz = sysconf(_SC_LOGIN_NAME_MAX);
614         assert_se(sz > 0);
615
616         if ((size_t) (i-u) > (size_t) sz)
617                 return false;
618
619         if ((size_t) (i-u) > UT_NAMESIZE - 1)
620                 return false;
621
622         return true;
623 }
624
625 bool valid_user_group_name_or_id(const char *u) {
626
627         /* Similar as above, but is also fine with numeric UID/GID specifications, as long as they are in the right
628          * range, and not the invalid user ids. */
629
630         if (isempty(u))
631                 return false;
632
633         if (valid_user_group_name(u))
634                 return true;
635
636         return parse_uid(u, NULL) >= 0;
637 }
638
639 bool valid_gecos(const char *d) {
640
641         if (!d)
642                 return false;
643
644         if (!utf8_is_valid(d))
645                 return false;
646
647         if (string_has_cc(d, NULL))
648                 return false;
649
650         /* Colons are used as field separators, and hence not OK */
651         if (strchr(d, ':'))
652                 return false;
653
654         return true;
655 }
656
657 bool valid_home(const char *p) {
658         /* Note that this function is also called by valid_shell(), any
659          * changes must account for that. */
660
661         if (isempty(p))
662                 return false;
663
664         if (!utf8_is_valid(p))
665                 return false;
666
667         if (string_has_cc(p, NULL))
668                 return false;
669
670         if (!path_is_absolute(p))
671                 return false;
672
673         if (!path_is_normalized(p))
674                 return false;
675
676         /* Colons are used as field separators, and hence not OK */
677         if (strchr(p, ':'))
678                 return false;
679
680         return true;
681 }
682
683 int maybe_setgroups(size_t size, const gid_t *list) {
684         int r;
685
686         /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
687         if (size == 0) { /* Dropping all aux groups? */
688                 _cleanup_free_ char *setgroups_content = NULL;
689                 bool can_setgroups;
690
691                 r = read_one_line_file("/proc/self/setgroups", &setgroups_content);
692                 if (r == -ENOENT)
693                         /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
694                         can_setgroups = true;
695                 else if (r < 0)
696                         return r;
697                 else
698                         can_setgroups = streq(setgroups_content, "allow");
699
700                 if (!can_setgroups) {
701                         log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
702                         return 0;
703                 }
704         }
705
706         if (setgroups(size, list) < 0)
707                 return -errno;
708
709         return 0;
710 }
711
712 bool synthesize_nobody(void) {
713
714 #ifdef NOLEGACY
715         return true;
716 #else
717         /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
718          * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
719          * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
720          *
721          * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
722          * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
723          * shouldn't matter as each initialization should come to the same result. */
724         static int cache = -1;
725
726         if (cache < 0)
727                 cache = access("/etc/elogind/dont-synthesize-nobody", F_OK) < 0;
728
729         return cache;
730 #endif
731 }
732
733 int putpwent_sane(const struct passwd *pw, FILE *stream) {
734         assert(pw);
735         assert(stream);
736
737         errno = 0;
738         if (putpwent(pw, stream) != 0)
739                 return errno > 0 ? -errno : -EIO;
740
741         return 0;
742 }
743
744 int putspent_sane(const struct spwd *sp, FILE *stream) {
745         assert(sp);
746         assert(stream);
747
748         errno = 0;
749         if (putspent(sp, stream) != 0)
750                 return errno > 0 ? -errno : -EIO;
751
752         return 0;
753 }
754
755 int putgrent_sane(const struct group *gr, FILE *stream) {
756         assert(gr);
757         assert(stream);
758
759         errno = 0;
760         if (putgrent(gr, stream) != 0)
761                 return errno > 0 ? -errno : -EIO;
762
763         return 0;
764 }
765
766 #if ENABLE_GSHADOW
767 int putsgent_sane(const struct sgrp *sg, FILE *stream) {
768         assert(sg);
769         assert(stream);
770
771         errno = 0;
772         if (putsgent(sg, stream) != 0)
773                 return errno > 0 ? -errno : -EIO;
774
775         return 0;
776 }
777 #endif
778
779 int fgetpwent_sane(FILE *stream, struct passwd **pw) {
780         struct passwd *p;
781
782         assert(pw);
783         assert(stream);
784
785         errno = 0;
786         p = fgetpwent(stream);
787         if (p == NULL) {
788                 if (errno == ENOENT)
789                         return false;
790                 return errno > 0 ? -errno : -EIO;
791         }
792
793         *pw = p;
794         return true;
795 }
796
797 int fgetspent_sane(FILE *stream, struct spwd **sp) {
798         struct spwd *s;
799
800         assert(sp);
801         assert(stream);
802
803         errno = 0;
804         s = fgetspent(stream);
805         if (s == NULL) {
806                 if (errno == ENOENT)
807                         return false;
808                 return errno > 0 ? -errno : -EIO;
809         }
810
811         *sp = s;
812         return true;
813 }
814
815 int fgetgrent_sane(FILE *stream, struct group **gr) {
816         struct group *g;
817
818         assert(gr);
819         assert(stream);
820
821         errno = 0;
822         g = fgetgrent(stream);
823         if (g == NULL) {
824                 if (errno == ENOENT)
825                         return false;
826                 return errno > 0 ? -errno : -EIO;
827         }
828
829         *gr = g;
830         return true;
831 }
832
833 #if ENABLE_GSHADOW
834 int fgetsgent_sane(FILE *stream, struct sgrp **sg) {
835         struct sgrp *s;
836
837         assert(sg);
838         assert(stream);
839
840         errno = 0;
841         s = fgetsgent(stream);
842         if (s == NULL) {
843                 if (errno == ENOENT)
844                         return false;
845                 return errno > 0 ? -errno : -EIO;
846         }
847
848         *sg = s;
849         return true;
850 }
851 #endif