]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/pam/pam_cgfs.c
pam_cgfs: strncat => strlcat
[mirror_lxc.git] / src / lxc / pam / pam_cgfs.c
1 /* pam-cgfs
2 *
3 * Copyright © 2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
5 * Author: Christian Brauner <christian.brauner@ubuntu.com>
6 *
7 * When a user logs in, this pam module will create cgroups which the user may
8 * administer. It handles both pure cgroupfs v1 and pure cgroupfs v2, as well as
9 * mixed mounts, where some controllers are mounted in a standard cgroupfs v1
10 * hierarchy location (/sys/fs/cgroup/<controller>) and others are in the
11 * cgroupfs v2 hierarchy.
12 * Writeable cgroups are either created for all controllers or, if specified,
13 * for any controllers listed on the command line.
14 * The cgroup created will be "user/$user/0" for the first session,
15 * "user/$user/1" for the second, etc.
16 *
17 * Systems with a systemd init system are treated specially, both with respect
18 * to cgroupfs v1 and cgroupfs v2. For both, cgroupfs v1 and cgroupfs v2, We
19 * check whether systemd already placed us in a cgroup it created:
20 *
21 * user.slice/user-uid.slice/session-n.scope
22 *
23 * by checking whether uid == our uid. If it did, we simply chown the last
24 * part (session-n.scope). If it did not we create a cgroup as outlined above
25 * (user/$user/n) and chown it to our uid.
26 * The same holds for cgroupfs v2 where this assumptions becomes crucial:
27 * We __have to__ be placed in our under the cgroup systemd created for us on
28 * login, otherwise things like starting an xserver or similar will not work.
29 *
30 * All requested cgroups must be mounted under /sys/fs/cgroup/$controller,
31 * no messing around with finding mountpoints.
32 *
33 * See COPYING file for details.
34 */
35
36 #include <ctype.h>
37 #include <dirent.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <pwd.h>
41 #include <stdarg.h>
42 #include <stdbool.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <syslog.h>
48 #include <unistd.h>
49 #include <linux/unistd.h>
50 #include <sys/mount.h>
51 #include <sys/param.h>
52 #include <sys/stat.h>
53 #include <sys/types.h>
54 #include <sys/vfs.h>
55
56 #define PAM_SM_SESSION
57 #include <security/_pam_macros.h>
58 #include <security/pam_modules.h>
59
60 #include "utils.h"
61
62 #ifndef HAVE_STRLCPY
63 #include "include/strlcpy.h"
64 #endif
65
66 #ifndef HAVE_STRLCAT
67 #include "include/strlcat.h"
68 #endif
69
70 #define pam_cgfs_debug_stream(stream, format, ...) \
71 do { \
72 fprintf(stream, "%s: %d: %s: " format, __FILE__, __LINE__, \
73 __func__, __VA_ARGS__); \
74 } while (false)
75
76 #define pam_cgfs_error(format, ...) pam_cgfs_debug_stream(stderr, format, __VA_ARGS__)
77
78 #ifdef DEBUG
79 #define pam_cgfs_debug(format, ...) pam_cgfs_error(format, __VA_ARGS__)
80 #else
81 #define pam_cgfs_debug(format, ...)
82 #endif /* DEBUG */
83
84 /* Taken over modified from the kernel sources. */
85 #define NBITS 32 /* bits in uint32_t */
86 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
87 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
88
89 static enum cg_mount_mode {
90 CGROUP_UNKNOWN = -1,
91 CGROUP_MIXED = 0,
92 CGROUP_PURE_V1 = 1,
93 CGROUP_PURE_V2 = 2,
94 CGROUP_UNINITIALIZED = 3,
95 } cg_mount_mode = CGROUP_UNINITIALIZED;
96
97 /* Common helper functions. Most of these have been taken from LXC. */
98 static void append_line(char **dest, size_t oldlen, char *new, size_t newlen);
99 static int append_null_to_list(void ***list);
100 static void batch_realloc(char **mem, size_t oldlen, size_t newlen);
101 static inline void clear_bit(unsigned bit, uint32_t *bitarr)
102 {
103 bitarr[bit / NBITS] &= ~(1 << (bit % NBITS));
104 }
105 static char *copy_to_eol(char *s);
106 static void free_string_list(char **list);
107 static char *get_mountpoint(char *line);
108 static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid);
109 static int handle_login(const char *user, uid_t uid, gid_t gid);
110 static inline bool is_set(unsigned bit, uint32_t *bitarr)
111 {
112 return (bitarr[bit / NBITS] & (1 << (bit % NBITS))) != 0;
113 }
114 static bool is_lxcfs(const char *line);
115 static bool is_cgv1(char *line);
116 static bool is_cgv2(char *line);
117 static void *must_alloc(size_t sz);
118 static void must_add_to_list(char ***clist, char *entry);
119 static void must_append_controller(char **klist, char **nlist, char ***clist,
120 char *entry);
121 static void must_append_string(char ***list, char *entry);
122 static void mysyslog(int err, const char *format, ...) __attribute__((sentinel));
123 static char *read_file(char *fnam);
124 static int read_from_file(const char *filename, void* buf, size_t count);
125 static int recursive_rmdir(char *dirname);
126 static inline void set_bit(unsigned bit, uint32_t *bitarr)
127 {
128 bitarr[bit / NBITS] |= (1 << (bit % NBITS));
129 }
130 static bool string_in_list(char **list, const char *entry);
131 static char *string_join(const char *sep, const char **parts, bool use_as_prefix);
132 static void trim(char *s);
133 static bool write_int(char *path, int v);
134 static ssize_t write_nointr(int fd, const void* buf, size_t count);
135 static int write_to_file(const char *filename, const void *buf, size_t count,
136 bool add_newline);
137
138 /* cgroupfs prototypes. */
139 static bool cg_belongs_to_uid_gid(const char *path, uid_t uid, gid_t gid);
140 static uint32_t *cg_cpumask(char *buf, size_t nbits);
141 static bool cg_copy_parent_file(char *path, char *file);
142 static char *cg_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits);
143 static bool cg_enter(const char *cgroup);
144 static void cg_escape(void);
145 static bool cg_filter_and_set_cpus(char *path, bool am_initialized);
146 static ssize_t cg_get_max_cpus(char *cpulist);
147 static int cg_get_version_of_mntpt(const char *path);
148 static bool cg_init(uid_t uid, gid_t gid);
149 static void cg_mark_to_make_rw(char **list);
150 static void cg_prune_empty_cgroups(const char *user);
151 static bool cg_systemd_created_user_slice(const char *base_cgroup,
152 const char *init_cgroup,
153 const char *in, uid_t uid);
154 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint,
155 const char *base_cgroup, uid_t uid,
156 gid_t gid,
157 bool systemd_user_slice);
158 static bool cg_systemd_under_user_slice_1(const char *in, uid_t uid);
159 static bool cg_systemd_under_user_slice_2(const char *base_cgroup,
160 const char *init_cgroup, uid_t uid);
161 static void cg_systemd_prune_init_scope(char *cg);
162 static bool is_lxcfs(const char *line);
163
164 /* cgroupfs v1 prototypes. */
165 struct cgv1_hierarchy {
166 char **controllers;
167 char *mountpoint;
168 char *base_cgroup;
169 char *fullcgpath;
170 char *init_cgroup;
171 bool create_rw_cgroup;
172 bool systemd_user_slice;
173 };
174
175 static struct cgv1_hierarchy **cgv1_hierarchies;
176
177 static void cgv1_add_controller(char **clist, char *mountpoint,
178 char *base_cgroup, char *init_cgroup);
179 static bool cgv1_controller_in_clist(char *cgline, char *c);
180 static bool cgv1_controller_lists_intersect(char **l1, char **l2);
181 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy **hlist,
182 char **clist);
183 static bool cgv1_create(const char *cgroup, uid_t uid, gid_t gid,
184 bool *existed);
185 static bool cgv1_create_one(struct cgv1_hierarchy *h, const char *cgroup,
186 uid_t uid, gid_t gid, bool *existed);
187 static bool cgv1_enter(const char *cgroup);
188 static void cgv1_escape(void);
189 static bool cgv1_get_controllers(char ***klist, char ***nlist);
190 static char *cgv1_get_current_cgroup(char *basecginfo, char *controller);
191 static char **cgv1_get_proc_mountinfo_controllers(char **klist, char **nlist,
192 char *line);
193 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy *h,
194 const char *cgroup);
195 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy *h);
196 static bool cgv1_init(uid_t uid, gid_t gid);
197 static void cgv1_mark_to_make_rw(char **clist);
198 static char *cgv1_must_prefix_named(char *entry);
199 static bool cgv1_prune_empty_cgroups(const char *user);
200 static bool cgv1_remove_one(struct cgv1_hierarchy *h, const char *cgroup);
201 static bool is_cgv1(char *line);
202
203 /* cgroupfs v2 prototypes. */
204 struct cgv2_hierarchy {
205 char **controllers;
206 char *mountpoint;
207 char *base_cgroup;
208 char *fullcgpath;
209 char *init_cgroup;
210 bool create_rw_cgroup;
211 bool systemd_user_slice;
212 };
213
214 /* Actually this should only be a single hierarchy. But for the sake of
215 * parallelism and because the layout of the cgroupfs v2 is still somewhat
216 * changing, we'll leave it as an array of structs.
217 */
218 static struct cgv2_hierarchy **cgv2_hierarchies;
219
220 static void cgv2_add_controller(char **clist, char *mountpoint,
221 char *base_cgroup, char *init_cgroup,
222 bool systemd_user_slice);
223 static bool cgv2_create(const char *cgroup, uid_t uid, gid_t gid,
224 bool *existed);
225 static bool cgv2_enter(const char *cgroup);
226 static void cgv2_escape(void);
227 static char *cgv2_get_current_cgroup(int pid);
228 static bool cgv2_init(uid_t uid, gid_t gid);
229 static void cgv2_mark_to_make_rw(char **clist);
230 static bool cgv2_prune_empty_cgroups(const char *user);
231 static bool cgv2_remove(const char *cgroup);
232 static bool is_cgv2(char *line);
233
234 static int do_mkdir(const char *path, mode_t mode)
235 {
236 int saved_errno;
237 mode_t mask;
238 int r;
239
240 mask = umask(0);
241 r = mkdir(path, mode);
242 saved_errno = errno;
243 umask(mask);
244 errno = saved_errno;
245 return (r);
246 }
247
248 /* Create directory and (if necessary) its parents. */
249 static bool mkdir_parent(const char *root, char *path)
250 {
251 char *b, orig, *e;
252
253 if (strlen(path) < strlen(root))
254 return false;
255
256 if (strlen(path) == strlen(root))
257 return true;
258
259 b = path + strlen(root) + 1;
260 while (true) {
261 while (*b && (*b == '/'))
262 b++;
263 if (!*b)
264 return true;
265
266 e = b + 1;
267 while (*e && *e != '/')
268 e++;
269
270 orig = *e;
271 if (orig)
272 *e = '\0';
273
274 if (file_exists(path))
275 goto next;
276
277 if (do_mkdir(path, 0755) < 0) {
278 pam_cgfs_debug("Failed to create %s: %s.\n", path, strerror(errno));
279 return false;
280 }
281
282 next:
283 if (!orig)
284 return true;
285
286 *e = orig;
287 b = e + 1;
288 }
289
290 return false;
291 }
292
293 /* Common helper functions. Most of these have been taken from LXC. */
294 static void mysyslog(int err, const char *format, ...)
295 {
296 va_list args;
297
298 va_start(args, format);
299 openlog("PAM-CGFS", LOG_CONS | LOG_PID, LOG_AUTH);
300 vsyslog(err, format, args);
301 va_end(args);
302 closelog();
303 }
304
305 /* realloc() pointer in batch sizes; do not fail. */
306 #define BATCH_SIZE 50
307 static void batch_realloc(char **mem, size_t oldlen, size_t newlen)
308 {
309 int newbatches = (newlen / BATCH_SIZE) + 1;
310 int oldbatches = (oldlen / BATCH_SIZE) + 1;
311
312 if (!*mem || newbatches > oldbatches)
313 *mem = must_realloc(*mem, newbatches * BATCH_SIZE);
314 }
315
316 /* Append lines as is to pointer; do not fail. */
317 static void append_line(char **dest, size_t oldlen, char *new, size_t newlen)
318 {
319 size_t full = oldlen + newlen;
320
321 batch_realloc(dest, oldlen, full + 1);
322
323 memcpy(*dest + oldlen, new, newlen + 1);
324 }
325
326 /* Read in whole file and return allocated pointer. */
327 static char *read_file(char *fnam)
328 {
329 FILE *f;
330 int linelen;
331 char *line = NULL, *buf = NULL;
332 size_t len = 0, fulllen = 0;
333
334 f = fopen(fnam, "r");
335 if (!f)
336 return NULL;
337
338 while ((linelen = getline(&line, &len, f)) != -1) {
339 append_line(&buf, fulllen, line, linelen);
340 fulllen += linelen;
341 }
342
343 fclose(f);
344 free(line);
345
346 return buf;
347 }
348
349 /* Given a pointer to a null-terminated array of pointers, realloc to add one
350 * entry, and point the new entry to NULL. Do not fail. Return the index to the
351 * second-to-last entry - that is, the one which is now available for use
352 * (keeping the list null-terminated).
353 */
354 static int append_null_to_list(void ***list)
355 {
356 int newentry = 0;
357
358 if (*list)
359 for (; (*list)[newentry]; newentry++) {
360 ;
361 }
362
363 *list = must_realloc(*list, (newentry + 2) * sizeof(void **));
364 (*list)[newentry + 1] = NULL;
365
366 return newentry;
367 }
368
369 /* Append new entry to null-terminated array of pointer; make sure that array of
370 * pointers will still be null-terminated.
371 */
372 static void must_append_string(char ***list, char *entry)
373 {
374 int newentry;
375 char *copy;
376
377 newentry = append_null_to_list((void ***)list);
378 copy = must_copy_string(entry);
379 (*list)[newentry] = copy;
380 }
381
382 /* Remove newlines from string. */
383 static void trim(char *s)
384 {
385 size_t len = strlen(s);
386
387 while ((len > 0) && s[len - 1] == '\n')
388 s[--len] = '\0';
389 }
390
391 /* Allocate pointer; do not fail. */
392 static void *must_alloc(size_t sz)
393 {
394 return must_realloc(NULL, sz);
395 }
396
397 /* Make allocated copy of string. End of string is taken to be '\n'. */
398 static char *copy_to_eol(char *s)
399 {
400 char *newline, *sret;
401 size_t len;
402
403 newline = strchr(s, '\n');
404 if (!newline)
405 return NULL;
406
407 len = newline - s;
408 sret = must_alloc(len + 1);
409 memcpy(sret, s, len);
410 sret[len] = '\0';
411
412 return sret;
413 }
414
415 /* Check if given entry under /proc/<pid>/mountinfo is a fuse.lxcfs mount. */
416 static bool is_lxcfs(const char *line)
417 {
418 char *p = strstr(line, " - ");
419 if (!p)
420 return false;
421
422 return strncmp(p, " - fuse.lxcfs ", 14) == 0;
423 }
424
425 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v1 mount. */
426 static bool is_cgv1(char *line)
427 {
428 char *p = strstr(line, " - ");
429 if (!p)
430 return false;
431
432 return strncmp(p, " - cgroup ", 10) == 0;
433 }
434
435 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v2 mount. */
436 static bool is_cgv2(char *line)
437 {
438 char *p = strstr(line, " - ");
439 if (!p)
440 return false;
441
442 return strncmp(p, " - cgroup2 ", 11) == 0;
443 }
444
445 /* Given a null-terminated array of strings, check whether @entry is one of the
446 * strings
447 */
448 static bool string_in_list(char **list, const char *entry)
449 {
450 char **it;
451
452 for (it = list; it && *it; it++)
453 if (strcmp(*it, entry) == 0)
454 return true;
455
456 return false;
457 }
458
459 /*
460 * Creates a null-terminated array of strings, made by splitting the entries in
461 * @str on each @sep. Caller is responsible for calling free_string_list.
462 */
463 static char **make_string_list(const char *str, const char *sep)
464 {
465 char *copy, *tok;
466 char *saveptr = NULL;
467 char **clist = NULL;
468
469 copy = must_copy_string(str);
470
471 for (tok = strtok_r(copy, sep, &saveptr); tok;
472 tok = strtok_r(NULL, sep, &saveptr))
473 must_add_to_list(&clist, tok);
474
475 free(copy);
476
477 return clist;
478 }
479
480 /* Gets the length of a null-terminated array of strings. */
481 static size_t string_list_length(char **list)
482 {
483 size_t len = 0;
484 char **it;
485
486 for (it = list; it && *it; it++)
487 len++;
488
489 return len;
490 }
491
492 /* Free null-terminated array of strings. */
493 static void free_string_list(char **list)
494 {
495 char **it;
496
497 for (it = list; it && *it; it++)
498 free(*it);
499 free(list);
500 }
501
502 /* Write single integer to file. */
503 static bool write_int(char *path, int v)
504 {
505 FILE *f;
506 bool ret = true;
507
508 f = fopen(path, "w");
509 if (!f)
510 return false;
511
512 if (fprintf(f, "%d\n", v) < 0)
513 ret = false;
514
515 if (fclose(f) != 0)
516 ret = false;
517
518 return ret;
519 }
520
521 /* Recursively remove directory and its parents. */
522 static int recursive_rmdir(char *dirname)
523 {
524 struct dirent *direntp;
525 DIR *dir;
526 int r = 0;
527
528 dir = opendir(dirname);
529 if (!dir)
530 return -ENOENT;
531
532 while ((direntp = readdir(dir))) {
533 struct stat st;
534 char *pathname;
535
536 if (!strcmp(direntp->d_name, ".") ||
537 !strcmp(direntp->d_name, ".."))
538 continue;
539
540 pathname = must_make_path(dirname, direntp->d_name, NULL);
541
542 if (lstat(pathname, &st)) {
543 if (!r)
544 pam_cgfs_debug("Failed to stat %s.\n", pathname);
545 r = -1;
546 goto next;
547 }
548
549 if (!S_ISDIR(st.st_mode))
550 goto next;
551
552 if (recursive_rmdir(pathname) < 0)
553 r = -1;
554 next:
555 free(pathname);
556 }
557
558 if (rmdir(dirname) < 0) {
559 if (!r)
560 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname, strerror(errno));
561 r = -1;
562 }
563
564 if (closedir(dir) < 0) {
565 if (!r)
566 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname, strerror(errno));
567 r = -1;
568 }
569
570 return r;
571 }
572
573 /* Add new entry to null-terminated array of pointers. Make sure array is still
574 * null-terminated.
575 */
576 static void must_add_to_list(char ***clist, char *entry)
577 {
578 int newentry;
579
580 newentry = append_null_to_list((void ***)clist);
581 (*clist)[newentry] = must_copy_string(entry);
582 }
583
584 /* Get mountpoint from a /proc/<pid>/mountinfo line. */
585 static char *get_mountpoint(char *line)
586 {
587 int i;
588 char *p, *sret, *p2;
589 size_t len;
590
591 p = line;
592
593 for (i = 0; i < 4; i++) {
594 p = strchr(p, ' ');
595 if (!p)
596 return NULL;
597 p++;
598 }
599
600 p2 = strchr(p, ' ');
601 if (p2)
602 *p2 = '\0';
603
604 len = strlen(p);
605 sret = must_alloc(len + 1);
606 memcpy(sret, p, len);
607 sret[len] = '\0';
608
609 return sret;
610 }
611
612 /* Create list of cgroupfs v1 controller found under /proc/self/cgroup. Skips
613 * the 0::/some/path cgroupfs v2 hierarchy listed. Splits controllers into
614 * kernel controllers (@klist) and named controllers (@nlist).
615 */
616 static bool cgv1_get_controllers(char ***klist, char ***nlist)
617 {
618 FILE *f;
619 char *line = NULL;
620 size_t len = 0;
621
622 f = fopen("/proc/self/cgroup", "r");
623 if (!f)
624 return false;
625
626 while (getline(&line, &len, f) != -1) {
627 char *p, *p2, *tok;
628 char *saveptr = NULL;
629
630 p = strchr(line, ':');
631 if (!p)
632 continue;
633 p++;
634
635 p2 = strchr(p, ':');
636 if (!p2)
637 continue;
638 *p2 = '\0';
639
640 /* Skip the v2 hierarchy. */
641 if ((p2 - p) == 0)
642 continue;
643
644 for (tok = strtok_r(p, ",", &saveptr); tok;
645 tok = strtok_r(NULL, ",", &saveptr)) {
646 if (strncmp(tok, "name=", 5) == 0)
647 must_append_string(nlist, tok);
648 else
649 must_append_string(klist, tok);
650 }
651 }
652
653 free(line);
654 fclose(f);
655
656 return true;
657 }
658
659 /* Get list of controllers for cgroupfs v2 hierarchy by looking at
660 * cgroup.controllers and/or cgroup.subtree_control of a given (parent) cgroup.
661 static bool cgv2_get_controllers(char ***klist)
662 {
663 return -ENOSYS;
664 }
665 */
666
667 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
668 static char *cgv2_get_current_cgroup(int pid)
669 {
670 int ret;
671 char *cgroups_v2;
672 char *current_cgroup;
673 char *copy = NULL;
674 /* The largest integer that can fit into long int is 2^64. This is a
675 * 20-digit number. */
676 #define __PIDLEN /* /proc */ 5 + /* /pid-to-str */ 21 + /* /cgroup */ 7 + /* \0 */ 1
677 char path[__PIDLEN];
678
679 ret = snprintf(path, __PIDLEN, "/proc/%d/cgroup", pid);
680 if (ret < 0 || ret >= __PIDLEN)
681 return NULL;
682
683 cgroups_v2 = read_file(path);
684 if (!cgroups_v2)
685 return NULL;
686
687 current_cgroup = strstr(cgroups_v2, "0::/");
688 if (!current_cgroup)
689 goto cleanup_on_err;
690
691 current_cgroup = current_cgroup + 3;
692 copy = copy_to_eol(current_cgroup);
693 if (!copy)
694 goto cleanup_on_err;
695
696 cleanup_on_err:
697 free(cgroups_v2);
698 if (copy)
699 trim(copy);
700
701 return copy;
702 }
703
704 /* Given two null-terminated lists of strings, return true if any string is in
705 * both.
706 */
707 static bool cgv1_controller_lists_intersect(char **l1, char **l2)
708 {
709 char **it;
710
711 if (!l2)
712 return false;
713
714 for (it = l1; it && *it; it++)
715 if (string_in_list(l2, *it))
716 return true;
717
718 return false;
719 }
720
721 /* For a null-terminated list of controllers @clist, return true if any of those
722 * controllers is already listed the null-terminated list of hierarchies @hlist.
723 * Realistically, if one is present, all must be present.
724 */
725 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy **hlist, char **clist)
726 {
727 struct cgv1_hierarchy **it;
728
729 for (it = hlist; it && *it; it++)
730 if ((*it)->controllers)
731 if (cgv1_controller_lists_intersect((*it)->controllers, clist))
732 return true;
733 return false;
734
735 }
736
737 /* Set boolean to mark controllers under which we are supposed create a
738 * writeable cgroup.
739 */
740 static void cgv1_mark_to_make_rw(char **clist)
741 {
742 struct cgv1_hierarchy **it;
743
744 for (it = cgv1_hierarchies; it && *it; it++)
745 if ((*it)->controllers)
746 if (cgv1_controller_lists_intersect((*it)->controllers, clist) ||
747 string_in_list(clist, "all"))
748 (*it)->create_rw_cgroup = true;
749 }
750
751 /* Set boolean to mark whether we are supposed to create a writeable cgroup in
752 * the cgroupfs v2 hierarchy.
753 */
754 static void cgv2_mark_to_make_rw(char **clist)
755 {
756 if (string_in_list(clist, "unified") || string_in_list(clist, "all"))
757 if (cgv2_hierarchies)
758 (*cgv2_hierarchies)->create_rw_cgroup = true;
759 }
760
761 /* Wrapper around cgv{1,2}_mark_to_make_rw(). */
762 static void cg_mark_to_make_rw(char **clist)
763 {
764 cgv1_mark_to_make_rw(clist);
765 cgv2_mark_to_make_rw(clist);
766 }
767
768 /* Prefix any named controllers with "name=", e.g. "name=systemd". */
769 static char *cgv1_must_prefix_named(char *entry)
770 {
771 char *s;
772 int ret;
773 size_t len;
774
775 len = strlen(entry);
776 s = must_alloc(len + 6);
777
778 ret = snprintf(s, len + 6, "name=%s", entry);
779 if (ret < 0 || (size_t)ret >= (len + 6))
780 return NULL;
781
782 return s;
783 }
784
785 /* Append kernel controller in @klist or named controller in @nlist to @clist */
786 static void must_append_controller(char **klist, char **nlist, char ***clist, char *entry)
787 {
788 int newentry;
789 char *copy;
790
791 if (string_in_list(klist, entry) && string_in_list(nlist, entry))
792 return;
793
794 newentry = append_null_to_list((void ***)clist);
795
796 if (strncmp(entry, "name=", 5) == 0)
797 copy = must_copy_string(entry);
798 else if (string_in_list(klist, entry))
799 copy = must_copy_string(entry);
800 else
801 copy = cgv1_must_prefix_named(entry);
802
803 (*clist)[newentry] = copy;
804 }
805
806 /* Get the controllers from a mountinfo line. There are other ways we could get
807 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
808 * could parse the mount options. But we simply assume that the mountpoint must
809 * be /sys/fs/cgroup/controller-list
810 */
811 static char **cgv1_get_proc_mountinfo_controllers(char **klist, char **nlist, char *line)
812 {
813 int i;
814 char *p, *p2, *tok;
815 char *saveptr = NULL;
816 char **aret = NULL;
817
818 p = line;
819
820 for (i = 0; i < 4; i++) {
821 p = strchr(p, ' ');
822 if (!p)
823 return NULL;
824 p++;
825 }
826 if (!p)
827 return NULL;
828
829 if (strncmp(p, "/sys/fs/cgroup/", 15) != 0)
830 return NULL;
831
832 p += 15;
833
834 p2 = strchr(p, ' ');
835 if (!p2)
836 return NULL;
837 *p2 = '\0';
838
839 for (tok = strtok_r(p, ",", &saveptr); tok;
840 tok = strtok_r(NULL, ",", &saveptr))
841 must_append_controller(klist, nlist, &aret, tok);
842
843 return aret;
844 }
845
846 /* Check if a cgroupfs v2 controller is present in the string @cgline. */
847 static bool cgv1_controller_in_clist(char *cgline, char *c)
848 {
849 size_t len;
850 char *tok, *eol, *tmp;
851 char *saveptr = NULL;
852
853 eol = strchr(cgline, ':');
854 if (!eol)
855 return false;
856
857 len = eol - cgline;
858 tmp = alloca(len + 1);
859 memcpy(tmp, cgline, len);
860 tmp[len] = '\0';
861
862 for (tok = strtok_r(tmp, ",", &saveptr); tok;
863 tok = strtok_r(NULL, ",", &saveptr)) {
864 if (strcmp(tok, c) == 0)
865 return true;
866 }
867 return false;
868 }
869
870 /* Get current cgroup from the /proc/<pid>/cgroup file passed in via @basecginfo
871 * of a given cgv1 controller passed in via @controller.
872 */
873 static char *cgv1_get_current_cgroup(char *basecginfo, char *controller)
874 {
875 char *p;
876
877 p = basecginfo;
878
879 while (true) {
880 p = strchr(p, ':');
881 if (!p)
882 return NULL;
883 p++;
884
885 if (cgv1_controller_in_clist(p, controller)) {
886 p = strchr(p, ':');
887 if (!p)
888 return NULL;
889 p++;
890
891 return copy_to_eol(p);
892 }
893
894 p = strchr(p, '\n');
895 if (!p)
896 return NULL;
897 p++;
898 }
899
900 return NULL;
901 }
902
903 /* Remove /init.scope from string @cg. This will mostly affect systemd-based
904 * systems.
905 */
906 #define INIT_SCOPE "/init.scope"
907 static void cg_systemd_prune_init_scope(char *cg)
908 {
909 char *point;
910
911 if (!cg)
912 return;
913
914 point = cg + strlen(cg) - strlen(INIT_SCOPE);
915 if (point < cg)
916 return;
917
918 if (strcmp(point, INIT_SCOPE) == 0) {
919 if (point == cg)
920 *(point + 1) = '\0';
921 else
922 *point = '\0';
923 }
924 }
925
926 /* Add new info about a mounted cgroupfs v1 hierarchy. Includes the controllers
927 * mounted into that hierarchy (e.g. cpu,cpuacct), the mountpoint of that
928 * hierarchy (/sys/fs/cgroup/<controller>, the base cgroup of the current
929 * process gathered from /proc/self/cgroup, and the init cgroup of PID1 gathered
930 * from /proc/1/cgroup.
931 */
932 static void cgv1_add_controller(char **clist, char *mountpoint, char *base_cgroup, char *init_cgroup)
933 {
934 struct cgv1_hierarchy *new;
935 int newentry;
936
937 new = must_alloc(sizeof(*new));
938 new->controllers = clist;
939 new->mountpoint = mountpoint;
940 new->base_cgroup = base_cgroup;
941 new->fullcgpath = NULL;
942 new->create_rw_cgroup = false;
943 new->init_cgroup = init_cgroup;
944 new->systemd_user_slice = false;
945
946 newentry = append_null_to_list((void ***)&cgv1_hierarchies);
947 cgv1_hierarchies[newentry] = new;
948 }
949
950 /* Add new info about the mounted cgroupfs v2 hierarchy. Can (but doesn't
951 * currently) include the controllers mounted into the hierarchy (e.g. memory,
952 * pids, blkio), the mountpoint of that hierarchy (Should usually be
953 * /sys/fs/cgroup but some init systems seems to think it might be a good idea
954 * to also mount empty cgroupfs v2 hierarchies at /sys/fs/cgroup/systemd.), the
955 * base cgroup of the current process gathered from /proc/self/cgroup, and the
956 * init cgroup of PID1 gathered from /proc/1/cgroup.
957 */
958 static void cgv2_add_controller(char **clist, char *mountpoint, char *base_cgroup, char *init_cgroup, bool systemd_user_slice)
959 {
960 struct cgv2_hierarchy *new;
961 int newentry;
962
963 new = must_alloc(sizeof(*new));
964 new->controllers = clist;
965 new->mountpoint = mountpoint;
966 new->base_cgroup = base_cgroup;
967 new->fullcgpath = NULL;
968 new->create_rw_cgroup = false;
969 new->init_cgroup = init_cgroup;
970 new->systemd_user_slice = systemd_user_slice;
971
972 newentry = append_null_to_list((void ***)&cgv2_hierarchies);
973 cgv2_hierarchies[newentry] = new;
974 }
975
976 /* In Ubuntu 14.04, the paths created for us were
977 * '/user/$uid.user/$something.session' This can be merged better with
978 * systemd_created_slice_for_us(), but keeping it separate makes it easier to
979 * reason about the correctness.
980 */
981 static bool cg_systemd_under_user_slice_1(const char *in, uid_t uid)
982 {
983 char *p;
984 size_t len;
985 int id;
986 char *copy = NULL;
987 bool bret = false;
988
989 copy = must_copy_string(in);
990 if (strlen(copy) < strlen("/user/1.user/1.session"))
991 goto cleanup;
992 p = copy + strlen(copy) - 1;
993
994 /* skip any trailing '/' (shouldn't be any, but be sure) */
995 while (p >= copy && *p == '/')
996 *(p--) = '\0';
997 if (p < copy)
998 goto cleanup;
999
1000 /* Get last path element */
1001 while (p >= copy && *p != '/')
1002 p--;
1003 if (p < copy)
1004 goto cleanup;
1005 /* make sure it is something.session */
1006 len = strlen(p + 1);
1007 if (len < strlen("1.session") ||
1008 strncmp(p + 1 + len - 8, ".session", 8) != 0)
1009 goto cleanup;
1010
1011 /* ok last path piece checks out, now check the second to last */
1012 *(p + 1) = '\0';
1013 while (p >= copy && *(--p) != '/')
1014 ;
1015 if (sscanf(p + 1, "%d.user/", &id) != 1)
1016 goto cleanup;
1017
1018 if (id != (int)uid)
1019 goto cleanup;
1020
1021 bret = true;
1022
1023 cleanup:
1024 free(copy);
1025 return bret;
1026 }
1027
1028 /* So long as our path relative to init starts with /user.slice/user-$uid.slice,
1029 * assume it belongs to $uid and chown it
1030 */
1031 static bool cg_systemd_under_user_slice_2(const char *base_cgroup,
1032 const char *init_cgroup, uid_t uid)
1033 {
1034 int ret;
1035 char buf[100];
1036 size_t curlen, initlen;
1037
1038 curlen = strlen(base_cgroup);
1039 initlen = strlen(init_cgroup);
1040 if (curlen <= initlen)
1041 return false;
1042
1043 if (strncmp(base_cgroup, init_cgroup, initlen) != 0)
1044 return false;
1045
1046 ret = snprintf(buf, 100, "/user.slice/user-%d.slice/", (int)uid);
1047 if (ret < 0 || ret >= 100)
1048 return false;
1049
1050 if (initlen == 1)
1051 initlen = 0; // skip the '/'
1052
1053 return strncmp(base_cgroup + initlen, buf, strlen(buf)) == 0;
1054 }
1055
1056 /* The systemd-created path is: user-$uid.slice/session-c$session.scope. If that
1057 * is not the end of our systemd path, then we're not part of the PAM call that
1058 * created that path.
1059 *
1060 * The last piece is chowned to $uid, the user- part not.
1061 * Note: If the user creates paths that look like what we're looking for to
1062 * 'fool' us, either
1063 * - they fool us, we create new cgroups, and they get auto-logged-out.
1064 * - they fool a root sudo, systemd cgroup is not changed but chowned, and they
1065 * lose ownership of their cgroups
1066 */
1067 static bool cg_systemd_created_user_slice(const char *base_cgroup,
1068 const char *init_cgroup,
1069 const char *in, uid_t uid)
1070 {
1071 char *p;
1072 size_t len;
1073 int id;
1074 char *copy = NULL;
1075 bool bret = false;
1076
1077 copy = must_copy_string(in);
1078
1079 /* An old version of systemd has already created a cgroup for us. */
1080 if (cg_systemd_under_user_slice_1(in, uid))
1081 goto succeed;
1082
1083 /* A new version of systemd has already created a cgroup for us. */
1084 if (cg_systemd_under_user_slice_2(base_cgroup, init_cgroup, uid))
1085 goto succeed;
1086
1087 if (strlen(copy) < strlen("/user-0.slice/session-0.scope"))
1088 goto cleanup;
1089
1090 p = copy + strlen(copy) - 1;
1091 /* Skip any trailing '/' (shouldn't be any, but be sure). */
1092 while (p >= copy && *p == '/')
1093 *(p--) = '\0';
1094
1095 if (p < copy)
1096 goto cleanup;
1097
1098 /* Get last path element */
1099 while (p >= copy && *p != '/')
1100 p--;
1101
1102 if (p < copy)
1103 goto cleanup;
1104
1105 /* Make sure it is session-something.scope. */
1106 len = strlen(p + 1);
1107 if (strncmp(p + 1, "session-", strlen("session-")) != 0 ||
1108 strncmp(p + 1 + len - 6, ".scope", 6) != 0)
1109 goto cleanup;
1110
1111 /* Ok last path piece checks out, now check the second to last. */
1112 *(p + 1) = '\0';
1113 while (p >= copy && *(--p) != '/')
1114 ;
1115
1116 if (sscanf(p + 1, "user-%d.slice/", &id) != 1)
1117 goto cleanup;
1118
1119 if (id != (int)uid)
1120 goto cleanup;
1121
1122 succeed:
1123 bret = true;
1124 cleanup:
1125 free(copy);
1126 return bret;
1127 }
1128
1129 /* Chown existing cgroup that systemd has already created for us. */
1130 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint,
1131 const char *base_cgroup, uid_t uid,
1132 gid_t gid, bool systemd_user_slice)
1133 {
1134 char *path;
1135
1136 if (!systemd_user_slice)
1137 return false;
1138
1139 path = must_make_path(mountpoint, base_cgroup, NULL);
1140
1141 /* A cgroup within name=systemd has already been created. So we only
1142 * need to chown it.
1143 */
1144 if (chown(path, uid, gid) < 0)
1145 mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %s.\n",
1146 path, (int)uid, (int)gid, strerror(errno), NULL);
1147 pam_cgfs_debug("Chowned %s to %d:%d.\n", path, (int)uid, (int)gid);
1148
1149 free(path);
1150 return true;
1151 }
1152
1153 /* Detect and store information about cgroupfs v1 hierarchies. */
1154 static bool cgv1_init(uid_t uid, gid_t gid)
1155 {
1156 FILE *f;
1157 struct cgv1_hierarchy **it;
1158 char *basecginfo;
1159 char *line = NULL;
1160 char **klist = NULL, **nlist = NULL;
1161 size_t len = 0;
1162
1163 basecginfo = read_file("/proc/self/cgroup");
1164 if (!basecginfo)
1165 return false;
1166
1167 f = fopen("/proc/self/mountinfo", "r");
1168 if (!f) {
1169 free(basecginfo);
1170 return false;
1171 }
1172
1173 cgv1_get_controllers(&klist, &nlist);
1174
1175 while (getline(&line, &len, f) != -1) {
1176 char **controller_list = NULL;
1177 char *mountpoint, *base_cgroup;
1178
1179 if (is_lxcfs(line) || !is_cgv1(line))
1180 continue;
1181
1182 controller_list = cgv1_get_proc_mountinfo_controllers(klist, nlist, line);
1183 if (!controller_list)
1184 continue;
1185
1186 if (cgv1_controller_list_is_dup(cgv1_hierarchies,
1187 controller_list)) {
1188 free(controller_list);
1189 continue;
1190 }
1191
1192 mountpoint = get_mountpoint(line);
1193 if (!mountpoint) {
1194 free_string_list(controller_list);
1195 continue;
1196 }
1197
1198 base_cgroup = cgv1_get_current_cgroup(basecginfo, controller_list[0]);
1199 if (!base_cgroup) {
1200 free_string_list(controller_list);
1201 free(mountpoint);
1202 continue;
1203 }
1204 trim(base_cgroup);
1205 pam_cgfs_debug("Detected cgroupfs v1 controller \"%s\" with "
1206 "mountpoint \"%s\" and cgroup \"%s\".\n",
1207 controller_list[0], mountpoint, base_cgroup);
1208 cgv1_add_controller(controller_list, mountpoint, base_cgroup,
1209 NULL);
1210 }
1211 free_string_list(klist);
1212 free_string_list(nlist);
1213 free(basecginfo);
1214 fclose(f);
1215 free(line);
1216
1217 /* Retrieve init cgroup path for all controllers. */
1218 basecginfo = read_file("/proc/1/cgroup");
1219 if (!basecginfo)
1220 return false;
1221
1222 for (it = cgv1_hierarchies; it && *it; it++) {
1223 if ((*it)->controllers) {
1224 char *init_cgroup, *user_slice;
1225 /* We've already stored the controller and received its
1226 * current cgroup. If we now fail to retrieve its init
1227 * cgroup, we should probably fail.
1228 */
1229 init_cgroup = cgv1_get_current_cgroup(basecginfo, (*it)->controllers[0]);
1230 if (!init_cgroup) {
1231 free(basecginfo);
1232 return false;
1233 }
1234 cg_systemd_prune_init_scope(init_cgroup);
1235 (*it)->init_cgroup = init_cgroup;
1236 pam_cgfs_debug("cgroupfs v1 controller \"%s\" has init "
1237 "cgroup \"%s\".\n",
1238 (*(*it)->controllers), init_cgroup);
1239 /* Check whether systemd has already created a cgroup
1240 * for us.
1241 */
1242 user_slice = must_make_path((*it)->mountpoint, (*it)->base_cgroup, NULL);
1243 if (cg_systemd_created_user_slice((*it)->base_cgroup, (*it)->init_cgroup, user_slice, uid))
1244 (*it)->systemd_user_slice = true;
1245 }
1246 }
1247 free(basecginfo);
1248
1249 return true;
1250 }
1251
1252 /* Check whether @path is a cgroupfs v1 or cgroupfs v2 mount. Returns -1 if
1253 * statfs fails. If @path is null /sys/fs/cgroup is checked.
1254 */
1255 static inline int cg_get_version_of_mntpt(const char *path)
1256 {
1257 if (has_fs_type(path, CGROUP_SUPER_MAGIC))
1258 return 1;
1259
1260 if (has_fs_type(path, CGROUP2_SUPER_MAGIC))
1261 return 2;
1262
1263 return 0;
1264 }
1265
1266 /* Detect and store information about the cgroupfs v2 hierarchy. Currently only
1267 * deals with the empty v2 hierachy as we do not retrieve enabled controllers.
1268 */
1269 static bool cgv2_init(uid_t uid, gid_t gid)
1270 {
1271 char *mountpoint;
1272 FILE *f = NULL;
1273 char *current_cgroup = NULL, *init_cgroup = NULL;
1274 char * line = NULL;
1275 size_t len = 0;
1276 int ret = false;
1277
1278 current_cgroup = cgv2_get_current_cgroup(getpid());
1279 if (!current_cgroup) {
1280 /* No v2 hierarchy present. We're done. */
1281 ret = true;
1282 goto cleanup;
1283 }
1284
1285 init_cgroup = cgv2_get_current_cgroup(1);
1286 if (!init_cgroup) {
1287 /* If we're here and didn't fail already above, then something's
1288 * certainly wrong, so error this time.
1289 */
1290 goto cleanup;
1291 }
1292 cg_systemd_prune_init_scope(init_cgroup);
1293
1294 /* Check if the v2 hierarchy is mounted at its standard location.
1295 * If so we can skip the rest of the work here. Although the unified
1296 * hierarchy can be mounted multiple times, each of those mountpoints
1297 * will expose identical information.
1298 */
1299 if (cg_get_version_of_mntpt("/sys/fs/cgroup") == 2) {
1300 char *user_slice;
1301 bool has_user_slice = false;
1302
1303 mountpoint = must_copy_string("/sys/fs/cgroup");
1304 if (!mountpoint)
1305 goto cleanup;
1306
1307 user_slice = must_make_path(mountpoint, current_cgroup, NULL);
1308 if (cg_systemd_created_user_slice(current_cgroup, init_cgroup, user_slice, uid))
1309 has_user_slice = true;
1310 free(user_slice);
1311
1312 cgv2_add_controller(NULL, mountpoint, current_cgroup, init_cgroup, has_user_slice);
1313
1314 ret = true;
1315 goto cleanup;
1316 }
1317
1318 f = fopen("/proc/self/mountinfo", "r");
1319 if (!f)
1320 goto cleanup;
1321
1322 /* we support simple cgroup mounts and lxcfs mounts */
1323 while (getline(&line, &len, f) != -1) {
1324 char *user_slice;
1325 bool has_user_slice = false;
1326 if (!is_cgv2(line))
1327 continue;
1328
1329 mountpoint = get_mountpoint(line);
1330 if (!mountpoint)
1331 continue;
1332
1333 user_slice = must_make_path(mountpoint, current_cgroup, NULL);
1334 if (cg_systemd_created_user_slice(current_cgroup, init_cgroup, user_slice, uid))
1335 has_user_slice = true;
1336 free(user_slice);
1337
1338 cgv2_add_controller(NULL, mountpoint, current_cgroup, init_cgroup, has_user_slice);
1339 /* Although the unified hierarchy can be mounted multiple times,
1340 * each of those mountpoints will expose identical information.
1341 * So let the first mountpoint we find, win.
1342 */
1343 ret = true;
1344 break;
1345 }
1346
1347 pam_cgfs_debug("Detected cgroupfs v2 hierarchy at mountpoint \"%s\" with "
1348 "current cgroup \"%s\" and init cgroup \"%s\".\n",
1349 mountpoint, current_cgroup, init_cgroup);
1350
1351 cleanup:
1352 if (f)
1353 fclose(f);
1354 free(line);
1355
1356 return ret;
1357 }
1358
1359 /* Detect and store information about mounted cgroupfs v1 hierarchies and the
1360 * cgroupfs v2 hierarchy.
1361 * Detect whether we are on a pure cgroupfs v1, cgroupfs v2, or mixed system,
1362 * where some controllers are mounted into their standard cgroupfs v1 locations
1363 * (/sys/fs/cgroup/<controller>) and others are mounted into the cgroupfs v2
1364 * hierarchy (/sys/fs/cgroup).
1365 */
1366 static bool cg_init(uid_t uid, gid_t gid)
1367 {
1368 if (!cgv1_init(uid, gid))
1369 return false;
1370
1371 if (!cgv2_init(uid, gid))
1372 return false;
1373
1374 if (cgv1_hierarchies && cgv2_hierarchies) {
1375 cg_mount_mode = CGROUP_MIXED;
1376 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 and v2 hierarchies.");
1377 } else if (cgv1_hierarchies && !cgv2_hierarchies) {
1378 cg_mount_mode = CGROUP_PURE_V1;
1379 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 hierarchies.");
1380 } else if (cgv2_hierarchies && !cgv1_hierarchies) {
1381 cg_mount_mode = CGROUP_PURE_V2;
1382 pam_cgfs_debug("%s\n", "Detected cgroupfs v2 hierarchies.");
1383 } else {
1384 cg_mount_mode = CGROUP_UNKNOWN;
1385 mysyslog(LOG_ERR, "Could not detect cgroupfs hierarchy.\n", NULL);
1386 }
1387
1388 if (cg_mount_mode == CGROUP_UNKNOWN)
1389 return false;
1390
1391 return true;
1392 }
1393
1394 /* Try to move/migrate us into @cgroup in a cgroupfs v1 hierarchy. */
1395 static bool cgv1_enter(const char *cgroup)
1396 {
1397 struct cgv1_hierarchy **it;
1398
1399 for (it = cgv1_hierarchies; it && *it; it++) {
1400 char **controller;
1401 bool entered = false;
1402
1403 if (!(*it)->controllers || !(*it)->mountpoint ||
1404 !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
1405 continue;
1406
1407 for (controller = (*it)->controllers; controller && *controller;
1408 controller++) {
1409 char *path;
1410
1411 /* We've already been placed in a user slice, so we
1412 * don't need to enter the cgroup again.
1413 */
1414 if ((*it)->systemd_user_slice) {
1415 entered = true;
1416 break;
1417 }
1418
1419 path = must_make_path((*it)->mountpoint,
1420 (*it)->init_cgroup,
1421 cgroup,
1422 "/cgroup.procs",
1423 NULL);
1424 if (!file_exists(path)) {
1425 free(path);
1426 path = must_make_path((*it)->mountpoint,
1427 (*it)->init_cgroup,
1428 cgroup,
1429 "/tasks",
1430 NULL);
1431 }
1432 pam_cgfs_debug("Attempting to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path);
1433 entered = write_int(path, (int)getpid());
1434 if (entered) {
1435 free(path);
1436 break;
1437 }
1438 pam_cgfs_debug("Failed to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path);
1439 free(path);
1440 }
1441 if (!entered)
1442 return false;
1443 }
1444
1445 return true;
1446 }
1447
1448 /* Try to move/migrate us into @cgroup in the cgroupfs v2 hierarchy. */
1449 static bool cgv2_enter(const char *cgroup)
1450 {
1451 struct cgv2_hierarchy *v2;
1452 char *path;
1453 bool entered = false;
1454
1455 if (!cgv2_hierarchies)
1456 return true;
1457
1458 v2 = *cgv2_hierarchies;
1459
1460 if (!v2->mountpoint || !v2->base_cgroup)
1461 return false;
1462
1463 if (!v2->create_rw_cgroup || v2->systemd_user_slice)
1464 return true;
1465
1466 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup, "/cgroup.procs", NULL);
1467 pam_cgfs_debug("Attempting to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path);
1468 entered = write_int(path, (int)getpid());
1469 if (!entered) {
1470 pam_cgfs_debug("Failed to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path);
1471 free(path);
1472 return false;
1473 }
1474
1475 free(path);
1476
1477 return true;
1478 }
1479
1480 /* Wrapper around cgv{1,2}_enter(). */
1481 static bool cg_enter(const char *cgroup)
1482 {
1483 if (!cgv1_enter(cgroup)) {
1484 mysyslog(LOG_WARNING, "cgroupfs v1: Failed to enter cgroups.\n", NULL);
1485 return false;
1486 }
1487
1488 if (!cgv2_enter(cgroup)) {
1489 mysyslog(LOG_WARNING, "cgroupfs v2: Failed to enter cgroups.\n", NULL);
1490 return false;
1491 }
1492
1493 return true;
1494 }
1495
1496 /* Escape to root cgroup in all detected cgroupfs v1 hierarchies. */
1497 static void cgv1_escape(void)
1498 {
1499 struct cgv1_hierarchy **it;
1500
1501 /* In case systemd hasn't already placed us in a user slice for the
1502 * cpuset v1 controller we will reside in the root cgroup. This means
1503 * that cgroup.clone_children will not have been initialized for us so
1504 * we need to do it.
1505 */
1506 for (it = cgv1_hierarchies; it && *it; it++)
1507 if (!cgv1_handle_root_cpuset_hierarchy(*it))
1508 mysyslog(LOG_WARNING, "cgroupfs v1: Failed to initialize cpuset.\n", NULL);
1509
1510 if (!cgv1_enter("/"))
1511 mysyslog(LOG_WARNING, "cgroupfs v1: Failed to escape to init's cgroup.\n", NULL);
1512 }
1513
1514 /* Escape to root cgroup in the cgroupfs v2 hierarchy. */
1515 static void cgv2_escape(void)
1516 {
1517 if (!cgv2_enter("/"))
1518 mysyslog(LOG_WARNING, "cgroupfs v2: Failed to escape to init's cgroup.\n", NULL);
1519 }
1520
1521 /* Wrapper around cgv{1,2}_escape(). */
1522 static void cg_escape(void)
1523 {
1524 cgv1_escape();
1525 cgv2_escape();
1526 }
1527
1528 /* Get uid and gid for @user. */
1529 static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid)
1530 {
1531 struct passwd pwent;
1532 struct passwd *pwentp = NULL;
1533 char *buf;
1534 size_t bufsize;
1535 int ret;
1536
1537 bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
1538 if (bufsize == -1)
1539 bufsize = 1024;
1540
1541 buf = malloc(bufsize);
1542 if (!buf)
1543 return false;
1544
1545 ret = getpwnam_r(user, &pwent, buf, bufsize, &pwentp);
1546 if (!pwentp) {
1547 if (ret == 0)
1548 mysyslog(LOG_ERR,
1549 "Could not find matched password record\n", NULL);
1550
1551 free(buf);
1552 return false;
1553 }
1554
1555 *uid = pwent.pw_uid;
1556 *gid = pwent.pw_gid;
1557 free(buf);
1558
1559 return true;
1560 }
1561
1562 /* Check if cgroup belongs to our uid and gid. If so, reuse it. */
1563 static bool cg_belongs_to_uid_gid(const char *path, uid_t uid, gid_t gid)
1564 {
1565 struct stat statbuf;
1566
1567 if (stat(path, &statbuf) < 0)
1568 return false;
1569
1570 if (!(statbuf.st_uid == uid) || !(statbuf.st_gid == gid))
1571 return false;
1572
1573 return true;
1574 }
1575
1576 /* Create cpumask from cpulist aka turn:
1577 *
1578 * 0,2-3
1579 *
1580 * into bit array
1581 *
1582 * 1 0 1 1
1583 */
1584 static uint32_t *cg_cpumask(char *buf, size_t nbits)
1585 {
1586 char *token;
1587 char *saveptr = NULL;
1588 size_t arrlen = BITS_TO_LONGS(nbits);
1589 uint32_t *bitarr = calloc(arrlen, sizeof(uint32_t));
1590 if (!bitarr)
1591 return NULL;
1592
1593 for (; (token = strtok_r(buf, ",", &saveptr)); buf = NULL) {
1594 errno = 0;
1595 unsigned start = strtoul(token, NULL, 0);
1596 unsigned end = start;
1597
1598 char *range = strchr(token, '-');
1599 if (range)
1600 end = strtoul(range + 1, NULL, 0);
1601 if (!(start <= end)) {
1602 free(bitarr);
1603 return NULL;
1604 }
1605
1606 if (end >= nbits) {
1607 free(bitarr);
1608 return NULL;
1609 }
1610
1611 while (start <= end)
1612 set_bit(start++, bitarr);
1613 }
1614
1615 return bitarr;
1616 }
1617
1618 static char *string_join(const char *sep, const char **parts, bool use_as_prefix)
1619 {
1620 char *result;
1621 char **p;
1622 size_t sep_len = strlen(sep);
1623 size_t result_len = use_as_prefix * sep_len;
1624 size_t buf_len;
1625
1626 if (!parts)
1627 return NULL;
1628
1629 /* calculate new string length */
1630 for (p = (char **)parts; *p; p++)
1631 result_len += (p > (char **)parts) * sep_len + strlen(*p);
1632
1633 buf_len = result_len + 1;
1634 result = calloc(buf_len, sizeof(char));
1635 if (!result)
1636 return NULL;
1637
1638 if (use_as_prefix)
1639 (void)strlcpy(result, sep, buf_len * sizeof(char));
1640
1641 for (p = (char **)parts; *p; p++) {
1642 if (p > (char **)parts)
1643 (void)strlcat(result, sep, buf_len * sizeof(char));
1644 (void)strlcat(result, *p, buf_len * sizeof(char));
1645 }
1646
1647 return result;
1648 }
1649
1650 /* The largest integer that can fit into long int is 2^64. This is a
1651 * 20-digit number.
1652 */
1653 #define __IN_TO_STR_LEN 21
1654 /* Turn cpumask into simple, comma-separated cpulist. */
1655 static char *cg_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits)
1656 {
1657 size_t i;
1658 int ret;
1659 char numstr[__IN_TO_STR_LEN] = {0};
1660 char **cpulist = NULL;
1661
1662 for (i = 0; i <= nbits; i++) {
1663 if (is_set(i, bitarr)) {
1664 ret = snprintf(numstr, __IN_TO_STR_LEN, "%zu", i);
1665 if (ret < 0 || (size_t)ret >= __IN_TO_STR_LEN) {
1666 free_string_list(cpulist);
1667 return NULL;
1668 }
1669 must_append_string(&cpulist, numstr);
1670 }
1671 }
1672 return string_join(",", (const char **)cpulist, false);
1673 }
1674
1675 static ssize_t cg_get_max_cpus(char *cpulist)
1676 {
1677 char *c1, *c2;
1678 char *maxcpus = cpulist;
1679 size_t cpus = 0;
1680
1681 c1 = strrchr(maxcpus, ',');
1682 if (c1)
1683 c1++;
1684
1685 c2 = strrchr(maxcpus, '-');
1686 if (c2)
1687 c2++;
1688
1689 if (!c1 && !c2)
1690 c1 = maxcpus;
1691 else if (c1 < c2)
1692 c1 = c2;
1693
1694 /* If the above logic is correct, c1 should always hold a valid string
1695 * here.
1696 */
1697
1698 errno = 0;
1699 cpus = strtoul(c1, NULL, 0);
1700 if (errno != 0)
1701 return -1;
1702
1703 return cpus;
1704 }
1705
1706 static ssize_t write_nointr(int fd, const void* buf, size_t count)
1707 {
1708 ssize_t ret;
1709 again:
1710 ret = write(fd, buf, count);
1711 if (ret < 0 && errno == EINTR)
1712 goto again;
1713 return ret;
1714 }
1715
1716 static int write_to_file(const char *filename, const void* buf, size_t count, bool add_newline)
1717 {
1718 int fd, saved_errno;
1719 ssize_t ret;
1720
1721 fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0666);
1722 if (fd < 0)
1723 return -1;
1724 ret = write_nointr(fd, buf, count);
1725 if (ret < 0)
1726 goto out_error;
1727 if ((size_t)ret != count)
1728 goto out_error;
1729 if (add_newline) {
1730 ret = write_nointr(fd, "\n", 1);
1731 if (ret != 1)
1732 goto out_error;
1733 }
1734 close(fd);
1735 return 0;
1736
1737 out_error:
1738 saved_errno = errno;
1739 close(fd);
1740 errno = saved_errno;
1741 return -1;
1742 }
1743
1744 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
1745 static bool cg_filter_and_set_cpus(char *path, bool am_initialized)
1746 {
1747 char *lastslash, *fpath, oldv;
1748 int ret;
1749 ssize_t i;
1750
1751 ssize_t maxposs = 0, maxisol = 0;
1752 char *cpulist = NULL, *posscpus = NULL, *isolcpus = NULL;
1753 uint32_t *possmask = NULL, *isolmask = NULL;
1754 bool bret = false, flipped_bit = false;
1755
1756 lastslash = strrchr(path, '/');
1757 if (!lastslash) { // bug... this shouldn't be possible
1758 pam_cgfs_debug("Invalid path: %s.\n", path);
1759 return bret;
1760 }
1761 oldv = *lastslash;
1762 *lastslash = '\0';
1763 fpath = must_make_path(path, "cpuset.cpus", NULL);
1764 posscpus = read_file(fpath);
1765 if (!posscpus) {
1766 pam_cgfs_debug("Could not read file: %s.\n", fpath);
1767 goto on_error;
1768 }
1769
1770 /* Get maximum number of cpus found in possible cpuset. */
1771 maxposs = cg_get_max_cpus(posscpus);
1772 if (maxposs < 0)
1773 goto on_error;
1774
1775 if (!file_exists(__ISOL_CPUS)) {
1776 /* This system doesn't expose isolated cpus. */
1777 pam_cgfs_debug("%s", "Path: "__ISOL_CPUS" to read isolated cpus from does not exist.\n");
1778 cpulist = posscpus;
1779 /* No isolated cpus but we weren't already initialized by
1780 * someone. We should simply copy the parents cpuset.cpus
1781 * values.
1782 */
1783 if (!am_initialized) {
1784 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1785 goto copy_parent;
1786 }
1787 /* No isolated cpus but we were already initialized by someone.
1788 * Nothing more to do for us.
1789 */
1790 goto on_success;
1791 }
1792
1793 isolcpus = read_file(__ISOL_CPUS);
1794 if (!isolcpus) {
1795 pam_cgfs_debug("%s", "Could not read file "__ISOL_CPUS"\n");
1796 goto on_error;
1797 }
1798 if (!isdigit(isolcpus[0])) {
1799 pam_cgfs_debug("%s", "No isolated cpus detected.\n");
1800 cpulist = posscpus;
1801 /* No isolated cpus but we weren't already initialized by
1802 * someone. We should simply copy the parents cpuset.cpus
1803 * values.
1804 */
1805 if (!am_initialized) {
1806 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1807 goto copy_parent;
1808 }
1809 /* No isolated cpus but we were already initialized by someone.
1810 * Nothing more to do for us.
1811 */
1812 goto on_success;
1813 }
1814
1815 /* Get maximum number of cpus found in isolated cpuset. */
1816 maxisol = cg_get_max_cpus(isolcpus);
1817 if (maxisol < 0)
1818 goto on_error;
1819
1820 if (maxposs < maxisol)
1821 maxposs = maxisol;
1822 maxposs++;
1823
1824 possmask = cg_cpumask(posscpus, maxposs);
1825 if (!possmask) {
1826 pam_cgfs_debug("%s", "Could not create cpumask for all possible cpus.\n");
1827 goto on_error;
1828 }
1829
1830 isolmask = cg_cpumask(isolcpus, maxposs);
1831 if (!isolmask) {
1832 pam_cgfs_debug("%s", "Could not create cpumask for all isolated cpus.\n");
1833 goto on_error;
1834 }
1835
1836 for (i = 0; i <= maxposs; i++) {
1837 if (is_set(i, isolmask) && is_set(i, possmask)) {
1838 flipped_bit = true;
1839 clear_bit(i, possmask);
1840 }
1841 }
1842
1843 if (!flipped_bit) {
1844 pam_cgfs_debug("%s", "No isolated cpus present in cpuset.\n");
1845 goto on_success;
1846 }
1847 pam_cgfs_debug("%s", "Removed isolated cpus from cpuset.\n");
1848
1849 cpulist = cg_cpumask_to_cpulist(possmask, maxposs);
1850 if (!cpulist) {
1851 pam_cgfs_debug("%s", "Could not create cpu list.\n");
1852 goto on_error;
1853 }
1854
1855 copy_parent:
1856 *lastslash = oldv;
1857 fpath = must_make_path(path, "cpuset.cpus", NULL);
1858 ret = write_to_file(fpath, cpulist, strlen(cpulist), false);
1859 if (ret < 0) {
1860 pam_cgfs_debug("Could not write cpu list to: %s.\n", fpath);
1861 goto on_error;
1862 }
1863
1864 on_success:
1865 bret = true;
1866
1867 on_error:
1868 free(fpath);
1869
1870 free(isolcpus);
1871 free(isolmask);
1872
1873 if (posscpus != cpulist)
1874 free(posscpus);
1875 free(possmask);
1876
1877 free(cpulist);
1878 return bret;
1879 }
1880
1881 int read_from_file(const char *filename, void* buf, size_t count)
1882 {
1883 int fd = -1, saved_errno;
1884 ssize_t ret;
1885
1886 fd = open(filename, O_RDONLY | O_CLOEXEC);
1887 if (fd < 0)
1888 return -1;
1889
1890 if (!buf || !count) {
1891 char buf2[100];
1892 size_t count2 = 0;
1893 while ((ret = read(fd, buf2, 100)) > 0)
1894 count2 += ret;
1895 if (ret >= 0)
1896 ret = count2;
1897 } else {
1898 memset(buf, 0, count);
1899 ret = read(fd, buf, count);
1900 }
1901
1902 if (ret < 0)
1903 pam_cgfs_debug("read %s: %s", filename, strerror(errno));
1904
1905 saved_errno = errno;
1906 close(fd);
1907 errno = saved_errno;
1908 return ret;
1909 }
1910
1911 /* Copy contents of parent(@path)/@file to @path/@file */
1912 static bool cg_copy_parent_file(char *path, char *file)
1913 {
1914 char *lastslash, *value = NULL, *fpath, oldv;
1915 int len = 0;
1916 int ret;
1917
1918 lastslash = strrchr(path, '/');
1919 if (!lastslash) { // bug... this shouldn't be possible
1920 pam_cgfs_debug("cgfsng:copy_parent_file: bad path %s", path);
1921 return false;
1922 }
1923 oldv = *lastslash;
1924 *lastslash = '\0';
1925 fpath = must_make_path(path, file, NULL);
1926 len = read_from_file(fpath, NULL, 0);
1927 if (len <= 0)
1928 goto bad;
1929 value = must_alloc(len + 1);
1930 if (read_from_file(fpath, value, len) != len)
1931 goto bad;
1932 free(fpath);
1933 *lastslash = oldv;
1934 fpath = must_make_path(path, file, NULL);
1935 ret = write_to_file(fpath, value, len, false);
1936 if (ret < 0)
1937 pam_cgfs_debug("Unable to write %s to %s", value, fpath);
1938 free(fpath);
1939 free(value);
1940 return ret >= 0;
1941
1942 bad:
1943 pam_cgfs_debug("Error reading '%s'", fpath);
1944 free(fpath);
1945 free(value);
1946 return false;
1947 }
1948
1949 /* In case systemd hasn't already placed us in a user slice for the cpuset v1
1950 * controller we will reside in the root cgroup. This means that
1951 * cgroup.clone_children will not have been initialized for us so we need to do
1952 * it.
1953 */
1954 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy *h)
1955 {
1956 char *clonechildrenpath, v;
1957
1958 if (!string_in_list(h->controllers, "cpuset"))
1959 return true;
1960
1961 clonechildrenpath = must_make_path(h->mountpoint, "cgroup.clone_children", NULL);
1962
1963 if (read_from_file(clonechildrenpath, &v, 1) < 0) {
1964 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath);
1965 free(clonechildrenpath);
1966 return false;
1967 }
1968
1969 if (v == '1') { /* already set for us by someone else */
1970 free(clonechildrenpath);
1971 return true;
1972 }
1973
1974 if (write_to_file(clonechildrenpath, "1", 1, false) < 0) {
1975 /* Set clone_children so children inherit our settings */
1976 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath);
1977 free(clonechildrenpath);
1978 return false;
1979 }
1980 free(clonechildrenpath);
1981 return true;
1982 }
1983
1984 /*
1985 * Initialize the cpuset hierarchy in first directory of @gname and
1986 * set cgroup.clone_children so that children inherit settings.
1987 * Since the h->base_path is populated by init or ourselves, we know
1988 * it is already initialized.
1989 */
1990 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy *h,
1991 const char *cgroup)
1992 {
1993 char *cgpath, *clonechildrenpath, v, *slash;
1994
1995 if (!string_in_list(h->controllers, "cpuset"))
1996 return true;
1997
1998 if (*cgroup == '/')
1999 cgroup++;
2000 slash = strchr(cgroup, '/');
2001 if (slash)
2002 *slash = '\0';
2003
2004 cgpath = must_make_path(h->mountpoint, h->base_cgroup, cgroup, NULL);
2005 if (slash)
2006 *slash = '/';
2007 if (do_mkdir(cgpath, 0755) < 0 && errno != EEXIST) {
2008 pam_cgfs_debug("Failed to create '%s'", cgpath);
2009 free(cgpath);
2010 return false;
2011 }
2012 clonechildrenpath = must_make_path(cgpath, "cgroup.clone_children", NULL);
2013 if (!file_exists(clonechildrenpath)) { /* unified hierarchy doesn't have clone_children */
2014 free(clonechildrenpath);
2015 free(cgpath);
2016 return true;
2017 }
2018 if (read_from_file(clonechildrenpath, &v, 1) < 0) {
2019 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath);
2020 free(clonechildrenpath);
2021 free(cgpath);
2022 return false;
2023 }
2024
2025 /* Make sure any isolated cpus are removed from cpuset.cpus. */
2026 if (!cg_filter_and_set_cpus(cgpath, v == '1')) {
2027 pam_cgfs_debug("%s", "Failed to remove isolated cpus.\n");
2028 free(clonechildrenpath);
2029 free(cgpath);
2030 return false;
2031 }
2032
2033 if (v == '1') { /* already set for us by someone else */
2034 pam_cgfs_debug("%s", "\"cgroup.clone_children\" was already set to \"1\".\n");
2035 free(clonechildrenpath);
2036 free(cgpath);
2037 return true;
2038 }
2039
2040 /* copy parent's settings */
2041 if (!cg_copy_parent_file(cgpath, "cpuset.mems")) {
2042 pam_cgfs_debug("%s", "Failed to copy \"cpuset.mems\" settings.\n");
2043 free(cgpath);
2044 free(clonechildrenpath);
2045 return false;
2046 }
2047 free(cgpath);
2048
2049 if (write_to_file(clonechildrenpath, "1", 1, false) < 0) {
2050 /* Set clone_children so children inherit our settings */
2051 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath);
2052 free(clonechildrenpath);
2053 return false;
2054 }
2055 free(clonechildrenpath);
2056 return true;
2057 }
2058
2059 /* Create and chown @cgroup for all given controllers in a cgroupfs v1 hierarchy
2060 * (For example, create @cgroup for the cpu and cpuacct controller mounted into
2061 * /sys/fs/cgroup/cpu,cpuacct). Check if the path already exists and report back
2062 * to the caller in @existed.
2063 */
2064 #define __PAM_CGFS_USER "/user/"
2065 #define __PAM_CGFS_USER_LEN 6
2066 static bool cgv1_create_one(struct cgv1_hierarchy *h, const char *cgroup, uid_t uid, gid_t gid, bool *existed)
2067 {
2068 char *clean_base_cgroup, *path;
2069 char **controller;
2070 struct cgv1_hierarchy *it;
2071 bool created = false;
2072
2073 *existed = false;
2074 it = h;
2075 for (controller = it->controllers; controller && *controller;
2076 controller++) {
2077 if (!cgv1_handle_cpuset_hierarchy(it, cgroup))
2078 return false;
2079
2080 /* If systemd has already created a cgroup for us, keep using
2081 * it.
2082 */
2083 if (cg_systemd_chown_existing_cgroup(it->mountpoint,
2084 it->base_cgroup, uid, gid,
2085 it->systemd_user_slice)) {
2086 return true;
2087 }
2088
2089 /* We need to make sure that we do not create an endless chain
2090 * of sub-cgroups. So we check if we have already logged in
2091 * somehow (sudo -i, su, etc.) and have created a
2092 * /user/PAM_user/idx cgroup. If so, we skip that part. For most
2093 * cgroups this is unnecessary since we use the init_cgroup
2094 * anyway, but for controllers which have an existing systemd
2095 * cgroup that does not match the current uid, this is pretty
2096 * useful.
2097 */
2098 if (strncmp(it->base_cgroup, __PAM_CGFS_USER, __PAM_CGFS_USER_LEN) == 0) {
2099 free(it->base_cgroup);
2100 it->base_cgroup = must_copy_string("/");
2101 } else {
2102 clean_base_cgroup =
2103 strstr(it->base_cgroup, __PAM_CGFS_USER);
2104 if (clean_base_cgroup)
2105 *clean_base_cgroup = '\0';
2106 }
2107
2108 path = must_make_path(it->mountpoint, it->init_cgroup, cgroup, NULL);
2109 pam_cgfs_debug("Constructing path: %s.\n", path);
2110 if (file_exists(path)) {
2111 bool our_cg = cg_belongs_to_uid_gid(path, uid, gid);
2112 pam_cgfs_debug("%s existed and does %shave our uid: %d and gid: %d.\n", path, our_cg ? "" : "not ", uid, gid);
2113 free(path);
2114 if (our_cg)
2115 *existed = false;
2116 else
2117 *existed = true;
2118 return our_cg;
2119 }
2120 created = mkdir_parent(it->mountpoint, path);
2121 if (!created) {
2122 free(path);
2123 continue;
2124 }
2125 if (chown(path, uid, gid) < 0)
2126 mysyslog(LOG_WARNING,
2127 "Failed to chown %s to %d:%d: %s.\n", path,
2128 (int)uid, (int)gid, strerror(errno), NULL);
2129 pam_cgfs_debug("Chowned %s to %d:%d.\n", path, (int)uid, (int)gid);
2130 free(path);
2131 break;
2132 }
2133
2134 return created;
2135 }
2136
2137 /* Try to remove @cgroup for all given controllers in a cgroupfs v1 hierarchy
2138 * (For example, try to remove @cgroup for the cpu and cpuacct controller
2139 * mounted into /sys/fs/cgroup/cpu,cpuacct). Ignores failures.
2140 */
2141 static bool cgv1_remove_one(struct cgv1_hierarchy *h, const char *cgroup)
2142 {
2143
2144 char *path;
2145
2146 /* Better safe than sorry. */
2147 if (!h->controllers)
2148 return true;
2149
2150 /* Cgroups created by systemd for us which we re-use won't be removed
2151 * here, since we're using init_cgroup + cgroup as path instead of
2152 * base_cgroup + cgroup.
2153 */
2154 path = must_make_path(h->mountpoint, h->init_cgroup, cgroup, NULL);
2155 (void)recursive_rmdir(path);
2156 free(path);
2157
2158 return true;
2159 }
2160
2161 /* Try to remove @cgroup the cgroupfs v2 hierarchy. */
2162 static bool cgv2_remove(const char *cgroup)
2163 {
2164 struct cgv2_hierarchy *v2;
2165 char *path;
2166
2167 if (!cgv2_hierarchies)
2168 return true;
2169
2170 v2 = *cgv2_hierarchies;
2171
2172 /* If we reused an already existing cgroup, don't bother trying to
2173 * remove (a potentially wrong)/the path.
2174 * Cgroups created by systemd for us which we re-use would be removed
2175 * here, since we're using base_cgroup + cgroup as path.
2176 */
2177 if (v2->systemd_user_slice)
2178 return true;
2179
2180 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup, NULL);
2181 (void)recursive_rmdir(path);
2182 free(path);
2183
2184 return true;
2185 }
2186
2187 /* Create @cgroup in all detected cgroupfs v1 hierarchy. If the creation fails
2188 * for any cgroupfs v1 hierarchy, remove all we have created so far. Report
2189 * back, to the caller if the creation failed due to @cgroup already existing
2190 * via @existed.
2191 */
2192 static bool cgv1_create(const char *cgroup, uid_t uid, gid_t gid, bool *existed)
2193 {
2194 struct cgv1_hierarchy **it, **rev_it;
2195 bool all_created = true;
2196
2197 for (it = cgv1_hierarchies; it && *it; it++) {
2198 if (!(*it)->controllers || !(*it)->mountpoint ||
2199 !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
2200 continue;
2201
2202 if (!cgv1_create_one(*it, cgroup, uid, gid, existed)) {
2203 all_created = false;
2204 break;
2205 }
2206 }
2207
2208 if (all_created)
2209 return true;
2210
2211 for (rev_it = cgv1_hierarchies; rev_it && *rev_it && (*rev_it != *it);
2212 rev_it++)
2213 cgv1_remove_one(*rev_it, cgroup);
2214
2215 return false;
2216 }
2217
2218 /* Create @cgroup in the cgroupfs v2 hierarchy. Report back, to the caller if
2219 * the creation failed due to @cgroup already existing via @existed.
2220 */
2221 static bool cgv2_create(const char *cgroup, uid_t uid, gid_t gid, bool *existed)
2222 {
2223 int ret;
2224 char *clean_base_cgroup;
2225 char *path;
2226 struct cgv2_hierarchy *v2;
2227 bool our_cg = false, created = false;
2228
2229 *existed = false;
2230
2231 if (!cgv2_hierarchies || !(*cgv2_hierarchies)->create_rw_cgroup)
2232 return true;
2233
2234 v2 = *cgv2_hierarchies;
2235
2236 /* We can't be placed under init's cgroup for the v2 hierarchy. We need
2237 * to be placed under our current cgroup.
2238 */
2239 if (cg_systemd_chown_existing_cgroup(v2->mountpoint, v2->base_cgroup,
2240 uid, gid, v2->systemd_user_slice))
2241 goto delegate_files;
2242
2243 /* We need to make sure that we do not create an endless chain of
2244 * sub-cgroups. So we check if we have already logged in somehow (sudo
2245 * -i, su, etc.) and have created a /user/PAM_user/idx cgroup. If so, we
2246 * skip that part.
2247 */
2248 if (strncmp(v2->base_cgroup, __PAM_CGFS_USER, __PAM_CGFS_USER_LEN) == 0) {
2249 free(v2->base_cgroup);
2250 v2->base_cgroup = must_copy_string("/");
2251 } else {
2252 clean_base_cgroup = strstr(v2->base_cgroup, __PAM_CGFS_USER);
2253 if (clean_base_cgroup)
2254 *clean_base_cgroup = '\0';
2255 }
2256
2257 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup, NULL);
2258 pam_cgfs_debug("Constructing path \"%s\".\n", path);
2259 if (file_exists(path)) {
2260 our_cg = cg_belongs_to_uid_gid(path, uid, gid);
2261 pam_cgfs_debug(
2262 "%s existed and does %shave our uid: %d and gid: %d.\n",
2263 path, our_cg ? "" : "not ", uid, gid);
2264 free(path);
2265 if (our_cg) {
2266 *existed = false;
2267 goto delegate_files;
2268 } else {
2269 *existed = true;
2270 return false;
2271 }
2272 }
2273
2274 created = mkdir_parent(v2->mountpoint, path);
2275 if (!created) {
2276 free(path);
2277 return false;
2278 }
2279
2280 /* chown cgroup to user */
2281 if (chown(path, uid, gid) < 0)
2282 mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %s.\n",
2283 path, (int)uid, (int)gid, strerror(errno), NULL);
2284 else
2285 pam_cgfs_debug("Chowned %s to %d:%d.\n", path, (int)uid, (int)gid);
2286 free(path);
2287
2288 delegate_files:
2289 /* chown cgroup.procs to user */
2290 if (v2->systemd_user_slice)
2291 path = must_make_path(v2->mountpoint, v2->base_cgroup,
2292 "/cgroup.procs", NULL);
2293 else
2294 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup,
2295 "/cgroup.procs", NULL);
2296 ret = chown(path, uid, gid);
2297 if (ret < 0)
2298 mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %s.\n",
2299 path, (int)uid, (int)gid, strerror(errno), NULL);
2300 else
2301 pam_cgfs_debug("Chowned %s to %d:%d.\n", path, (int)uid, (int)gid);
2302 free(path);
2303
2304 /* chown cgroup.subtree_control to user */
2305 if (v2->systemd_user_slice)
2306 path = must_make_path(v2->mountpoint, v2->base_cgroup,
2307 "/cgroup.subtree_control", NULL);
2308 else
2309 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup,
2310 "/cgroup.subtree_control", NULL);
2311 ret = chown(path, uid, gid);
2312 if (ret < 0)
2313 mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %s.\n",
2314 path, (int)uid, (int)gid, strerror(errno), NULL);
2315 free(path);
2316
2317 /* chown cgroup.threads to user */
2318 if (v2->systemd_user_slice)
2319 path = must_make_path(v2->mountpoint, v2->base_cgroup,
2320 "/cgroup.threads", NULL);
2321 else
2322 path = must_make_path(v2->mountpoint, v2->base_cgroup, cgroup,
2323 "/cgroup.threads", NULL);
2324 ret = chown(path, uid, gid);
2325 if (ret < 0 && errno != ENOENT)
2326 mysyslog(LOG_WARNING, "Failed to chown %s to %d:%d: %s.\n",
2327 path, (int)uid, (int)gid, strerror(errno), NULL);
2328 free(path);
2329
2330 return true;
2331 }
2332
2333 /* Create writeable cgroups for @user at login. Details can be found in the
2334 * preamble/license at the top of this file.
2335 */
2336 static int handle_login(const char *user, uid_t uid, gid_t gid)
2337 {
2338 int idx = 0, ret;
2339 bool existed;
2340 char cg[MAXPATHLEN];
2341
2342 cg_escape();
2343
2344 while (idx >= 0) {
2345 ret = snprintf(cg, MAXPATHLEN, "/user/%s/%d", user, idx);
2346 if (ret < 0 || ret >= MAXPATHLEN) {
2347 mysyslog(LOG_ERR, "Username too long.\n", NULL);
2348 return PAM_SESSION_ERR;
2349 }
2350
2351 existed = false;
2352 if (!cgv2_create(cg, uid, gid, &existed)) {
2353 if (existed) {
2354 cgv2_remove(cg);
2355 idx++;
2356 continue;
2357 }
2358 mysyslog(LOG_ERR, "Failed to create a cgroup for user %s.\n", user, NULL);
2359 return PAM_SESSION_ERR;
2360 }
2361
2362 existed = false;
2363 if (!cgv1_create(cg, uid, gid, &existed)) {
2364 if (existed) {
2365 cgv2_remove(cg);
2366 idx++;
2367 continue;
2368 }
2369 mysyslog(LOG_ERR, "Failed to create a cgroup for user %s.\n", user, NULL);
2370 return PAM_SESSION_ERR;
2371 }
2372
2373 if (!cg_enter(cg)) {
2374 mysyslog( LOG_ERR, "Failed to enter user cgroup %s for user %s.\n", cg, user, NULL);
2375 return PAM_SESSION_ERR;
2376 }
2377 break;
2378 }
2379
2380 return PAM_SUCCESS;
2381 }
2382
2383 /* Try to prune cgroups we created and that now are empty from all cgroupfs v1
2384 * hierarchies.
2385 */
2386 static bool cgv1_prune_empty_cgroups(const char *user)
2387 {
2388 bool controller_removed = true;
2389 bool all_removed = true;
2390 struct cgv1_hierarchy **it;
2391
2392 for (it = cgv1_hierarchies; it && *it; it++) {
2393 int ret;
2394 char *path_base, *path_init;
2395 char **controller;
2396
2397 if (!(*it)->controllers || !(*it)->mountpoint ||
2398 !(*it)->init_cgroup || !(*it)->create_rw_cgroup)
2399 continue;
2400
2401 for (controller = (*it)->controllers; controller && *controller;
2402 controller++) {
2403 bool path_base_rm, path_init_rm;
2404
2405 path_base = must_make_path((*it)->mountpoint, (*it)->base_cgroup, "/user", user, NULL);
2406 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_base);
2407 ret = recursive_rmdir(path_base);
2408 if (ret == -ENOENT || ret >= 0)
2409 path_base_rm = true;
2410 else
2411 path_base_rm = false;
2412 free(path_base);
2413
2414 path_init = must_make_path((*it)->mountpoint, (*it)->init_cgroup, "/user", user, NULL);
2415 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_init);
2416 ret = recursive_rmdir(path_init);
2417 if (ret == -ENOENT || ret >= 0)
2418 path_init_rm = true;
2419 else
2420 path_init_rm = false;
2421 free(path_init);
2422
2423 if (!path_base_rm && !path_init_rm) {
2424 controller_removed = false;
2425 continue;
2426 }
2427
2428 controller_removed = true;
2429 break;
2430 }
2431 if (!controller_removed)
2432 all_removed = false;
2433 }
2434
2435 return all_removed;
2436 }
2437
2438 /* Try to prune cgroup we created and that now is empty from the cgroupfs v2
2439 * hierarchy.
2440 */
2441 static bool cgv2_prune_empty_cgroups(const char *user)
2442 {
2443 int ret;
2444 struct cgv2_hierarchy *v2;
2445 char *path_base, *path_init;
2446 bool path_base_rm, path_init_rm;
2447
2448 if (!cgv2_hierarchies)
2449 return true;
2450
2451 v2 = *cgv2_hierarchies;
2452
2453 path_base = must_make_path(v2->mountpoint, v2->base_cgroup, "/user", user, NULL);
2454 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_base);
2455 ret = recursive_rmdir(path_base);
2456 if (ret == -ENOENT || ret >= 0)
2457 path_base_rm = true;
2458 else
2459 path_base_rm = false;
2460 free(path_base);
2461
2462 path_init = must_make_path(v2->mountpoint, v2->init_cgroup, "/user", user, NULL);
2463 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_init);
2464 ret = recursive_rmdir(path_init);
2465 if (ret == -ENOENT || ret >= 0)
2466 path_init_rm = true;
2467 else
2468 path_init_rm = false;
2469 free(path_init);
2470
2471 if (!path_base_rm && !path_init_rm)
2472 return false;
2473
2474 return true;
2475 }
2476
2477 /* Wrapper around cgv{1,2}_prune_empty_cgroups(). */
2478 static void cg_prune_empty_cgroups(const char *user)
2479 {
2480 (void)cgv1_prune_empty_cgroups(user);
2481 (void)cgv2_prune_empty_cgroups(user);
2482 }
2483
2484 /* Free allocated information for detected cgroupfs v1 hierarchies. */
2485 static void cgv1_free_hierarchies(void)
2486 {
2487 struct cgv1_hierarchy **it;
2488
2489 if (!cgv1_hierarchies)
2490 return;
2491
2492 for (it = cgv1_hierarchies; it && *it; it++) {
2493 if ((*it)->controllers) {
2494 char **tmp;
2495 for (tmp = (*it)->controllers; tmp && *tmp; tmp++)
2496 free(*tmp);
2497
2498 free((*it)->controllers);
2499 }
2500 free((*it)->mountpoint);
2501 free((*it)->base_cgroup);
2502 free((*it)->fullcgpath);
2503 free((*it)->init_cgroup);
2504 }
2505 free(cgv1_hierarchies);
2506 }
2507
2508 /* Free allocated information for the detected cgroupfs v2 hierarchy. */
2509 static void cgv2_free_hierarchies(void)
2510 {
2511 struct cgv2_hierarchy **it;
2512
2513 if (!cgv2_hierarchies)
2514 return;
2515
2516 for (it = cgv2_hierarchies; it && *it; it++) {
2517 if ((*it)->controllers) {
2518 char **tmp;
2519 for (tmp = (*it)->controllers; tmp && *tmp; tmp++)
2520 free(*tmp);
2521
2522 free((*it)->controllers);
2523 }
2524 free((*it)->mountpoint);
2525 free((*it)->base_cgroup);
2526 free((*it)->fullcgpath);
2527 free((*it)->init_cgroup);
2528 }
2529 free(cgv2_hierarchies);
2530 }
2531
2532 /* Wrapper around cgv{1,2}_free_hierarchies(). */
2533 static void cg_exit(void)
2534 {
2535 cgv1_free_hierarchies();
2536 cgv2_free_hierarchies();
2537 }
2538
2539 int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc,
2540 const char **argv)
2541 {
2542 int ret;
2543 uid_t uid = 0;
2544 gid_t gid = 0;
2545 const char *PAM_user = NULL;
2546
2547 ret = pam_get_user(pamh, &PAM_user, NULL);
2548 if (ret != PAM_SUCCESS) {
2549 mysyslog(LOG_ERR, "PAM-CGFS: couldn't get user\n", NULL);
2550 return PAM_SESSION_ERR;
2551 }
2552
2553 if (!get_uid_gid(PAM_user, &uid, &gid)) {
2554 mysyslog(LOG_ERR, "Failed to get uid and gid for %s.\n", PAM_user, NULL);
2555 return PAM_SESSION_ERR;
2556 }
2557
2558 if (!cg_init(uid, gid)) {
2559 mysyslog(LOG_ERR, "Failed to get list of controllers\n", NULL);
2560 return PAM_SESSION_ERR;
2561 }
2562
2563 /* Try to prune cgroups, that are actually empty but were still marked
2564 * as busy by the kernel so we couldn't remove them on session close.
2565 */
2566 cg_prune_empty_cgroups(PAM_user);
2567
2568 if (cg_mount_mode == CGROUP_UNKNOWN)
2569 return PAM_SESSION_ERR;
2570
2571 if (argc > 1 && !strcmp(argv[0], "-c")) {
2572 char **clist = make_string_list(argv[1], ",");
2573
2574 /*
2575 * We don't allow using "all" and other controllers explicitly because
2576 * that simply doesn't make any sense.
2577 */
2578 if (string_list_length(clist) > 1 && string_in_list(clist, "all")) {
2579 mysyslog(LOG_ERR, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL);
2580 free_string_list(clist);
2581 return PAM_SESSION_ERR;
2582 }
2583
2584 cg_mark_to_make_rw(clist);
2585 free_string_list(clist);
2586 }
2587
2588 return handle_login(PAM_user, uid, gid);
2589 }
2590
2591 int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc,
2592 const char **argv)
2593 {
2594 int ret;
2595 uid_t uid = 0;
2596 gid_t gid = 0;
2597 const char *PAM_user = NULL;
2598
2599 ret = pam_get_user(pamh, &PAM_user, NULL);
2600 if (ret != PAM_SUCCESS) {
2601 mysyslog(LOG_ERR, "PAM-CGFS: couldn't get user\n", NULL);
2602 return PAM_SESSION_ERR;
2603 }
2604
2605 if (!get_uid_gid(PAM_user, &uid, &gid)) {
2606 mysyslog(LOG_ERR, "Failed to get uid and gid for %s.\n", PAM_user, NULL);
2607 return PAM_SESSION_ERR;
2608 }
2609
2610 if (cg_mount_mode == CGROUP_UNINITIALIZED) {
2611 if (!cg_init(uid, gid))
2612 mysyslog(LOG_ERR, "Failed to get list of controllers\n", NULL);
2613
2614 if (argc > 1 && !strcmp(argv[0], "-c")) {
2615 char **clist = make_string_list(argv[1], ",");
2616
2617 /*
2618 * We don't allow using "all" and other controllers explicitly because
2619 * that simply doesn't make any sense.
2620 */
2621 if (string_list_length(clist) > 1 && string_in_list(clist, "all")) {
2622 mysyslog(LOG_ERR, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL);
2623 free_string_list(clist);
2624 return PAM_SESSION_ERR;
2625 }
2626
2627 cg_mark_to_make_rw(clist);
2628 free_string_list(clist);
2629 }
2630 }
2631
2632 cg_prune_empty_cgroups(PAM_user);
2633 cg_exit();
2634
2635 return PAM_SUCCESS;
2636 }