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