chiark / gitweb /
build-sys: ensure selinux configure check follows logic of other optional features
[elogind.git] / src / pam-module.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
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.
12
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.
17
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/>.
20 ***/
21
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <sys/file.h>
25 #include <pwd.h>
26 #include <endian.h>
27
28 #include <security/pam_modules.h>
29 #include <security/_pam_macros.h>
30 #include <security/pam_modutil.h>
31 #include <security/pam_ext.h>
32 #include <security/pam_misc.h>
33
34 #include "util.h"
35 #include "cgroup-util.h"
36 #include "macro.h"
37 #include "sd-daemon.h"
38 #include "strv.h"
39
40 static int parse_argv(pam_handle_t *handle,
41                       int argc, const char **argv,
42                       bool *create_session,
43                       bool *kill_session,
44                       bool *kill_user,
45                       bool *keep_root,
46                       char ***controllers,
47                       char ***reset_controllers) {
48
49         unsigned i;
50         bool reset_controller_set = false;
51
52         assert(argc >= 0);
53         assert(argc == 0 || argv);
54
55         for (i = 0; i < (unsigned) argc; i++) {
56                 int k;
57
58                 if (startswith(argv[i], "create-session=")) {
59                         if ((k = parse_boolean(argv[i] + 15)) < 0) {
60                                 pam_syslog(handle, LOG_ERR, "Failed to parse create-session= argument.");
61                                 return k;
62                         }
63
64                         if (create_session)
65                                 *create_session = k;
66
67                 } else if (startswith(argv[i], "kill-session=")) {
68                         if ((k = parse_boolean(argv[i] + 13)) < 0) {
69                                 pam_syslog(handle, LOG_ERR, "Failed to parse kill-session= argument.");
70                                 return k;
71                         }
72
73                         if (kill_session)
74                                 *kill_session = k;
75
76                 } else if (startswith(argv[i], "kill-user=")) {
77                         if ((k = parse_boolean(argv[i] + 10)) < 0) {
78                                 pam_syslog(handle, LOG_ERR, "Failed to parse kill-user= argument.");
79                                 return k;
80                         }
81
82                         if (kill_user)
83                                 *kill_user = k;
84
85                 } else if (startswith(argv[i], "keep-root=")) {
86                         if ((k = parse_boolean(argv[i] + 10)) < 0) {
87                                 pam_syslog(handle, LOG_ERR, "Failed to parse keep-root= argument.");
88                                 return k;
89                         }
90
91                         if (keep_root)
92                                 *keep_root = k;
93
94                 } else if (startswith(argv[i], "controllers=")) {
95
96                         if (controllers) {
97                                 char **l;
98
99                                 if (!(l = strv_split(argv[i] + 12, ","))) {
100                                         pam_syslog(handle, LOG_ERR, "Out of memory.");
101                                         return -ENOMEM;
102                                 }
103
104                                 strv_free(*controllers);
105                                 *controllers = l;
106                         }
107
108                 } else if (startswith(argv[i], "reset-controllers=")) {
109
110                         if (reset_controllers) {
111                                 char **l;
112
113                                 if (!(l = strv_split(argv[i] + 18, ","))) {
114                                         pam_syslog(handle, LOG_ERR, "Out of memory.");
115                                         return -ENOMEM;
116                                 }
117
118                                 strv_free(*reset_controllers);
119                                 *reset_controllers = l;
120                         }
121
122                         reset_controller_set = true;
123
124                 } else {
125                         pam_syslog(handle, LOG_ERR, "Unknown parameter '%s'.", argv[i]);
126                         return -EINVAL;
127                 }
128         }
129
130         if (!reset_controller_set && reset_controllers) {
131                 char **l;
132
133                 if (!(l = strv_new("cpu", NULL))) {
134                         pam_syslog(handle, LOG_ERR, "Out of memory");
135                         return -ENOMEM;
136                 }
137
138                 *reset_controllers = l;
139         }
140
141         if (controllers)
142                 strv_remove(*controllers, "name=systemd");
143
144         if (reset_controllers)
145                 strv_remove(*reset_controllers, "name=systemd");
146
147         if (kill_session && *kill_session && kill_user)
148                 *kill_user = true;
149
150         return 0;
151 }
152
153 static int open_file_and_lock(const char *fn) {
154         int fd;
155
156         assert(fn);
157
158         if ((fd = open(fn, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW|O_CREAT, 0600)) < 0)
159                 return -errno;
160
161         /* The BSD socket semantics are a lot nicer than those of
162          * POSIX locks. Which is why we use flock() here. BSD locking
163          * does not work across NFS which however is not needed here
164          * as the filesystems in question should be local, and only
165          * locally accessible, and most likely even tmpfs. */
166
167         if (flock(fd, LOCK_EX) < 0)
168                 return -errno;
169
170         return fd;
171 }
172
173 enum {
174         SESSION_ID_AUDIT = 'a',
175         SESSION_ID_COUNTER = 'c',
176         SESSION_ID_RANDOM = 'r'
177 };
178
179 static uint64_t get_session_id(int *mode) {
180         char *s;
181         int fd;
182
183         assert(mode);
184
185         /* First attempt: let's use the session ID of the audit
186          * system, if it is available. */
187         if (read_one_line_file("/proc/self/sessionid", &s) >= 0) {
188                 uint32_t u;
189                 int r;
190
191                 r = safe_atou32(s, &u);
192                 free(s);
193
194                 if (r >= 0 && u != (uint32_t) -1 && u > 0) {
195                         *mode = SESSION_ID_AUDIT;
196                         return (uint64_t) u;
197                 }
198         }
199
200         /* Second attempt, use our own counter. */
201         if ((fd = open_file_and_lock(RUNTIME_DIR "/user/.pam-systemd-session")) >= 0) {
202                 uint64_t counter;
203                 ssize_t r;
204
205                 /* We do a bit of endianess swapping here, just to be
206                  * sure. /var should be machine specific anyway, and
207                  * /var/run even mounted from tmpfs, so this
208                  * byteswapping should really not be necessary. But
209                  * then again, you never know, so let's avoid any
210                  * risk. */
211
212                 if (loop_read(fd, &counter, sizeof(counter), false) != sizeof(counter))
213                         counter = 1;
214                 else
215                         counter = le64toh(counter) + 1;
216
217                 if (lseek(fd, 0, SEEK_SET) == 0) {
218                         uint64_t swapped = htole64(counter);
219
220                         r = loop_write(fd, &swapped, sizeof(swapped), false);
221
222                         if (r != sizeof(swapped))
223                                 r = -EIO;
224                 } else
225                         r = -errno;
226
227                 close_nointr_nofail(fd);
228
229                 if (r >= 0) {
230                         *mode = SESSION_ID_COUNTER;
231                         return counter;
232                 }
233         }
234
235         *mode = SESSION_ID_RANDOM;
236
237         /* Last attempt, pick a random value */
238         return (uint64_t) random_ull();
239 }
240 static int get_user_data(
241                 pam_handle_t *handle,
242                 const char **ret_username,
243                 struct passwd **ret_pw) {
244
245         const char *username = NULL;
246         struct passwd *pw = NULL;
247         int r;
248         bool have_loginuid = false;
249         char *s;
250
251         assert(handle);
252         assert(ret_username);
253         assert(ret_pw);
254
255         if (read_one_line_file("/proc/self/loginuid", &s) >= 0) {
256                 uint32_t u;
257
258                 r = safe_atou32(s, &u);
259                 free(s);
260
261                 if (r >= 0 && u != (uint32_t) -1 && u > 0) {
262                         have_loginuid = true;
263                         pw = pam_modutil_getpwuid(handle, u);
264                 }
265         }
266
267         if (!have_loginuid) {
268                 if ((r = pam_get_user(handle, &username, NULL)) != PAM_SUCCESS) {
269                         pam_syslog(handle, LOG_ERR, "Failed to get user name.");
270                         return r;
271                 }
272
273                 if (!username || !*username) {
274                         pam_syslog(handle, LOG_ERR, "User name not valid.");
275                         return PAM_AUTH_ERR;
276                 }
277
278                 pw = pam_modutil_getpwnam(handle, username);
279         }
280
281         if (!pw) {
282                 pam_syslog(handle, LOG_ERR, "Failed to get user data.");
283                 return PAM_USER_UNKNOWN;
284         }
285
286         *ret_pw = pw;
287         *ret_username = username ? username : pw->pw_name;
288
289         return PAM_SUCCESS;
290 }
291
292 static int create_user_group(
293                 pam_handle_t *handle,
294                 const char *controller,
295                 const char *group,
296                 struct passwd *pw,
297                 bool attach,
298                 bool remember) {
299
300         int r;
301
302         assert(handle);
303         assert(group);
304
305         if (attach)
306                 r = cg_create_and_attach(controller, group, 0);
307         else
308                 r = cg_create(controller, group);
309
310         if (r < 0) {
311                 pam_syslog(handle, LOG_ERR, "Failed to create cgroup: %s", strerror(-r));
312                 return PAM_SESSION_ERR;
313         }
314
315         if (r > 0 && remember) {
316                 /* Remember that it was us who created this group, and
317                  * that hence we need to remove it too. This is a
318                  * protection against removing the cgroup when run
319                  * recursively. */
320                 if ((r = pam_set_data(handle, "systemd.created", INT_TO_PTR(1), NULL)) != PAM_SUCCESS) {
321                         pam_syslog(handle, LOG_ERR, "Failed to install created variable.");
322                         return r;
323                 }
324         }
325
326         if ((r = cg_set_task_access(controller, group, 0644, pw->pw_uid, pw->pw_gid)) < 0 ||
327             (r = cg_set_group_access(controller, group, 0755, pw->pw_uid, pw->pw_gid)) < 0) {
328                 pam_syslog(handle, LOG_ERR, "Failed to change access modes: %s", strerror(-r));
329                 return PAM_SESSION_ERR;
330         }
331
332         return PAM_SUCCESS;
333 }
334
335 static int reset_group(
336                 pam_handle_t *handle,
337                 const char *controller) {
338
339         int r;
340
341         assert(handle);
342
343         if ((r = cg_attach(controller, "/", 0)) < 0) {
344                 pam_syslog(handle, LOG_ERR, "Failed to reset cgroup for controller %s: %s", controller, strerror(-r));
345                 return PAM_SESSION_ERR;
346         }
347
348         return PAM_SUCCESS;
349 }
350
351 _public_ PAM_EXTERN int pam_sm_open_session(
352                 pam_handle_t *handle,
353                 int flags,
354                 int argc, const char **argv) {
355
356         const char *username = NULL;
357         struct passwd *pw;
358         int r;
359         char *buf = NULL;
360         int lock_fd = -1;
361         bool create_session = true;
362         char **controllers = NULL, **reset_controllers = NULL, **c;
363
364         assert(handle);
365
366         /* pam_syslog(handle, LOG_DEBUG, "pam-systemd initializing"); */
367
368         /* Make this a NOP on non-systemd systems */
369         if (sd_booted() <= 0)
370                 return PAM_SUCCESS;
371
372         if (parse_argv(handle, argc, argv, &create_session, NULL, NULL, NULL, &controllers, &reset_controllers) < 0)
373                 return PAM_SESSION_ERR;
374
375         if ((r = get_user_data(handle, &username, &pw)) != PAM_SUCCESS)
376                 goto finish;
377
378         if (safe_mkdir(RUNTIME_DIR "/user", 0755, 0, 0) < 0) {
379                 pam_syslog(handle, LOG_ERR, "Failed to create runtime directory: %m");
380                 r = PAM_SYSTEM_ERR;
381                 goto finish;
382         }
383
384         if ((lock_fd = open_file_and_lock(RUNTIME_DIR "/user/.pam-systemd-lock")) < 0) {
385                 pam_syslog(handle, LOG_ERR, "Failed to lock runtime directory: %m");
386                 r = PAM_SYSTEM_ERR;
387                 goto finish;
388         }
389
390         /* Create /var/run/$USER */
391         free(buf);
392         if (asprintf(&buf, RUNTIME_DIR "/user/%s", username) < 0) {
393                 r = PAM_BUF_ERR;
394                 goto finish;
395         }
396
397         if (safe_mkdir(buf, 0700, pw->pw_uid, pw->pw_gid) < 0) {
398                 pam_syslog(handle, LOG_WARNING, "Failed to create runtime directory: %m");
399                 r = PAM_SYSTEM_ERR;
400                 goto finish;
401         } else if ((r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", buf, 0)) != PAM_SUCCESS) {
402                 pam_syslog(handle, LOG_ERR, "Failed to set runtime dir.");
403                 goto finish;
404         }
405
406         free(buf);
407         buf = NULL;
408
409         if (create_session) {
410                 const char *id;
411
412                 /* Reuse or create XDG session ID */
413                 if (!(id = pam_getenv(handle, "XDG_SESSION_ID"))) {
414                         int mode;
415
416                         if (asprintf(&buf, "%llux", (unsigned long long) get_session_id(&mode)) < 0) {
417                                 r = PAM_BUF_ERR;
418                                 goto finish;
419                         }
420
421                         /* To avoid id clashes we add the session id
422                          * source to our session ids. Note that the
423                          * session id source might change during
424                          * runtime, because a filesystem became
425                          * writable or the system reconfigured. */
426                         buf[strlen(buf)-1] =
427                                 mode != SESSION_ID_AUDIT ? (char) mode : 0;
428
429                         if ((r = pam_misc_setenv(handle, "XDG_SESSION_ID", buf, 0)) != PAM_SUCCESS) {
430                                 pam_syslog(handle, LOG_ERR, "Failed to set session id.");
431                                 goto finish;
432                         }
433
434                         if (!(id = pam_getenv(handle, "XDG_SESSION_ID"))) {
435                                 pam_syslog(handle, LOG_ERR, "Failed to get session id.");
436                                 r = PAM_SESSION_ERR;
437                                 goto finish;
438                         }
439                 }
440
441                 r = asprintf(&buf, "/user/%s/%s", username, id);
442         } else
443                 r = asprintf(&buf, "/user/%s/master", username);
444
445         if (r < 0) {
446                 r = PAM_BUF_ERR;
447                 goto finish;
448         }
449
450         pam_syslog(handle, LOG_INFO, "Moving new user session for %s into control group %s.", username, buf);
451
452         if ((r = create_user_group(handle, SYSTEMD_CGROUP_CONTROLLER, buf, pw, true, true)) != PAM_SUCCESS)
453                 goto finish;
454
455         /* The additional controllers don't really matter, so we
456          * ignore the return value */
457         STRV_FOREACH(c, controllers)
458                 create_user_group(handle, *c, buf, pw, true, false);
459
460         STRV_FOREACH(c, reset_controllers)
461                 reset_group(handle, *c);
462
463         r = PAM_SUCCESS;
464
465 finish:
466         free(buf);
467
468         if (lock_fd >= 0)
469                 close_nointr_nofail(lock_fd);
470
471         strv_free(controllers);
472         strv_free(reset_controllers);
473
474         return r;
475 }
476
477 static int session_remains(pam_handle_t *handle, const char *user_path) {
478         int r;
479         bool remains = false;
480         DIR *d;
481         char *subgroup;
482
483         if ((r = cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER, user_path, &d)) < 0)
484                 return r;
485
486         while ((r = cg_read_subgroup(d, &subgroup)) > 0) {
487
488                 remains = !streq(subgroup, "master");
489                 free(subgroup);
490
491                 if (remains)
492                         break;
493         }
494
495         closedir(d);
496
497         if (r < 0)
498                 return r;
499
500         return !!remains;
501 }
502
503 _public_ PAM_EXTERN int pam_sm_close_session(
504                 pam_handle_t *handle,
505                 int flags,
506                 int argc, const char **argv) {
507
508         const char *username = NULL;
509         bool kill_session = false;
510         bool kill_user = false;
511         bool keep_root = true;
512         int lock_fd = -1, r;
513         char *session_path = NULL, *nosession_path = NULL, *user_path = NULL;
514         const char *id;
515         struct passwd *pw;
516         const void *created = NULL;
517         char **controllers = NULL, **c;
518
519         assert(handle);
520
521         /* Make this a NOP on non-systemd systems */
522         if (sd_booted() <= 0)
523                 return PAM_SUCCESS;
524
525         if (parse_argv(handle, argc, argv, NULL, &kill_session, &kill_user, &keep_root, &controllers, NULL) < 0)
526                 return PAM_SESSION_ERR;
527
528         if ((r = get_user_data(handle, &username, &pw)) != PAM_SUCCESS)
529                 goto finish;
530
531         if ((lock_fd = open_file_and_lock(RUNTIME_DIR "/user/.pam-systemd-lock")) < 0) {
532                 pam_syslog(handle, LOG_ERR, "Failed to lock runtime directory: %m");
533                 r = PAM_SYSTEM_ERR;
534                 goto finish;
535         }
536
537         /* We are probably still in some session/user dir. Move ourselves out of the way as first step */
538         if ((r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, "/user", 0)) < 0)
539                 pam_syslog(handle, LOG_ERR, "Failed to move us away: %s", strerror(-r));
540
541         STRV_FOREACH(c, controllers)
542                 if ((r = cg_attach(*c, "/user", 0)) < 0)
543                         pam_syslog(handle, LOG_ERR, "Failed to move us away in %s hierarchy: %s", *c, strerror(-r));
544
545         if (asprintf(&user_path, "/user/%s", username) < 0) {
546                 r = PAM_BUF_ERR;
547                 goto finish;
548         }
549
550         pam_get_data(handle, "systemd.created", &created);
551
552         if ((id = pam_getenv(handle, "XDG_SESSION_ID")) && created) {
553
554                 if (asprintf(&session_path, "/user/%s/%s", username, id) < 0 ||
555                     asprintf(&nosession_path, "/user/%s/master", username) < 0) {
556                         r = PAM_BUF_ERR;
557                         goto finish;
558                 }
559
560                 if (kill_session && (pw->pw_uid != 0 || !keep_root))  {
561                         pam_syslog(handle, LOG_INFO, "Killing remaining processes of user session %s of %s.", id, username);
562
563                         /* Kill processes in session cgroup, and delete it */
564                         if ((r = cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, session_path, true)) < 0)
565                                 pam_syslog(handle, LOG_ERR, "Failed to kill session cgroup: %s", strerror(-r));
566                 } else {
567                         pam_syslog(handle, LOG_INFO, "Moving remaining processes of user session %s of %s into control group %s.", id, username, nosession_path);
568
569                         /* Migrate processes from session to user
570                          * cgroup. First, try to create the user group
571                          * in case it doesn't exist yet. Also, delete
572                          * the session group. */
573                         create_user_group(handle, SYSTEMD_CGROUP_CONTROLLER, nosession_path, pw, false, false);
574
575                         if ((r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, session_path, nosession_path, false, true)) < 0)
576                                 pam_syslog(handle, LOG_ERR, "Failed to migrate session cgroup: %s", strerror(-r));
577                 }
578
579                 STRV_FOREACH(c, controllers) {
580                         create_user_group(handle, *c, nosession_path, pw, false, false);
581
582                         if ((r = cg_migrate_recursive(*c, session_path, nosession_path, false, true)) < 0)
583                                 pam_syslog(handle, LOG_ERR, "Failed to migrate session cgroup in hierarchy %s: %s", *c, strerror(-r));
584                 }
585         }
586
587         /* GC user tree */
588         cg_trim(SYSTEMD_CGROUP_CONTROLLER, user_path, false);
589
590         if ((r = session_remains(handle, user_path)) < 0)
591                 pam_syslog(handle, LOG_ERR, "Failed to determine whether a session remains: %s", strerror(-r));
592
593         /* Kill user processes not attached to any session */
594         if (kill_user && r == 0 && (pw->pw_uid != 0 || !keep_root)) {
595
596                 /* Kill user cgroup */
597                 if ((r = cg_kill_recursive_and_wait(SYSTEMD_CGROUP_CONTROLLER, user_path, true)) < 0)
598                         pam_syslog(handle, LOG_ERR, "Failed to kill user cgroup: %s", strerror(-r));
599         } else {
600
601                 if ((r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, user_path, true)) < 0)
602                         pam_syslog(handle, LOG_ERR, "Failed to check user cgroup: %s", strerror(-r));
603
604                 /* Remove user cgroup */
605                 if (r > 0) {
606                         if ((r = cg_delete(SYSTEMD_CGROUP_CONTROLLER, user_path)) < 0)
607                                 pam_syslog(handle, LOG_ERR, "Failed to delete user cgroup: %s", strerror(-r));
608
609                 /* If we managed to find somebody, don't cleanup the cgroup. */
610                 } else if (r == 0)
611                         r = -EBUSY;
612         }
613
614         STRV_FOREACH(c, controllers)
615                 cg_trim(*c, user_path, true);
616
617         if (r >= 0) {
618                 const char *runtime_dir;
619
620                 if ((runtime_dir = pam_getenv(handle, "XDG_RUNTIME_DIR")))
621                         if ((r = rm_rf(runtime_dir, false, true)) < 0)
622                                 pam_syslog(handle, LOG_ERR, "Failed to remove runtime directory: %s", strerror(-r));
623         }
624
625         /* pam_syslog(handle, LOG_DEBUG, "pam-systemd done"); */
626
627         r = PAM_SUCCESS;
628
629 finish:
630         if (lock_fd >= 0)
631                 close_nointr_nofail(lock_fd);
632
633         free(session_path);
634         free(nosession_path);
635         free(user_path);
636
637         strv_free(controllers);
638
639         return r;
640 }