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