]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/login/pam_systemd.c
pam-systemd: port over to use a UserRecord structure
[thirdparty/systemd.git] / src / login / pam_systemd.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
8c6db833 2
00229fe4 3#include <endian.h>
8c6db833
LP
4#include <errno.h>
5#include <fcntl.h>
8c6db833 6#include <pwd.h>
8c6db833 7#include <security/_pam_macros.h>
8c6db833
LP
8#include <security/pam_ext.h>
9#include <security/pam_misc.h>
00229fe4
LP
10#include <security/pam_modules.h>
11#include <security/pam_modutil.h>
12#include <sys/file.h>
ca78ad1d
ZJS
13#include <sys/stat.h>
14#include <sys/types.h>
15#include <unistd.h>
8c6db833 16
b5efdb8a 17#include "alloc-util.h"
430f0182 18#include "audit-util.h"
00229fe4
LP
19#include "bus-common-errors.h"
20#include "bus-error.h"
47094ce0 21#include "bus-internal.h"
ffcfcb6b 22#include "bus-util.h"
fdb3deca 23#include "cgroup-setup.h"
4bbccb02 24#include "errno-util.h"
3ffd4af2 25#include "fd-util.h"
a5c32cff 26#include "fileio.h"
f97b34a6 27#include "format-util.h"
958b66ea 28#include "hostname-util.h"
00229fe4
LP
29#include "login-util.h"
30#include "macro.h"
d750dde2 31#include "pam-util.h"
6bedfcbb 32#include "parse-util.h"
e37e5ed3 33#include "path-util.h"
df0ff127 34#include "process-util.h"
00229fe4 35#include "socket-util.h"
055c08ef 36#include "stdio-util.h"
00229fe4
LP
37#include "strv.h"
38#include "terminal-util.h"
9ab0d3eb
LP
39#include "user-util.h"
40#include "userdb.h"
8c6db833 41
fbcb6300
LP
42#define LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC (2*USEC_PER_MINUTE)
43
baae0358
LP
44static int parse_argv(
45 pam_handle_t *handle,
46 int argc, const char **argv,
47 const char **class,
49ebd11f 48 const char **type,
f5cb2820 49 const char **desktop,
baae0358 50 bool *debug) {
8c6db833
LP
51
52 unsigned i;
53
54 assert(argc >= 0);
55 assert(argc == 0 || argv);
56
49ebd11f 57 for (i = 0; i < (unsigned) argc; i++) {
d9608d40
LP
58 const char *p;
59
60 if ((p = startswith(argv[i], "class="))) {
485507b8 61 if (class)
d9608d40 62 *class = p;
485507b8 63
d9608d40 64 } else if ((p = startswith(argv[i], "type="))) {
49ebd11f 65 if (type)
d9608d40 66 *type = p;
49ebd11f 67
d9608d40 68 } else if ((p = startswith(argv[i], "desktop="))) {
f5cb2820 69 if (desktop)
d9608d40 70 *desktop = p;
f5cb2820 71
05a049cc
ZJS
72 } else if (streq(argv[i], "debug")) {
73 if (debug)
74 *debug = true;
fb6becb4 75
d9608d40 76 } else if ((p = startswith(argv[i], "debug="))) {
05a049cc 77 int k;
0e318cad 78
d9608d40 79 k = parse_boolean(p);
05a049cc 80 if (k < 0)
d9608d40 81 pam_syslog(handle, LOG_WARNING, "Failed to parse debug= argument, ignoring: %s", p);
05a049cc 82 else if (debug)
0e318cad
MS
83 *debug = k;
84
05a049cc 85 } else
fb6becb4 86 pam_syslog(handle, LOG_WARNING, "Unknown parameter '%s', ignoring", argv[i]);
49ebd11f 87 }
8c6db833 88
8c6db833
LP
89 return 0;
90}
91
9ab0d3eb 92static int acquire_user_record(
8c6db833 93 pam_handle_t *handle,
9ab0d3eb 94 UserRecord **ret_record) {
8c6db833 95
9ab0d3eb
LP
96 _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
97 const char *username = NULL, *json = NULL;
8c6db833
LP
98 int r;
99
100 assert(handle);
8c6db833 101
baae0358
LP
102 r = pam_get_user(handle, &username, NULL);
103 if (r != PAM_SUCCESS) {
d9608d40 104 pam_syslog(handle, LOG_ERR, "Failed to get user name: %s", pam_strerror(handle, r));
baae0358
LP
105 return r;
106 }
d90b9d27 107
baae0358
LP
108 if (isempty(username)) {
109 pam_syslog(handle, LOG_ERR, "User name not valid.");
9ab0d3eb 110 return PAM_SERVICE_ERR;
8c6db833
LP
111 }
112
9ab0d3eb
LP
113 /* If pam_systemd_homed (or some other module) already acqired the user record we can reuse it
114 * here. */
115 r = pam_get_data(handle, "systemd-user-record", (const void**) &json);
116 if (r != PAM_SUCCESS || !json) {
117 _cleanup_free_ char *formatted = NULL;
118
119 if (!IN_SET(r, PAM_SUCCESS, PAM_NO_MODULE_DATA)) {
120 pam_syslog(handle, LOG_ERR, "Failed to get PAM user record data: %s", pam_strerror(handle, r));
121 return r;
122 }
123
124 /* Request the record ourselves */
125 r = userdb_by_name(username, 0, &ur);
126 if (r < 0) {
127 pam_syslog(handle, LOG_ERR, "Failed to get user record: %s", strerror_safe(r));
128 return PAM_USER_UNKNOWN;
129 }
130
131 r = json_variant_format(ur->json, 0, &formatted);
132 if (r < 0) {
133 pam_syslog(handle, LOG_ERR, "Failed to format user JSON: %s", strerror_safe(r));
134 return PAM_SERVICE_ERR;
135 }
136
137 /* And cache it for everyone else */
138 r = pam_set_data(handle, "systemd-user-record", formatted, pam_cleanup_free);
139 if (r < 0) {
140 pam_syslog(handle, LOG_ERR, "Failed to set PAM user record data: %s", pam_strerror(handle, r));
141 return r;
142 }
143
144 TAKE_PTR(formatted);
145 } else {
146 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
147
148 /* Parse cached record */
149 r = json_parse(json, JSON_PARSE_SENSITIVE, &v, NULL, NULL);
150 if (r < 0) {
151 pam_syslog(handle, LOG_ERR, "Failed to parse JSON user record: %s", strerror_safe(r));
152 return PAM_SERVICE_ERR;
153 }
154
155 ur = user_record_new();
156 if (!ur)
157 return pam_log_oom(handle);
158
159 r = user_record_load(ur, v, USER_RECORD_LOAD_REFUSE_SECRET);
160 if (r < 0) {
161 pam_syslog(handle, LOG_ERR, "Failed to load user record: %s", strerror_safe(r));
162 return PAM_SERVICE_ERR;
163 }
164
165 /* Safety check if cached record actually matches what we are looking for */
166 if (!streq_ptr(username, ur->user_name)) {
167 pam_syslog(handle, LOG_ERR, "Acquired user record does not match user name.");
168 return PAM_SERVICE_ERR;
169 }
170 }
171
172 if (!uid_is_valid(ur->uid)) {
173 pam_syslog(handle, LOG_ERR, "Acquired user record does not have a UID.");
174 return PAM_SERVICE_ERR;
8c6db833
LP
175 }
176
9ab0d3eb
LP
177 if (ret_record)
178 *ret_record = TAKE_PTR(ur);
8c6db833
LP
179
180 return PAM_SUCCESS;
181}
182
ecd5f1a9
LP
183static bool display_is_local(const char *display) {
184 assert(display);
185
186 return
187 display[0] == ':' &&
188 display[1] >= '0' &&
189 display[1] <= '9';
190}
191
f7b8b5c4
LP
192static int socket_from_display(const char *display, char **path) {
193 size_t k;
194 char *f, *c;
195
196 assert(display);
197 assert(path);
198
199 if (!display_is_local(display))
200 return -EINVAL;
201
202 k = strspn(display+1, "0123456789");
203
204 f = new(char, STRLEN("/tmp/.X11-unix/X") + k + 1);
205 if (!f)
206 return -ENOMEM;
207
208 c = stpcpy(f, "/tmp/.X11-unix/X");
209 memcpy(c, display+1, k);
210 c[k] = 0;
211
212 *path = f;
213
214 return 0;
215}
216
4d6d6518 217static int get_seat_from_display(const char *display, const char **seat, uint32_t *vtnr) {
15a3e96f 218 union sockaddr_union sa = {};
baae0358
LP
219 _cleanup_free_ char *p = NULL, *tty = NULL;
220 _cleanup_close_ int fd = -1;
4d6d6518 221 struct ucred ucred;
15a3e96f 222 int v, r, salen;
4d6d6518
LP
223
224 assert(display);
4d6d6518
LP
225 assert(vtnr);
226
227 /* We deduce the X11 socket from the display name, then use
228 * SO_PEERCRED to determine the X11 server process, ask for
229 * the controlling tty of that and if it's a VC then we know
230 * the seat and the virtual terminal. Sounds ugly, is only
231 * semi-ugly. */
232
233 r = socket_from_display(display, &p);
234 if (r < 0)
235 return r;
15a3e96f
LP
236 salen = sockaddr_un_set_path(&sa.un, p);
237 if (salen < 0)
238 return salen;
4d6d6518
LP
239
240 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
b92bea5d 241 if (fd < 0)
4d6d6518 242 return -errno;
4d6d6518 243
15a3e96f 244 if (connect(fd, &sa.sa, salen) < 0)
4d6d6518 245 return -errno;
4d6d6518 246
eff05270 247 r = getpeercred(fd, &ucred);
4d6d6518 248 if (r < 0)
eff05270 249 return r;
4d6d6518
LP
250
251 r = get_ctty(ucred.pid, NULL, &tty);
252 if (r < 0)
253 return r;
254
255 v = vtnr_from_tty(tty);
4d6d6518
LP
256 if (v < 0)
257 return v;
258 else if (v == 0)
259 return -ENOENT;
260
fc7985ed
LP
261 if (seat)
262 *seat = "seat0";
4d6d6518
LP
263 *vtnr = (uint32_t) v;
264
265 return 0;
266}
267
00efd498
ZJS
268static int export_legacy_dbus_address(
269 pam_handle_t *handle,
270 uid_t uid,
271 const char *runtime) {
272
15ee6c20
ZJS
273 const char *s;
274 _cleanup_free_ char *t = NULL;
00efd498
ZJS
275 int r = PAM_BUF_ERR;
276
15ee6c20
ZJS
277 /* We need to export $DBUS_SESSION_BUS_ADDRESS because various applications will not connect
278 * correctly to the bus without it. This setting matches what dbus.socket does for the user
279 * session using 'systemctl --user set-environment'. We want to have the same configuration
280 * in processes started from the PAM session.
281 *
282 * The setting of the address is guarded by the access() check because it is also possible to compile
283 * dbus without --enable-user-session, in which case this socket is not used, and
284 * $DBUS_SESSION_BUS_ADDRESS should not be set. An alternative approach would to not do the access()
285 * check here, and let applications try on their own, by using "unix:path=%s/bus;autolaunch:". But we
286 * expect the socket to be present by the time we do this check, so we can just as well check once
287 * here. */
288
289 s = strjoina(runtime, "/bus");
290 if (access(s, F_OK) < 0)
291 return PAM_SUCCESS;
292
293 if (asprintf(&t, DEFAULT_USER_BUS_ADDRESS_FMT, runtime) < 0)
d750dde2 294 return pam_log_oom(handle);
00efd498 295
15ee6c20 296 r = pam_misc_setenv(handle, "DBUS_SESSION_BUS_ADDRESS", t, 0);
d750dde2
LP
297 if (r != PAM_SUCCESS) {
298 pam_syslog(handle, LOG_ERR, "Failed to set bus variable: %s", pam_strerror(handle, r));
299 return r;
300 }
00efd498
ZJS
301
302 return PAM_SUCCESS;
00efd498
ZJS
303}
304
22f93314
JS
305static int append_session_memory_max(pam_handle_t *handle, sd_bus_message *m, const char *limit) {
306 uint64_t val;
307 int r;
308
309 if (isempty(limit))
310 return 0;
311
312 if (streq(limit, "infinity")) {
313 r = sd_bus_message_append(m, "(sv)", "MemoryMax", "t", (uint64_t)-1);
d750dde2
LP
314 if (r < 0)
315 return pam_bus_log_create_error(handle, r);
316
317 return 0;
318 }
319
320 r = parse_permille(limit);
321 if (r >= 0) {
322 r = sd_bus_message_append(m, "(sv)", "MemoryMaxScale", "u", (uint32_t) (((uint64_t) r * UINT32_MAX) / 1000U));
323 if (r < 0)
324 return pam_bus_log_create_error(handle, r);
325
326 return 0;
327 }
328
329 r = parse_size(limit, 1024, &val);
330 if (r >= 0) {
331 r = sd_bus_message_append(m, "(sv)", "MemoryMax", "t", val);
332 if (r < 0)
333 return pam_bus_log_create_error(handle, r);
334
335 return 0;
22f93314
JS
336 }
337
d750dde2 338 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.memory_max, ignoring: %s", limit);
22f93314
JS
339 return 0;
340}
341
adc09af2
PW
342static int append_session_runtime_max_sec(pam_handle_t *handle, sd_bus_message *m, const char *limit) {
343 usec_t val;
344 int r;
345
346 /* No need to parse "infinity" here, it will be set by default later in scope_init() */
347 if (isempty(limit) || streq(limit, "infinity"))
348 return 0;
349
350 r = parse_sec(limit, &val);
351 if (r >= 0) {
352 r = sd_bus_message_append(m, "(sv)", "RuntimeMaxUSec", "t", (uint64_t) val);
353 if (r < 0) {
354 pam_syslog(handle, LOG_ERR, "Failed to append to bus message: %s", strerror_safe(r));
355 return r;
356 }
357 } else
358 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.runtime_max_sec: %s, ignoring.", limit);
359
360 return 0;
361}
362
5fdfbbd5 363static int append_session_tasks_max(pam_handle_t *handle, sd_bus_message *m, const char *limit) {
22f93314
JS
364 uint64_t val;
365 int r;
366
367 /* No need to parse "infinity" here, it will be set unconditionally later in manager_start_scope() */
368 if (isempty(limit) || streq(limit, "infinity"))
369 return 0;
370
371 r = safe_atou64(limit, &val);
372 if (r >= 0) {
373 r = sd_bus_message_append(m, "(sv)", "TasksMax", "t", val);
d750dde2
LP
374 if (r < 0)
375 return pam_bus_log_create_error(handle, r);
22f93314 376 } else
d750dde2 377 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.tasks_max, ignoring: %s", limit);
22f93314
JS
378
379 return 0;
380}
381
382static int append_session_cg_weight(pam_handle_t *handle, sd_bus_message *m, const char *limit, const char *field) {
383 uint64_t val;
384 int r;
385
36a4dbae
LP
386 if (isempty(limit))
387 return 0;
388
389 r = cg_weight_parse(limit, &val);
390 if (r >= 0) {
391 r = sd_bus_message_append(m, "(sv)", field, "t", val);
d750dde2
LP
392 if (r < 0)
393 return pam_bus_log_create_error(handle, r);
36a4dbae 394 } else if (streq(field, "CPUWeight"))
d750dde2 395 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.cpu_weight, ignoring: %s", limit);
36a4dbae 396 else
d750dde2 397 pam_syslog(handle, LOG_WARNING, "Failed to parse systemd.io_weight, ignoring: %s", limit);
22f93314
JS
398
399 return 0;
400}
401
0ecc1c9d
LP
402static const char* getenv_harder(pam_handle_t *handle, const char *key, const char *fallback) {
403 const char *v;
404
405 assert(handle);
406 assert(key);
407
5238e957 408 /* Looks for an environment variable, preferably in the environment block associated with the
83d4ab55
LP
409 * specified PAM handle, falling back to the process' block instead. Why check both? Because we want
410 * to permit configuration of session properties from unit files that invoke PAM services, so that
411 * PAM services don't have to be reworked to set systemd-specific properties, but these properties
412 * can still be set from the unit file Environment= block. */
0ecc1c9d
LP
413
414 v = pam_getenv(handle, key);
415 if (!isempty(v))
416 return v;
417
83d4ab55
LP
418 /* We use secure_getenv() here, since we might get loaded into su/sudo, which are SUID. Ideally
419 * they'd clean up the environment before invoking foreign code (such as PAM modules), but alas they
420 * currently don't (to be precise, they clean up the environment they pass to their children, but
421 * not their own environ[]). */
422 v = secure_getenv(key);
0ecc1c9d
LP
423 if (!isempty(v))
424 return v;
425
426 return fallback;
427}
428
d6baaa69
LP
429static int update_environment(pam_handle_t *handle, const char *key, const char *value) {
430 int r;
431
432 assert(handle);
433 assert(key);
434
435 /* Updates the environment, but only if there's actually a value set. Also, log about errors */
436
437 if (isempty(value))
438 return PAM_SUCCESS;
439
440 r = pam_misc_setenv(handle, key, value, 0);
441 if (r != PAM_SUCCESS)
d9608d40 442 pam_syslog(handle, LOG_ERR, "Failed to set environment variable %s: %s", key, pam_strerror(handle, r));
d6baaa69
LP
443
444 return r;
445}
446
b9217112
LP
447static bool validate_runtime_directory(pam_handle_t *handle, const char *path, uid_t uid) {
448 struct stat st;
449
dca81e28 450 assert(handle);
b9217112
LP
451 assert(path);
452
453 /* Just some extra paranoia: let's not set $XDG_RUNTIME_DIR if the directory we'd set it to isn't actually set
454 * up properly for us. */
455
456 if (lstat(path, &st) < 0) {
4bbccb02 457 pam_syslog(handle, LOG_ERR, "Failed to stat() runtime directory '%s': %s", path, strerror_safe(errno));
b9217112
LP
458 goto fail;
459 }
460
461 if (!S_ISDIR(st.st_mode)) {
462 pam_syslog(handle, LOG_ERR, "Runtime directory '%s' is not actually a directory.", path);
463 goto fail;
464 }
465
466 if (st.st_uid != uid) {
467 pam_syslog(handle, LOG_ERR, "Runtime directory '%s' is not owned by UID " UID_FMT ", as it should.", path, uid);
468 goto fail;
469 }
470
471 return true;
472
473fail:
474 pam_syslog(handle, LOG_WARNING, "Not setting $XDG_RUNTIME_DIR, as the directory is not in order.");
475 return false;
476}
477
98a28fef 478_public_ PAM_EXTERN int pam_sm_open_session(
8c6db833
LP
479 pam_handle_t *handle,
480 int flags,
481 int argc, const char **argv) {
482
4afd3348 483 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
22f93314 484 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
d1529c9e 485 const char
9ab0d3eb 486 *id, *object_path, *runtime_path,
d1529c9e
LP
487 *service = NULL,
488 *tty = NULL, *display = NULL,
489 *remote_user = NULL, *remote_host = NULL,
490 *seat = NULL,
491 *type = NULL, *class = NULL,
f5cb2820 492 *class_pam = NULL, *type_pam = NULL, *cvtnr = NULL, *desktop = NULL, *desktop_pam = NULL,
adc09af2 493 *memory_max = NULL, *tasks_max = NULL, *cpu_weight = NULL, *io_weight = NULL, *runtime_max_sec = NULL;
4afd3348 494 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
9ab0d3eb 495 _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
d1529c9e 496 int session_fd = -1, existing, r;
d1529c9e 497 bool debug = false, remote;
baae0358
LP
498 uint32_t vtnr = 0;
499 uid_t original_uid;
8c6db833 500
ffcfcb6b 501 assert(handle);
98a28fef 502
79d860fe
MP
503 /* Make this a NOP on non-logind systems */
504 if (!logind_running())
8c6db833
LP
505 return PAM_SUCCESS;
506
e9fbc77c
LP
507 if (parse_argv(handle,
508 argc, argv,
fb6becb4 509 &class_pam,
49ebd11f 510 &type_pam,
f5cb2820 511 &desktop_pam,
5a330cda
ZJS
512 &debug) < 0)
513 return PAM_SESSION_ERR;
74fe1fe3 514
baae0358 515 if (debug)
3831838a 516 pam_syslog(handle, LOG_DEBUG, "pam-systemd initializing");
baae0358 517
9ab0d3eb 518 r = acquire_user_record(handle, &ur);
42e66809 519 if (r != PAM_SUCCESS)
5a330cda 520 return r;
8c6db833 521
30b2c336
LP
522 /* Make sure we don't enter a loop by talking to
523 * systemd-logind when it is actually waiting for the
524 * background to finish start-up. If the service is
5c390a4a 525 * "systemd-user" we simply set XDG_RUNTIME_DIR and
30b2c336
LP
526 * leave. */
527
1798f5af 528 (void) pam_get_item(handle, PAM_SERVICE, (const void**) &service);
5c390a4a 529 if (streq_ptr(service, "systemd-user")) {
055c08ef 530 char rt[STRLEN("/run/user/") + DECIMAL_STR_MAX(uid_t)];
30b2c336 531
9ab0d3eb
LP
532 xsprintf(rt, "/run/user/"UID_FMT, ur->uid);
533 if (validate_runtime_directory(handle, rt, ur->uid)) {
b9217112
LP
534 r = pam_misc_setenv(handle, "XDG_RUNTIME_DIR", rt, 0);
535 if (r != PAM_SUCCESS) {
d9608d40 536 pam_syslog(handle, LOG_ERR, "Failed to set runtime dir: %s", pam_strerror(handle, r));
b9217112
LP
537 return r;
538 }
30b2c336
LP
539 }
540
9ab0d3eb 541 r = export_legacy_dbus_address(handle, ur->uid, rt);
00efd498
ZJS
542 if (r != PAM_SUCCESS)
543 return r;
544
ffcfcb6b 545 return PAM_SUCCESS;
8c6db833
LP
546 }
547
ffcfcb6b 548 /* Otherwise, we ask logind to create a session for us */
8c6db833 549
1798f5af
LP
550 (void) pam_get_item(handle, PAM_XDISPLAY, (const void**) &display);
551 (void) pam_get_item(handle, PAM_TTY, (const void**) &tty);
552 (void) pam_get_item(handle, PAM_RUSER, (const void**) &remote_user);
553 (void) pam_get_item(handle, PAM_RHOST, (const void**) &remote_host);
a8573ccc 554
0ecc1c9d
LP
555 seat = getenv_harder(handle, "XDG_SEAT", NULL);
556 cvtnr = getenv_harder(handle, "XDG_VTNR", NULL);
557 type = getenv_harder(handle, "XDG_SESSION_TYPE", type_pam);
558 class = getenv_harder(handle, "XDG_SESSION_CLASS", class_pam);
f5cb2820 559 desktop = getenv_harder(handle, "XDG_SESSION_DESKTOP", desktop_pam);
a4cd87e9 560
ed18b08b 561 tty = strempty(tty);
98a28fef 562
ee8545b0 563 if (strchr(tty, ':')) {
3a736949
LP
564 /* A tty with a colon is usually an X11 display, placed there to show up in utmp. We rearrange things
565 * and don't pretend that an X display was a tty. */
ee8545b0
LP
566 if (isempty(display))
567 display = tty;
a4cd87e9 568 tty = NULL;
3a736949 569
1a4459d6 570 } else if (streq(tty, "cron")) {
3a736949
LP
571 /* cron is setting PAM_TTY to "cron" for some reason (the commit carries no information why, but
572 * probably because it wants to set it to something as pam_time/pam_access/… require PAM_TTY to be set
573 * (as they otherwise even try to update it!) — but cron doesn't actually allocate a TTY for its forked
574 * off processes.) */
0ad1271f 575 type = "unspecified";
49ebd11f 576 class = "background";
a4cd87e9 577 tty = NULL;
3a736949 578
0ad1271f 579 } else if (streq(tty, "ssh")) {
3a736949
LP
580 /* ssh has been setting PAM_TTY to "ssh" (for the same reason as cron does this, see above. For further
581 * details look for "PAM_TTY_KLUDGE" in the openssh sources). */
0ad1271f 582 type ="tty";
49ebd11f 583 class = "user";
3a736949
LP
584 tty = NULL; /* This one is particularly sad, as this means that ssh sessions — even though usually
585 * associated with a pty — won't be tracked by their tty in logind. This is because ssh
586 * does the PAM session registration early for new connections, and registers a pty only
587 * much later (this is because it doesn't know yet if it needs one at all, as whether to
588 * register a pty or not is negotiated much later in the protocol). */
589
c9ed61e7
LP
590 } else
591 /* Chop off leading /dev prefix that some clients specify, but others do not. */
592 tty = skip_dev_prefix(tty);
ee8545b0 593
8e7705e5 594 /* If this fails vtnr will be 0, that's intended */
4d6d6518 595 if (!isempty(cvtnr))
2ae4842b 596 (void) safe_atou32(cvtnr, &vtnr);
4d6d6518 597
92bd5ff3 598 if (!isempty(display) && !vtnr) {
fc7985ed 599 if (isempty(seat))
d487e2d6 600 (void) get_seat_from_display(display, &seat, &vtnr);
fc7985ed 601 else if (streq(seat, "seat0"))
d487e2d6 602 (void) get_seat_from_display(display, NULL, &vtnr);
fc7985ed 603 }
4d6d6518 604
49ebd11f 605 if (seat && !streq(seat, "seat0") && vtnr != 0) {
2675747f
LP
606 if (debug)
607 pam_syslog(handle, LOG_DEBUG, "Ignoring vtnr %"PRIu32" for %s which is not seat0", vtnr, seat);
d7353ef6
MM
608 vtnr = 0;
609 }
610
49ebd11f 611 if (isempty(type))
0ad1271f 612 type = !isempty(display) ? "x11" :
49ebd11f 613 !isempty(tty) ? "tty" : "unspecified";
98a28fef 614
55efac6c 615 if (isempty(class))
e2acb67b 616 class = streq(type, "unspecified") ? "background" : "user";
55efac6c 617
fecc80c1 618 remote = !isempty(remote_host) && !is_localhost(remote_host);
98a28fef 619
22f93314
JS
620 (void) pam_get_data(handle, "systemd.memory_max", (const void **)&memory_max);
621 (void) pam_get_data(handle, "systemd.tasks_max", (const void **)&tasks_max);
622 (void) pam_get_data(handle, "systemd.cpu_weight", (const void **)&cpu_weight);
623 (void) pam_get_data(handle, "systemd.io_weight", (const void **)&io_weight);
adc09af2 624 (void) pam_get_data(handle, "systemd.runtime_max_sec", (const void **)&runtime_max_sec);
22f93314 625
4d49b48c 626 /* Talk to logind over the message bus */
5a330cda 627
355c9966
LP
628 r = pam_acquire_bus_connection(handle, &bus);
629 if (r != PAM_SUCCESS)
630 return r;
cc377381 631
22f93314 632 if (debug) {
ce959314 633 pam_syslog(handle, LOG_DEBUG, "Asking logind to create session: "
1fa2f38f 634 "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",
9ab0d3eb 635 ur->uid, getpid_cached(),
baae0358 636 strempty(service),
cda7ecb0 637 type, class, strempty(desktop),
a4cd87e9 638 strempty(seat), vtnr, strempty(tty), strempty(display),
baae0358 639 yes_no(remote), strempty(remote_user), strempty(remote_host));
22f93314 640 pam_syslog(handle, LOG_DEBUG, "Session limits: "
adc09af2
PW
641 "memory_max=%s tasks_max=%s cpu_weight=%s io_weight=%s runtime_max_sec=%s",
642 strna(memory_max), strna(tasks_max), strna(cpu_weight), strna(io_weight), strna(runtime_max_sec));
22f93314
JS
643 }
644
645 r = sd_bus_message_new_method_call(
646 bus,
647 &m,
648 "org.freedesktop.login1",
649 "/org/freedesktop/login1",
650 "org.freedesktop.login1.Manager",
651 "CreateSession");
d750dde2
LP
652 if (r < 0)
653 return pam_bus_log_create_error(handle, r);
22f93314
JS
654
655 r = sd_bus_message_append(m, "uusssssussbss",
9ab0d3eb 656 (uint32_t) ur->uid,
da0da5ec 657 0,
22f93314
JS
658 service,
659 type,
660 class,
661 desktop,
662 seat,
663 vtnr,
664 tty,
665 display,
666 remote,
667 remote_user,
668 remote_host);
d750dde2
LP
669 if (r < 0)
670 return pam_bus_log_create_error(handle, r);
22f93314
JS
671
672 r = sd_bus_message_open_container(m, 'a', "(sv)");
d750dde2
LP
673 if (r < 0)
674 return pam_bus_log_create_error(handle, r);
22f93314
JS
675
676 r = append_session_memory_max(handle, m, memory_max);
677 if (r < 0)
678 return PAM_SESSION_ERR;
679
adc09af2
PW
680 r = append_session_runtime_max_sec(handle, m, runtime_max_sec);
681 if (r < 0)
682 return PAM_SESSION_ERR;
683
22f93314
JS
684 r = append_session_tasks_max(handle, m, tasks_max);
685 if (r < 0)
686 return PAM_SESSION_ERR;
687
688 r = append_session_cg_weight(handle, m, cpu_weight, "CPUWeight");
689 if (r < 0)
690 return PAM_SESSION_ERR;
691
692 r = append_session_cg_weight(handle, m, io_weight, "IOWeight");
693 if (r < 0)
694 return PAM_SESSION_ERR;
695
696 r = sd_bus_message_close_container(m);
d750dde2
LP
697 if (r < 0)
698 return pam_bus_log_create_error(handle, r);
ce959314 699
fbcb6300 700 r = sd_bus_call(bus, m, LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC, &error, &reply);
ffcfcb6b 701 if (r < 0) {
b80120c4 702 if (sd_bus_error_has_name(&error, BUS_ERROR_SESSION_BUSY)) {
2675747f 703 if (debug)
c7e93c4d 704 pam_syslog(handle, LOG_DEBUG, "Not creating session: %s", bus_error_message(&error, r));
b80120c4
DH
705 return PAM_SUCCESS;
706 } else {
707 pam_syslog(handle, LOG_ERR, "Failed to create session: %s", bus_error_message(&error, r));
8d46418e 708 return PAM_SESSION_ERR;
b80120c4 709 }
98a28fef 710 }
74fe1fe3 711
ffcfcb6b 712 r = sd_bus_message_read(reply,
baae0358 713 "soshusub",
ffcfcb6b
ZJS
714 &id,
715 &object_path,
716 &runtime_path,
717 &session_fd,
baae0358 718 &original_uid,
ffcfcb6b
ZJS
719 &seat,
720 &vtnr,
721 &existing);
d750dde2
LP
722 if (r < 0)
723 return pam_bus_log_parse_error(handle, r);
74fe1fe3 724
ce959314
MS
725 if (debug)
726 pam_syslog(handle, LOG_DEBUG, "Reply from logind: "
baae0358
LP
727 "id=%s object_path=%s runtime_path=%s session_fd=%d seat=%s vtnr=%u original_uid=%u",
728 id, object_path, runtime_path, session_fd, seat, vtnr, original_uid);
ce959314 729
d6baaa69
LP
730 r = update_environment(handle, "XDG_SESSION_ID", id);
731 if (r != PAM_SUCCESS)
5a330cda 732 return r;
8c6db833 733
9ab0d3eb 734 if (original_uid == ur->uid) {
baae0358
LP
735 /* Don't set $XDG_RUNTIME_DIR if the user we now
736 * authenticated for does not match the original user
737 * of the session. We do this in order not to result
738 * in privileged apps clobbering the runtime directory
739 * unnecessarily. */
740
9ab0d3eb 741 if (validate_runtime_directory(handle, runtime_path, ur->uid)) {
b9217112
LP
742 r = update_environment(handle, "XDG_RUNTIME_DIR", runtime_path);
743 if (r != PAM_SUCCESS)
744 return r;
745 }
00efd498 746
9ab0d3eb 747 r = export_legacy_dbus_address(handle, ur->uid, runtime_path);
00efd498
ZJS
748 if (r != PAM_SUCCESS)
749 return r;
98a28fef 750 }
8c6db833 751
b2f74f07
LP
752 /* Most likely we got the session/type/class from environment variables, but might have gotten the data
753 * somewhere else (for example PAM module parameters). Let's now update the environment variables, so that this
754 * data is inherited into the session processes, and programs can rely on them to be initialized. */
755
756 r = update_environment(handle, "XDG_SESSION_TYPE", type);
757 if (r != PAM_SUCCESS)
758 return r;
759
760 r = update_environment(handle, "XDG_SESSION_CLASS", class);
761 if (r != PAM_SUCCESS)
762 return r;
763
764 r = update_environment(handle, "XDG_SESSION_DESKTOP", desktop);
765 if (r != PAM_SUCCESS)
766 return r;
767
d6baaa69
LP
768 r = update_environment(handle, "XDG_SEAT", seat);
769 if (r != PAM_SUCCESS)
770 return r;
bbc73283
LP
771
772 if (vtnr > 0) {
29d230f6 773 char buf[DECIMAL_STR_MAX(vtnr)];
baae0358 774 sprintf(buf, "%u", vtnr);
bbc73283 775
d6baaa69
LP
776 r = update_environment(handle, "XDG_VTNR", buf);
777 if (r != PAM_SUCCESS)
5a330cda 778 return r;
bbc73283
LP
779 }
780
77085881
LP
781 r = pam_set_data(handle, "systemd.existing", INT_TO_PTR(!!existing), NULL);
782 if (r != PAM_SUCCESS) {
d9608d40 783 pam_syslog(handle, LOG_ERR, "Failed to install existing flag: %s", pam_strerror(handle, r));
5a330cda 784 return r;
77085881
LP
785 }
786
21c390cc 787 if (session_fd >= 0) {
85c08dc0 788 session_fd = fcntl(session_fd, F_DUPFD_CLOEXEC, 3);
5a330cda
ZJS
789 if (session_fd < 0) {
790 pam_syslog(handle, LOG_ERR, "Failed to dup session fd: %m");
791 return PAM_SESSION_ERR;
792 }
793
23e096cc 794 r = pam_set_data(handle, "systemd.session-fd", FD_TO_PTR(session_fd), NULL);
21c390cc 795 if (r != PAM_SUCCESS) {
d9608d40 796 pam_syslog(handle, LOG_ERR, "Failed to install session fd: %s", pam_strerror(handle, r));
03e334a1 797 safe_close(session_fd);
5a330cda 798 return r;
21c390cc 799 }
98a28fef 800 }
8c6db833 801
355c9966
LP
802 /* Let's release the D-Bus connection, after all the session might live quite a long time, and we are
803 * not going to process the bus connection in that time, so let's better close before the daemon
804 * kicks us off because we are not processing anything. */
805 (void) pam_release_bus_connection(handle);
ffcfcb6b 806 return PAM_SUCCESS;
98a28fef 807}
8c6db833 808
98a28fef
LP
809_public_ PAM_EXTERN int pam_sm_close_session(
810 pam_handle_t *handle,
811 int flags,
812 int argc, const char **argv) {
8c6db833 813
5f41d1f1 814 const void *existing = NULL;
75c8e3cf 815 const char *id;
75c8e3cf 816 int r;
8c6db833 817
ffcfcb6b 818 assert(handle);
75c8e3cf 819
77085881
LP
820 /* Only release session if it wasn't pre-existing when we
821 * tried to create it */
d487e2d6 822 (void) pam_get_data(handle, "systemd.existing", &existing);
77085881 823
75c8e3cf 824 id = pam_getenv(handle, "XDG_SESSION_ID");
77085881 825 if (id && !existing) {
355c9966
LP
826 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
827 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
75c8e3cf 828
355c9966
LP
829 /* Before we go and close the FIFO we need to tell logind that this is a clean session
830 * shutdown, so that it doesn't just go and slaughter us immediately after closing the fd */
75c8e3cf 831
355c9966
LP
832 r = pam_acquire_bus_connection(handle, &bus);
833 if (r != PAM_SUCCESS)
834 return r;
75c8e3cf 835
ffcfcb6b
ZJS
836 r = sd_bus_call_method(bus,
837 "org.freedesktop.login1",
838 "/org/freedesktop/login1",
839 "org.freedesktop.login1.Manager",
840 "ReleaseSession",
841 &error,
842 NULL,
843 "s",
844 id);
845 if (r < 0) {
5f41d1f1
LP
846 pam_syslog(handle, LOG_ERR, "Failed to release session: %s", bus_error_message(&error, r));
847 return PAM_SESSION_ERR;
75c8e3cf
LP
848 }
849 }
850
355c9966
LP
851 /* Note that we are knowingly leaking the FIFO fd here. This way, logind can watch us die. If we
852 * closed it here it would not have any clue when that is completed. Given that one cannot really
853 * have multiple PAM sessions open from the same process this means we will leak one FD at max. */
75c8e3cf 854
5f41d1f1 855 return PAM_SUCCESS;
8c6db833 856}