]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/pam/pam_cgfs.c
3 * Copyright © 2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
5 * Author: Christian Brauner <christian.brauner@ubuntu.com>
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.
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:
21 * user.slice/user-uid.slice/session-n.scope
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.
30 * All requested cgroups must be mounted under /sys/fs/cgroup/$controller,
31 * no messing around with finding mountpoints.
33 * See COPYING file for details.
49 #include <linux/unistd.h>
50 #include <sys/mount.h>
51 #include <sys/param.h>
53 #include <sys/types.h>
56 #define PAM_SM_SESSION
57 #include <security/_pam_macros.h>
58 #include <security/pam_modules.h>
63 #include "include/strlcpy.h"
67 #include "include/strlcat.h"
70 #define pam_cgfs_debug_stream(stream, format, ...) \
72 fprintf(stream, "%s: %d: %s: " format, __FILE__, __LINE__, \
73 __func__, __VA_ARGS__); \
76 #define pam_cgfs_error(format, ...) pam_cgfs_debug_stream(stderr, format, __VA_ARGS__)
79 #define pam_cgfs_debug(format, ...) pam_cgfs_error(format, __VA_ARGS__)
81 #define pam_cgfs_debug(format, ...)
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)
89 static enum cg_mount_mode
{
94 CGROUP_UNINITIALIZED
= 3,
95 } cg_mount_mode
= CGROUP_UNINITIALIZED
;
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
)
103 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
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
)
112 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
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
,
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
)
128 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
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
,
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
,
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
);
164 /* cgroupfs v1 prototypes. */
165 struct cgv1_hierarchy
{
171 bool create_rw_cgroup
;
172 bool systemd_user_slice
;
175 static struct cgv1_hierarchy
**cgv1_hierarchies
;
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
,
183 static bool cgv1_create(const char *cgroup
, uid_t uid
, gid_t gid
,
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
,
193 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy
*h
,
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
);
203 /* cgroupfs v2 prototypes. */
204 struct cgv2_hierarchy
{
210 bool create_rw_cgroup
;
211 bool systemd_user_slice
;
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.
218 static struct cgv2_hierarchy
**cgv2_hierarchies
;
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
,
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
);
234 static int do_mkdir(const char *path
, mode_t mode
)
241 r
= mkdir(path
, mode
);
248 /* Create directory and (if necessary) its parents. */
249 static bool mkdir_parent(const char *root
, char *path
)
253 if (strlen(path
) < strlen(root
))
256 if (strlen(path
) == strlen(root
))
259 b
= path
+ strlen(root
) + 1;
261 while (*b
&& (*b
== '/'))
267 while (*e
&& *e
!= '/')
274 if (file_exists(path
))
277 if (do_mkdir(path
, 0755) < 0) {
278 pam_cgfs_debug("Failed to create %s: %s.\n", path
, strerror(errno
));
293 /* Common helper functions. Most of these have been taken from LXC. */
294 static void mysyslog(int err
, const char *format
, ...)
298 va_start(args
, format
);
299 openlog("PAM-CGFS", LOG_CONS
| LOG_PID
, LOG_AUTH
);
300 vsyslog(err
, format
, args
);
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
)
309 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
310 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
312 if (!*mem
|| newbatches
> oldbatches
)
313 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
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
)
319 size_t full
= oldlen
+ newlen
;
321 batch_realloc(dest
, oldlen
, full
+ 1);
323 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
326 /* Read in whole file and return allocated pointer. */
327 static char *read_file(char *fnam
)
331 char *line
= NULL
, *buf
= NULL
;
332 size_t len
= 0, fulllen
= 0;
334 f
= fopen(fnam
, "r");
338 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
339 append_line(&buf
, fulllen
, line
, linelen
);
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).
354 static int append_null_to_list(void ***list
)
359 for (; (*list
)[newentry
]; newentry
++) {
363 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
364 (*list
)[newentry
+ 1] = NULL
;
369 /* Append new entry to null-terminated array of pointer; make sure that array of
370 * pointers will still be null-terminated.
372 static void must_append_string(char ***list
, char *entry
)
377 newentry
= append_null_to_list((void ***)list
);
378 copy
= must_copy_string(entry
);
379 (*list
)[newentry
] = copy
;
382 /* Remove newlines from string. */
383 static void trim(char *s
)
385 size_t len
= strlen(s
);
387 while ((len
> 0) && s
[len
- 1] == '\n')
391 /* Allocate pointer; do not fail. */
392 static void *must_alloc(size_t sz
)
394 return must_realloc(NULL
, sz
);
397 /* Make allocated copy of string. End of string is taken to be '\n'. */
398 static char *copy_to_eol(char *s
)
400 char *newline
, *sret
;
403 newline
= strchr(s
, '\n');
408 sret
= must_alloc(len
+ 1);
409 memcpy(sret
, s
, len
);
415 /* Check if given entry under /proc/<pid>/mountinfo is a fuse.lxcfs mount. */
416 static bool is_lxcfs(const char *line
)
418 char *p
= strstr(line
, " - ");
422 return strncmp(p
, " - fuse.lxcfs ", 14) == 0;
425 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v1 mount. */
426 static bool is_cgv1(char *line
)
428 char *p
= strstr(line
, " - ");
432 return strncmp(p
, " - cgroup ", 10) == 0;
435 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v2 mount. */
436 static bool is_cgv2(char *line
)
438 char *p
= strstr(line
, " - ");
442 return strncmp(p
, " - cgroup2 ", 11) == 0;
445 /* Given a null-terminated array of strings, check whether @entry is one of the
448 static bool string_in_list(char **list
, const char *entry
)
452 for (it
= list
; it
&& *it
; it
++)
453 if (strcmp(*it
, entry
) == 0)
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.
463 static char **make_string_list(const char *str
, const char *sep
)
466 char *saveptr
= NULL
;
469 copy
= must_copy_string(str
);
471 for (tok
= strtok_r(copy
, sep
, &saveptr
); tok
;
472 tok
= strtok_r(NULL
, sep
, &saveptr
))
473 must_add_to_list(&clist
, tok
);
480 /* Gets the length of a null-terminated array of strings. */
481 static size_t string_list_length(char **list
)
486 for (it
= list
; it
&& *it
; it
++)
492 /* Free null-terminated array of strings. */
493 static void free_string_list(char **list
)
497 for (it
= list
; it
&& *it
; it
++)
502 /* Write single integer to file. */
503 static bool write_int(char *path
, int v
)
508 f
= fopen(path
, "w");
512 if (fprintf(f
, "%d\n", v
) < 0)
521 /* Recursively remove directory and its parents. */
522 static int recursive_rmdir(char *dirname
)
524 struct dirent
*direntp
;
528 dir
= opendir(dirname
);
532 while ((direntp
= readdir(dir
))) {
536 if (!strcmp(direntp
->d_name
, ".") ||
537 !strcmp(direntp
->d_name
, ".."))
540 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
542 if (lstat(pathname
, &st
)) {
544 pam_cgfs_debug("Failed to stat %s.\n", pathname
);
549 if (!S_ISDIR(st
.st_mode
))
552 if (recursive_rmdir(pathname
) < 0)
558 if (rmdir(dirname
) < 0) {
560 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
564 if (closedir(dir
) < 0) {
566 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
573 /* Add new entry to null-terminated array of pointers. Make sure array is still
576 static void must_add_to_list(char ***clist
, char *entry
)
580 newentry
= append_null_to_list((void ***)clist
);
581 (*clist
)[newentry
] = must_copy_string(entry
);
584 /* Get mountpoint from a /proc/<pid>/mountinfo line. */
585 static char *get_mountpoint(char *line
)
593 for (i
= 0; i
< 4; i
++) {
605 sret
= must_alloc(len
+ 1);
606 memcpy(sret
, p
, len
);
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).
616 static bool cgv1_get_controllers(char ***klist
, char ***nlist
)
622 f
= fopen("/proc/self/cgroup", "r");
626 while (getline(&line
, &len
, f
) != -1) {
628 char *saveptr
= NULL
;
630 p
= strchr(line
, ':');
640 /* Skip the v2 hierarchy. */
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
);
649 must_append_string(klist
, tok
);
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)
667 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
668 static char *cgv2_get_current_cgroup(int pid
)
672 char *current_cgroup
;
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
679 ret
= snprintf(path
, __PIDLEN
, "/proc/%d/cgroup", pid
);
680 if (ret
< 0 || ret
>= __PIDLEN
)
683 cgroups_v2
= read_file(path
);
687 current_cgroup
= strstr(cgroups_v2
, "0::/");
691 current_cgroup
= current_cgroup
+ 3;
692 copy
= copy_to_eol(current_cgroup
);
704 /* Given two null-terminated lists of strings, return true if any string is in
707 static bool cgv1_controller_lists_intersect(char **l1
, char **l2
)
714 for (it
= l1
; it
&& *it
; it
++)
715 if (string_in_list(l2
, *it
))
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.
725 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy
**hlist
, char **clist
)
727 struct cgv1_hierarchy
**it
;
729 for (it
= hlist
; it
&& *it
; it
++)
730 if ((*it
)->controllers
)
731 if (cgv1_controller_lists_intersect((*it
)->controllers
, clist
))
737 /* Set boolean to mark controllers under which we are supposed create a
740 static void cgv1_mark_to_make_rw(char **clist
)
742 struct cgv1_hierarchy
**it
;
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;
751 /* Set boolean to mark whether we are supposed to create a writeable cgroup in
752 * the cgroupfs v2 hierarchy.
754 static void cgv2_mark_to_make_rw(char **clist
)
756 if (string_in_list(clist
, "unified") || string_in_list(clist
, "all"))
757 if (cgv2_hierarchies
)
758 (*cgv2_hierarchies
)->create_rw_cgroup
= true;
761 /* Wrapper around cgv{1,2}_mark_to_make_rw(). */
762 static void cg_mark_to_make_rw(char **clist
)
764 cgv1_mark_to_make_rw(clist
);
765 cgv2_mark_to_make_rw(clist
);
768 /* Prefix any named controllers with "name=", e.g. "name=systemd". */
769 static char *cgv1_must_prefix_named(char *entry
)
776 s
= must_alloc(len
+ 6);
778 ret
= snprintf(s
, len
+ 6, "name=%s", entry
);
779 if (ret
< 0 || (size_t)ret
>= (len
+ 6))
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
)
791 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
))
794 newentry
= append_null_to_list((void ***)clist
);
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
);
801 copy
= cgv1_must_prefix_named(entry
);
803 (*clist
)[newentry
] = copy
;
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
811 static char **cgv1_get_proc_mountinfo_controllers(char **klist
, char **nlist
, char *line
)
815 char *saveptr
= NULL
;
820 for (i
= 0; i
< 4; i
++) {
829 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
839 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
840 tok
= strtok_r(NULL
, ",", &saveptr
))
841 must_append_controller(klist
, nlist
, &aret
, tok
);
846 /* Check if a cgroupfs v2 controller is present in the string @cgline. */
847 static bool cgv1_controller_in_clist(char *cgline
, char *c
)
850 char *tok
, *eol
, *tmp
;
851 char *saveptr
= NULL
;
853 eol
= strchr(cgline
, ':');
858 tmp
= alloca(len
+ 1);
859 memcpy(tmp
, cgline
, len
);
862 for (tok
= strtok_r(tmp
, ",", &saveptr
); tok
;
863 tok
= strtok_r(NULL
, ",", &saveptr
)) {
864 if (strcmp(tok
, c
) == 0)
870 /* Get current cgroup from the /proc/<pid>/cgroup file passed in via @basecginfo
871 * of a given cgv1 controller passed in via @controller.
873 static char *cgv1_get_current_cgroup(char *basecginfo
, char *controller
)
885 if (cgv1_controller_in_clist(p
, controller
)) {
891 return copy_to_eol(p
);
903 /* Remove /init.scope from string @cg. This will mostly affect systemd-based
906 #define INIT_SCOPE "/init.scope"
907 static void cg_systemd_prune_init_scope(char *cg
)
914 point
= cg
+ strlen(cg
) - strlen(INIT_SCOPE
);
918 if (strcmp(point
, INIT_SCOPE
) == 0) {
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.
932 static void cgv1_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
)
934 struct cgv1_hierarchy
*new;
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;
946 newentry
= append_null_to_list((void ***)&cgv1_hierarchies
);
947 cgv1_hierarchies
[newentry
] = new;
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.
958 static void cgv2_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
, bool systemd_user_slice
)
960 struct cgv2_hierarchy
*new;
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
;
972 newentry
= append_null_to_list((void ***)&cgv2_hierarchies
);
973 cgv2_hierarchies
[newentry
] = new;
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.
981 static bool cg_systemd_under_user_slice_1(const char *in
, uid_t uid
)
989 copy
= must_copy_string(in
);
990 if (strlen(copy
) < strlen("/user/1.user/1.session"))
992 p
= copy
+ strlen(copy
) - 1;
994 /* skip any trailing '/' (shouldn't be any, but be sure) */
995 while (p
>= copy
&& *p
== '/')
1000 /* Get last path element */
1001 while (p
>= copy
&& *p
!= '/')
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)
1011 /* ok last path piece checks out, now check the second to last */
1013 while (p
>= copy
&& *(--p
) != '/')
1015 if (sscanf(p
+ 1, "%d.user/", &id
) != 1)
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
1031 static bool cg_systemd_under_user_slice_2(const char *base_cgroup
,
1032 const char *init_cgroup
, uid_t uid
)
1036 size_t curlen
, initlen
;
1038 curlen
= strlen(base_cgroup
);
1039 initlen
= strlen(init_cgroup
);
1040 if (curlen
<= initlen
)
1043 if (strncmp(base_cgroup
, init_cgroup
, initlen
) != 0)
1046 ret
= snprintf(buf
, 100, "/user.slice/user-%d.slice/", (int)uid
);
1047 if (ret
< 0 || ret
>= 100)
1051 initlen
= 0; // skip the '/'
1053 return strncmp(base_cgroup
+ initlen
, buf
, strlen(buf
)) == 0;
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.
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
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
1067 static bool cg_systemd_created_user_slice(const char *base_cgroup
,
1068 const char *init_cgroup
,
1069 const char *in
, uid_t uid
)
1077 copy
= must_copy_string(in
);
1079 /* An old version of systemd has already created a cgroup for us. */
1080 if (cg_systemd_under_user_slice_1(in
, uid
))
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
))
1087 if (strlen(copy
) < strlen("/user-0.slice/session-0.scope"))
1090 p
= copy
+ strlen(copy
) - 1;
1091 /* Skip any trailing '/' (shouldn't be any, but be sure). */
1092 while (p
>= copy
&& *p
== '/')
1098 /* Get last path element */
1099 while (p
>= copy
&& *p
!= '/')
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)
1111 /* Ok last path piece checks out, now check the second to last. */
1113 while (p
>= copy
&& *(--p
) != '/')
1116 if (sscanf(p
+ 1, "user-%d.slice/", &id
) != 1)
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
)
1136 if (!systemd_user_slice
)
1139 path
= must_make_path(mountpoint
, base_cgroup
, NULL
);
1141 /* A cgroup within name=systemd has already been created. So we only
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
);
1153 /* Detect and store information about cgroupfs v1 hierarchies. */
1154 static bool cgv1_init(uid_t uid
, gid_t gid
)
1157 struct cgv1_hierarchy
**it
;
1160 char **klist
= NULL
, **nlist
= NULL
;
1163 basecginfo
= read_file("/proc/self/cgroup");
1167 f
= fopen("/proc/self/mountinfo", "r");
1173 cgv1_get_controllers(&klist
, &nlist
);
1175 while (getline(&line
, &len
, f
) != -1) {
1176 char **controller_list
= NULL
;
1177 char *mountpoint
, *base_cgroup
;
1179 if (is_lxcfs(line
) || !is_cgv1(line
))
1182 controller_list
= cgv1_get_proc_mountinfo_controllers(klist
, nlist
, line
);
1183 if (!controller_list
)
1186 if (cgv1_controller_list_is_dup(cgv1_hierarchies
,
1188 free(controller_list
);
1192 mountpoint
= get_mountpoint(line
);
1194 free_string_list(controller_list
);
1198 base_cgroup
= cgv1_get_current_cgroup(basecginfo
, controller_list
[0]);
1200 free_string_list(controller_list
);
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
,
1211 free_string_list(klist
);
1212 free_string_list(nlist
);
1217 /* Retrieve init cgroup path for all controllers. */
1218 basecginfo
= read_file("/proc/1/cgroup");
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.
1229 init_cgroup
= cgv1_get_current_cgroup(basecginfo
, (*it
)->controllers
[0]);
1234 cg_systemd_prune_init_scope(init_cgroup
);
1235 (*it
)->init_cgroup
= init_cgroup
;
1236 pam_cgfs_debug("cgroupfs v1 controller \"%s\" has init "
1238 (*(*it
)->controllers
), init_cgroup
);
1239 /* Check whether systemd has already created a cgroup
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;
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.
1255 static inline int cg_get_version_of_mntpt(const char *path
)
1257 if (has_fs_type(path
, CGROUP_SUPER_MAGIC
))
1260 if (has_fs_type(path
, CGROUP2_SUPER_MAGIC
))
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.
1269 static bool cgv2_init(uid_t uid
, gid_t gid
)
1273 char *current_cgroup
= NULL
, *init_cgroup
= NULL
;
1278 current_cgroup
= cgv2_get_current_cgroup(getpid());
1279 if (!current_cgroup
) {
1280 /* No v2 hierarchy present. We're done. */
1285 init_cgroup
= cgv2_get_current_cgroup(1);
1287 /* If we're here and didn't fail already above, then something's
1288 * certainly wrong, so error this time.
1292 cg_systemd_prune_init_scope(init_cgroup
);
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.
1299 if (cg_get_version_of_mntpt("/sys/fs/cgroup") == 2) {
1301 bool has_user_slice
= false;
1303 mountpoint
= must_copy_string("/sys/fs/cgroup");
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;
1312 cgv2_add_controller(NULL
, mountpoint
, current_cgroup
, init_cgroup
, has_user_slice
);
1318 f
= fopen("/proc/self/mountinfo", "r");
1322 /* we support simple cgroup mounts and lxcfs mounts */
1323 while (getline(&line
, &len
, f
) != -1) {
1325 bool has_user_slice
= false;
1329 mountpoint
= get_mountpoint(line
);
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;
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.
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
);
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).
1366 static bool cg_init(uid_t uid
, gid_t gid
)
1368 if (!cgv1_init(uid
, gid
))
1371 if (!cgv2_init(uid
, gid
))
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.");
1384 cg_mount_mode
= CGROUP_UNKNOWN
;
1385 mysyslog(LOG_ERR
, "Could not detect cgroupfs hierarchy.\n", NULL
);
1388 if (cg_mount_mode
== CGROUP_UNKNOWN
)
1394 /* Try to move/migrate us into @cgroup in a cgroupfs v1 hierarchy. */
1395 static bool cgv1_enter(const char *cgroup
)
1397 struct cgv1_hierarchy
**it
;
1399 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
1401 bool entered
= false;
1403 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
1404 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
1407 for (controller
= (*it
)->controllers
; controller
&& *controller
;
1411 /* We've already been placed in a user slice, so we
1412 * don't need to enter the cgroup again.
1414 if ((*it
)->systemd_user_slice
) {
1419 path
= must_make_path((*it
)->mountpoint
,
1424 if (!file_exists(path
)) {
1426 path
= must_make_path((*it
)->mountpoint
,
1432 pam_cgfs_debug("Attempting to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1433 entered
= write_int(path
, (int)getpid());
1438 pam_cgfs_debug("Failed to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1448 /* Try to move/migrate us into @cgroup in the cgroupfs v2 hierarchy. */
1449 static bool cgv2_enter(const char *cgroup
)
1451 struct cgv2_hierarchy
*v2
;
1453 bool entered
= false;
1455 if (!cgv2_hierarchies
)
1458 v2
= *cgv2_hierarchies
;
1460 if (!v2
->mountpoint
|| !v2
->base_cgroup
)
1463 if (!v2
->create_rw_cgroup
|| v2
->systemd_user_slice
)
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());
1470 pam_cgfs_debug("Failed to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path
);
1480 /* Wrapper around cgv{1,2}_enter(). */
1481 static bool cg_enter(const char *cgroup
)
1483 if (!cgv1_enter(cgroup
)) {
1484 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to enter cgroups.\n", NULL
);
1488 if (!cgv2_enter(cgroup
)) {
1489 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to enter cgroups.\n", NULL
);
1496 /* Escape to root cgroup in all detected cgroupfs v1 hierarchies. */
1497 static void cgv1_escape(void)
1499 struct cgv1_hierarchy
**it
;
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
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
);
1510 if (!cgv1_enter("/"))
1511 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to escape to init's cgroup.\n", NULL
);
1514 /* Escape to root cgroup in the cgroupfs v2 hierarchy. */
1515 static void cgv2_escape(void)
1517 if (!cgv2_enter("/"))
1518 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to escape to init's cgroup.\n", NULL
);
1521 /* Wrapper around cgv{1,2}_escape(). */
1522 static void cg_escape(void)
1528 /* Get uid and gid for @user. */
1529 static bool get_uid_gid(const char *user
, uid_t
*uid
, gid_t
*gid
)
1531 struct passwd pwent
;
1532 struct passwd
*pwentp
= NULL
;
1537 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1541 buf
= malloc(bufsize
);
1545 ret
= getpwnam_r(user
, &pwent
, buf
, bufsize
, &pwentp
);
1549 "Could not find matched password record\n", NULL
);
1555 *uid
= pwent
.pw_uid
;
1556 *gid
= pwent
.pw_gid
;
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
)
1565 struct stat statbuf
;
1567 if (stat(path
, &statbuf
) < 0)
1570 if (!(statbuf
.st_uid
== uid
) || !(statbuf
.st_gid
== gid
))
1576 /* Create cpumask from cpulist aka turn:
1584 static uint32_t *cg_cpumask(char *buf
, size_t nbits
)
1587 char *saveptr
= NULL
;
1588 size_t arrlen
= BITS_TO_LONGS(nbits
);
1589 uint32_t *bitarr
= calloc(arrlen
, sizeof(uint32_t));
1593 for (; (token
= strtok_r(buf
, ",", &saveptr
)); buf
= NULL
) {
1595 unsigned start
= strtoul(token
, NULL
, 0);
1596 unsigned end
= start
;
1598 char *range
= strchr(token
, '-');
1600 end
= strtoul(range
+ 1, NULL
, 0);
1601 if (!(start
<= end
)) {
1611 while (start
<= end
)
1612 set_bit(start
++, bitarr
);
1618 static char *string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
1622 size_t sep_len
= strlen(sep
);
1623 size_t result_len
= use_as_prefix
* sep_len
;
1629 /* calculate new string length */
1630 for (p
= (char **)parts
; *p
; p
++)
1631 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
1633 buf_len
= result_len
+ 1;
1634 result
= calloc(buf_len
, sizeof(char));
1639 (void)strlcpy(result
, sep
, buf_len
* sizeof(char));
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));
1650 /* The largest integer that can fit into long int is 2^64. This is a
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
)
1659 char numstr
[__IN_TO_STR_LEN
] = {0};
1660 char **cpulist
= NULL
;
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
);
1669 must_append_string(&cpulist
, numstr
);
1672 return string_join(",", (const char **)cpulist
, false);
1675 static ssize_t
cg_get_max_cpus(char *cpulist
)
1678 char *maxcpus
= cpulist
;
1681 c1
= strrchr(maxcpus
, ',');
1685 c2
= strrchr(maxcpus
, '-');
1694 /* If the above logic is correct, c1 should always hold a valid string
1699 cpus
= strtoul(c1
, NULL
, 0);
1706 static ssize_t
write_nointr(int fd
, const void* buf
, size_t count
)
1710 ret
= write(fd
, buf
, count
);
1711 if (ret
< 0 && errno
== EINTR
)
1716 static int write_to_file(const char *filename
, const void* buf
, size_t count
, bool add_newline
)
1718 int fd
, saved_errno
;
1721 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, 0666);
1724 ret
= write_nointr(fd
, buf
, count
);
1727 if ((size_t)ret
!= count
)
1730 ret
= write_nointr(fd
, "\n", 1);
1738 saved_errno
= errno
;
1740 errno
= saved_errno
;
1744 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
1745 static bool cg_filter_and_set_cpus(char *path
, bool am_initialized
)
1747 char *lastslash
, *fpath
, oldv
;
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;
1756 lastslash
= strrchr(path
, '/');
1757 if (!lastslash
) { // bug... this shouldn't be possible
1758 pam_cgfs_debug("Invalid path: %s.\n", path
);
1763 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1764 posscpus
= read_file(fpath
);
1766 pam_cgfs_debug("Could not read file: %s.\n", fpath
);
1770 /* Get maximum number of cpus found in possible cpuset. */
1771 maxposs
= cg_get_max_cpus(posscpus
);
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");
1779 /* No isolated cpus but we weren't already initialized by
1780 * someone. We should simply copy the parents cpuset.cpus
1783 if (!am_initialized
) {
1784 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1787 /* No isolated cpus but we were already initialized by someone.
1788 * Nothing more to do for us.
1793 isolcpus
= read_file(__ISOL_CPUS
);
1795 pam_cgfs_debug("%s", "Could not read file "__ISOL_CPUS
"\n");
1798 if (!isdigit(isolcpus
[0])) {
1799 pam_cgfs_debug("%s", "No isolated cpus detected.\n");
1801 /* No isolated cpus but we weren't already initialized by
1802 * someone. We should simply copy the parents cpuset.cpus
1805 if (!am_initialized
) {
1806 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1809 /* No isolated cpus but we were already initialized by someone.
1810 * Nothing more to do for us.
1815 /* Get maximum number of cpus found in isolated cpuset. */
1816 maxisol
= cg_get_max_cpus(isolcpus
);
1820 if (maxposs
< maxisol
)
1824 possmask
= cg_cpumask(posscpus
, maxposs
);
1826 pam_cgfs_debug("%s", "Could not create cpumask for all possible cpus.\n");
1830 isolmask
= cg_cpumask(isolcpus
, maxposs
);
1832 pam_cgfs_debug("%s", "Could not create cpumask for all isolated cpus.\n");
1836 for (i
= 0; i
<= maxposs
; i
++) {
1837 if (is_set(i
, isolmask
) && is_set(i
, possmask
)) {
1839 clear_bit(i
, possmask
);
1844 pam_cgfs_debug("%s", "No isolated cpus present in cpuset.\n");
1847 pam_cgfs_debug("%s", "Removed isolated cpus from cpuset.\n");
1849 cpulist
= cg_cpumask_to_cpulist(possmask
, maxposs
);
1851 pam_cgfs_debug("%s", "Could not create cpu list.\n");
1857 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1858 ret
= write_to_file(fpath
, cpulist
, strlen(cpulist
), false);
1860 pam_cgfs_debug("Could not write cpu list to: %s.\n", fpath
);
1873 if (posscpus
!= cpulist
)
1881 int read_from_file(const char *filename
, void* buf
, size_t count
)
1883 int fd
= -1, saved_errno
;
1886 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1890 if (!buf
|| !count
) {
1893 while ((ret
= read(fd
, buf2
, 100)) > 0)
1898 memset(buf
, 0, count
);
1899 ret
= read(fd
, buf
, count
);
1903 pam_cgfs_debug("read %s: %s", filename
, strerror(errno
));
1905 saved_errno
= errno
;
1907 errno
= saved_errno
;
1911 /* Copy contents of parent(@path)/@file to @path/@file */
1912 static bool cg_copy_parent_file(char *path
, char *file
)
1914 char *lastslash
, *value
= NULL
, *fpath
, oldv
;
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
);
1925 fpath
= must_make_path(path
, file
, NULL
);
1926 len
= read_from_file(fpath
, NULL
, 0);
1929 value
= must_alloc(len
+ 1);
1930 if (read_from_file(fpath
, value
, len
) != len
)
1934 fpath
= must_make_path(path
, file
, NULL
);
1935 ret
= write_to_file(fpath
, value
, len
, false);
1937 pam_cgfs_debug("Unable to write %s to %s", value
, fpath
);
1943 pam_cgfs_debug("Error reading '%s'", fpath
);
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
1954 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy
*h
)
1956 char *clonechildrenpath
, v
;
1958 if (!string_in_list(h
->controllers
, "cpuset"))
1961 clonechildrenpath
= must_make_path(h
->mountpoint
, "cgroup.clone_children", NULL
);
1963 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
1964 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
1965 free(clonechildrenpath
);
1969 if (v
== '1') { /* already set for us by someone else */
1970 free(clonechildrenpath
);
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
);
1980 free(clonechildrenpath
);
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.
1990 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy
*h
,
1993 char *cgpath
, *clonechildrenpath
, v
, *slash
;
1995 if (!string_in_list(h
->controllers
, "cpuset"))
2000 slash
= strchr(cgroup
, '/');
2004 cgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgroup
, NULL
);
2007 if (do_mkdir(cgpath
, 0755) < 0 && errno
!= EEXIST
) {
2008 pam_cgfs_debug("Failed to create '%s'", cgpath
);
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
);
2018 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
2019 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
2020 free(clonechildrenpath
);
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
);
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
);
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");
2044 free(clonechildrenpath
);
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
);
2055 free(clonechildrenpath
);
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.
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
)
2068 char *clean_base_cgroup
, *path
;
2070 struct cgv1_hierarchy
*it
;
2071 bool created
= false;
2075 for (controller
= it
->controllers
; controller
&& *controller
;
2077 if (!cgv1_handle_cpuset_hierarchy(it
, cgroup
))
2080 /* If systemd has already created a cgroup for us, keep using
2083 if (cg_systemd_chown_existing_cgroup(it
->mountpoint
,
2084 it
->base_cgroup
, uid
, gid
,
2085 it
->systemd_user_slice
)) {
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
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("/");
2103 strstr(it
->base_cgroup
, __PAM_CGFS_USER
);
2104 if (clean_base_cgroup
)
2105 *clean_base_cgroup
= '\0';
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
);
2120 created
= mkdir_parent(it
->mountpoint
, path
);
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
);
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.
2141 static bool cgv1_remove_one(struct cgv1_hierarchy
*h
, const char *cgroup
)
2146 /* Better safe than sorry. */
2147 if (!h
->controllers
)
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.
2154 path
= must_make_path(h
->mountpoint
, h
->init_cgroup
, cgroup
, NULL
);
2155 (void)recursive_rmdir(path
);
2161 /* Try to remove @cgroup the cgroupfs v2 hierarchy. */
2162 static bool cgv2_remove(const char *cgroup
)
2164 struct cgv2_hierarchy
*v2
;
2167 if (!cgv2_hierarchies
)
2170 v2
= *cgv2_hierarchies
;
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.
2177 if (v2
->systemd_user_slice
)
2180 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, NULL
);
2181 (void)recursive_rmdir(path
);
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
2192 static bool cgv1_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2194 struct cgv1_hierarchy
**it
, **rev_it
;
2195 bool all_created
= true;
2197 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2198 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2199 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2202 if (!cgv1_create_one(*it
, cgroup
, uid
, gid
, existed
)) {
2203 all_created
= false;
2211 for (rev_it
= cgv1_hierarchies
; rev_it
&& *rev_it
&& (*rev_it
!= *it
);
2213 cgv1_remove_one(*rev_it
, cgroup
);
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.
2221 static bool cgv2_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2224 char *clean_base_cgroup
;
2226 struct cgv2_hierarchy
*v2
;
2227 bool our_cg
= false, created
= false;
2231 if (!cgv2_hierarchies
|| !(*cgv2_hierarchies
)->create_rw_cgroup
)
2234 v2
= *cgv2_hierarchies
;
2236 /* We can't be placed under init's cgroup for the v2 hierarchy. We need
2237 * to be placed under our current cgroup.
2239 if (cg_systemd_chown_existing_cgroup(v2
->mountpoint
, v2
->base_cgroup
,
2240 uid
, gid
, v2
->systemd_user_slice
))
2241 goto delegate_files
;
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
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("/");
2252 clean_base_cgroup
= strstr(v2
->base_cgroup
, __PAM_CGFS_USER
);
2253 if (clean_base_cgroup
)
2254 *clean_base_cgroup
= '\0';
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
);
2262 "%s existed and does %shave our uid: %d and gid: %d.\n",
2263 path
, our_cg
? "" : "not ", uid
, gid
);
2267 goto delegate_files
;
2274 created
= mkdir_parent(v2
->mountpoint
, path
);
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
);
2285 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
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
);
2294 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2295 "/cgroup.procs", NULL
);
2296 ret
= chown(path
, uid
, gid
);
2298 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2299 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2301 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
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
);
2309 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2310 "/cgroup.subtree_control", NULL
);
2311 ret
= chown(path
, uid
, gid
);
2313 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2314 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
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
);
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
);
2333 /* Create writeable cgroups for @user at login. Details can be found in the
2334 * preamble/license at the top of this file.
2336 static int handle_login(const char *user
, uid_t uid
, gid_t gid
)
2340 char cg
[MAXPATHLEN
];
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
;
2352 if (!cgv2_create(cg
, uid
, gid
, &existed
)) {
2358 mysyslog(LOG_ERR
, "Failed to create a cgroup for user %s.\n", user
, NULL
);
2359 return PAM_SESSION_ERR
;
2363 if (!cgv1_create(cg
, uid
, gid
, &existed
)) {
2369 mysyslog(LOG_ERR
, "Failed to create a cgroup for user %s.\n", user
, NULL
);
2370 return PAM_SESSION_ERR
;
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
;
2383 /* Try to prune cgroups we created and that now are empty from all cgroupfs v1
2386 static bool cgv1_prune_empty_cgroups(const char *user
)
2388 bool controller_removed
= true;
2389 bool all_removed
= true;
2390 struct cgv1_hierarchy
**it
;
2392 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2394 char *path_base
, *path_init
;
2397 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2398 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2401 for (controller
= (*it
)->controllers
; controller
&& *controller
;
2403 bool path_base_rm
, path_init_rm
;
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;
2411 path_base_rm
= false;
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;
2420 path_init_rm
= false;
2423 if (!path_base_rm
&& !path_init_rm
) {
2424 controller_removed
= false;
2428 controller_removed
= true;
2431 if (!controller_removed
)
2432 all_removed
= false;
2438 /* Try to prune cgroup we created and that now is empty from the cgroupfs v2
2441 static bool cgv2_prune_empty_cgroups(const char *user
)
2444 struct cgv2_hierarchy
*v2
;
2445 char *path_base
, *path_init
;
2446 bool path_base_rm
, path_init_rm
;
2448 if (!cgv2_hierarchies
)
2451 v2
= *cgv2_hierarchies
;
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;
2459 path_base_rm
= false;
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;
2468 path_init_rm
= false;
2471 if (!path_base_rm
&& !path_init_rm
)
2477 /* Wrapper around cgv{1,2}_prune_empty_cgroups(). */
2478 static void cg_prune_empty_cgroups(const char *user
)
2480 (void)cgv1_prune_empty_cgroups(user
);
2481 (void)cgv2_prune_empty_cgroups(user
);
2484 /* Free allocated information for detected cgroupfs v1 hierarchies. */
2485 static void cgv1_free_hierarchies(void)
2487 struct cgv1_hierarchy
**it
;
2489 if (!cgv1_hierarchies
)
2492 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2493 if ((*it
)->controllers
) {
2495 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2498 free((*it
)->controllers
);
2500 free((*it
)->mountpoint
);
2501 free((*it
)->base_cgroup
);
2502 free((*it
)->fullcgpath
);
2503 free((*it
)->init_cgroup
);
2505 free(cgv1_hierarchies
);
2508 /* Free allocated information for the detected cgroupfs v2 hierarchy. */
2509 static void cgv2_free_hierarchies(void)
2511 struct cgv2_hierarchy
**it
;
2513 if (!cgv2_hierarchies
)
2516 for (it
= cgv2_hierarchies
; it
&& *it
; it
++) {
2517 if ((*it
)->controllers
) {
2519 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2522 free((*it
)->controllers
);
2524 free((*it
)->mountpoint
);
2525 free((*it
)->base_cgroup
);
2526 free((*it
)->fullcgpath
);
2527 free((*it
)->init_cgroup
);
2529 free(cgv2_hierarchies
);
2532 /* Wrapper around cgv{1,2}_free_hierarchies(). */
2533 static void cg_exit(void)
2535 cgv1_free_hierarchies();
2536 cgv2_free_hierarchies();
2539 int pam_sm_open_session(pam_handle_t
*pamh
, int flags
, int argc
,
2545 const char *PAM_user
= NULL
;
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
;
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
;
2558 if (!cg_init(uid
, gid
)) {
2559 mysyslog(LOG_ERR
, "Failed to get list of controllers\n", NULL
);
2560 return PAM_SESSION_ERR
;
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.
2566 cg_prune_empty_cgroups(PAM_user
);
2568 if (cg_mount_mode
== CGROUP_UNKNOWN
)
2569 return PAM_SESSION_ERR
;
2571 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2572 char **clist
= make_string_list(argv
[1], ",");
2575 * We don't allow using "all" and other controllers explicitly because
2576 * that simply doesn't make any sense.
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
;
2584 cg_mark_to_make_rw(clist
);
2585 free_string_list(clist
);
2588 return handle_login(PAM_user
, uid
, gid
);
2591 int pam_sm_close_session(pam_handle_t
*pamh
, int flags
, int argc
,
2597 const char *PAM_user
= NULL
;
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
;
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
;
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
);
2614 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2615 char **clist
= make_string_list(argv
[1], ",");
2618 * We don't allow using "all" and other controllers explicitly because
2619 * that simply doesn't make any sense.
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
;
2627 cg_mark_to_make_rw(clist
);
2628 free_string_list(clist
);
2632 cg_prune_empty_cgroups(PAM_user
);