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