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