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