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