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