]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/login/pam_systemd.c
525b2a0393f1a5ff386d766cae7939d2a291845e
[thirdparty/systemd.git] / src / login / pam_systemd.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <endian.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <pwd.h>
7 #include <security/_pam_macros.h>
8 #include <security/pam_ext.h>
9 #include <security/pam_misc.h>
10 #include <security/pam_modules.h>
11 #include <security/pam_modutil.h>
12 #include <sys/file.h>
13 #include <sys/stat.h>
14 #include <sys/sysmacros.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17
18 #include "alloc-util.h"
19 #include "audit-util.h"
20 #include "bus-common-errors.h"
21 #include "bus-error.h"
22 #include "bus-internal.h"
23 #include "bus-locator.h"
24 #include "cgroup-setup.h"
25 #include "errno-util.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "format-util.h"
29 #include "fs-util.h"
30 #include "hostname-util.h"
31 #include "locale-util.h"
32 #include "login-util.h"
33 #include "macro.h"
34 #include "pam-util.h"
35 #include "parse-util.h"
36 #include "path-util.h"
37 #include "process-util.h"
38 #include "rlimit-util.h"
39 #include "socket-util.h"
40 #include "stdio-util.h"
41 #include "strv.h"
42 #include "terminal-util.h"
43 #include "user-util.h"
44 #include "userdb.h"
45
46 #define LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC (2*USEC_PER_MINUTE)
47
48 static int parse_argv(
49 pam_handle_t *handle,
50 int argc, const char **argv,
51 const char **class,
52 const char **type,
53 const char **desktop,
54 bool *debug) {
55
56 unsigned i;
57
58 assert(argc >= 0);
59 assert(argc == 0 || argv);
60
61 for (i = 0; i < (unsigned) argc; i++) {
62 const char *p;
63
64 if ((p = startswith(argv[i], "class="))) {
65 if (class)
66 *class = p;
67
68 } else if ((p = startswith(argv[i], "type="))) {
69 if (type)
70 *type = p;
71
72 } else if ((p = startswith(argv[i], "desktop="))) {
73 if (desktop)
74 *desktop = p;
75
76 } else if (streq(argv[i], "debug")) {
77 if (debug)
78 *debug = true;
79
80 } else if ((p = startswith(argv[i], "debug="))) {
81 int k;
82
83 k = parse_boolean(p);
84 if (k < 0)
85 pam_syslog(handle, LOG_WARNING, "Failed to parse debug= argument, ignoring: %s", p);
86 else if (debug)
87 *debug = k;
88
89 } else
90 pam_syslog(handle, LOG_WARNING, "Unknown parameter '%s', ignoring", argv[i]);
91 }
92
93 return 0;
94 }
95
96 static int acquire_user_record(
97 pam_handle_t *handle,
98 UserRecord **ret_record) {
99
100 _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
101 const char *username = NULL, *json = NULL;
102 _cleanup_free_ char *field = NULL;
103 int r;
104
105 assert(handle);
106
107 r = pam_get_user(handle, &username, NULL);
108 if (r != PAM_SUCCESS) {
109 pam_syslog(handle, LOG_ERR, "Failed to get user name: %s", pam_strerror(handle, r));
110 return r;
111 }
112
113 if (isempty(username)) {
114 pam_syslog(handle, LOG_ERR, "User name not valid.");
115 return PAM_SERVICE_ERR;
116 }
117
118 /* If pam_systemd_homed (or some other module) already acquired the user record we can reuse it
119 * here. */
120 field = strjoin("systemd-user-record-", username);
121 if (!field)
122 return pam_log_oom(handle);
123
124 r = pam_get_data(handle, field, (const void**) &json);
125 if (!IN_SET(r, PAM_SUCCESS, PAM_NO_MODULE_DATA)) {
126 pam_syslog(handle, LOG_ERR, "Failed to get PAM user record data: %s", pam_strerror(handle, r));
127 return r;
128 }
129 if (r == PAM_SUCCESS && json) {
130 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
131
132 /* Parse cached record */
133 r = json_parse(json, JSON_PARSE_SENSITIVE, &v, NULL, NULL);
134 if (r < 0) {
135 pam_syslog(handle, LOG_ERR, "Failed to parse JSON user record: %s", strerror_safe(r));
136 return PAM_SERVICE_ERR;
137 }
138
139 ur = user_record_new();
140 if (!ur)
141 return pam_log_oom(handle);
142
143 r = user_record_load(ur, v, USER_RECORD_LOAD_REFUSE_SECRET);
144 if (r < 0) {
145 pam_syslog(handle, LOG_ERR, "Failed to load user record: %s", strerror_safe(r));
146 return PAM_SERVICE_ERR;
147 }
148
149 /* Safety check if cached record actually matches what we are looking for */
150 if (!streq_ptr(username, ur->user_name)) {
151 pam_syslog(handle, LOG_ERR, "Acquired user record does not match user name.");
152 return PAM_SERVICE_ERR;
153 }
154 } else {
155 _cleanup_free_ char *formatted = NULL;
156
157 /* Request the record ourselves */
158 r = userdb_by_name(username, 0, &ur);
159 if (r < 0) {
160 pam_syslog(handle, LOG_ERR, "Failed to get user record: %s", strerror_safe(r));
161 return PAM_USER_UNKNOWN;
162 }
163
164 r = json_variant_format(ur->json, 0, &formatted);
165 if (r < 0) {
166 pam_syslog(handle, LOG_ERR, "Failed to format user JSON: %s", strerror_safe(r));
167 return PAM_SERVICE_ERR;
168 }
169
170 /* And cache it for everyone else */
171 r = pam_set_data(handle, field, formatted, pam_cleanup_free);
172 if (r < 0) {
173 pam_syslog(handle, LOG_ERR, "Failed to set PAM user record data '%s': %s",
174 field, pam_strerror(handle, r));
175 return r;
176 }
177
178 TAKE_PTR(formatted);
179 }
180
181 if (!uid_is_valid(ur->uid)) {
182 pam_syslog(handle, LOG_ERR, "Acquired user record does not have a UID.");
183 return PAM_SERVICE_ERR;
184 }
185
186 if (ret_record)
187 *ret_record = TAKE_PTR(ur);
188
189 return PAM_SUCCESS;
190 }
191
192 static bool display_is_local(const char *display) {
193 assert(display);
194
195 return
196 display[0] == ':' &&
197 display[1] >= '0' &&
198 display[1] <= '9';
199 }
200
201 static int socket_from_display(const char *display, char **path) {
202 size_t k;
203 char *f, *c;
204
205 assert(display);
206 assert(path);
207
208 if (!display_is_local(display))
209 return -EINVAL;
210
211 k = strspn(display+1, "0123456789");
212
213 f = new(char, STRLEN("/tmp/.X11-unix/X") + k + 1);
214 if (!f)
215 return -ENOMEM;
216
217 c = stpcpy(f, "/tmp/.X11-unix/X");
218 memcpy(c, display+1, k);
219 c[k] = 0;
220
221 *path = f;
222
223 return 0;
224 }
225
226 static int get_seat_from_display(const char *display, const char **seat, uint32_t *vtnr) {
227 union sockaddr_union sa;
228 socklen_t sa_len;
229 _cleanup_free_ char *p = NULL, *sys_path = NULL, *tty = NULL;
230 _cleanup_close_ int fd = -1;
231 struct ucred ucred;
232 int v, r;
233 dev_t display_ctty;
234
235 assert(display);
236 assert(vtnr);
237
238 /* We deduce the X11 socket from the display name, then use
239 * SO_PEERCRED to determine the X11 server process, ask for
240 * the controlling tty of that and if it's a VC then we know
241 * the seat and the virtual terminal. Sounds ugly, is only
242 * semi-ugly. */
243
244 r = socket_from_display(display, &p);
245 if (r < 0)
246 return r;
247 r = sockaddr_un_set_path(&sa.un, p);
248 if (r < 0)
249 return r;
250 sa_len = r;
251
252 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
253 if (fd < 0)
254 return -errno;
255
256 if (connect(fd, &sa.sa, sa_len) < 0)
257 return -errno;
258
259 r = getpeercred(fd, &ucred);
260 if (r < 0)
261 return r;
262
263 r = get_ctty_devnr(ucred.pid, &display_ctty);
264 if (r < 0)
265 return r;
266
267 if (asprintf(&sys_path, "/sys/dev/char/%d:%d", major(display_ctty), minor(display_ctty)) < 0)
268 return -ENOMEM;
269 r = readlink_value(sys_path, &tty);
270 if (r < 0)
271 return r;
272
273 v = vtnr_from_tty(tty);
274 if (v < 0)
275 return v;
276 else if (v == 0)
277 return -ENOENT;
278
279 if (seat)
280 *seat = "seat0";
281 *vtnr = (uint32_t) v;
282
283 return 0;
284 }
285
286 static int export_legacy_dbus_address(
287 pam_handle_t *handle,
288 const char *runtime) {
289
290 const char *s;
291 _cleanup_free_ char *t = NULL;
292 int r = PAM_BUF_ERR;
293
294 /* We need to export $DBUS_SESSION_BUS_ADDRESS because various applications will not connect
295 * correctly to the bus without it. This setting matches what dbus.socket does for the user
296 * session using 'systemctl --user set-environment'. We want to have the same configuration
297 * in processes started from the PAM session.
298 *
299 * The setting of the address is guarded by the access() check because it is also possible to compile
300 * dbus without --enable-user-session, in which case this socket is not used, and
301 * $DBUS_SESSION_BUS_ADDRESS should not be set. An alternative approach would to not do the access()
302 * check here, and let applications try on their own, by using "unix:path=%s/bus;autolaunch:". But we
303 * expect the socket to be present by the time we do this check, so we can just as well check once
304 * here. */
305
306 s = strjoina(runtime, "/bus");
307 if (access(s, F_OK) < 0)
308 return PAM_SUCCESS;
309
310 if (asprintf(&t, DEFAULT_USER_BUS_ADDRESS_FMT, runtime) < 0)
311 return pam_log_oom(handle);
312
313 r = pam_misc_setenv(handle, "DBUS_SESSION_BUS_ADDRESS", t, 0);
314 if (r != PAM_SUCCESS) {
315 pam_syslog(handle, LOG_ERR, "Failed to set bus variable: %s", pam_strerror(handle, r));
316 return r;
317 }
318
319 return PAM_SUCCESS;
320 }
321
322 static int append_session_memory_max(pam_handle_t *handle, sd_bus_message *m, const char *limit) {
323 uint64_t val;
324 int r;
325
326 if (isempty(limit))
327 return PAM_SUCCESS;
328
329 if (streq(limit, "infinity")) {
330 r = sd_bus_message_append(m, "(sv)", "MemoryMax", "t", (uint64_t)-1);
331 if (r < 0)
332 return pam_bus_log_create_error(handle, r);
333
334 return PAM_SUCCESS;
335 }
336
337 r = parse_permille(limit);
338 if (r >= 0) {
339 r = sd_bus_message_append(m, "(sv)", "MemoryMaxScale", "u", (uint32_t) (((uint64_t) r * UINT32_MAX) / 1000U));
340 if (r < 0)
341 return pam_bus_log_create_error(handle, r);
342
343 return PAM_SUCCESS;
344 }
345
346 r = parse_size(limit, 1024, &val);
347 if (r >= 0) {
348 r = sd_bus_message_append(m, "(sv)", "MemoryMax", "t", val);
349 if (r < 0)
350 return pam_bus_log_create_error(handle, r);
351
352 return PAM_SUCCESS;
353 }
354
355 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.memory_max, ignoring: %s", limit);
356 return PAM_SUCCESS;
357 }
358
359 static int append_session_runtime_max_sec(pam_handle_t *handle, sd_bus_message *m, const char *limit) {
360 usec_t val;
361 int r;
362
363 /* No need to parse "infinity" here, it will be set by default later in scope_init() */
364 if (isempty(limit) || streq(limit, "infinity"))
365 return PAM_SUCCESS;
366
367 r = parse_sec(limit, &val);
368 if (r >= 0) {
369 r = sd_bus_message_append(m, "(sv)", "RuntimeMaxUSec", "t", (uint64_t) val);
370 if (r < 0)
371 return pam_bus_log_create_error(handle, r);
372 } else
373 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.runtime_max_sec: %s, ignoring.", limit);
374
375 return PAM_SUCCESS;
376 }
377
378 static int append_session_tasks_max(pam_handle_t *handle, sd_bus_message *m, const char *limit) {
379 uint64_t val;
380 int r;
381
382 /* No need to parse "infinity" here, it will be set unconditionally later in manager_start_scope() */
383 if (isempty(limit) || streq(limit, "infinity"))
384 return PAM_SUCCESS;
385
386 r = safe_atou64(limit, &val);
387 if (r >= 0) {
388 r = sd_bus_message_append(m, "(sv)", "TasksMax", "t", val);
389 if (r < 0)
390 return pam_bus_log_create_error(handle, r);
391 } else
392 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.tasks_max, ignoring: %s", limit);
393
394 return PAM_SUCCESS;
395 }
396
397 static int append_session_cg_weight(pam_handle_t *handle, sd_bus_message *m, const char *limit, const char *field) {
398 uint64_t val;
399 int r;
400
401 if (isempty(limit))
402 return PAM_SUCCESS;
403
404 r = cg_weight_parse(limit, &val);
405 if (r >= 0) {
406 r = sd_bus_message_append(m, "(sv)", field, "t", val);
407 if (r < 0)
408 return pam_bus_log_create_error(handle, r);
409 } else if (streq(field, "CPUWeight"))
410 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.cpu_weight, ignoring: %s", limit);
411 else
412 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.io_weight, ignoring: %s", limit);
413
414 return PAM_SUCCESS;
415 }
416
417 static const char* getenv_harder(pam_handle_t *handle, const char *key, const char *fallback) {
418 const char *v;
419
420 assert(handle);
421 assert(key);
422
423 /* Looks for an environment variable, preferably in the environment block associated with the
424 * specified PAM handle, falling back to the process' block instead. Why check both? Because we want
425 * to permit configuration of session properties from unit files that invoke PAM services, so that
426 * PAM services don't have to be reworked to set systemd-specific properties, but these properties
427 * can still be set from the unit file Environment= block. */
428
429 v = pam_getenv(handle, key);
430 if (!isempty(v))
431 return v;
432
433 /* We use secure_getenv() here, since we might get loaded into su/sudo, which are SUID. Ideally
434 * they'd clean up the environment before invoking foreign code (such as PAM modules), but alas they
435 * currently don't (to be precise, they clean up the environment they pass to their children, but
436 * not their own environ[]). */
437 v = secure_getenv(key);
438 if (!isempty(v))
439 return v;
440
441 return fallback;
442 }
443
444 static int update_environment(pam_handle_t *handle, const char *key, const char *value) {
445 int r;
446
447 assert(handle);
448 assert(key);
449
450 /* Updates the environment, but only if there's actually a value set. Also, log about errors */
451
452 if (isempty(value))
453 return PAM_SUCCESS;
454
455 r = pam_misc_setenv(handle, key, value, 0);
456 if (r != PAM_SUCCESS)
457 pam_syslog(handle, LOG_ERR, "Failed to set environment variable %s: %s", key, pam_strerror(handle, r));
458
459 return r;
460 }
461
462 static bool validate_runtime_directory(pam_handle_t *handle, const char *path, uid_t uid) {
463 struct stat st;
464
465 assert(handle);
466 assert(path);
467
468 /* Some extra paranoia: let's not set $XDG_RUNTIME_DIR if the directory we'd set it to isn't actually
469 * set up properly for us. This is supposed to provide a careful safety net for supporting su/sudo
470 * type transitions: in that case the UID changes, but the session and thus the user owning it
471 * doesn't change. Since the $XDG_RUNTIME_DIR life-cycle is bound to the session's user being logged
472 * in at least once we should be particularly careful when setting the environment variable, since
473 * otherwise we might end up setting $XDG_RUNTIME_DIR to some directory owned by the wrong user. */
474
475 if (!path_is_absolute(path)) {
476 pam_syslog(handle, LOG_ERR, "Provided runtime directory '%s' is not absolute.", path);
477 goto fail;
478 }
479
480 if (lstat(path, &st) < 0) {
481 pam_syslog(handle, LOG_ERR, "Failed to stat() runtime directory '%s': %s", path, strerror_safe(errno));
482 goto fail;
483 }
484
485 if (!S_ISDIR(st.st_mode)) {
486 pam_syslog(handle, LOG_ERR, "Runtime directory '%s' is not actually a directory.", path);
487 goto fail;
488 }
489
490 if (st.st_uid != uid) {
491 pam_syslog(handle, LOG_ERR, "Runtime directory '%s' is not owned by UID " UID_FMT ", as it should.", path, uid);
492 goto fail;
493 }
494
495 return true;
496
497 fail:
498 pam_syslog(handle, LOG_WARNING, "Not setting $XDG_RUNTIME_DIR, as the directory is not in order.");
499 return false;
500 }
501
502 static int pam_putenv_and_log(pam_handle_t *handle, const char *e, bool debug) {
503 int r;
504
505 assert(handle);
506 assert(e);
507
508 r = pam_putenv(handle, e);
509 if (r != PAM_SUCCESS) {
510 pam_syslog(handle, LOG_ERR, "Failed to set PAM environment variable %s: %s", e, pam_strerror(handle, r));
511 return r;
512 }
513
514 if (debug)
515 pam_syslog(handle, LOG_DEBUG, "PAM environment variable %s set based on user record.", e);
516
517 return PAM_SUCCESS;
518 }
519
520 static int apply_user_record_settings(pam_handle_t *handle, UserRecord *ur, bool debug) {
521 char **i;
522 int r;
523
524 assert(handle);
525 assert(ur);
526
527 if (ur->umask != MODE_INVALID) {
528 umask(ur->umask);
529
530 if (debug)
531 pam_syslog(handle, LOG_DEBUG, "Set user umask to %04o based on user record.", ur->umask);
532 }
533
534 STRV_FOREACH(i, ur->environment) {
535 _cleanup_free_ char *n = NULL;
536 const char *e;
537
538 assert_se(e = strchr(*i, '=')); /* environment was already validated while parsing JSON record, this thus must hold */
539
540 n = strndup(*i, e - *i);
541 if (!n)
542 return pam_log_oom(handle);
543
544 if (pam_getenv(handle, n)) {
545 if (debug)
546 pam_syslog(handle, LOG_DEBUG, "PAM environment variable $%s already set, not changing based on record.", *i);
547 continue;
548 }
549
550 r = pam_putenv_and_log(handle, *i, debug);
551 if (r != PAM_SUCCESS)
552 return r;
553 }
554
555 if (ur->email_address) {
556 if (pam_getenv(handle, "EMAIL")) {
557 if (debug)
558 pam_syslog(handle, LOG_DEBUG, "PAM environment variable $EMAIL already set, not changing based on user record.");
559 } else {
560 _cleanup_free_ char *joined = NULL;
561
562 joined = strjoin("EMAIL=", ur->email_address);
563 if (!joined)
564 return pam_log_oom(handle);
565
566 r = pam_putenv_and_log(handle, joined, debug);
567 if (r != PAM_SUCCESS)
568 return r;
569 }
570 }
571
572 if (ur->time_zone) {
573 if (pam_getenv(handle, "TZ")) {
574 if (debug)
575 pam_syslog(handle, LOG_DEBUG, "PAM environment variable $TZ already set, not changing based on user record.");
576 } else if (!timezone_is_valid(ur->time_zone, LOG_DEBUG)) {
577 if (debug)
578 pam_syslog(handle, LOG_DEBUG, "Time zone specified in user record is not valid locally, not setting $TZ.");
579 } else {
580 _cleanup_free_ char *joined = NULL;
581
582 joined = strjoin("TZ=:", ur->time_zone);
583 if (!joined)
584 return pam_log_oom(handle);
585
586 r = pam_putenv_and_log(handle, joined, debug);
587 if (r != PAM_SUCCESS)
588 return r;
589 }
590 }
591
592 if (ur->preferred_language) {
593 if (pam_getenv(handle, "LANG")) {
594 if (debug)
595 pam_syslog(handle, LOG_DEBUG, "PAM environment variable $LANG already set, not changing based on user record.");
596 } else if (locale_is_installed(ur->preferred_language) <= 0) {
597 if (debug)
598 pam_syslog(handle, LOG_DEBUG, "Preferred language specified in user record is not valid or not installed, not setting $LANG.");
599 } else {
600 _cleanup_free_ char *joined = NULL;
601
602 joined = strjoin("LANG=", ur->preferred_language);
603 if (!joined)
604 return pam_log_oom(handle);
605
606 r = pam_putenv_and_log(handle, joined, debug);
607 if (r != PAM_SUCCESS)
608 return r;
609 }
610 }
611
612 if (nice_is_valid(ur->nice_level)) {
613 if (nice(ur->nice_level) < 0)
614 pam_syslog(handle, LOG_ERR, "Failed to set nice level to %i, ignoring: %s", ur->nice_level, strerror_safe(errno));
615 else if (debug)
616 pam_syslog(handle, LOG_DEBUG, "Nice level set, based on user record.");
617 }
618
619 for (int rl = 0; rl < _RLIMIT_MAX; rl++) {
620
621 if (!ur->rlimits[rl])
622 continue;
623
624 r = setrlimit_closest(rl, ur->rlimits[rl]);
625 if (r < 0)
626 pam_syslog(handle, LOG_ERR, "Failed to set resource limit %s, ignoring: %s", rlimit_to_string(rl), strerror_safe(r));
627 else if (debug)
628 pam_syslog(handle, LOG_DEBUG, "Resource limit %s set, based on user record.", rlimit_to_string(rl));
629 }
630
631 return PAM_SUCCESS;
632 }
633
634 static int configure_runtime_directory(
635 pam_handle_t *handle,
636 UserRecord *ur,
637 const char *rt) {
638
639 int r;
640
641 assert(handle);
642 assert(ur);
643 assert(rt);
644
645 if (!validate_runtime_directory(handle, rt, ur->uid))
646 return PAM_SUCCESS;
647
648 r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", rt, 0);
649 if (r != PAM_SUCCESS) {
650 pam_syslog(handle, LOG_ERR, "Failed to set runtime dir: %s", pam_strerror(handle, r));
651 return r;
652 }
653
654 return export_legacy_dbus_address(handle, rt);
655 }
656
657 _public_ PAM_EXTERN int pam_sm_open_session(
658 pam_handle_t *handle,
659 int flags,
660 int argc, const char **argv) {
661
662 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
663 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
664 const char
665 *id, *object_path, *runtime_path,
666 *service = NULL,
667 *tty = NULL, *display = NULL,
668 *remote_user = NULL, *remote_host = NULL,
669 *seat = NULL,
670 *type = NULL, *class = NULL,
671 *class_pam = NULL, *type_pam = NULL, *cvtnr = NULL, *desktop = NULL, *desktop_pam = NULL,
672 *memory_max = NULL, *tasks_max = NULL, *cpu_weight = NULL, *io_weight = NULL, *runtime_max_sec = NULL;
673 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
674 _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
675 int session_fd = -1, existing, r;
676 bool debug = false, remote;
677 uint32_t vtnr = 0;
678 uid_t original_uid;
679
680 assert(handle);
681
682 if (parse_argv(handle,
683 argc, argv,
684 &class_pam,
685 &type_pam,
686 &desktop_pam,
687 &debug) < 0)
688 return PAM_SESSION_ERR;
689
690 if (debug)
691 pam_syslog(handle, LOG_DEBUG, "pam-systemd initializing");
692
693 r = acquire_user_record(handle, &ur);
694 if (r != PAM_SUCCESS)
695 return r;
696
697 /* Make most of this a NOP on non-logind systems */
698 if (!logind_running())
699 goto success;
700
701 /* Make sure we don't enter a loop by talking to
702 * systemd-logind when it is actually waiting for the
703 * background to finish start-up. If the service is
704 * "systemd-user" we simply set XDG_RUNTIME_DIR and
705 * leave. */
706
707 (void) pam_get_item(handle, PAM_SERVICE, (const void**) &service);
708 if (streq_ptr(service, "systemd-user")) {
709 char rt[STRLEN("/run/user/") + DECIMAL_STR_MAX(uid_t)];
710
711 xsprintf(rt, "/run/user/"UID_FMT, ur->uid);
712 r = configure_runtime_directory(handle, ur, rt);
713 if (r != PAM_SUCCESS)
714 return r;
715
716 goto success;
717 }
718
719 /* Otherwise, we ask logind to create a session for us */
720
721 (void) pam_get_item(handle, PAM_XDISPLAY, (const void**) &display);
722 (void) pam_get_item(handle, PAM_TTY, (const void**) &tty);
723 (void) pam_get_item(handle, PAM_RUSER, (const void**) &remote_user);
724 (void) pam_get_item(handle, PAM_RHOST, (const void**) &remote_host);
725
726 seat = getenv_harder(handle, "XDG_SEAT", NULL);
727 cvtnr = getenv_harder(handle, "XDG_VTNR", NULL);
728 type = getenv_harder(handle, "XDG_SESSION_TYPE", type_pam);
729 class = getenv_harder(handle, "XDG_SESSION_CLASS", class_pam);
730 desktop = getenv_harder(handle, "XDG_SESSION_DESKTOP", desktop_pam);
731
732 tty = strempty(tty);
733
734 if (strchr(tty, ':')) {
735 /* A tty with a colon is usually an X11 display, placed there to show up in utmp. We rearrange things
736 * and don't pretend that an X display was a tty. */
737 if (isempty(display))
738 display = tty;
739 tty = NULL;
740
741 } else if (streq(tty, "cron")) {
742 /* cron is setting PAM_TTY to "cron" for some reason (the commit carries no information why, but
743 * probably because it wants to set it to something as pam_time/pam_access/… require PAM_TTY to be set
744 * (as they otherwise even try to update it!) — but cron doesn't actually allocate a TTY for its forked
745 * off processes.) */
746 type = "unspecified";
747 class = "background";
748 tty = NULL;
749
750 } else if (streq(tty, "ssh")) {
751 /* ssh has been setting PAM_TTY to "ssh" (for the same reason as cron does this, see above. For further
752 * details look for "PAM_TTY_KLUDGE" in the openssh sources). */
753 type ="tty";
754 class = "user";
755 tty = NULL; /* This one is particularly sad, as this means that ssh sessions — even though usually
756 * associated with a pty — won't be tracked by their tty in logind. This is because ssh
757 * does the PAM session registration early for new connections, and registers a pty only
758 * much later (this is because it doesn't know yet if it needs one at all, as whether to
759 * register a pty or not is negotiated much later in the protocol). */
760
761 } else
762 /* Chop off leading /dev prefix that some clients specify, but others do not. */
763 tty = skip_dev_prefix(tty);
764
765 /* If this fails vtnr will be 0, that's intended */
766 if (!isempty(cvtnr))
767 (void) safe_atou32(cvtnr, &vtnr);
768
769 if (!isempty(display) && !vtnr) {
770 if (isempty(seat))
771 (void) get_seat_from_display(display, &seat, &vtnr);
772 else if (streq(seat, "seat0"))
773 (void) get_seat_from_display(display, NULL, &vtnr);
774 }
775
776 if (seat && !streq(seat, "seat0") && vtnr != 0) {
777 if (debug)
778 pam_syslog(handle, LOG_DEBUG, "Ignoring vtnr %"PRIu32" for %s which is not seat0", vtnr, seat);
779 vtnr = 0;
780 }
781
782 if (isempty(type))
783 type = !isempty(display) ? "x11" :
784 !isempty(tty) ? "tty" : "unspecified";
785
786 if (isempty(class))
787 class = streq(type, "unspecified") ? "background" : "user";
788
789 remote = !isempty(remote_host) && !is_localhost(remote_host);
790
791 (void) pam_get_data(handle, "systemd.memory_max", (const void **)&memory_max);
792 (void) pam_get_data(handle, "systemd.tasks_max", (const void **)&tasks_max);
793 (void) pam_get_data(handle, "systemd.cpu_weight", (const void **)&cpu_weight);
794 (void) pam_get_data(handle, "systemd.io_weight", (const void **)&io_weight);
795 (void) pam_get_data(handle, "systemd.runtime_max_sec", (const void **)&runtime_max_sec);
796
797 /* Talk to logind over the message bus */
798
799 r = pam_acquire_bus_connection(handle, &bus);
800 if (r != PAM_SUCCESS)
801 return r;
802
803 if (debug) {
804 pam_syslog(handle, LOG_DEBUG, "Asking logind to create session: "
805 "uid="UID_FMT" pid="PID_FMT" service=%s type=%s class=%s desktop=%s seat=%s vtnr=%"PRIu32" tty=%s display=%s remote=%s remote_user=%s remote_host=%s",
806 ur->uid, getpid_cached(),
807 strempty(service),
808 type, class, strempty(desktop),
809 strempty(seat), vtnr, strempty(tty), strempty(display),
810 yes_no(remote), strempty(remote_user), strempty(remote_host));
811 pam_syslog(handle, LOG_DEBUG, "Session limits: "
812 "memory_max=%s tasks_max=%s cpu_weight=%s io_weight=%s runtime_max_sec=%s",
813 strna(memory_max), strna(tasks_max), strna(cpu_weight), strna(io_weight), strna(runtime_max_sec));
814 }
815
816 r = bus_message_new_method_call(bus, &m, bus_login_mgr, "CreateSession");
817 if (r < 0)
818 return pam_bus_log_create_error(handle, r);
819
820 r = sd_bus_message_append(m, "uusssssussbss",
821 (uint32_t) ur->uid,
822 0,
823 service,
824 type,
825 class,
826 desktop,
827 seat,
828 vtnr,
829 tty,
830 display,
831 remote,
832 remote_user,
833 remote_host);
834 if (r < 0)
835 return pam_bus_log_create_error(handle, r);
836
837 r = sd_bus_message_open_container(m, 'a', "(sv)");
838 if (r < 0)
839 return pam_bus_log_create_error(handle, r);
840
841 r = append_session_memory_max(handle, m, memory_max);
842 if (r != PAM_SUCCESS)
843 return r;
844
845 r = append_session_runtime_max_sec(handle, m, runtime_max_sec);
846 if (r != PAM_SUCCESS)
847 return r;
848
849 r = append_session_tasks_max(handle, m, tasks_max);
850 if (r != PAM_SUCCESS)
851 return r;
852
853 r = append_session_cg_weight(handle, m, cpu_weight, "CPUWeight");
854 if (r != PAM_SUCCESS)
855 return r;
856
857 r = append_session_cg_weight(handle, m, io_weight, "IOWeight");
858 if (r != PAM_SUCCESS)
859 return r;
860
861 r = sd_bus_message_close_container(m);
862 if (r < 0)
863 return pam_bus_log_create_error(handle, r);
864
865 r = sd_bus_call(bus, m, LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC, &error, &reply);
866 if (r < 0) {
867 if (sd_bus_error_has_name(&error, BUS_ERROR_SESSION_BUSY)) {
868 if (debug)
869 pam_syslog(handle, LOG_DEBUG, "Not creating session: %s", bus_error_message(&error, r));
870
871 /* We are already in a session, don't do anything */
872 goto success;
873 } else {
874 pam_syslog(handle, LOG_ERR, "Failed to create session: %s", bus_error_message(&error, r));
875 return PAM_SESSION_ERR;
876 }
877 }
878
879 r = sd_bus_message_read(reply,
880 "soshusub",
881 &id,
882 &object_path,
883 &runtime_path,
884 &session_fd,
885 &original_uid,
886 &seat,
887 &vtnr,
888 &existing);
889 if (r < 0)
890 return pam_bus_log_parse_error(handle, r);
891
892 if (debug)
893 pam_syslog(handle, LOG_DEBUG, "Reply from logind: "
894 "id=%s object_path=%s runtime_path=%s session_fd=%d seat=%s vtnr=%u original_uid=%u",
895 id, object_path, runtime_path, session_fd, seat, vtnr, original_uid);
896
897 r = update_environment(handle, "XDG_SESSION_ID", id);
898 if (r != PAM_SUCCESS)
899 return r;
900
901 if (original_uid == ur->uid) {
902 /* Don't set $XDG_RUNTIME_DIR if the user we now authenticated for does not match the
903 * original user of the session. We do this in order not to result in privileged apps
904 * clobbering the runtime directory unnecessarily. */
905
906 r = configure_runtime_directory(handle, ur, runtime_path);
907 if (r != PAM_SUCCESS)
908 return r;
909 }
910
911 /* Most likely we got the session/type/class from environment variables, but might have gotten the data
912 * somewhere else (for example PAM module parameters). Let's now update the environment variables, so that this
913 * data is inherited into the session processes, and programs can rely on them to be initialized. */
914
915 r = update_environment(handle, "XDG_SESSION_TYPE", type);
916 if (r != PAM_SUCCESS)
917 return r;
918
919 r = update_environment(handle, "XDG_SESSION_CLASS", class);
920 if (r != PAM_SUCCESS)
921 return r;
922
923 r = update_environment(handle, "XDG_SESSION_DESKTOP", desktop);
924 if (r != PAM_SUCCESS)
925 return r;
926
927 r = update_environment(handle, "XDG_SEAT", seat);
928 if (r != PAM_SUCCESS)
929 return r;
930
931 if (vtnr > 0) {
932 char buf[DECIMAL_STR_MAX(vtnr)];
933 sprintf(buf, "%u", vtnr);
934
935 r = update_environment(handle, "XDG_VTNR", buf);
936 if (r != PAM_SUCCESS)
937 return r;
938 }
939
940 r = pam_set_data(handle, "systemd.existing", INT_TO_PTR(!!existing), NULL);
941 if (r != PAM_SUCCESS) {
942 pam_syslog(handle, LOG_ERR, "Failed to install existing flag: %s", pam_strerror(handle, r));
943 return r;
944 }
945
946 if (session_fd >= 0) {
947 session_fd = fcntl(session_fd, F_DUPFD_CLOEXEC, 3);
948 if (session_fd < 0) {
949 pam_syslog(handle, LOG_ERR, "Failed to dup session fd: %m");
950 return PAM_SESSION_ERR;
951 }
952
953 r = pam_set_data(handle, "systemd.session-fd", FD_TO_PTR(session_fd), NULL);
954 if (r != PAM_SUCCESS) {
955 pam_syslog(handle, LOG_ERR, "Failed to install session fd: %s", pam_strerror(handle, r));
956 safe_close(session_fd);
957 return r;
958 }
959 }
960
961 success:
962 r = apply_user_record_settings(handle, ur, debug);
963 if (r != PAM_SUCCESS)
964 return r;
965
966 /* Let's release the D-Bus connection, after all the session might live quite a long time, and we are
967 * not going to use the bus connection in that time, so let's better close before the daemon kicks us
968 * off because we are not processing anything. */
969 (void) pam_release_bus_connection(handle);
970 return PAM_SUCCESS;
971 }
972
973 _public_ PAM_EXTERN int pam_sm_close_session(
974 pam_handle_t *handle,
975 int flags,
976 int argc, const char **argv) {
977
978 const void *existing = NULL;
979 bool debug = false;
980 const char *id;
981 int r;
982
983 assert(handle);
984
985 if (parse_argv(handle,
986 argc, argv,
987 NULL,
988 NULL,
989 NULL,
990 &debug) < 0)
991 return PAM_SESSION_ERR;
992
993 if (debug)
994 pam_syslog(handle, LOG_DEBUG, "pam-systemd shutting down");
995
996 /* Only release session if it wasn't pre-existing when we
997 * tried to create it */
998 (void) pam_get_data(handle, "systemd.existing", &existing);
999
1000 id = pam_getenv(handle, "XDG_SESSION_ID");
1001 if (id && !existing) {
1002 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1003 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1004
1005 /* Before we go and close the FIFO we need to tell logind that this is a clean session
1006 * shutdown, so that it doesn't just go and slaughter us immediately after closing the fd */
1007
1008 r = pam_acquire_bus_connection(handle, &bus);
1009 if (r != PAM_SUCCESS)
1010 return r;
1011
1012 r = bus_call_method(bus, bus_login_mgr, "ReleaseSession", &error, NULL, "s", id);
1013 if (r < 0) {
1014 pam_syslog(handle, LOG_ERR, "Failed to release session: %s", bus_error_message(&error, r));
1015 return PAM_SESSION_ERR;
1016 }
1017 }
1018
1019 /* Note that we are knowingly leaking the FIFO fd here. This way, logind can watch us die. If we
1020 * closed it here it would not have any clue when that is completed. Given that one cannot really
1021 * have multiple PAM sessions open from the same process this means we will leak one FD at max. */
1022
1023 return PAM_SUCCESS;
1024 }