1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include <sys/capability.h>
29 #include <security/pam_modules.h>
30 #include <security/_pam_macros.h>
31 #include <security/pam_modutil.h>
32 #include <security/pam_ext.h>
33 #include <security/pam_misc.h>
36 #include "cgroup-util.h"
38 #include "sd-daemon.h"
41 static int parse_argv(pam_handle_t *handle,
42 int argc, const char **argv,
47 char ***reset_controllers,
48 char ***kill_only_users,
49 char ***kill_exclude_users) {
52 bool reset_controller_set = false;
53 bool kill_exclude_users_set = false;
56 assert(argc == 0 || argv);
58 for (i = 0; i < (unsigned) argc; i++) {
61 if (startswith(argv[i], "create-session=")) {
62 if ((k = parse_boolean(argv[i] + 15)) < 0) {
63 pam_syslog(handle, LOG_ERR, "Failed to parse create-session= argument.");
70 } else if (startswith(argv[i], "kill-session=")) {
71 if ((k = parse_boolean(argv[i] + 13)) < 0) {
72 pam_syslog(handle, LOG_ERR, "Failed to parse kill-session= argument.");
79 } else if (startswith(argv[i], "kill-user=")) {
80 if ((k = parse_boolean(argv[i] + 10)) < 0) {
81 pam_syslog(handle, LOG_ERR, "Failed to parse kill-user= argument.");
88 } else if (startswith(argv[i], "controllers=")) {
93 if (!(l = strv_split(argv[i] + 12, ","))) {
94 pam_syslog(handle, LOG_ERR, "Out of memory.");
98 strv_free(*controllers);
102 } else if (startswith(argv[i], "reset-controllers=")) {
104 if (reset_controllers) {
107 if (!(l = strv_split(argv[i] + 18, ","))) {
108 pam_syslog(handle, LOG_ERR, "Out of memory.");
112 strv_free(*reset_controllers);
113 *reset_controllers = l;
116 reset_controller_set = true;
118 } else if (startswith(argv[i], "kill-only-users=")) {
120 if (kill_only_users) {
123 if (!(l = strv_split(argv[i] + 16, ","))) {
124 pam_syslog(handle, LOG_ERR, "Out of memory.");
128 strv_free(*kill_only_users);
129 *kill_only_users = l;
132 } else if (startswith(argv[i], "kill-exclude-users=")) {
134 if (kill_exclude_users) {
137 if (!(l = strv_split(argv[i] + 19, ","))) {
138 pam_syslog(handle, LOG_ERR, "Out of memory.");
142 strv_free(*kill_exclude_users);
143 *kill_exclude_users = l;
146 kill_exclude_users_set = true;
149 pam_syslog(handle, LOG_ERR, "Unknown parameter '%s'.", argv[i]);
154 if (!reset_controller_set && reset_controllers) {
157 if (!(l = strv_new("cpu", NULL))) {
158 pam_syslog(handle, LOG_ERR, "Out of memory");
162 *reset_controllers = l;
166 strv_remove(*controllers, "name=systemd");
168 if (reset_controllers)
169 strv_remove(*reset_controllers, "name=systemd");
171 if (kill_session && *kill_session && kill_user)
174 if (!kill_exclude_users_set && kill_exclude_users) {
177 if (!(l = strv_new("root", NULL))) {
178 pam_syslog(handle, LOG_ERR, "Out of memory");
182 *kill_exclude_users = l;
188 static int open_file_and_lock(const char *fn) {
193 if ((fd = open(fn, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_CREAT, 0600)) < 0)
196 /* The BSD socket semantics are a lot nicer than those of
197 * POSIX locks. Which is why we use flock() here. BSD locking
198 * does not work across NFS which however is not needed here
199 * as the filesystems in question should be local, and only
200 * locally accessible, and most likely even tmpfs. */
202 if (flock(fd, LOCK_EX) < 0) {
203 close_nointr_nofail(fd);
211 SESSION_ID_AUDIT = 'a',
212 SESSION_ID_COUNTER = 'c',
213 SESSION_ID_RANDOM = 'r'
216 static uint64_t get_session_id(int *mode) {
222 /* First attempt: let's use the session ID of the audit
223 * system, if it is available. */
224 if (read_one_line_file("/proc/self/sessionid", &s) >= 0) {
228 r = safe_atou32(s, &u);
231 if (r >= 0 && u != (uint32_t) -1 && u > 0) {
232 *mode = SESSION_ID_AUDIT;
237 /* Second attempt, use our own counter. */
238 if ((fd = open_file_and_lock(RUNTIME_DIR "/user/.pam-systemd-session")) >= 0) {
242 /* We do a bit of endianess swapping here, just to be
243 * sure. /run should be machine specific anyway, and
244 * even mounted from tmpfs, so this byteswapping
245 * should really not be necessary. But then again, you
246 * never know, so let's avoid any risk. */
248 if (loop_read(fd, &counter, sizeof(counter), false) != sizeof(counter))
251 counter = le64toh(counter) + 1;
253 if (lseek(fd, 0, SEEK_SET) == 0) {
254 uint64_t swapped = htole64(counter);
256 r = loop_write(fd, &swapped, sizeof(swapped), false);
258 if (r != sizeof(swapped))
263 close_nointr_nofail(fd);
266 *mode = SESSION_ID_COUNTER;
271 *mode = SESSION_ID_RANDOM;
273 /* Last attempt, pick a random value */
274 return (uint64_t) random_ull();
277 static int get_user_data(
278 pam_handle_t *handle,
279 const char **ret_username,
280 struct passwd **ret_pw) {
282 const char *username = NULL;
283 struct passwd *pw = NULL;
285 bool have_loginuid = false;
289 assert(ret_username);
292 if (have_effective_cap(CAP_AUDIT_CONTROL)) {
293 /* Only use audit login uid if we are executed with
294 * sufficient capabilities so that pam_loginuid could
295 * do its job. If we are lacking the CAP_AUDIT_CONTROL
296 * capabality we most likely are being run in a
297 * container and /proc/self/loginuid is useless since
298 * it probably contains a uid of the host system. */
300 if (read_one_line_file("/proc/self/loginuid", &s) >= 0) {
303 r = safe_atou32(s, &u);
306 if (r >= 0 && u != (uint32_t) -1 && u > 0) {
307 have_loginuid = true;
308 pw = pam_modutil_getpwuid(handle, u);
313 if (!have_loginuid) {
314 if ((r = pam_get_user(handle, &username, NULL)) != PAM_SUCCESS) {
315 pam_syslog(handle, LOG_ERR, "Failed to get user name.");
319 if (!username || !*username) {
320 pam_syslog(handle, LOG_ERR, "User name not valid.");
324 pw = pam_modutil_getpwnam(handle, username);
328 pam_syslog(handle, LOG_ERR, "Failed to get user data.");
329 return PAM_USER_UNKNOWN;
333 *ret_username = username ? username : pw->pw_name;
338 static int create_user_group(
339 pam_handle_t *handle,
340 const char *controller,
352 r = cg_create_and_attach(controller, group, 0);
354 r = cg_create(controller, group);
357 pam_syslog(handle, LOG_ERR, "Failed to create cgroup: %s", strerror(-r));
358 return PAM_SESSION_ERR;
361 if (r > 0 && remember) {
362 /* Remember that it was us who created this group, and
363 * that hence we need to remove it too. This is a
364 * protection against removing the cgroup when run
366 if ((r = pam_set_data(handle, "systemd.created", INT_TO_PTR(1), NULL)) != PAM_SUCCESS) {
367 pam_syslog(handle, LOG_ERR, "Failed to install created variable.");
372 if ((r = cg_set_task_access(controller, group, 0644, pw->pw_uid, pw->pw_gid)) < 0 ||
373 (r = cg_set_group_access(controller, group, 0755, pw->pw_uid, pw->pw_gid)) < 0) {
374 pam_syslog(handle, LOG_ERR, "Failed to change access modes: %s", strerror(-r));
375 return PAM_SESSION_ERR;
381 static int reset_group(
382 pam_handle_t *handle,
383 const char *controller) {
389 if ((r = cg_attach(controller, "/", 0)) < 0) {
390 pam_syslog(handle, LOG_ERR, "Failed to reset cgroup for controller %s: %s", controller, strerror(-r));
391 return PAM_SESSION_ERR;
397 _public_ PAM_EXTERN int pam_sm_open_session(
398 pam_handle_t *handle,
400 int argc, const char **argv) {
402 const char *username = NULL;
407 bool create_session = true;
408 char **controllers = NULL, **reset_controllers = NULL, **c;
409 char *cgroup_user_tree = NULL;
413 /* pam_syslog(handle, LOG_DEBUG, "pam-systemd initializing"); */
415 /* Make this a NOP on non-systemd systems */
416 if (sd_booted() <= 0)
419 if (parse_argv(handle,
421 &create_session, NULL, NULL,
422 &controllers, &reset_controllers,
424 return PAM_SESSION_ERR;
426 if ((r = get_user_data(handle, &username, &pw)) != PAM_SUCCESS)
429 if ((r = cg_get_user_path(&cgroup_user_tree)) < 0) {
430 pam_syslog(handle, LOG_ERR, "Failed to determine user cgroup tree: %s", strerror(-r));
435 if (safe_mkdir(RUNTIME_DIR "/user", 0755, 0, 0) < 0) {
436 pam_syslog(handle, LOG_ERR, "Failed to create runtime directory: %m");
441 if ((lock_fd = open_file_and_lock(RUNTIME_DIR "/user/.pam-systemd-lock")) < 0) {
442 pam_syslog(handle, LOG_ERR, "Failed to lock runtime directory: %m");
447 /* Create /run/user/$USER */
449 if (asprintf(&buf, RUNTIME_DIR "/user/%s", username) < 0) {
454 if (safe_mkdir(buf, 0700, pw->pw_uid, pw->pw_gid) < 0) {
455 pam_syslog(handle, LOG_WARNING, "Failed to create runtime directory: %m");
458 } else if ((r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", buf, 0)) != PAM_SUCCESS) {
459 pam_syslog(handle, LOG_ERR, "Failed to set runtime dir.");
466 if (create_session) {
469 /* Reuse or create XDG session ID */
470 if (!(id = pam_getenv(handle, "XDG_SESSION_ID"))) {
473 if (asprintf(&buf, "%llux", (unsigned long long) get_session_id(&mode)) < 0) {
478 /* To avoid id clashes we add the session id
479 * source to our session ids. Note that the
480 * session id source might change during
481 * runtime, because a filesystem became
482 * writable or the system reconfigured. */
484 mode != SESSION_ID_AUDIT ? (char) mode : 0;
486 if ((r = pam_misc_setenv(handle, "XDG_SESSION_ID", buf, 0)) != PAM_SUCCESS) {
487 pam_syslog(handle, LOG_ERR, "Failed to set session id.");
491 if (!(id = pam_getenv(handle, "XDG_SESSION_ID"))) {
492 pam_syslog(handle, LOG_ERR, "Failed to get session id.");
498 r = asprintf(&buf, "%s/%s/%s", cgroup_user_tree, username, id);
500 r = asprintf(&buf, "%s/%s/master", cgroup_user_tree, username);
507 pam_syslog(handle, LOG_INFO, "Moving new user session for %s into control group %s.", username, buf);
509 if ((r = create_user_group(handle, SYSTEMD_CGROUP_CONTROLLER, buf, pw, true, true)) != PAM_SUCCESS)
512 /* The additional controllers don't really matter, so we
513 * ignore the return value */
514 STRV_FOREACH(c, controllers)
515 create_user_group(handle, *c, buf, pw, true, false);
517 STRV_FOREACH(c, reset_controllers)
518 reset_group(handle, *c);
526 close_nointr_nofail(lock_fd);
528 strv_free(controllers);
529 strv_free(reset_controllers);
531 free(cgroup_user_tree);
536 static int session_remains(pam_handle_t *handle, const char *user_path) {
538 bool remains = false;
542 if ((r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, user_path, &d)) < 0)
545 while ((r = cg_read_subgroup(d, &subgroup)) > 0) {
547 remains = !streq(subgroup, "master");
562 static bool check_user_lists(
563 pam_handle_t *handle,
565 char **kill_only_users,
566 char **kill_exclude_users) {
568 const char *name = NULL;
574 name = "root"; /* Avoid obvious NSS requests, to suppress network traffic */
578 if ((pw = pam_modutil_getpwuid(handle, uid)))
582 STRV_FOREACH(l, kill_exclude_users) {
585 if (safe_atou32(*l, &id) >= 0)
586 if ((uid_t) id == uid)
589 if (name && streq(name, *l))
593 if (strv_isempty(kill_only_users))
596 STRV_FOREACH(l, kill_only_users) {
599 if (safe_atou32(*l, &id) >= 0)
600 if ((uid_t) id == uid)
603 if (name && streq(name, *l))
610 _public_ PAM_EXTERN int pam_sm_close_session(
611 pam_handle_t *handle,
613 int argc, const char **argv) {
615 const char *username = NULL;
616 bool kill_session = false;
617 bool kill_user = false;
619 char *session_path = NULL, *nosession_path = NULL, *user_path = NULL;
622 const void *created = NULL;
623 char **controllers = NULL, **c, **kill_only_users = NULL, **kill_exclude_users = NULL;
624 char *cgroup_user_tree = NULL;
628 /* Make this a NOP on non-systemd systems */
629 if (sd_booted() <= 0)
632 if (parse_argv(handle,
634 NULL, &kill_session, &kill_user,
636 &kill_only_users, &kill_exclude_users) < 0)
637 return PAM_SESSION_ERR;
639 if ((r = get_user_data(handle, &username, &pw)) != PAM_SUCCESS)
642 if ((r = cg_get_user_path(&cgroup_user_tree)) < 0) {
643 pam_syslog(handle, LOG_ERR, "Failed to determine user cgroup tree: %s", strerror(-r));
648 if ((lock_fd = open_file_and_lock(RUNTIME_DIR "/user/.pam-systemd-lock")) < 0) {
649 pam_syslog(handle, LOG_ERR, "Failed to lock runtime directory: %m");
654 /* We are probably still in some session/user dir. Move ourselves out of the way as first step */
655 if ((r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, cgroup_user_tree, 0)) < 0)
656 pam_syslog(handle, LOG_ERR, "Failed to move us away: %s", strerror(-r));
658 STRV_FOREACH(c, controllers)
659 if ((r = cg_attach(*c, cgroup_user_tree, 0)) < 0)
660 pam_syslog(handle, LOG_ERR, "Failed to move us away in %s hierarchy: %s", *c, strerror(-r));
662 if (asprintf(&user_path, "%s/%s", cgroup_user_tree, username) < 0) {
667 pam_get_data(handle, "systemd.created", &created);
669 if ((id = pam_getenv(handle, "XDG_SESSION_ID")) && created) {
671 if (asprintf(&session_path, "%s/%s/%s", cgroup_user_tree, username, id) < 0 ||
672 asprintf(&nosession_path, "%s/%s/master", cgroup_user_tree, username) < 0) {
677 if (kill_session && check_user_lists(handle, pw->pw_uid, kill_only_users, kill_exclude_users)) {
678 pam_syslog(handle, LOG_INFO, "Killing remaining processes of user session %s of %s.", id, username);
680 /* Kill processes in session cgroup, and delete it */
681 if ((r = cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, session_path, true)) < 0)
682 pam_syslog(handle, LOG_ERR, "Failed to kill session cgroup: %s", strerror(-r));
684 pam_syslog(handle, LOG_INFO, "Moving remaining processes of user session %s of %s into control group %s.", id, username, nosession_path);
686 /* Migrate processes from session to user
687 * cgroup. First, try to create the user group
688 * in case it doesn't exist yet. Also, delete
689 * the session group. */
690 create_user_group(handle, SYSTEMD_CGROUP_CONTROLLER, nosession_path, pw, false, false);
692 if ((r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, session_path, nosession_path, false, true)) < 0)
693 pam_syslog(handle, LOG_ERR, "Failed to migrate session cgroup: %s", strerror(-r));
696 STRV_FOREACH(c, controllers) {
697 create_user_group(handle, *c, nosession_path, pw, false, false);
699 if ((r = cg_migrate_recursive(*c, session_path, nosession_path, false, true)) < 0)
700 pam_syslog(handle, LOG_ERR, "Failed to migrate session cgroup in hierarchy %s: %s", *c, strerror(-r));
705 cg_trim(SYSTEMD_CGROUP_CONTROLLER, user_path, false);
707 if ((r = session_remains(handle, user_path)) < 0)
708 pam_syslog(handle, LOG_ERR, "Failed to determine whether a session remains: %s", strerror(-r));
710 /* Kill user processes not attached to any session */
711 if (kill_user && r == 0 && check_user_lists(handle, pw->pw_uid, kill_only_users, kill_exclude_users)) {
713 /* Kill user cgroup */
714 if ((r = cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, user_path, true)) < 0)
715 pam_syslog(handle, LOG_ERR, "Failed to kill user cgroup: %s", strerror(-r));
718 if ((r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, user_path, true)) < 0)
719 pam_syslog(handle, LOG_ERR, "Failed to check user cgroup: %s", strerror(-r));
721 /* Remove user cgroup */
723 if ((r = cg_delete(SYSTEMD_CGROUP_CONTROLLER, user_path)) < 0)
724 pam_syslog(handle, LOG_ERR, "Failed to delete user cgroup: %s", strerror(-r));
726 /* If we managed to find somebody, don't cleanup the cgroup. */
731 STRV_FOREACH(c, controllers)
732 cg_trim(*c, user_path, true);
735 const char *runtime_dir;
737 if ((runtime_dir = pam_getenv(handle, "XDG_RUNTIME_DIR")))
738 if ((r = rm_rf(runtime_dir, false, true)) < 0)
739 pam_syslog(handle, LOG_ERR, "Failed to remove runtime directory: %s", strerror(-r));
742 /* pam_syslog(handle, LOG_DEBUG, "pam-systemd done"); */
748 close_nointr_nofail(lock_fd);
751 free(nosession_path);
754 strv_free(controllers);
755 strv_free(kill_exclude_users);
756 strv_free(kill_only_users);
758 free(cgroup_user_tree);