]>
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>
62 #define pam_cgfs_debug_stream(stream, format, ...) \
64 fprintf(stream, "%s: %d: %s: " format, __FILE__, __LINE__, \
65 __func__, __VA_ARGS__); \
68 #define pam_cgfs_error(format, ...) pam_cgfs_debug_stream(stderr, format, __VA_ARGS__)
71 #define pam_cgfs_debug(format, ...) pam_cgfs_error(format, __VA_ARGS__)
73 #define pam_cgfs_debug(format, ...)
76 /* Taken over modified from the kernel sources. */
77 #define NBITS 32 /* bits in uint32_t */
78 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
79 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
81 static enum cg_mount_mode
{
86 CGROUP_UNINITIALIZED
= 3,
87 } cg_mount_mode
= CGROUP_UNINITIALIZED
;
89 /* Common helper functions. Most of these have been taken from LXC. */
90 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
);
91 static int append_null_to_list(void ***list
);
92 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
);
93 static inline void clear_bit(unsigned bit
, uint32_t *bitarr
)
95 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
97 static char *copy_to_eol(char *s
);
98 static void free_string_list(char **list
);
99 static char *get_mountpoint(char *line
);
100 static bool get_uid_gid(const char *user
, uid_t
*uid
, gid_t
*gid
);
101 static int handle_login(const char *user
, uid_t uid
, gid_t gid
);
102 static inline bool is_set(unsigned bit
, uint32_t *bitarr
)
104 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
106 static bool is_lxcfs(const char *line
);
107 static bool is_cgv1(char *line
);
108 static bool is_cgv2(char *line
);
109 static void *must_alloc(size_t sz
);
110 static void must_add_to_list(char ***clist
, char *entry
);
111 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
113 static void must_append_string(char ***list
, char *entry
);
114 static void mysyslog(int err
, const char *format
, ...) __attribute__((sentinel
));
115 static char *read_file(char *fnam
);
116 static int read_from_file(const char *filename
, void* buf
, size_t count
);
117 static int recursive_rmdir(char *dirname
);
118 static inline void set_bit(unsigned bit
, uint32_t *bitarr
)
120 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
122 static bool string_in_list(char **list
, const char *entry
);
123 static char *string_join(const char *sep
, const char **parts
, bool use_as_prefix
);
124 static void trim(char *s
);
125 static bool write_int(char *path
, int v
);
126 static ssize_t
write_nointr(int fd
, const void* buf
, size_t count
);
127 static int write_to_file(const char *filename
, const void *buf
, size_t count
,
130 /* cgroupfs prototypes. */
131 static bool cg_belongs_to_uid_gid(const char *path
, uid_t uid
, gid_t gid
);
132 static uint32_t *cg_cpumask(char *buf
, size_t nbits
);
133 static bool cg_copy_parent_file(char *path
, char *file
);
134 static char *cg_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
);
135 static bool cg_enter(const char *cgroup
);
136 static void cg_escape(void);
137 static bool cg_filter_and_set_cpus(char *path
, bool am_initialized
);
138 static ssize_t
cg_get_max_cpus(char *cpulist
);
139 static int cg_get_version_of_mntpt(const char *path
);
140 static bool cg_init(uid_t uid
, gid_t gid
);
141 static void cg_mark_to_make_rw(char **list
);
142 static void cg_prune_empty_cgroups(const char *user
);
143 static bool cg_systemd_created_user_slice(const char *base_cgroup
,
144 const char *init_cgroup
,
145 const char *in
, uid_t uid
);
146 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint
,
147 const char *base_cgroup
, uid_t uid
,
149 bool systemd_user_slice
);
150 static bool cg_systemd_under_user_slice_1(const char *in
, uid_t uid
);
151 static bool cg_systemd_under_user_slice_2(const char *base_cgroup
,
152 const char *init_cgroup
, uid_t uid
);
153 static void cg_systemd_prune_init_scope(char *cg
);
154 static bool is_lxcfs(const char *line
);
156 /* cgroupfs v1 prototypes. */
157 struct cgv1_hierarchy
{
163 bool create_rw_cgroup
;
164 bool systemd_user_slice
;
167 static struct cgv1_hierarchy
**cgv1_hierarchies
;
169 static void cgv1_add_controller(char **clist
, char *mountpoint
,
170 char *base_cgroup
, char *init_cgroup
);
171 static bool cgv1_controller_in_clist(char *cgline
, char *c
);
172 static bool cgv1_controller_lists_intersect(char **l1
, char **l2
);
173 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy
**hlist
,
175 static bool cgv1_create(const char *cgroup
, uid_t uid
, gid_t gid
,
177 static bool cgv1_create_one(struct cgv1_hierarchy
*h
, const char *cgroup
,
178 uid_t uid
, gid_t gid
, bool *existed
);
179 static bool cgv1_enter(const char *cgroup
);
180 static void cgv1_escape(void);
181 static bool cgv1_get_controllers(char ***klist
, char ***nlist
);
182 static char *cgv1_get_current_cgroup(char *basecginfo
, char *controller
);
183 static char **cgv1_get_proc_mountinfo_controllers(char **klist
, char **nlist
,
185 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy
*h
,
187 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy
*h
);
188 static bool cgv1_init(uid_t uid
, gid_t gid
);
189 static void cgv1_mark_to_make_rw(char **clist
);
190 static char *cgv1_must_prefix_named(char *entry
);
191 static bool cgv1_prune_empty_cgroups(const char *user
);
192 static bool cgv1_remove_one(struct cgv1_hierarchy
*h
, const char *cgroup
);
193 static bool is_cgv1(char *line
);
195 /* cgroupfs v2 prototypes. */
196 struct cgv2_hierarchy
{
202 bool create_rw_cgroup
;
203 bool systemd_user_slice
;
206 /* Actually this should only be a single hierarchy. But for the sake of
207 * parallelism and because the layout of the cgroupfs v2 is still somewhat
208 * changing, we'll leave it as an array of structs.
210 static struct cgv2_hierarchy
**cgv2_hierarchies
;
212 static void cgv2_add_controller(char **clist
, char *mountpoint
,
213 char *base_cgroup
, char *init_cgroup
,
214 bool systemd_user_slice
);
215 static bool cgv2_create(const char *cgroup
, uid_t uid
, gid_t gid
,
217 static bool cgv2_enter(const char *cgroup
);
218 static void cgv2_escape(void);
219 static char *cgv2_get_current_cgroup(int pid
);
220 static bool cgv2_init(uid_t uid
, gid_t gid
);
221 static void cgv2_mark_to_make_rw(char **clist
);
222 static bool cgv2_prune_empty_cgroups(const char *user
);
223 static bool cgv2_remove(const char *cgroup
);
224 static bool is_cgv2(char *line
);
226 static int do_mkdir(const char *path
, mode_t mode
)
233 r
= mkdir(path
, mode
);
240 /* Create directory and (if necessary) its parents. */
241 static bool mkdir_parent(const char *root
, char *path
)
245 if (strlen(path
) < strlen(root
))
248 if (strlen(path
) == strlen(root
))
251 b
= path
+ strlen(root
) + 1;
253 while (*b
&& (*b
== '/'))
259 while (*e
&& *e
!= '/')
266 if (file_exists(path
))
269 if (do_mkdir(path
, 0755) < 0) {
270 pam_cgfs_debug("Failed to create %s: %s.\n", path
, strerror(errno
));
285 /* Common helper functions. Most of these have been taken from LXC. */
286 static void mysyslog(int err
, const char *format
, ...)
290 va_start(args
, format
);
291 openlog("PAM-CGFS", LOG_CONS
| LOG_PID
, LOG_AUTH
);
292 vsyslog(err
, format
, args
);
297 /* realloc() pointer in batch sizes; do not fail. */
298 #define BATCH_SIZE 50
299 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
301 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
302 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
304 if (!*mem
|| newbatches
> oldbatches
)
305 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
308 /* Append lines as is to pointer; do not fail. */
309 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
311 size_t full
= oldlen
+ newlen
;
313 batch_realloc(dest
, oldlen
, full
+ 1);
315 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
318 /* Read in whole file and return allocated pointer. */
319 static char *read_file(char *fnam
)
323 char *line
= NULL
, *buf
= NULL
;
324 size_t len
= 0, fulllen
= 0;
326 f
= fopen(fnam
, "r");
330 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
331 append_line(&buf
, fulllen
, line
, linelen
);
341 /* Given a pointer to a null-terminated array of pointers, realloc to add one
342 * entry, and point the new entry to NULL. Do not fail. Return the index to the
343 * second-to-last entry - that is, the one which is now available for use
344 * (keeping the list null-terminated).
346 static int append_null_to_list(void ***list
)
351 for (; (*list
)[newentry
]; newentry
++) {
355 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
356 (*list
)[newentry
+ 1] = NULL
;
361 /* Append new entry to null-terminated array of pointer; make sure that array of
362 * pointers will still be null-terminated.
364 static void must_append_string(char ***list
, char *entry
)
369 newentry
= append_null_to_list((void ***)list
);
370 copy
= must_copy_string(entry
);
371 (*list
)[newentry
] = copy
;
374 /* Remove newlines from string. */
375 static void trim(char *s
)
377 size_t len
= strlen(s
);
379 while ((len
> 0) && s
[len
- 1] == '\n')
383 /* Allocate pointer; do not fail. */
384 static void *must_alloc(size_t sz
)
386 return must_realloc(NULL
, sz
);
389 /* Make allocated copy of string. End of string is taken to be '\n'. */
390 static char *copy_to_eol(char *s
)
392 char *newline
, *sret
;
395 newline
= strchr(s
, '\n');
400 sret
= must_alloc(len
+ 1);
401 memcpy(sret
, s
, len
);
407 /* Check if given entry under /proc/<pid>/mountinfo is a fuse.lxcfs mount. */
408 static bool is_lxcfs(const char *line
)
410 char *p
= strstr(line
, " - ");
414 return strncmp(p
, " - fuse.lxcfs ", 14) == 0;
417 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v1 mount. */
418 static bool is_cgv1(char *line
)
420 char *p
= strstr(line
, " - ");
424 return strncmp(p
, " - cgroup ", 10) == 0;
427 /* Check if given entry under /proc/<pid>/mountinfo is a cgroupfs v2 mount. */
428 static bool is_cgv2(char *line
)
430 char *p
= strstr(line
, " - ");
434 return strncmp(p
, " - cgroup2 ", 11) == 0;
437 /* Given a null-terminated array of strings, check whether @entry is one of the
440 static bool string_in_list(char **list
, const char *entry
)
444 for (it
= list
; it
&& *it
; it
++)
445 if (strcmp(*it
, entry
) == 0)
452 * Creates a null-terminated array of strings, made by splitting the entries in
453 * @str on each @sep. Caller is responsible for calling free_string_list.
455 static char **make_string_list(const char *str
, const char *sep
)
458 char *saveptr
= NULL
;
461 copy
= must_copy_string(str
);
463 for (tok
= strtok_r(copy
, sep
, &saveptr
); tok
;
464 tok
= strtok_r(NULL
, sep
, &saveptr
))
465 must_add_to_list(&clist
, tok
);
472 /* Gets the length of a null-terminated array of strings. */
473 static size_t string_list_length(char **list
)
478 for (it
= list
; it
&& *it
; it
++)
484 /* Free null-terminated array of strings. */
485 static void free_string_list(char **list
)
489 for (it
= list
; it
&& *it
; it
++)
494 /* Write single integer to file. */
495 static bool write_int(char *path
, int v
)
500 f
= fopen(path
, "w");
504 if (fprintf(f
, "%d\n", v
) < 0)
513 /* Recursively remove directory and its parents. */
514 static int recursive_rmdir(char *dirname
)
516 struct dirent
*direntp
;
520 dir
= opendir(dirname
);
524 while ((direntp
= readdir(dir
))) {
528 if (!strcmp(direntp
->d_name
, ".") ||
529 !strcmp(direntp
->d_name
, ".."))
532 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
534 if (lstat(pathname
, &st
)) {
536 pam_cgfs_debug("Failed to stat %s.\n", pathname
);
541 if (!S_ISDIR(st
.st_mode
))
544 if (recursive_rmdir(pathname
) < 0)
550 if (rmdir(dirname
) < 0) {
552 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
556 if (closedir(dir
) < 0) {
558 pam_cgfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
565 /* Add new entry to null-terminated array of pointers. Make sure array is still
568 static void must_add_to_list(char ***clist
, char *entry
)
572 newentry
= append_null_to_list((void ***)clist
);
573 (*clist
)[newentry
] = must_copy_string(entry
);
576 /* Get mountpoint from a /proc/<pid>/mountinfo line. */
577 static char *get_mountpoint(char *line
)
585 for (i
= 0; i
< 4; i
++) {
597 sret
= must_alloc(len
+ 1);
598 memcpy(sret
, p
, len
);
604 /* Create list of cgroupfs v1 controller found under /proc/self/cgroup. Skips
605 * the 0::/some/path cgroupfs v2 hierarchy listed. Splits controllers into
606 * kernel controllers (@klist) and named controllers (@nlist).
608 static bool cgv1_get_controllers(char ***klist
, char ***nlist
)
614 f
= fopen("/proc/self/cgroup", "r");
618 while (getline(&line
, &len
, f
) != -1) {
620 char *saveptr
= NULL
;
622 p
= strchr(line
, ':');
632 /* Skip the v2 hierarchy. */
636 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
637 tok
= strtok_r(NULL
, ",", &saveptr
)) {
638 if (strncmp(tok
, "name=", 5) == 0)
639 must_append_string(nlist
, tok
);
641 must_append_string(klist
, tok
);
651 /* Get list of controllers for cgroupfs v2 hierarchy by looking at
652 * cgroup.controllers and/or cgroup.subtree_control of a given (parent) cgroup.
653 static bool cgv2_get_controllers(char ***klist)
659 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
660 static char *cgv2_get_current_cgroup(int pid
)
664 char *current_cgroup
;
666 /* The largest integer that can fit into long int is 2^64. This is a
667 * 20-digit number. */
668 #define __PIDLEN /* /proc */ 5 + /* /pid-to-str */ 21 + /* /cgroup */ 7 + /* \0 */ 1
671 ret
= snprintf(path
, __PIDLEN
, "/proc/%d/cgroup", pid
);
672 if (ret
< 0 || ret
>= __PIDLEN
)
675 cgroups_v2
= read_file(path
);
679 current_cgroup
= strstr(cgroups_v2
, "0::/");
683 current_cgroup
= current_cgroup
+ 3;
684 copy
= copy_to_eol(current_cgroup
);
696 /* Given two null-terminated lists of strings, return true if any string is in
699 static bool cgv1_controller_lists_intersect(char **l1
, char **l2
)
706 for (it
= l1
; it
&& *it
; it
++)
707 if (string_in_list(l2
, *it
))
713 /* For a null-terminated list of controllers @clist, return true if any of those
714 * controllers is already listed the null-terminated list of hierarchies @hlist.
715 * Realistically, if one is present, all must be present.
717 static bool cgv1_controller_list_is_dup(struct cgv1_hierarchy
**hlist
, char **clist
)
719 struct cgv1_hierarchy
**it
;
721 for (it
= hlist
; it
&& *it
; it
++)
722 if ((*it
)->controllers
)
723 if (cgv1_controller_lists_intersect((*it
)->controllers
, clist
))
729 /* Set boolean to mark controllers under which we are supposed create a
732 static void cgv1_mark_to_make_rw(char **clist
)
734 struct cgv1_hierarchy
**it
;
736 for (it
= cgv1_hierarchies
; it
&& *it
; it
++)
737 if ((*it
)->controllers
)
738 if (cgv1_controller_lists_intersect((*it
)->controllers
, clist
) ||
739 string_in_list(clist
, "all"))
740 (*it
)->create_rw_cgroup
= true;
743 /* Set boolean to mark whether we are supposed to create a writeable cgroup in
744 * the cgroupfs v2 hierarchy.
746 static void cgv2_mark_to_make_rw(char **clist
)
748 if (string_in_list(clist
, "unified") || string_in_list(clist
, "all"))
749 if (cgv2_hierarchies
)
750 (*cgv2_hierarchies
)->create_rw_cgroup
= true;
753 /* Wrapper around cgv{1,2}_mark_to_make_rw(). */
754 static void cg_mark_to_make_rw(char **clist
)
756 cgv1_mark_to_make_rw(clist
);
757 cgv2_mark_to_make_rw(clist
);
760 /* Prefix any named controllers with "name=", e.g. "name=systemd". */
761 static char *cgv1_must_prefix_named(char *entry
)
768 s
= must_alloc(len
+ 6);
770 ret
= snprintf(s
, len
+ 6, "name=%s", entry
);
771 if (ret
< 0 || (size_t)ret
>= (len
+ 6))
777 /* Append kernel controller in @klist or named controller in @nlist to @clist */
778 static void must_append_controller(char **klist
, char **nlist
, char ***clist
, char *entry
)
783 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
))
786 newentry
= append_null_to_list((void ***)clist
);
788 if (strncmp(entry
, "name=", 5) == 0)
789 copy
= must_copy_string(entry
);
790 else if (string_in_list(klist
, entry
))
791 copy
= must_copy_string(entry
);
793 copy
= cgv1_must_prefix_named(entry
);
795 (*clist
)[newentry
] = copy
;
798 /* Get the controllers from a mountinfo line. There are other ways we could get
799 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
800 * could parse the mount options. But we simply assume that the mountpoint must
801 * be /sys/fs/cgroup/controller-list
803 static char **cgv1_get_proc_mountinfo_controllers(char **klist
, char **nlist
, char *line
)
807 char *saveptr
= NULL
;
812 for (i
= 0; i
< 4; i
++) {
821 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
831 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
832 tok
= strtok_r(NULL
, ",", &saveptr
))
833 must_append_controller(klist
, nlist
, &aret
, tok
);
838 /* Check if a cgroupfs v2 controller is present in the string @cgline. */
839 static bool cgv1_controller_in_clist(char *cgline
, char *c
)
842 char *tok
, *eol
, *tmp
;
843 char *saveptr
= NULL
;
845 eol
= strchr(cgline
, ':');
850 tmp
= alloca(len
+ 1);
851 memcpy(tmp
, cgline
, len
);
854 for (tok
= strtok_r(tmp
, ",", &saveptr
); tok
;
855 tok
= strtok_r(NULL
, ",", &saveptr
)) {
856 if (strcmp(tok
, c
) == 0)
862 /* Get current cgroup from the /proc/<pid>/cgroup file passed in via @basecginfo
863 * of a given cgv1 controller passed in via @controller.
865 static char *cgv1_get_current_cgroup(char *basecginfo
, char *controller
)
877 if (cgv1_controller_in_clist(p
, controller
)) {
883 return copy_to_eol(p
);
895 /* Remove /init.scope from string @cg. This will mostly affect systemd-based
898 #define INIT_SCOPE "/init.scope"
899 static void cg_systemd_prune_init_scope(char *cg
)
906 point
= cg
+ strlen(cg
) - strlen(INIT_SCOPE
);
910 if (strcmp(point
, INIT_SCOPE
) == 0) {
918 /* Add new info about a mounted cgroupfs v1 hierarchy. Includes the controllers
919 * mounted into that hierarchy (e.g. cpu,cpuacct), the mountpoint of that
920 * hierarchy (/sys/fs/cgroup/<controller>, the base cgroup of the current
921 * process gathered from /proc/self/cgroup, and the init cgroup of PID1 gathered
922 * from /proc/1/cgroup.
924 static void cgv1_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
)
926 struct cgv1_hierarchy
*new;
929 new = must_alloc(sizeof(*new));
930 new->controllers
= clist
;
931 new->mountpoint
= mountpoint
;
932 new->base_cgroup
= base_cgroup
;
933 new->fullcgpath
= NULL
;
934 new->create_rw_cgroup
= false;
935 new->init_cgroup
= init_cgroup
;
936 new->systemd_user_slice
= false;
938 newentry
= append_null_to_list((void ***)&cgv1_hierarchies
);
939 cgv1_hierarchies
[newentry
] = new;
942 /* Add new info about the mounted cgroupfs v2 hierarchy. Can (but doesn't
943 * currently) include the controllers mounted into the hierarchy (e.g. memory,
944 * pids, blkio), the mountpoint of that hierarchy (Should usually be
945 * /sys/fs/cgroup but some init systems seems to think it might be a good idea
946 * to also mount empty cgroupfs v2 hierarchies at /sys/fs/cgroup/systemd.), the
947 * base cgroup of the current process gathered from /proc/self/cgroup, and the
948 * init cgroup of PID1 gathered from /proc/1/cgroup.
950 static void cgv2_add_controller(char **clist
, char *mountpoint
, char *base_cgroup
, char *init_cgroup
, bool systemd_user_slice
)
952 struct cgv2_hierarchy
*new;
955 new = must_alloc(sizeof(*new));
956 new->controllers
= clist
;
957 new->mountpoint
= mountpoint
;
958 new->base_cgroup
= base_cgroup
;
959 new->fullcgpath
= NULL
;
960 new->create_rw_cgroup
= false;
961 new->init_cgroup
= init_cgroup
;
962 new->systemd_user_slice
= systemd_user_slice
;
964 newentry
= append_null_to_list((void ***)&cgv2_hierarchies
);
965 cgv2_hierarchies
[newentry
] = new;
968 /* In Ubuntu 14.04, the paths created for us were
969 * '/user/$uid.user/$something.session' This can be merged better with
970 * systemd_created_slice_for_us(), but keeping it separate makes it easier to
971 * reason about the correctness.
973 static bool cg_systemd_under_user_slice_1(const char *in
, uid_t uid
)
981 copy
= must_copy_string(in
);
982 if (strlen(copy
) < strlen("/user/1.user/1.session"))
984 p
= copy
+ strlen(copy
) - 1;
986 /* skip any trailing '/' (shouldn't be any, but be sure) */
987 while (p
>= copy
&& *p
== '/')
992 /* Get last path element */
993 while (p
>= copy
&& *p
!= '/')
997 /* make sure it is something.session */
999 if (len
< strlen("1.session") ||
1000 strncmp(p
+ 1 + len
- 8, ".session", 8) != 0)
1003 /* ok last path piece checks out, now check the second to last */
1005 while (p
>= copy
&& *(--p
) != '/')
1007 if (sscanf(p
+ 1, "%d.user/", &id
) != 1)
1020 /* So long as our path relative to init starts with /user.slice/user-$uid.slice,
1021 * assume it belongs to $uid and chown it
1023 static bool cg_systemd_under_user_slice_2(const char *base_cgroup
,
1024 const char *init_cgroup
, uid_t uid
)
1028 size_t curlen
, initlen
;
1030 curlen
= strlen(base_cgroup
);
1031 initlen
= strlen(init_cgroup
);
1032 if (curlen
<= initlen
)
1035 if (strncmp(base_cgroup
, init_cgroup
, initlen
) != 0)
1038 ret
= snprintf(buf
, 100, "/user.slice/user-%d.slice/", (int)uid
);
1039 if (ret
< 0 || ret
>= 100)
1043 initlen
= 0; // skip the '/'
1045 return strncmp(base_cgroup
+ initlen
, buf
, strlen(buf
)) == 0;
1048 /* The systemd-created path is: user-$uid.slice/session-c$session.scope. If that
1049 * is not the end of our systemd path, then we're not part of the PAM call that
1050 * created that path.
1052 * The last piece is chowned to $uid, the user- part not.
1053 * Note: If the user creates paths that look like what we're looking for to
1055 * - they fool us, we create new cgroups, and they get auto-logged-out.
1056 * - they fool a root sudo, systemd cgroup is not changed but chowned, and they
1057 * lose ownership of their cgroups
1059 static bool cg_systemd_created_user_slice(const char *base_cgroup
,
1060 const char *init_cgroup
,
1061 const char *in
, uid_t uid
)
1069 copy
= must_copy_string(in
);
1071 /* An old version of systemd has already created a cgroup for us. */
1072 if (cg_systemd_under_user_slice_1(in
, uid
))
1075 /* A new version of systemd has already created a cgroup for us. */
1076 if (cg_systemd_under_user_slice_2(base_cgroup
, init_cgroup
, uid
))
1079 if (strlen(copy
) < strlen("/user-0.slice/session-0.scope"))
1082 p
= copy
+ strlen(copy
) - 1;
1083 /* Skip any trailing '/' (shouldn't be any, but be sure). */
1084 while (p
>= copy
&& *p
== '/')
1090 /* Get last path element */
1091 while (p
>= copy
&& *p
!= '/')
1097 /* Make sure it is session-something.scope. */
1098 len
= strlen(p
+ 1);
1099 if (strncmp(p
+ 1, "session-", strlen("session-")) != 0 ||
1100 strncmp(p
+ 1 + len
- 6, ".scope", 6) != 0)
1103 /* Ok last path piece checks out, now check the second to last. */
1105 while (p
>= copy
&& *(--p
) != '/')
1108 if (sscanf(p
+ 1, "user-%d.slice/", &id
) != 1)
1121 /* Chown existing cgroup that systemd has already created for us. */
1122 static bool cg_systemd_chown_existing_cgroup(const char *mountpoint
,
1123 const char *base_cgroup
, uid_t uid
,
1124 gid_t gid
, bool systemd_user_slice
)
1128 if (!systemd_user_slice
)
1131 path
= must_make_path(mountpoint
, base_cgroup
, NULL
);
1133 /* A cgroup within name=systemd has already been created. So we only
1136 if (chown(path
, uid
, gid
) < 0)
1137 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
1138 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
1139 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
1145 /* Detect and store information about cgroupfs v1 hierarchies. */
1146 static bool cgv1_init(uid_t uid
, gid_t gid
)
1149 struct cgv1_hierarchy
**it
;
1152 char **klist
= NULL
, **nlist
= NULL
;
1155 basecginfo
= read_file("/proc/self/cgroup");
1159 f
= fopen("/proc/self/mountinfo", "r");
1165 cgv1_get_controllers(&klist
, &nlist
);
1167 while (getline(&line
, &len
, f
) != -1) {
1168 char **controller_list
= NULL
;
1169 char *mountpoint
, *base_cgroup
;
1171 if (is_lxcfs(line
) || !is_cgv1(line
))
1174 controller_list
= cgv1_get_proc_mountinfo_controllers(klist
, nlist
, line
);
1175 if (!controller_list
)
1178 if (cgv1_controller_list_is_dup(cgv1_hierarchies
,
1180 free(controller_list
);
1184 mountpoint
= get_mountpoint(line
);
1186 free_string_list(controller_list
);
1190 base_cgroup
= cgv1_get_current_cgroup(basecginfo
, controller_list
[0]);
1192 free_string_list(controller_list
);
1197 pam_cgfs_debug("Detected cgroupfs v1 controller \"%s\" with "
1198 "mountpoint \"%s\" and cgroup \"%s\".\n",
1199 controller_list
[0], mountpoint
, base_cgroup
);
1200 cgv1_add_controller(controller_list
, mountpoint
, base_cgroup
,
1203 free_string_list(klist
);
1204 free_string_list(nlist
);
1209 /* Retrieve init cgroup path for all controllers. */
1210 basecginfo
= read_file("/proc/1/cgroup");
1214 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
1215 if ((*it
)->controllers
) {
1216 char *init_cgroup
, *user_slice
;
1217 /* We've already stored the controller and received its
1218 * current cgroup. If we now fail to retrieve its init
1219 * cgroup, we should probably fail.
1221 init_cgroup
= cgv1_get_current_cgroup(basecginfo
, (*it
)->controllers
[0]);
1226 cg_systemd_prune_init_scope(init_cgroup
);
1227 (*it
)->init_cgroup
= init_cgroup
;
1228 pam_cgfs_debug("cgroupfs v1 controller \"%s\" has init "
1230 (*(*it
)->controllers
), init_cgroup
);
1231 /* Check whether systemd has already created a cgroup
1234 user_slice
= must_make_path((*it
)->mountpoint
, (*it
)->base_cgroup
, NULL
);
1235 if (cg_systemd_created_user_slice((*it
)->base_cgroup
, (*it
)->init_cgroup
, user_slice
, uid
))
1236 (*it
)->systemd_user_slice
= true;
1244 /* Check whether @path is a cgroupfs v1 or cgroupfs v2 mount. Returns -1 if
1245 * statfs fails. If @path is null /sys/fs/cgroup is checked.
1247 static inline int cg_get_version_of_mntpt(const char *path
)
1249 if (has_fs_type(path
, CGROUP_SUPER_MAGIC
))
1252 if (has_fs_type(path
, CGROUP2_SUPER_MAGIC
))
1258 /* Detect and store information about the cgroupfs v2 hierarchy. Currently only
1259 * deals with the empty v2 hierachy as we do not retrieve enabled controllers.
1261 static bool cgv2_init(uid_t uid
, gid_t gid
)
1265 char *current_cgroup
= NULL
, *init_cgroup
= NULL
;
1270 current_cgroup
= cgv2_get_current_cgroup(getpid());
1271 if (!current_cgroup
) {
1272 /* No v2 hierarchy present. We're done. */
1277 init_cgroup
= cgv2_get_current_cgroup(1);
1279 /* If we're here and didn't fail already above, then something's
1280 * certainly wrong, so error this time.
1284 cg_systemd_prune_init_scope(init_cgroup
);
1286 /* Check if the v2 hierarchy is mounted at its standard location.
1287 * If so we can skip the rest of the work here. Although the unified
1288 * hierarchy can be mounted multiple times, each of those mountpoints
1289 * will expose identical information.
1291 if (cg_get_version_of_mntpt("/sys/fs/cgroup") == 2) {
1293 bool has_user_slice
= false;
1295 mountpoint
= must_copy_string("/sys/fs/cgroup");
1299 user_slice
= must_make_path(mountpoint
, current_cgroup
, NULL
);
1300 if (cg_systemd_created_user_slice(current_cgroup
, init_cgroup
, user_slice
, uid
))
1301 has_user_slice
= true;
1304 cgv2_add_controller(NULL
, mountpoint
, current_cgroup
, init_cgroup
, has_user_slice
);
1310 f
= fopen("/proc/self/mountinfo", "r");
1314 /* we support simple cgroup mounts and lxcfs mounts */
1315 while (getline(&line
, &len
, f
) != -1) {
1317 bool has_user_slice
= false;
1321 mountpoint
= get_mountpoint(line
);
1325 user_slice
= must_make_path(mountpoint
, current_cgroup
, NULL
);
1326 if (cg_systemd_created_user_slice(current_cgroup
, init_cgroup
, user_slice
, uid
))
1327 has_user_slice
= true;
1330 cgv2_add_controller(NULL
, mountpoint
, current_cgroup
, init_cgroup
, has_user_slice
);
1331 /* Although the unified hierarchy can be mounted multiple times,
1332 * each of those mountpoints will expose identical information.
1333 * So let the first mountpoint we find, win.
1339 pam_cgfs_debug("Detected cgroupfs v2 hierarchy at mountpoint \"%s\" with "
1340 "current cgroup \"%s\" and init cgroup \"%s\".\n",
1341 mountpoint
, current_cgroup
, init_cgroup
);
1351 /* Detect and store information about mounted cgroupfs v1 hierarchies and the
1352 * cgroupfs v2 hierarchy.
1353 * Detect whether we are on a pure cgroupfs v1, cgroupfs v2, or mixed system,
1354 * where some controllers are mounted into their standard cgroupfs v1 locations
1355 * (/sys/fs/cgroup/<controller>) and others are mounted into the cgroupfs v2
1356 * hierarchy (/sys/fs/cgroup).
1358 static bool cg_init(uid_t uid
, gid_t gid
)
1360 if (!cgv1_init(uid
, gid
))
1363 if (!cgv2_init(uid
, gid
))
1366 if (cgv1_hierarchies
&& cgv2_hierarchies
) {
1367 cg_mount_mode
= CGROUP_MIXED
;
1368 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 and v2 hierarchies.");
1369 } else if (cgv1_hierarchies
&& !cgv2_hierarchies
) {
1370 cg_mount_mode
= CGROUP_PURE_V1
;
1371 pam_cgfs_debug("%s\n", "Detected cgroupfs v1 hierarchies.");
1372 } else if (cgv2_hierarchies
&& !cgv1_hierarchies
) {
1373 cg_mount_mode
= CGROUP_PURE_V2
;
1374 pam_cgfs_debug("%s\n", "Detected cgroupfs v2 hierarchies.");
1376 cg_mount_mode
= CGROUP_UNKNOWN
;
1377 mysyslog(LOG_ERR
, "Could not detect cgroupfs hierarchy.\n", NULL
);
1380 if (cg_mount_mode
== CGROUP_UNKNOWN
)
1386 /* Try to move/migrate us into @cgroup in a cgroupfs v1 hierarchy. */
1387 static bool cgv1_enter(const char *cgroup
)
1389 struct cgv1_hierarchy
**it
;
1391 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
1393 bool entered
= false;
1395 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
1396 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
1399 for (controller
= (*it
)->controllers
; controller
&& *controller
;
1403 /* We've already been placed in a user slice, so we
1404 * don't need to enter the cgroup again.
1406 if ((*it
)->systemd_user_slice
) {
1411 path
= must_make_path((*it
)->mountpoint
,
1416 if (!file_exists(path
)) {
1418 path
= must_make_path((*it
)->mountpoint
,
1424 pam_cgfs_debug("Attempting to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1425 entered
= write_int(path
, (int)getpid());
1430 pam_cgfs_debug("Failed to enter cgroupfs v1 hierarchy in \"%s\" cgroup.\n", path
);
1440 /* Try to move/migrate us into @cgroup in the cgroupfs v2 hierarchy. */
1441 static bool cgv2_enter(const char *cgroup
)
1443 struct cgv2_hierarchy
*v2
;
1445 bool entered
= false;
1447 if (!cgv2_hierarchies
)
1450 v2
= *cgv2_hierarchies
;
1452 if (!v2
->mountpoint
|| !v2
->base_cgroup
)
1455 if (!v2
->create_rw_cgroup
|| v2
->systemd_user_slice
)
1458 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, "/cgroup.procs", NULL
);
1459 pam_cgfs_debug("Attempting to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path
);
1460 entered
= write_int(path
, (int)getpid());
1462 pam_cgfs_debug("Failed to enter cgroupfs v2 hierarchy in cgroup \"%s\".\n", path
);
1472 /* Wrapper around cgv{1,2}_enter(). */
1473 static bool cg_enter(const char *cgroup
)
1475 if (!cgv1_enter(cgroup
)) {
1476 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to enter cgroups.\n", NULL
);
1480 if (!cgv2_enter(cgroup
)) {
1481 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to enter cgroups.\n", NULL
);
1488 /* Escape to root cgroup in all detected cgroupfs v1 hierarchies. */
1489 static void cgv1_escape(void)
1491 struct cgv1_hierarchy
**it
;
1493 /* In case systemd hasn't already placed us in a user slice for the
1494 * cpuset v1 controller we will reside in the root cgroup. This means
1495 * that cgroup.clone_children will not have been initialized for us so
1498 for (it
= cgv1_hierarchies
; it
&& *it
; it
++)
1499 if (!cgv1_handle_root_cpuset_hierarchy(*it
))
1500 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to initialize cpuset.\n", NULL
);
1502 if (!cgv1_enter("/"))
1503 mysyslog(LOG_WARNING
, "cgroupfs v1: Failed to escape to init's cgroup.\n", NULL
);
1506 /* Escape to root cgroup in the cgroupfs v2 hierarchy. */
1507 static void cgv2_escape(void)
1509 if (!cgv2_enter("/"))
1510 mysyslog(LOG_WARNING
, "cgroupfs v2: Failed to escape to init's cgroup.\n", NULL
);
1513 /* Wrapper around cgv{1,2}_escape(). */
1514 static void cg_escape(void)
1520 /* Get uid and gid for @user. */
1521 static bool get_uid_gid(const char *user
, uid_t
*uid
, gid_t
*gid
)
1523 struct passwd pwent
;
1524 struct passwd
*pwentp
= NULL
;
1529 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1533 buf
= malloc(bufsize
);
1537 ret
= getpwnam_r(user
, &pwent
, buf
, bufsize
, &pwentp
);
1541 "Could not find matched password record\n", NULL
);
1547 *uid
= pwent
.pw_uid
;
1548 *gid
= pwent
.pw_gid
;
1554 /* Check if cgroup belongs to our uid and gid. If so, reuse it. */
1555 static bool cg_belongs_to_uid_gid(const char *path
, uid_t uid
, gid_t gid
)
1557 struct stat statbuf
;
1559 if (stat(path
, &statbuf
) < 0)
1562 if (!(statbuf
.st_uid
== uid
) || !(statbuf
.st_gid
== gid
))
1568 /* Create cpumask from cpulist aka turn:
1576 static uint32_t *cg_cpumask(char *buf
, size_t nbits
)
1579 char *saveptr
= NULL
;
1580 size_t arrlen
= BITS_TO_LONGS(nbits
);
1581 uint32_t *bitarr
= calloc(arrlen
, sizeof(uint32_t));
1585 for (; (token
= strtok_r(buf
, ",", &saveptr
)); buf
= NULL
) {
1587 unsigned start
= strtoul(token
, NULL
, 0);
1588 unsigned end
= start
;
1590 char *range
= strchr(token
, '-');
1592 end
= strtoul(range
+ 1, NULL
, 0);
1593 if (!(start
<= end
)) {
1603 while (start
<= end
)
1604 set_bit(start
++, bitarr
);
1610 static char *string_join(const char *sep
, const char **parts
, bool use_as_prefix
)
1614 size_t sep_len
= strlen(sep
);
1615 size_t result_len
= use_as_prefix
* sep_len
;
1620 /* calculate new string length */
1621 for (p
= (char **)parts
; *p
; p
++)
1622 result_len
+= (p
> (char **)parts
) * sep_len
+ strlen(*p
);
1624 result
= calloc(result_len
+ 1, sizeof(char));
1629 strcpy(result
, sep
);
1630 for (p
= (char **)parts
; *p
; p
++) {
1631 if (p
> (char **)parts
)
1632 strcat(result
, sep
);
1639 /* The largest integer that can fit into long int is 2^64. This is a
1642 #define __IN_TO_STR_LEN 21
1643 /* Turn cpumask into simple, comma-separated cpulist. */
1644 static char *cg_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
1648 char numstr
[__IN_TO_STR_LEN
] = {0};
1649 char **cpulist
= NULL
;
1651 for (i
= 0; i
<= nbits
; i
++) {
1652 if (is_set(i
, bitarr
)) {
1653 ret
= snprintf(numstr
, __IN_TO_STR_LEN
, "%zu", i
);
1654 if (ret
< 0 || (size_t)ret
>= __IN_TO_STR_LEN
) {
1655 free_string_list(cpulist
);
1658 must_append_string(&cpulist
, numstr
);
1661 return string_join(",", (const char **)cpulist
, false);
1664 static ssize_t
cg_get_max_cpus(char *cpulist
)
1667 char *maxcpus
= cpulist
;
1670 c1
= strrchr(maxcpus
, ',');
1674 c2
= strrchr(maxcpus
, '-');
1683 /* If the above logic is correct, c1 should always hold a valid string
1688 cpus
= strtoul(c1
, NULL
, 0);
1695 static ssize_t
write_nointr(int fd
, const void* buf
, size_t count
)
1699 ret
= write(fd
, buf
, count
);
1700 if (ret
< 0 && errno
== EINTR
)
1705 static int write_to_file(const char *filename
, const void* buf
, size_t count
, bool add_newline
)
1707 int fd
, saved_errno
;
1710 fd
= open(filename
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_CLOEXEC
, 0666);
1713 ret
= write_nointr(fd
, buf
, count
);
1716 if ((size_t)ret
!= count
)
1719 ret
= write_nointr(fd
, "\n", 1);
1727 saved_errno
= errno
;
1729 errno
= saved_errno
;
1733 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
1734 static bool cg_filter_and_set_cpus(char *path
, bool am_initialized
)
1736 char *lastslash
, *fpath
, oldv
;
1740 ssize_t maxposs
= 0, maxisol
= 0;
1741 char *cpulist
= NULL
, *posscpus
= NULL
, *isolcpus
= NULL
;
1742 uint32_t *possmask
= NULL
, *isolmask
= NULL
;
1743 bool bret
= false, flipped_bit
= false;
1745 lastslash
= strrchr(path
, '/');
1746 if (!lastslash
) { // bug... this shouldn't be possible
1747 pam_cgfs_debug("Invalid path: %s.\n", path
);
1752 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1753 posscpus
= read_file(fpath
);
1755 pam_cgfs_debug("Could not read file: %s.\n", fpath
);
1759 /* Get maximum number of cpus found in possible cpuset. */
1760 maxposs
= cg_get_max_cpus(posscpus
);
1764 if (!file_exists(__ISOL_CPUS
)) {
1765 /* This system doesn't expose isolated cpus. */
1766 pam_cgfs_debug("%s", "Path: "__ISOL_CPUS
" to read isolated cpus from does not exist.\n");
1768 /* No isolated cpus but we weren't already initialized by
1769 * someone. We should simply copy the parents cpuset.cpus
1772 if (!am_initialized
) {
1773 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1776 /* No isolated cpus but we were already initialized by someone.
1777 * Nothing more to do for us.
1782 isolcpus
= read_file(__ISOL_CPUS
);
1784 pam_cgfs_debug("%s", "Could not read file "__ISOL_CPUS
"\n");
1787 if (!isdigit(isolcpus
[0])) {
1788 pam_cgfs_debug("%s", "No isolated cpus detected.\n");
1790 /* No isolated cpus but we weren't already initialized by
1791 * someone. We should simply copy the parents cpuset.cpus
1794 if (!am_initialized
) {
1795 pam_cgfs_debug("%s", "Copying cpuset of parent cgroup.\n");
1798 /* No isolated cpus but we were already initialized by someone.
1799 * Nothing more to do for us.
1804 /* Get maximum number of cpus found in isolated cpuset. */
1805 maxisol
= cg_get_max_cpus(isolcpus
);
1809 if (maxposs
< maxisol
)
1813 possmask
= cg_cpumask(posscpus
, maxposs
);
1815 pam_cgfs_debug("%s", "Could not create cpumask for all possible cpus.\n");
1819 isolmask
= cg_cpumask(isolcpus
, maxposs
);
1821 pam_cgfs_debug("%s", "Could not create cpumask for all isolated cpus.\n");
1825 for (i
= 0; i
<= maxposs
; i
++) {
1826 if (is_set(i
, isolmask
) && is_set(i
, possmask
)) {
1828 clear_bit(i
, possmask
);
1833 pam_cgfs_debug("%s", "No isolated cpus present in cpuset.\n");
1836 pam_cgfs_debug("%s", "Removed isolated cpus from cpuset.\n");
1838 cpulist
= cg_cpumask_to_cpulist(possmask
, maxposs
);
1840 pam_cgfs_debug("%s", "Could not create cpu list.\n");
1846 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
1847 ret
= write_to_file(fpath
, cpulist
, strlen(cpulist
), false);
1849 pam_cgfs_debug("Could not write cpu list to: %s.\n", fpath
);
1862 if (posscpus
!= cpulist
)
1870 int read_from_file(const char *filename
, void* buf
, size_t count
)
1872 int fd
= -1, saved_errno
;
1875 fd
= open(filename
, O_RDONLY
| O_CLOEXEC
);
1879 if (!buf
|| !count
) {
1882 while ((ret
= read(fd
, buf2
, 100)) > 0)
1887 memset(buf
, 0, count
);
1888 ret
= read(fd
, buf
, count
);
1892 pam_cgfs_debug("read %s: %s", filename
, strerror(errno
));
1894 saved_errno
= errno
;
1896 errno
= saved_errno
;
1900 /* Copy contents of parent(@path)/@file to @path/@file */
1901 static bool cg_copy_parent_file(char *path
, char *file
)
1903 char *lastslash
, *value
= NULL
, *fpath
, oldv
;
1907 lastslash
= strrchr(path
, '/');
1908 if (!lastslash
) { // bug... this shouldn't be possible
1909 pam_cgfs_debug("cgfsng:copy_parent_file: bad path %s", path
);
1914 fpath
= must_make_path(path
, file
, NULL
);
1915 len
= read_from_file(fpath
, NULL
, 0);
1918 value
= must_alloc(len
+ 1);
1919 if (read_from_file(fpath
, value
, len
) != len
)
1923 fpath
= must_make_path(path
, file
, NULL
);
1924 ret
= write_to_file(fpath
, value
, len
, false);
1926 pam_cgfs_debug("Unable to write %s to %s", value
, fpath
);
1932 pam_cgfs_debug("Error reading '%s'", fpath
);
1938 /* In case systemd hasn't already placed us in a user slice for the cpuset v1
1939 * controller we will reside in the root cgroup. This means that
1940 * cgroup.clone_children will not have been initialized for us so we need to do
1943 static bool cgv1_handle_root_cpuset_hierarchy(struct cgv1_hierarchy
*h
)
1945 char *clonechildrenpath
, v
;
1947 if (!string_in_list(h
->controllers
, "cpuset"))
1950 clonechildrenpath
= must_make_path(h
->mountpoint
, "cgroup.clone_children", NULL
);
1952 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
1953 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
1954 free(clonechildrenpath
);
1958 if (v
== '1') { /* already set for us by someone else */
1959 free(clonechildrenpath
);
1963 if (write_to_file(clonechildrenpath
, "1", 1, false) < 0) {
1964 /* Set clone_children so children inherit our settings */
1965 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath
);
1966 free(clonechildrenpath
);
1969 free(clonechildrenpath
);
1974 * Initialize the cpuset hierarchy in first directory of @gname and
1975 * set cgroup.clone_children so that children inherit settings.
1976 * Since the h->base_path is populated by init or ourselves, we know
1977 * it is already initialized.
1979 static bool cgv1_handle_cpuset_hierarchy(struct cgv1_hierarchy
*h
,
1982 char *cgpath
, *clonechildrenpath
, v
, *slash
;
1984 if (!string_in_list(h
->controllers
, "cpuset"))
1989 slash
= strchr(cgroup
, '/');
1993 cgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgroup
, NULL
);
1996 if (do_mkdir(cgpath
, 0755) < 0 && errno
!= EEXIST
) {
1997 pam_cgfs_debug("Failed to create '%s'", cgpath
);
2001 clonechildrenpath
= must_make_path(cgpath
, "cgroup.clone_children", NULL
);
2002 if (!file_exists(clonechildrenpath
)) { /* unified hierarchy doesn't have clone_children */
2003 free(clonechildrenpath
);
2007 if (read_from_file(clonechildrenpath
, &v
, 1) < 0) {
2008 pam_cgfs_debug("Failed to read '%s'", clonechildrenpath
);
2009 free(clonechildrenpath
);
2014 /* Make sure any isolated cpus are removed from cpuset.cpus. */
2015 if (!cg_filter_and_set_cpus(cgpath
, v
== '1')) {
2016 pam_cgfs_debug("%s", "Failed to remove isolated cpus.\n");
2017 free(clonechildrenpath
);
2022 if (v
== '1') { /* already set for us by someone else */
2023 pam_cgfs_debug("%s", "\"cgroup.clone_children\" was already set to \"1\".\n");
2024 free(clonechildrenpath
);
2029 /* copy parent's settings */
2030 if (!cg_copy_parent_file(cgpath
, "cpuset.mems")) {
2031 pam_cgfs_debug("%s", "Failed to copy \"cpuset.mems\" settings.\n");
2033 free(clonechildrenpath
);
2038 if (write_to_file(clonechildrenpath
, "1", 1, false) < 0) {
2039 /* Set clone_children so children inherit our settings */
2040 pam_cgfs_debug("Failed to write 1 to %s", clonechildrenpath
);
2041 free(clonechildrenpath
);
2044 free(clonechildrenpath
);
2048 /* Create and chown @cgroup for all given controllers in a cgroupfs v1 hierarchy
2049 * (For example, create @cgroup for the cpu and cpuacct controller mounted into
2050 * /sys/fs/cgroup/cpu,cpuacct). Check if the path already exists and report back
2051 * to the caller in @existed.
2053 #define __PAM_CGFS_USER "/user/"
2054 #define __PAM_CGFS_USER_LEN 6
2055 static bool cgv1_create_one(struct cgv1_hierarchy
*h
, const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2057 char *clean_base_cgroup
, *path
;
2059 struct cgv1_hierarchy
*it
;
2060 bool created
= false;
2064 for (controller
= it
->controllers
; controller
&& *controller
;
2066 if (!cgv1_handle_cpuset_hierarchy(it
, cgroup
))
2069 /* If systemd has already created a cgroup for us, keep using
2072 if (cg_systemd_chown_existing_cgroup(it
->mountpoint
,
2073 it
->base_cgroup
, uid
, gid
,
2074 it
->systemd_user_slice
)) {
2078 /* We need to make sure that we do not create an endless chain
2079 * of sub-cgroups. So we check if we have already logged in
2080 * somehow (sudo -i, su, etc.) and have created a
2081 * /user/PAM_user/idx cgroup. If so, we skip that part. For most
2082 * cgroups this is unnecessary since we use the init_cgroup
2083 * anyway, but for controllers which have an existing systemd
2084 * cgroup that does not match the current uid, this is pretty
2087 if (strncmp(it
->base_cgroup
, __PAM_CGFS_USER
, __PAM_CGFS_USER_LEN
) == 0) {
2088 free(it
->base_cgroup
);
2089 it
->base_cgroup
= must_copy_string("/");
2092 strstr(it
->base_cgroup
, __PAM_CGFS_USER
);
2093 if (clean_base_cgroup
)
2094 *clean_base_cgroup
= '\0';
2097 path
= must_make_path(it
->mountpoint
, it
->init_cgroup
, cgroup
, NULL
);
2098 pam_cgfs_debug("Constructing path: %s.\n", path
);
2099 if (file_exists(path
)) {
2100 bool our_cg
= cg_belongs_to_uid_gid(path
, uid
, gid
);
2101 pam_cgfs_debug("%s existed and does %shave our uid: %d and gid: %d.\n", path
, our_cg
? "" : "not ", uid
, gid
);
2109 created
= mkdir_parent(it
->mountpoint
, path
);
2114 if (chown(path
, uid
, gid
) < 0)
2115 mysyslog(LOG_WARNING
,
2116 "Failed to chown %s to %d:%d: %s.\n", path
,
2117 (int)uid
, (int)gid
, strerror(errno
), NULL
);
2118 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2126 /* Try to remove @cgroup for all given controllers in a cgroupfs v1 hierarchy
2127 * (For example, try to remove @cgroup for the cpu and cpuacct controller
2128 * mounted into /sys/fs/cgroup/cpu,cpuacct). Ignores failures.
2130 static bool cgv1_remove_one(struct cgv1_hierarchy
*h
, const char *cgroup
)
2135 /* Better safe than sorry. */
2136 if (!h
->controllers
)
2139 /* Cgroups created by systemd for us which we re-use won't be removed
2140 * here, since we're using init_cgroup + cgroup as path instead of
2141 * base_cgroup + cgroup.
2143 path
= must_make_path(h
->mountpoint
, h
->init_cgroup
, cgroup
, NULL
);
2144 (void)recursive_rmdir(path
);
2150 /* Try to remove @cgroup the cgroupfs v2 hierarchy. */
2151 static bool cgv2_remove(const char *cgroup
)
2153 struct cgv2_hierarchy
*v2
;
2156 if (!cgv2_hierarchies
)
2159 v2
= *cgv2_hierarchies
;
2161 /* If we reused an already existing cgroup, don't bother trying to
2162 * remove (a potentially wrong)/the path.
2163 * Cgroups created by systemd for us which we re-use would be removed
2164 * here, since we're using base_cgroup + cgroup as path.
2166 if (v2
->systemd_user_slice
)
2169 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, NULL
);
2170 (void)recursive_rmdir(path
);
2176 /* Create @cgroup in all detected cgroupfs v1 hierarchy. If the creation fails
2177 * for any cgroupfs v1 hierarchy, remove all we have created so far. Report
2178 * back, to the caller if the creation failed due to @cgroup already existing
2181 static bool cgv1_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2183 struct cgv1_hierarchy
**it
, **rev_it
;
2184 bool all_created
= true;
2186 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2187 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2188 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2191 if (!cgv1_create_one(*it
, cgroup
, uid
, gid
, existed
)) {
2192 all_created
= false;
2200 for (rev_it
= cgv1_hierarchies
; rev_it
&& *rev_it
&& (*rev_it
!= *it
);
2202 cgv1_remove_one(*rev_it
, cgroup
);
2207 /* Create @cgroup in the cgroupfs v2 hierarchy. Report back, to the caller if
2208 * the creation failed due to @cgroup already existing via @existed.
2210 static bool cgv2_create(const char *cgroup
, uid_t uid
, gid_t gid
, bool *existed
)
2213 char *clean_base_cgroup
;
2215 struct cgv2_hierarchy
*v2
;
2216 bool our_cg
= false, created
= false;
2220 if (!cgv2_hierarchies
|| !(*cgv2_hierarchies
)->create_rw_cgroup
)
2223 v2
= *cgv2_hierarchies
;
2225 /* We can't be placed under init's cgroup for the v2 hierarchy. We need
2226 * to be placed under our current cgroup.
2228 if (cg_systemd_chown_existing_cgroup(v2
->mountpoint
, v2
->base_cgroup
,
2229 uid
, gid
, v2
->systemd_user_slice
))
2230 goto delegate_files
;
2232 /* We need to make sure that we do not create an endless chain of
2233 * sub-cgroups. So we check if we have already logged in somehow (sudo
2234 * -i, su, etc.) and have created a /user/PAM_user/idx cgroup. If so, we
2237 if (strncmp(v2
->base_cgroup
, __PAM_CGFS_USER
, __PAM_CGFS_USER_LEN
) == 0) {
2238 free(v2
->base_cgroup
);
2239 v2
->base_cgroup
= must_copy_string("/");
2241 clean_base_cgroup
= strstr(v2
->base_cgroup
, __PAM_CGFS_USER
);
2242 if (clean_base_cgroup
)
2243 *clean_base_cgroup
= '\0';
2246 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
, NULL
);
2247 pam_cgfs_debug("Constructing path \"%s\".\n", path
);
2248 if (file_exists(path
)) {
2249 our_cg
= cg_belongs_to_uid_gid(path
, uid
, gid
);
2251 "%s existed and does %shave our uid: %d and gid: %d.\n",
2252 path
, our_cg
? "" : "not ", uid
, gid
);
2256 goto delegate_files
;
2263 created
= mkdir_parent(v2
->mountpoint
, path
);
2269 /* chown cgroup to user */
2270 if (chown(path
, uid
, gid
) < 0)
2271 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2272 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2274 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2278 /* chown cgroup.procs to user */
2279 if (v2
->systemd_user_slice
)
2280 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2281 "/cgroup.procs", NULL
);
2283 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2284 "/cgroup.procs", NULL
);
2285 ret
= chown(path
, uid
, gid
);
2287 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2288 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2290 pam_cgfs_debug("Chowned %s to %d:%d.\n", path
, (int)uid
, (int)gid
);
2293 /* chown cgroup.subtree_control to user */
2294 if (v2
->systemd_user_slice
)
2295 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2296 "/cgroup.subtree_control", NULL
);
2298 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2299 "/cgroup.subtree_control", NULL
);
2300 ret
= chown(path
, uid
, gid
);
2302 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2303 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2306 /* chown cgroup.threads to user */
2307 if (v2
->systemd_user_slice
)
2308 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
,
2309 "/cgroup.threads", NULL
);
2311 path
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, cgroup
,
2312 "/cgroup.threads", NULL
);
2313 ret
= chown(path
, uid
, gid
);
2314 if (ret
< 0 && errno
!= ENOENT
)
2315 mysyslog(LOG_WARNING
, "Failed to chown %s to %d:%d: %s.\n",
2316 path
, (int)uid
, (int)gid
, strerror(errno
), NULL
);
2322 /* Create writeable cgroups for @user at login. Details can be found in the
2323 * preamble/license at the top of this file.
2325 static int handle_login(const char *user
, uid_t uid
, gid_t gid
)
2329 char cg
[MAXPATHLEN
];
2334 ret
= snprintf(cg
, MAXPATHLEN
, "/user/%s/%d", user
, idx
);
2335 if (ret
< 0 || ret
>= MAXPATHLEN
) {
2336 mysyslog(LOG_ERR
, "Username too long.\n", NULL
);
2337 return PAM_SESSION_ERR
;
2341 if (!cgv2_create(cg
, uid
, gid
, &existed
)) {
2347 mysyslog(LOG_ERR
, "Failed to create a cgroup for user %s.\n", user
, NULL
);
2348 return PAM_SESSION_ERR
;
2352 if (!cgv1_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
;
2362 if (!cg_enter(cg
)) {
2363 mysyslog( LOG_ERR
, "Failed to enter user cgroup %s for user %s.\n", cg
, user
, NULL
);
2364 return PAM_SESSION_ERR
;
2372 /* Try to prune cgroups we created and that now are empty from all cgroupfs v1
2375 static bool cgv1_prune_empty_cgroups(const char *user
)
2377 bool controller_removed
= true;
2378 bool all_removed
= true;
2379 struct cgv1_hierarchy
**it
;
2381 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2383 char *path_base
, *path_init
;
2386 if (!(*it
)->controllers
|| !(*it
)->mountpoint
||
2387 !(*it
)->init_cgroup
|| !(*it
)->create_rw_cgroup
)
2390 for (controller
= (*it
)->controllers
; controller
&& *controller
;
2392 bool path_base_rm
, path_init_rm
;
2394 path_base
= must_make_path((*it
)->mountpoint
, (*it
)->base_cgroup
, "/user", user
, NULL
);
2395 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_base
);
2396 ret
= recursive_rmdir(path_base
);
2397 if (ret
== -ENOENT
|| ret
>= 0)
2398 path_base_rm
= true;
2400 path_base_rm
= false;
2403 path_init
= must_make_path((*it
)->mountpoint
, (*it
)->init_cgroup
, "/user", user
, NULL
);
2404 pam_cgfs_debug("cgroupfs v1: Trying to prune \"%s\".\n", path_init
);
2405 ret
= recursive_rmdir(path_init
);
2406 if (ret
== -ENOENT
|| ret
>= 0)
2407 path_init_rm
= true;
2409 path_init_rm
= false;
2412 if (!path_base_rm
&& !path_init_rm
) {
2413 controller_removed
= false;
2417 controller_removed
= true;
2420 if (!controller_removed
)
2421 all_removed
= false;
2427 /* Try to prune cgroup we created and that now is empty from the cgroupfs v2
2430 static bool cgv2_prune_empty_cgroups(const char *user
)
2433 struct cgv2_hierarchy
*v2
;
2434 char *path_base
, *path_init
;
2435 bool path_base_rm
, path_init_rm
;
2437 if (!cgv2_hierarchies
)
2440 v2
= *cgv2_hierarchies
;
2442 path_base
= must_make_path(v2
->mountpoint
, v2
->base_cgroup
, "/user", user
, NULL
);
2443 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_base
);
2444 ret
= recursive_rmdir(path_base
);
2445 if (ret
== -ENOENT
|| ret
>= 0)
2446 path_base_rm
= true;
2448 path_base_rm
= false;
2451 path_init
= must_make_path(v2
->mountpoint
, v2
->init_cgroup
, "/user", user
, NULL
);
2452 pam_cgfs_debug("cgroupfs v2: Trying to prune \"%s\".\n", path_init
);
2453 ret
= recursive_rmdir(path_init
);
2454 if (ret
== -ENOENT
|| ret
>= 0)
2455 path_init_rm
= true;
2457 path_init_rm
= false;
2460 if (!path_base_rm
&& !path_init_rm
)
2466 /* Wrapper around cgv{1,2}_prune_empty_cgroups(). */
2467 static void cg_prune_empty_cgroups(const char *user
)
2469 (void)cgv1_prune_empty_cgroups(user
);
2470 (void)cgv2_prune_empty_cgroups(user
);
2473 /* Free allocated information for detected cgroupfs v1 hierarchies. */
2474 static void cgv1_free_hierarchies(void)
2476 struct cgv1_hierarchy
**it
;
2478 if (!cgv1_hierarchies
)
2481 for (it
= cgv1_hierarchies
; it
&& *it
; it
++) {
2482 if ((*it
)->controllers
) {
2484 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2487 free((*it
)->controllers
);
2489 free((*it
)->mountpoint
);
2490 free((*it
)->base_cgroup
);
2491 free((*it
)->fullcgpath
);
2492 free((*it
)->init_cgroup
);
2494 free(cgv1_hierarchies
);
2497 /* Free allocated information for the detected cgroupfs v2 hierarchy. */
2498 static void cgv2_free_hierarchies(void)
2500 struct cgv2_hierarchy
**it
;
2502 if (!cgv2_hierarchies
)
2505 for (it
= cgv2_hierarchies
; it
&& *it
; it
++) {
2506 if ((*it
)->controllers
) {
2508 for (tmp
= (*it
)->controllers
; tmp
&& *tmp
; tmp
++)
2511 free((*it
)->controllers
);
2513 free((*it
)->mountpoint
);
2514 free((*it
)->base_cgroup
);
2515 free((*it
)->fullcgpath
);
2516 free((*it
)->init_cgroup
);
2518 free(cgv2_hierarchies
);
2521 /* Wrapper around cgv{1,2}_free_hierarchies(). */
2522 static void cg_exit(void)
2524 cgv1_free_hierarchies();
2525 cgv2_free_hierarchies();
2528 int pam_sm_open_session(pam_handle_t
*pamh
, int flags
, int argc
,
2534 const char *PAM_user
= NULL
;
2536 ret
= pam_get_user(pamh
, &PAM_user
, NULL
);
2537 if (ret
!= PAM_SUCCESS
) {
2538 mysyslog(LOG_ERR
, "PAM-CGFS: couldn't get user\n", NULL
);
2539 return PAM_SESSION_ERR
;
2542 if (!get_uid_gid(PAM_user
, &uid
, &gid
)) {
2543 mysyslog(LOG_ERR
, "Failed to get uid and gid for %s.\n", PAM_user
, NULL
);
2544 return PAM_SESSION_ERR
;
2547 if (!cg_init(uid
, gid
)) {
2548 mysyslog(LOG_ERR
, "Failed to get list of controllers\n", NULL
);
2549 return PAM_SESSION_ERR
;
2552 /* Try to prune cgroups, that are actually empty but were still marked
2553 * as busy by the kernel so we couldn't remove them on session close.
2555 cg_prune_empty_cgroups(PAM_user
);
2557 if (cg_mount_mode
== CGROUP_UNKNOWN
)
2558 return PAM_SESSION_ERR
;
2560 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2561 char **clist
= make_string_list(argv
[1], ",");
2564 * We don't allow using "all" and other controllers explicitly because
2565 * that simply doesn't make any sense.
2567 if (string_list_length(clist
) > 1 && string_in_list(clist
, "all")) {
2568 mysyslog(LOG_ERR
, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL
);
2569 free_string_list(clist
);
2570 return PAM_SESSION_ERR
;
2573 cg_mark_to_make_rw(clist
);
2574 free_string_list(clist
);
2577 return handle_login(PAM_user
, uid
, gid
);
2580 int pam_sm_close_session(pam_handle_t
*pamh
, int flags
, int argc
,
2586 const char *PAM_user
= NULL
;
2588 ret
= pam_get_user(pamh
, &PAM_user
, NULL
);
2589 if (ret
!= PAM_SUCCESS
) {
2590 mysyslog(LOG_ERR
, "PAM-CGFS: couldn't get user\n", NULL
);
2591 return PAM_SESSION_ERR
;
2594 if (!get_uid_gid(PAM_user
, &uid
, &gid
)) {
2595 mysyslog(LOG_ERR
, "Failed to get uid and gid for %s.\n", PAM_user
, NULL
);
2596 return PAM_SESSION_ERR
;
2599 if (cg_mount_mode
== CGROUP_UNINITIALIZED
) {
2600 if (!cg_init(uid
, gid
))
2601 mysyslog(LOG_ERR
, "Failed to get list of controllers\n", NULL
);
2603 if (argc
> 1 && !strcmp(argv
[0], "-c")) {
2604 char **clist
= make_string_list(argv
[1], ",");
2607 * We don't allow using "all" and other controllers explicitly because
2608 * that simply doesn't make any sense.
2610 if (string_list_length(clist
) > 1 && string_in_list(clist
, "all")) {
2611 mysyslog(LOG_ERR
, "Invalid -c option, cannot specify individual controllers alongside 'all'.\n", NULL
);
2612 free_string_list(clist
);
2613 return PAM_SESSION_ERR
;
2616 cg_mark_to_make_rw(clist
);
2617 free_string_list(clist
);
2621 cg_prune_empty_cgroups(PAM_user
);