]>
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)) {
787 /* Append kernel controller in @klist or named controller in @nlist to @clist */
788 static void must_append_controller(char **klist
, char **nlist
, char ***clist
, char *entry
)
793 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
))
796 newentry
= append_null_to_list((void ***)clist
);
798 if (strncmp(entry
, "name=", 5) == 0)
799 copy
= must_copy_string(entry
);
800 else if (string_in_list(klist
, entry
))
801 copy
= must_copy_string(entry
);
803 copy
= cgv1_must_prefix_named(entry
);
805 (*clist
)[newentry
] = copy
;
808 /* Get the controllers from a mountinfo line. There are other ways we could get
809 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
810 * could parse the mount options. But we simply assume that the mountpoint must
811 * be /sys/fs/cgroup/controller-list
813 static char **cgv1_get_proc_mountinfo_controllers(char **klist
, char **nlist
, char *line
)
817 char *saveptr
= NULL
;
822 for (i
= 0; i
< 4; i
++) {
831 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
841 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
842 tok
= strtok_r(NULL
, ",", &saveptr
))
843 must_append_controller(klist
, nlist
, &aret
, tok
);
848 /* Check if a cgroupfs v2 controller is present in the string @cgline. */
849 static bool cgv1_controller_in_clist(char *cgline
, char *c
)
852 char *tok
, *eol
, *tmp
;
853 char *saveptr
= NULL
;
855 eol
= strchr(cgline
, ':');
860 tmp
= alloca(len
+ 1);
861 memcpy(tmp
, cgline
, len
);
864 for (tok
= strtok_r(tmp
, ",", &saveptr
); tok
;
865 tok
= strtok_r(NULL
, ",", &saveptr
)) {
866 if (strcmp(tok
, c
) == 0)
872 /* Get current cgroup from the /proc/<pid>/cgroup file passed in via @basecginfo
873 * of a given cgv1 controller passed in via @controller.
875 static char *cgv1_get_current_cgroup(char *basecginfo
, char *controller
)
887 if (cgv1_controller_in_clist(p
, controller
)) {
893 return copy_to_eol(p
);
905 /* Remove /init.scope from string @cg. This will mostly affect systemd-based
908 #define INIT_SCOPE "/init.scope"
909 static void cg_systemd_prune_init_scope(char *cg
)
916 point
= cg
+ strlen(cg
) - strlen(INIT_SCOPE
);
920 if (strcmp(point
, INIT_SCOPE
) == 0) {
928 /* Add new info about a mounted cgroupfs v1 hierarchy. Includes the controllers
929 * mounted into that hierarchy (e.g. cpu,cpuacct), the mountpoint of that
930 * hierarchy (/sys/fs/cgroup/<controller>, the base cgroup of the current
931 * process gathered from /proc/self/cgroup, and the init cgroup of PID1 gathered
932 * from /proc/1/cgroup.
934 static void cgv1_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
)
936 struct cgv1_hierarchy
*new;
939 new = must_alloc(sizeof(*new));
940 new->controllers
= clist
;
941 new->mountpoint
= mountpoint
;
942 new->base_cgroup
= base_cgroup
;
943 new->fullcgpath
= NULL
;
944 new->create_rw_cgroup
= false;
945 new->init_cgroup
= init_cgroup
;
946 new->systemd_user_slice
= false;
948 newentry
= append_null_to_list((void ***)&cgv1_hierarchies
);
949 cgv1_hierarchies
[newentry
] = new;
952 /* Add new info about the mounted cgroupfs v2 hierarchy. Can (but doesn't
953 * currently) include the controllers mounted into the hierarchy (e.g. memory,
954 * pids, blkio), the mountpoint of that hierarchy (Should usually be
955 * /sys/fs/cgroup but some init systems seems to think it might be a good idea
956 * to also mount empty cgroupfs v2 hierarchies at /sys/fs/cgroup/systemd.), the
957 * base cgroup of the current process gathered from /proc/self/cgroup, and the
958 * init cgroup of PID1 gathered from /proc/1/cgroup.
960 static void cgv2_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
, bool systemd_user_slice
)
962 struct cgv2_hierarchy
*new;
965 new = must_alloc(sizeof(*new));
966 new->controllers
= clist
;
967 new->mountpoint
= mountpoint
;
968 new->base_cgroup
= base_cgroup
;
969 new->fullcgpath
= NULL
;
970 new->create_rw_cgroup
= false;
971 new->init_cgroup
= init_cgroup
;
972 new->systemd_user_slice
= systemd_user_slice
;
974 newentry
= append_null_to_list((void ***)&cgv2_hierarchies
);
975 cgv2_hierarchies
[newentry
] = new;
978 /* In Ubuntu 14.04, the paths created for us were
979 * '/user/$uid.user/$something.session' This can be merged better with
980 * systemd_created_slice_for_us(), but keeping it separate makes it easier to
981 * reason about the correctness.
983 static bool cg_systemd_under_user_slice_1(const char *in
, uid_t uid
)
991 copy
= must_copy_string(in
);
992 if (strlen(copy
) < strlen("/user/1.user/1.session"))
994 p
= copy
+ strlen(copy
) - 1;
996 /* skip any trailing '/' (shouldn't be any, but be sure) */
997 while (p
>= copy
&& *p
== '/')
1002 /* Get last path element */
1003 while (p
>= copy
&& *p
!= '/')
1007 /* make sure it is something.session */
1008 len
= strlen(p
+ 1);
1009 if (len
< strlen("1.session") ||
1010 strncmp(p
+ 1 + len
- 8, ".session", 8) != 0)
1013 /* ok last path piece checks out, now check the second to last */
1015 while (p
>= copy
&& *(--p
) != '/')
1017 if (sscanf(p
+ 1, "%d.user/", &id
) != 1)
1030 /* So long as our path relative to init starts with /user.slice/user-$uid.slice,
1031 * assume it belongs to $uid and chown it
1033 static bool cg_systemd_under_user_slice_2(const char *base_cgroup
,
1034 const char *init_cgroup
, uid_t uid
)
1038 size_t curlen
, initlen
;
1040 curlen
= strlen(base_cgroup
);
1041 initlen
= strlen(init_cgroup
);
1042 if (curlen
<= initlen
)
1045 if (strncmp(base_cgroup
, init_cgroup
, initlen
) != 0)
1048 ret
= snprintf(buf
, 100, "/user.slice/user-%d.slice/", (int)uid
);
1049 if (ret
< 0 || ret
>= 100)
1053 initlen
= 0; // skip the '/'
1055 return strncmp(base_cgroup
+ initlen
, buf
, strlen(buf
)) == 0;
1058 /* The systemd-created path is: user-$uid.slice/session-c$session.scope. If that
1059 * is not the end of our systemd path, then we're not part of the PAM call that
1060 * created that path.
1062 * The last piece is chowned to $uid, the user- part not.
1063 * Note: If the user creates paths that look like what we're looking for to
1065 * - they fool us, we create new cgroups, and they get auto-logged-out.
1066 * - they fool a root sudo, systemd cgroup is not changed but chowned, and they
1067 * lose ownership of their cgroups
1069 static bool cg_systemd_created_user_slice(const char *base_cgroup
,
1070 const char *init_cgroup
,
1071 const char *in
, uid_t uid
)
1079 copy
= must_copy_string(in
);
1081 /* An old version of systemd has already created a cgroup for us. */
1082 if (cg_systemd_under_user_slice_1(in
, uid
))
1085 /* A new version of systemd has already created a cgroup for us. */
1086 if (cg_systemd_under_user_slice_2(base_cgroup
, init_cgroup
, uid
))
1089 if (strlen(copy
) < strlen("/user-0.slice/session-0.scope"))
1092 p
= copy
+ strlen(copy
) - 1;
1093 /* Skip any trailing '/' (shouldn't be any, but be sure). */
1094 while (p
>= copy
&& *p
== '/')
1100 /* Get last path element */
1101 while (p
>= copy
&& *p
!= '/')
1107 /* Make sure it is session-something.scope. */
1108 len
= strlen(p
+ 1);
1109 if (strncmp(p
+ 1, "session-", strlen("session-")) != 0 ||
1110 strncmp(p
+ 1 + len
- 6, ".scope", 6) != 0)
1113 /* Ok last path piece checks out, now check the second to last. */
1115 while (p
>= copy
&& *(--p
) != '/')
1118 if (sscanf(p
+ 1, "user-%d.slice/", &id
) != 1)
1131 /* Chown existing cgroup that systemd has already created for us. */
1132 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint
,
1133 const char *base_cgroup
, uid_t uid
,
1134 gid_t gid
, bool systemd_user_slice
)
1138 if (!systemd_user_slice
)
1141 path
= must_make_path(mountpoint
, base_cgroup
, NULL
);
1143 /* A cgroup within name=systemd has already been created. So we only
1146 if (chown(path
, uid
, gid
) < 0)
1147 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
1148 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
1149 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
1155 /* Detect and store information about cgroupfs v1 hierarchies. */
1156 static bool cgv1_init(uid_t uid
, gid_t gid
)
1159 struct cgv1_hierarchy
**it
;
1162 char **klist
= NULL
, **nlist
= NULL
;
1165 basecginfo
= read_file("/proc/self/cgroup");
1169 f
= fopen("/proc/self/mountinfo", "r");
1175 cgv1_get_controllers(&klist
, &nlist
);
1177 while (getline(&line
, &len
, f
) != -1) {
1178 char **controller_list
= NULL
;
1179 char *mountpoint
, *base_cgroup
;
1181 if (is_lxcfs(line
) || !is_cgv1(line
))
1184 controller_list
= cgv1_get_proc_mountinfo_controllers(klist
, nlist
, line
);
1185 if (!controller_list
)
1188 if (cgv1_controller_list_is_dup(cgv1_hierarchies
, controller_list
)) {
1189 free(controller_list
);
1193 mountpoint
= get_mountpoint(line
);
1195 free_string_list(controller_list
);
1199 base_cgroup
= cgv1_get_current_cgroup(basecginfo
, controller_list
[0]);
1201 free_string_list(controller_list
);
1207 pam_cgfs_debug("Detected cgroupfs v1 controller \"%s\" with "
1208 "mountpoint \"%s\" and cgroup \"%s\"\n",
1209 controller_list
[0], mountpoint
, base_cgroup
);
1210 cgv1_add_controller(controller_list
, mountpoint
, base_cgroup
, NULL
);
1213 free_string_list(klist
);
1214 free_string_list(nlist
);
1219 /* Retrieve init cgroup path for all controllers. */
1220 basecginfo
= read_file("/proc/1/cgroup");
1224 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
1225 if ((*it
)->controllers
) {
1226 char *init_cgroup
, *user_slice
;
1228 /* We've already stored the controller and received its
1229 * current cgroup. If we now fail to retrieve its init
1230 * cgroup, we should probably fail.
1232 init_cgroup
= cgv1_get_current_cgroup(basecginfo
, (*it
)->controllers
[0]);
1238 cg_systemd_prune_init_scope(init_cgroup
);
1239 (*it
)->init_cgroup
= init_cgroup
;
1240 pam_cgfs_debug("cgroupfs v1 controller \"%s\" has init "
1242 (*(*it
)->controllers
), init_cgroup
);
1243 /* Check whether systemd has already created a cgroup
1246 user_slice
= must_make_path((*it
)->mountpoint
, (*it
)->base_cgroup
, NULL
);
1247 if (cg_systemd_created_user_slice((*it
)->base_cgroup
, (*it
)->init_cgroup
, user_slice
, uid
))
1248 (*it
)->systemd_user_slice
= true;
1258 /* Check whether @path is a cgroupfs v1 or cgroupfs v2 mount. Returns -1 if
1259 * statfs fails. If @path is null /sys/fs/cgroup is checked.
1261 static inline int cg_get_version_of_mntpt(const char *path
)
1263 if (has_fs_type(path
, CGROUP_SUPER_MAGIC
))
1266 if (has_fs_type(path
, CGROUP2_SUPER_MAGIC
))
1272 /* Detect and store information about the cgroupfs v2 hierarchy. Currently only
1273 * deals with the empty v2 hierachy as we do not retrieve enabled controllers.
1275 static bool cgv2_init(uid_t uid
, gid_t gid
)
1279 char *current_cgroup
= NULL
, *init_cgroup
= NULL
;
1284 current_cgroup
= cgv2_get_current_cgroup(getpid());
1285 if (!current_cgroup
) {
1286 /* No v2 hierarchy present. We're done. */
1291 init_cgroup
= cgv2_get_current_cgroup(1);
1293 /* If we're here and didn't fail already above, then something's
1294 * certainly wrong, so error this time.
1299 cg_systemd_prune_init_scope(init_cgroup
);
1301 /* Check if the v2 hierarchy is mounted at its standard location.
1302 * If so we can skip the rest of the work here. Although the unified
1303 * hierarchy can be mounted multiple times, each of those mountpoints
1304 * will expose identical information.
1306 if (cg_get_version_of_mntpt("/sys/fs/cgroup") == 2) {
1308 bool has_user_slice
= false;
1310 mountpoint
= must_copy_string("/sys/fs/cgroup");
1314 user_slice
= must_make_path(mountpoint
, current_cgroup
, NULL
);
1315 if (cg_systemd_created_user_slice(current_cgroup
, init_cgroup
, user_slice
, uid
))
1316 has_user_slice
= true;
1319 cgv2_add_controller(NULL
, mountpoint
, current_cgroup
, init_cgroup
, has_user_slice
);
1325 f
= fopen("/proc/self/mountinfo", "r");
1329 /* we support simple cgroup mounts and lxcfs mounts */
1330 while (getline(&line
, &len
, f
) != -1) {
1332 bool has_user_slice
= false;
1337 mountpoint
= get_mountpoint(line
);
1341 user_slice
= must_make_path(mountpoint
, current_cgroup
, NULL
);
1342 if (cg_systemd_created_user_slice(current_cgroup
, init_cgroup
, user_slice
, uid
))
1343 has_user_slice
= true;
1346 cgv2_add_controller(NULL
, mountpoint
, current_cgroup
, init_cgroup
, has_user_slice
);
1348 /* Although the unified hierarchy can be mounted multiple times,
1349 * each of those mountpoints will expose identical information.
1350 * So let the first mountpoint we find, win.
1356 pam_cgfs_debug("Detected cgroupfs v2 hierarchy at mountpoint \"%s\" with "
1357 "current cgroup \"%s\" and init cgroup \"%s\"\n",
1358 mountpoint
, current_cgroup
, init_cgroup
);
1367 free(current_cgroup
);
1373 /* Detect and store information about mounted cgroupfs v1 hierarchies and the
1374 * cgroupfs v2 hierarchy.
1375 * Detect whether we are on a pure cgroupfs v1, cgroupfs v2, or mixed system,
1376 * where some controllers are mounted into their standard cgroupfs v1 locations
1377 * (/sys/fs/cgroup/<controller>) and others are mounted into the cgroupfs v2
1378 * hierarchy (/sys/fs/cgroup).
1380 static bool cg_init(uid_t uid
, gid_t gid
)
1382 if (!cgv1_init(uid
, gid
))
1385 if (!cgv2_init(uid
, gid
))
1388 if (cgv1_hierarchies
&& cgv2_hierarchies
) {
1389 cg_mount_mode
= CGROUP_MIXED
;
1390 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 and v2 hierarchies.");
1391 } else if (cgv1_hierarchies
&& !cgv2_hierarchies
) {
1392 cg_mount_mode
= CGROUP_PURE_V1
;
1393 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 hierarchies.");
1394 } else if (cgv2_hierarchies
&& !cgv1_hierarchies
) {
1395 cg_mount_mode
= CGROUP_PURE_V2
;
1396 pam_cgfs_debug("%s\n", "Detected cgroupfs v2 hierarchies.");
1398 cg_mount_mode
= CGROUP_UNKNOWN
;
1399 mysyslog(LOG_ERR
, "Could not detect cgroupfs hierarchy.\n", NULL
);
1402 if (cg_mount_mode
== CGROUP_UNKNOWN
)
1408 /* Try to move/migrate us into @cgroup in a cgroupfs v1 hierarchy. */
1409 static bool cgv1_enter(const char *cgroup
)
1411 struct cgv1_hierarchy
**it
;
1413 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
1415 bool entered
= false;
1417 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
1418 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
1421 for (controller
= (*it
)->controllers
; controller
&& *controller
;
1425 /* We've already been placed in a user slice, so we
1426 * don't need to enter the cgroup again.
1428 if ((*it
)->systemd_user_slice
) {
1433 path
= must_make_path((*it
)->mountpoint
,
1438 if (!file_exists(path
)) {
1440 path
= must_make_path((*it
)->mountpoint
,
1446 pam_cgfs_debug("Attempting to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1447 entered
= write_int(path
, (int)getpid());
1452 pam_cgfs_debug("Failed to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1462 /* Try to move/migrate us into @cgroup in the cgroupfs v2 hierarchy. */
1463 static bool cgv2_enter(const char *cgroup
)
1465 struct cgv2_hierarchy
*v2
;
1467 bool entered
= false;
1469 if (!cgv2_hierarchies
)
1472 v2
= *cgv2_hierarchies
;
1474 if (!v2
->mountpoint
|| !v2
->base_cgroup
)
1477 if (!v2
->create_rw_cgroup
|| v2
->systemd_user_slice
)
1480 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, "/cgroup.procs", NULL
);
1481 pam_cgfs_debug("Attempting to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path
);
1482 entered
= write_int(path
, (int)getpid());
1484 pam_cgfs_debug("Failed to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path
);
1494 /* Wrapper around cgv{1,2}_enter(). */
1495 static bool cg_enter(const char *cgroup
)
1497 if (!cgv1_enter(cgroup
)) {
1498 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to enter cgroups.\n", NULL
);
1502 if (!cgv2_enter(cgroup
)) {
1503 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to enter cgroups.\n", NULL
);
1510 /* Escape to root cgroup in all detected cgroupfs v1 hierarchies. */
1511 static void cgv1_escape(void)
1513 struct cgv1_hierarchy
**it
;
1515 /* In case systemd hasn't already placed us in a user slice for the
1516 * cpuset v1 controller we will reside in the root cgroup. This means
1517 * that cgroup.clone_children will not have been initialized for us so
1520 for (it
= cgv1_hierarchies
; it
&& *it
; it
++)
1521 if (!cgv1_handle_root_cpuset_hierarchy(*it
))
1522 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to initialize cpuset.\n", NULL
);
1524 if (!cgv1_enter("/"))
1525 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to escape to init's cgroup.\n", NULL
);
1528 /* Escape to root cgroup in the cgroupfs v2 hierarchy. */
1529 static void cgv2_escape(void)
1531 if (!cgv2_enter("/"))
1532 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to escape to init's cgroup.\n", NULL
);
1535 /* Wrapper around cgv{1,2}_escape(). */
1536 static void cg_escape(void)
1542 /* Get uid and gid for @user. */
1543 static bool get_uid_gid(const char *user
, uid_t
*uid
, gid_t
*gid
)
1545 struct passwd pwent
;
1546 struct passwd
*pwentp
= NULL
;
1551 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1555 buf
= malloc(bufsize
);
1559 ret
= getpwnam_r(user
, &pwent
, buf
, bufsize
, &pwentp
);
1563 "Could not find matched password record\n", NULL
);
1569 *uid
= pwent
.pw_uid
;
1570 *gid
= pwent
.pw_gid
;
1576 /* Check if cgroup belongs to our uid and gid. If so, reuse it. */
1577 static bool cg_belongs_to_uid_gid(const char *path
, uid_t uid
, gid_t gid
)
1579 struct stat statbuf
;
1581 if (stat(path
, &statbuf
) < 0)
1584 if (!(statbuf
.st_uid
== uid
) || !(statbuf
.st_gid
== gid
))
1590 /* Create cpumask from cpulist aka turn:
1598 static uint32_t *cg_cpumask(char *buf
, size_t nbits
)
1601 char *saveptr
= NULL
;
1602 size_t arrlen
= BITS_TO_LONGS(nbits
);
1603 uint32_t *bitarr
= calloc(arrlen
, sizeof(uint32_t));
1607 for (; (token
= strtok_r(buf
, ",", &saveptr
)); buf
= NULL
) {
1609 unsigned start
= strtoul(token
, NULL
, 0);
1610 unsigned end
= start
;
1612 char *range
= strchr(token
, '-');
1614 end
= strtoul(range
+ 1, NULL
, 0);
1615 if (!(start
<= end
)) {
1625 while (start
<= end
)
1626 set_bit(start
++, bitarr
);
1632 static char *string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
1636 size_t sep_len
= strlen(sep
);
1637 size_t result_len
= use_as_prefix
* sep_len
;
1643 /* calculate new string length */
1644 for (p
= (char **)parts
; *p
; p
++)
1645 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
1647 buf_len
= result_len
+ 1;
1648 result
= calloc(buf_len
, sizeof(char));
1653 (void)strlcpy(result
, sep
, buf_len
* sizeof(char));
1655 for (p
= (char **)parts
; *p
; p
++) {
1656 if (p
> (char **)parts
)
1657 (void)strlcat(result
, sep
, buf_len
* sizeof(char));
1658 (void)strlcat(result
, *p
, buf_len
* sizeof(char));
1664 /* The largest integer that can fit into long int is 2^64. This is a
1667 #define __IN_TO_STR_LEN 21
1668 /* Turn cpumask into simple, comma-separated cpulist. */
1669 static char *cg_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
1673 char numstr
[__IN_TO_STR_LEN
] = {0};
1674 char **cpulist
= NULL
;
1676 for (i
= 0; i
<= nbits
; i
++) {
1677 if (is_set(i
, bitarr
)) {
1678 ret
= snprintf(numstr
, __IN_TO_STR_LEN
, "%zu", i
);
1679 if (ret
< 0 || (size_t)ret
>= __IN_TO_STR_LEN
) {
1680 free_string_list(cpulist
);
1683 must_append_string(&cpulist
, numstr
);
1686 return string_join(",", (const char **)cpulist
, false);
1689 static ssize_t
cg_get_max_cpus(char *cpulist
)
1692 char *maxcpus
= cpulist
;
1695 c1
= strrchr(maxcpus
, ',');
1699 c2
= strrchr(maxcpus
, '-');
1708 /* If the above logic is correct, c1 should always hold a valid string
1713 cpus
= strtoul(c1
, NULL
, 0);
1720 static ssize_t
write_nointr(int fd
, const void* buf
, size_t count
)
1724 ret
= write(fd
, buf
, count
);
1725 if (ret
< 0 && errno
== EINTR
)
1730 static int write_to_file(const char *filename
, const void* buf
, size_t count
, bool add_newline
)
1732 int fd
, saved_errno
;
1735 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, 0666);
1738 ret
= write_nointr(fd
, buf
, count
);
1741 if ((size_t)ret
!= count
)
1744 ret
= write_nointr(fd
, "\n", 1);
1752 saved_errno
= errno
;
1754 errno
= saved_errno
;
1758 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
1759 static bool cg_filter_and_set_cpus(char *path
, bool am_initialized
)
1761 char *lastslash
, *fpath
, oldv
;
1765 ssize_t maxposs
= 0, maxisol
= 0;
1766 char *cpulist
= NULL
, *posscpus
= NULL
, *isolcpus
= NULL
;
1767 uint32_t *possmask
= NULL
, *isolmask
= NULL
;
1768 bool bret
= false, flipped_bit
= false;
1770 lastslash
= strrchr(path
, '/');
1771 if (!lastslash
) { // bug... this shouldn't be possible
1772 pam_cgfs_debug("Invalid path: %s.\n", path
);
1777 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1778 posscpus
= read_file(fpath
);
1780 pam_cgfs_debug("Could not read file: %s.\n", fpath
);
1784 /* Get maximum number of cpus found in possible cpuset. */
1785 maxposs
= cg_get_max_cpus(posscpus
);
1789 if (!file_exists(__ISOL_CPUS
)) {
1790 /* This system doesn't expose isolated cpus. */
1791 pam_cgfs_debug("%s", "Path: "__ISOL_CPUS
" to read isolated cpus from does not exist.\n");
1793 /* No isolated cpus but we weren't already initialized by
1794 * someone. We should simply copy the parents cpuset.cpus
1797 if (!am_initialized
) {
1798 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1801 /* No isolated cpus but we were already initialized by someone.
1802 * Nothing more to do for us.
1807 isolcpus
= read_file(__ISOL_CPUS
);
1809 pam_cgfs_debug("%s", "Could not read file "__ISOL_CPUS
"\n");
1812 if (!isdigit(isolcpus
[0])) {
1813 pam_cgfs_debug("%s", "No isolated cpus detected.\n");
1815 /* No isolated cpus but we weren't already initialized by
1816 * someone. We should simply copy the parents cpuset.cpus
1819 if (!am_initialized
) {
1820 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1823 /* No isolated cpus but we were already initialized by someone.
1824 * Nothing more to do for us.
1829 /* Get maximum number of cpus found in isolated cpuset. */
1830 maxisol
= cg_get_max_cpus(isolcpus
);
1834 if (maxposs
< maxisol
)
1838 possmask
= cg_cpumask(posscpus
, maxposs
);
1840 pam_cgfs_debug("%s", "Could not create cpumask for all possible cpus.\n");
1844 isolmask
= cg_cpumask(isolcpus
, maxposs
);
1846 pam_cgfs_debug("%s", "Could not create cpumask for all isolated cpus.\n");
1850 for (i
= 0; i
<= maxposs
; i
++) {
1851 if (is_set(i
, isolmask
) && is_set(i
, possmask
)) {
1853 clear_bit(i
, possmask
);
1858 pam_cgfs_debug("%s", "No isolated cpus present in cpuset.\n");
1861 pam_cgfs_debug("%s", "Removed isolated cpus from cpuset.\n");
1863 cpulist
= cg_cpumask_to_cpulist(possmask
, maxposs
);
1865 pam_cgfs_debug("%s", "Could not create cpu list.\n");
1871 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1872 ret
= write_to_file(fpath
, cpulist
, strlen(cpulist
), false);
1874 pam_cgfs_debug("Could not write cpu list to: %s.\n", fpath
);
1887 if (posscpus
!= cpulist
)
1895 int read_from_file(const char *filename
, void* buf
, size_t count
)
1897 int fd
= -1, saved_errno
;
1900 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1904 if (!buf
|| !count
) {
1907 while ((ret
= read(fd
, buf2
, 100)) > 0)
1912 memset(buf
, 0, count
);
1913 ret
= read(fd
, buf
, count
);
1917 pam_cgfs_debug("read %s: %s", filename
, strerror(errno
));
1919 saved_errno
= errno
;
1921 errno
= saved_errno
;
1925 /* Copy contents of parent(@path)/@file to @path/@file */
1926 static bool cg_copy_parent_file(char *path
, char *file
)
1928 char *lastslash
, *value
= NULL
, *fpath
, oldv
;
1932 lastslash
= strrchr(path
, '/');
1933 if (!lastslash
) { // bug... this shouldn't be possible
1934 pam_cgfs_debug("cgfsng:copy_parent_file: bad path %s", path
);
1939 fpath
= must_make_path(path
, file
, NULL
);
1940 len
= read_from_file(fpath
, NULL
, 0);
1943 value
= must_alloc(len
+ 1);
1944 if (read_from_file(fpath
, value
, len
) != len
)
1948 fpath
= must_make_path(path
, file
, NULL
);
1949 ret
= write_to_file(fpath
, value
, len
, false);
1951 pam_cgfs_debug("Unable to write %s to %s", value
, fpath
);
1957 pam_cgfs_debug("Error reading '%s'", fpath
);
1963 /* In case systemd hasn't already placed us in a user slice for the cpuset v1
1964 * controller we will reside in the root cgroup. This means that
1965 * cgroup.clone_children will not have been initialized for us so we need to do
1968 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy
*h
)
1970 char *clonechildrenpath
, v
;
1972 if (!string_in_list(h
->controllers
, "cpuset"))
1975 clonechildrenpath
= must_make_path(h
->mountpoint
, "cgroup.clone_children", NULL
);
1977 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
1978 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
1979 free(clonechildrenpath
);
1983 if (v
== '1') { /* already set for us by someone else */
1984 free(clonechildrenpath
);
1988 if (write_to_file(clonechildrenpath
, "1", 1, false) < 0) {
1989 /* Set clone_children so children inherit our settings */
1990 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath
);
1991 free(clonechildrenpath
);
1994 free(clonechildrenpath
);
1999 * Initialize the cpuset hierarchy in first directory of @gname and
2000 * set cgroup.clone_children so that children inherit settings.
2001 * Since the h->base_path is populated by init or ourselves, we know
2002 * it is already initialized.
2004 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy
*h
,
2007 char *cgpath
, *clonechildrenpath
, v
, *slash
;
2009 if (!string_in_list(h
->controllers
, "cpuset"))
2014 slash
= strchr(cgroup
, '/');
2018 cgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgroup
, NULL
);
2021 if (do_mkdir(cgpath
, 0755) < 0 && errno
!= EEXIST
) {
2022 pam_cgfs_debug("Failed to create '%s'", cgpath
);
2026 clonechildrenpath
= must_make_path(cgpath
, "cgroup.clone_children", NULL
);
2027 if (!file_exists(clonechildrenpath
)) { /* unified hierarchy doesn't have clone_children */
2028 free(clonechildrenpath
);
2032 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
2033 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
2034 free(clonechildrenpath
);
2039 /* Make sure any isolated cpus are removed from cpuset.cpus. */
2040 if (!cg_filter_and_set_cpus(cgpath
, v
== '1')) {
2041 pam_cgfs_debug("%s", "Failed to remove isolated cpus.\n");
2042 free(clonechildrenpath
);
2047 if (v
== '1') { /* already set for us by someone else */
2048 pam_cgfs_debug("%s", "\"cgroup.clone_children\" was already set to \"1\".\n");
2049 free(clonechildrenpath
);
2054 /* copy parent's settings */
2055 if (!cg_copy_parent_file(cgpath
, "cpuset.mems")) {
2056 pam_cgfs_debug("%s", "Failed to copy \"cpuset.mems\" settings.\n");
2058 free(clonechildrenpath
);
2063 if (write_to_file(clonechildrenpath
, "1", 1, false) < 0) {
2064 /* Set clone_children so children inherit our settings */
2065 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath
);
2066 free(clonechildrenpath
);
2069 free(clonechildrenpath
);
2073 /* Create and chown @cgroup for all given controllers in a cgroupfs v1 hierarchy
2074 * (For example, create @cgroup for the cpu and cpuacct controller mounted into
2075 * /sys/fs/cgroup/cpu,cpuacct). Check if the path already exists and report back
2076 * to the caller in @existed.
2078 #define __PAM_CGFS_USER "/user/"
2079 #define __PAM_CGFS_USER_LEN 6
2080 static bool cgv1_create_one(struct cgv1_hierarchy
*h
, const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2082 char *clean_base_cgroup
, *path
;
2084 struct cgv1_hierarchy
*it
;
2085 bool created
= false;
2089 for (controller
= it
->controllers
; controller
&& *controller
;
2091 if (!cgv1_handle_cpuset_hierarchy(it
, cgroup
))
2094 /* If systemd has already created a cgroup for us, keep using
2097 if (cg_systemd_chown_existing_cgroup(it
->mountpoint
,
2098 it
->base_cgroup
, uid
, gid
,
2099 it
->systemd_user_slice
)) {
2103 /* We need to make sure that we do not create an endless chain
2104 * of sub-cgroups. So we check if we have already logged in
2105 * somehow (sudo -i, su, etc.) and have created a
2106 * /user/PAM_user/idx cgroup. If so, we skip that part. For most
2107 * cgroups this is unnecessary since we use the init_cgroup
2108 * anyway, but for controllers which have an existing systemd
2109 * cgroup that does not match the current uid, this is pretty
2112 if (strncmp(it
->base_cgroup
, __PAM_CGFS_USER
, __PAM_CGFS_USER_LEN
) == 0) {
2113 free(it
->base_cgroup
);
2114 it
->base_cgroup
= must_copy_string("/");
2117 strstr(it
->base_cgroup
, __PAM_CGFS_USER
);
2118 if (clean_base_cgroup
)
2119 *clean_base_cgroup
= '\0';
2122 path
= must_make_path(it
->mountpoint
, it
->init_cgroup
, cgroup
, NULL
);
2123 pam_cgfs_debug("Constructing path: %s.\n", path
);
2124 if (file_exists(path
)) {
2125 bool our_cg
= cg_belongs_to_uid_gid(path
, uid
, gid
);
2126 pam_cgfs_debug("%s existed and does %shave our uid: %d and gid: %d.\n", path
, our_cg
? "" : "not ", uid
, gid
);
2134 created
= mkdir_parent(it
->mountpoint
, path
);
2139 if (chown(path
, uid
, gid
) < 0)
2140 mysyslog(LOG_WARNING
,
2141 "Failed to chown %s to %d:%d: %s.\n", path
,
2142 (int)uid
, (int)gid
, strerror(errno
), NULL
);
2143 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2151 /* Try to remove @cgroup for all given controllers in a cgroupfs v1 hierarchy
2152 * (For example, try to remove @cgroup for the cpu and cpuacct controller
2153 * mounted into /sys/fs/cgroup/cpu,cpuacct). Ignores failures.
2155 static bool cgv1_remove_one(struct cgv1_hierarchy
*h
, const char *cgroup
)
2160 /* Better safe than sorry. */
2161 if (!h
->controllers
)
2164 /* Cgroups created by systemd for us which we re-use won't be removed
2165 * here, since we're using init_cgroup + cgroup as path instead of
2166 * base_cgroup + cgroup.
2168 path
= must_make_path(h
->mountpoint
, h
->init_cgroup
, cgroup
, NULL
);
2169 (void)recursive_rmdir(path
);
2175 /* Try to remove @cgroup the cgroupfs v2 hierarchy. */
2176 static bool cgv2_remove(const char *cgroup
)
2178 struct cgv2_hierarchy
*v2
;
2181 if (!cgv2_hierarchies
)
2184 v2
= *cgv2_hierarchies
;
2186 /* If we reused an already existing cgroup, don't bother trying to
2187 * remove (a potentially wrong)/the path.
2188 * Cgroups created by systemd for us which we re-use would be removed
2189 * here, since we're using base_cgroup + cgroup as path.
2191 if (v2
->systemd_user_slice
)
2194 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, NULL
);
2195 (void)recursive_rmdir(path
);
2201 /* Create @cgroup in all detected cgroupfs v1 hierarchy. If the creation fails
2202 * for any cgroupfs v1 hierarchy, remove all we have created so far. Report
2203 * back, to the caller if the creation failed due to @cgroup already existing
2206 static bool cgv1_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2208 struct cgv1_hierarchy
**it
, **rev_it
;
2209 bool all_created
= true;
2211 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2212 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2213 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2216 if (!cgv1_create_one(*it
, cgroup
, uid
, gid
, existed
)) {
2217 all_created
= false;
2225 for (rev_it
= cgv1_hierarchies
; rev_it
&& *rev_it
&& (*rev_it
!= *it
);
2227 cgv1_remove_one(*rev_it
, cgroup
);
2232 /* Create @cgroup in the cgroupfs v2 hierarchy. Report back, to the caller if
2233 * the creation failed due to @cgroup already existing via @existed.
2235 static bool cgv2_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2238 char *clean_base_cgroup
;
2240 struct cgv2_hierarchy
*v2
;
2241 bool our_cg
= false, created
= false;
2245 if (!cgv2_hierarchies
|| !(*cgv2_hierarchies
)->create_rw_cgroup
)
2248 v2
= *cgv2_hierarchies
;
2250 /* We can't be placed under init's cgroup for the v2 hierarchy. We need
2251 * to be placed under our current cgroup.
2253 if (cg_systemd_chown_existing_cgroup(v2
->mountpoint
, v2
->base_cgroup
,
2254 uid
, gid
, v2
->systemd_user_slice
))
2255 goto delegate_files
;
2257 /* We need to make sure that we do not create an endless chain of
2258 * sub-cgroups. So we check if we have already logged in somehow (sudo
2259 * -i, su, etc.) and have created a /user/PAM_user/idx cgroup. If so, we
2262 if (strncmp(v2
->base_cgroup
, __PAM_CGFS_USER
, __PAM_CGFS_USER_LEN
) == 0) {
2263 free(v2
->base_cgroup
);
2264 v2
->base_cgroup
= must_copy_string("/");
2266 clean_base_cgroup
= strstr(v2
->base_cgroup
, __PAM_CGFS_USER
);
2267 if (clean_base_cgroup
)
2268 *clean_base_cgroup
= '\0';
2271 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, NULL
);
2272 pam_cgfs_debug("Constructing path \"%s\".\n", path
);
2273 if (file_exists(path
)) {
2274 our_cg
= cg_belongs_to_uid_gid(path
, uid
, gid
);
2276 "%s existed and does %shave our uid: %d and gid: %d.\n",
2277 path
, our_cg
? "" : "not ", uid
, gid
);
2281 goto delegate_files
;
2288 created
= mkdir_parent(v2
->mountpoint
, path
);
2294 /* chown cgroup to user */
2295 if (chown(path
, uid
, gid
) < 0)
2296 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2297 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2299 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2303 /* chown cgroup.procs to user */
2304 if (v2
->systemd_user_slice
)
2305 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2306 "/cgroup.procs", NULL
);
2308 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2309 "/cgroup.procs", NULL
);
2310 ret
= chown(path
, uid
, gid
);
2312 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2313 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2315 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2318 /* chown cgroup.subtree_control to user */
2319 if (v2
->systemd_user_slice
)
2320 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2321 "/cgroup.subtree_control", NULL
);
2323 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2324 "/cgroup.subtree_control", NULL
);
2325 ret
= chown(path
, uid
, gid
);
2327 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2328 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2331 /* chown cgroup.threads to user */
2332 if (v2
->systemd_user_slice
)
2333 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2334 "/cgroup.threads", NULL
);
2336 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2337 "/cgroup.threads", NULL
);
2338 ret
= chown(path
, uid
, gid
);
2339 if (ret
< 0 && errno
!= ENOENT
)
2340 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2341 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2347 /* Create writeable cgroups for @user at login. Details can be found in the
2348 * preamble/license at the top of this file.
2350 static int handle_login(const char *user
, uid_t uid
, gid_t gid
)
2354 char cg
[MAXPATHLEN
];
2359 ret
= snprintf(cg
, MAXPATHLEN
, "/user/%s/%d", user
, idx
);
2360 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2361 mysyslog(LOG_ERR
, "Username too long.\n", NULL
);
2362 return PAM_SESSION_ERR
;
2366 if (!cgv2_create(cg
, uid
, gid
, &existed
)) {
2372 mysyslog(LOG_ERR
, "Failed to create a cgroup for user %s.\n", user
, NULL
);
2373 return PAM_SESSION_ERR
;
2377 if (!cgv1_create(cg
, uid
, gid
, &existed
)) {
2383 mysyslog(LOG_ERR
, "Failed to create a cgroup for user %s.\n", user
, NULL
);
2384 return PAM_SESSION_ERR
;
2387 if (!cg_enter(cg
)) {
2388 mysyslog( LOG_ERR
, "Failed to enter user cgroup %s for user %s.\n", cg
, user
, NULL
);
2389 return PAM_SESSION_ERR
;
2397 /* Try to prune cgroups we created and that now are empty from all cgroupfs v1
2400 static bool cgv1_prune_empty_cgroups(const char *user
)
2402 bool controller_removed
= true;
2403 bool all_removed
= true;
2404 struct cgv1_hierarchy
**it
;
2406 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2408 char *path_base
, *path_init
;
2411 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2412 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2415 for (controller
= (*it
)->controllers
; controller
&& *controller
;
2417 bool path_base_rm
, path_init_rm
;
2419 path_base
= must_make_path((*it
)->mountpoint
, (*it
)->base_cgroup
, "/user", user
, NULL
);
2420 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_base
);
2421 ret
= recursive_rmdir(path_base
);
2422 if (ret
== -ENOENT
|| ret
>= 0)
2423 path_base_rm
= true;
2425 path_base_rm
= false;
2428 path_init
= must_make_path((*it
)->mountpoint
, (*it
)->init_cgroup
, "/user", user
, NULL
);
2429 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_init
);
2430 ret
= recursive_rmdir(path_init
);
2431 if (ret
== -ENOENT
|| ret
>= 0)
2432 path_init_rm
= true;
2434 path_init_rm
= false;
2437 if (!path_base_rm
&& !path_init_rm
) {
2438 controller_removed
= false;
2442 controller_removed
= true;
2445 if (!controller_removed
)
2446 all_removed
= false;
2452 /* Try to prune cgroup we created and that now is empty from the cgroupfs v2
2455 static bool cgv2_prune_empty_cgroups(const char *user
)
2458 struct cgv2_hierarchy
*v2
;
2459 char *path_base
, *path_init
;
2460 bool path_base_rm
, path_init_rm
;
2462 if (!cgv2_hierarchies
)
2465 v2
= *cgv2_hierarchies
;
2467 path_base
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, "/user", user
, NULL
);
2468 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_base
);
2469 ret
= recursive_rmdir(path_base
);
2470 if (ret
== -ENOENT
|| ret
>= 0)
2471 path_base_rm
= true;
2473 path_base_rm
= false;
2476 path_init
= must_make_path(v2
->mountpoint
, v2
->init_cgroup
, "/user", user
, NULL
);
2477 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_init
);
2478 ret
= recursive_rmdir(path_init
);
2479 if (ret
== -ENOENT
|| ret
>= 0)
2480 path_init_rm
= true;
2482 path_init_rm
= false;
2485 if (!path_base_rm
&& !path_init_rm
)
2491 /* Wrapper around cgv{1,2}_prune_empty_cgroups(). */
2492 static void cg_prune_empty_cgroups(const char *user
)
2494 (void)cgv1_prune_empty_cgroups(user
);
2495 (void)cgv2_prune_empty_cgroups(user
);
2498 /* Free allocated information for detected cgroupfs v1 hierarchies. */
2499 static void cgv1_free_hierarchies(void)
2501 struct cgv1_hierarchy
**it
;
2503 if (!cgv1_hierarchies
)
2506 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2507 if ((*it
)->controllers
) {
2509 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2512 free((*it
)->controllers
);
2514 free((*it
)->mountpoint
);
2515 free((*it
)->base_cgroup
);
2516 free((*it
)->fullcgpath
);
2517 free((*it
)->init_cgroup
);
2519 free(cgv1_hierarchies
);
2522 /* Free allocated information for the detected cgroupfs v2 hierarchy. */
2523 static void cgv2_free_hierarchies(void)
2525 struct cgv2_hierarchy
**it
;
2527 if (!cgv2_hierarchies
)
2530 for (it
= cgv2_hierarchies
; it
&& *it
; it
++) {
2531 if ((*it
)->controllers
) {
2533 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2536 free((*it
)->controllers
);
2538 free((*it
)->mountpoint
);
2539 free((*it
)->base_cgroup
);
2540 free((*it
)->fullcgpath
);
2541 free((*it
)->init_cgroup
);
2543 free(cgv2_hierarchies
);
2546 /* Wrapper around cgv{1,2}_free_hierarchies(). */
2547 static void cg_exit(void)
2549 cgv1_free_hierarchies();
2550 cgv2_free_hierarchies();
2553 int pam_sm_open_session(pam_handle_t
*pamh
, int flags
, int argc
,
2559 const char *PAM_user
= NULL
;
2561 ret
= pam_get_user(pamh
, &PAM_user
, NULL
);
2562 if (ret
!= PAM_SUCCESS
) {
2563 mysyslog(LOG_ERR
, "PAM-CGFS: couldn't get user\n", NULL
);
2564 return PAM_SESSION_ERR
;
2567 if (!get_uid_gid(PAM_user
, &uid
, &gid
)) {
2568 mysyslog(LOG_ERR
, "Failed to get uid and gid for %s.\n", PAM_user
, NULL
);
2569 return PAM_SESSION_ERR
;
2572 if (!cg_init(uid
, gid
)) {
2573 mysyslog(LOG_ERR
, "Failed to get list of controllers\n", NULL
);
2574 return PAM_SESSION_ERR
;
2577 /* Try to prune cgroups, that are actually empty but were still marked
2578 * as busy by the kernel so we couldn't remove them on session close.
2580 cg_prune_empty_cgroups(PAM_user
);
2582 if (cg_mount_mode
== CGROUP_UNKNOWN
)
2583 return PAM_SESSION_ERR
;
2585 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2586 char **clist
= make_string_list(argv
[1], ",");
2589 * We don't allow using "all" and other controllers explicitly because
2590 * that simply doesn't make any sense.
2592 if (string_list_length(clist
) > 1 && string_in_list(clist
, "all")) {
2593 mysyslog(LOG_ERR
, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL
);
2594 free_string_list(clist
);
2595 return PAM_SESSION_ERR
;
2598 cg_mark_to_make_rw(clist
);
2599 free_string_list(clist
);
2602 return handle_login(PAM_user
, uid
, gid
);
2605 int pam_sm_close_session(pam_handle_t
*pamh
, int flags
, int argc
,
2611 const char *PAM_user
= NULL
;
2613 ret
= pam_get_user(pamh
, &PAM_user
, NULL
);
2614 if (ret
!= PAM_SUCCESS
) {
2615 mysyslog(LOG_ERR
, "PAM-CGFS: couldn't get user\n", NULL
);
2616 return PAM_SESSION_ERR
;
2619 if (!get_uid_gid(PAM_user
, &uid
, &gid
)) {
2620 mysyslog(LOG_ERR
, "Failed to get uid and gid for %s.\n", PAM_user
, NULL
);
2621 return PAM_SESSION_ERR
;
2624 if (cg_mount_mode
== CGROUP_UNINITIALIZED
) {
2625 if (!cg_init(uid
, gid
))
2626 mysyslog(LOG_ERR
, "Failed to get list of controllers\n", NULL
);
2628 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2629 char **clist
= make_string_list(argv
[1], ",");
2632 * We don't allow using "all" and other controllers explicitly because
2633 * that simply doesn't make any sense.
2635 if (string_list_length(clist
) > 1 && string_in_list(clist
, "all")) {
2636 mysyslog(LOG_ERR
, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL
);
2637 free_string_list(clist
);
2638 return PAM_SESSION_ERR
;
2641 cg_mark_to_make_rw(clist
);
2642 free_string_list(clist
);
2646 cg_prune_empty_cgroups(PAM_user
);