1 /* SPDX-License-Identifier: LGPL-2.1+ */
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>
14 #include "alloc-util.h"
15 #include "audit-util.h"
16 #include "bus-common-errors.h"
17 #include "bus-error.h"
18 #include "bus-internal.h"
20 #include "cgroup-util.h"
23 #include "format-util.h"
24 #include "hostname-util.h"
25 #include "login-util.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "process-util.h"
30 #include "socket-util.h"
31 #include "stdio-util.h"
33 #include "terminal-util.h"
36 static int parse_argv(
38 int argc
, const char **argv
,
47 assert(argc
== 0 || argv
);
49 for (i
= 0; i
< (unsigned) argc
; i
++) {
50 if (startswith(argv
[i
], "class=")) {
54 } else if (startswith(argv
[i
], "type=")) {
58 } else if (startswith(argv
[i
], "desktop=")) {
60 *desktop
= argv
[i
] + 8;
62 } else if (streq(argv
[i
], "debug")) {
66 } else if (startswith(argv
[i
], "debug=")) {
69 k
= parse_boolean(argv
[i
] + 6);
71 pam_syslog(handle
, LOG_WARNING
, "Failed to parse debug= argument, ignoring.");
76 pam_syslog(handle
, LOG_WARNING
, "Unknown parameter '%s', ignoring", argv
[i
]);
82 static int get_user_data(
84 const char **ret_username
,
85 struct passwd
**ret_pw
) {
87 const char *username
= NULL
;
88 struct passwd
*pw
= NULL
;
95 r
= pam_get_user(handle
, &username
, NULL
);
96 if (r
!= PAM_SUCCESS
) {
97 pam_syslog(handle
, LOG_ERR
, "Failed to get user name.");
101 if (isempty(username
)) {
102 pam_syslog(handle
, LOG_ERR
, "User name not valid.");
106 pw
= pam_modutil_getpwnam(handle
, username
);
108 pam_syslog(handle
, LOG_ERR
, "Failed to get user data.");
109 return PAM_USER_UNKNOWN
;
113 *ret_username
= username
;
118 static bool display_is_local(const char *display
) {
127 static int socket_from_display(const char *display
, char **path
) {
134 if (!display_is_local(display
))
137 k
= strspn(display
+1, "0123456789");
139 f
= new(char, STRLEN("/tmp/.X11-unix/X") + k
+ 1);
143 c
= stpcpy(f
, "/tmp/.X11-unix/X");
144 memcpy(c
, display
+1, k
);
152 static int get_seat_from_display(const char *display
, const char **seat
, uint32_t *vtnr
) {
153 union sockaddr_union sa
= {};
154 _cleanup_free_
char *p
= NULL
, *tty
= NULL
;
155 _cleanup_close_
int fd
= -1;
162 /* We deduce the X11 socket from the display name, then use
163 * SO_PEERCRED to determine the X11 server process, ask for
164 * the controlling tty of that and if it's a VC then we know
165 * the seat and the virtual terminal. Sounds ugly, is only
168 r
= socket_from_display(display
, &p
);
171 salen
= sockaddr_un_set_path(&sa
.un
, p
);
175 fd
= socket(AF_UNIX
, SOCK_STREAM
|SOCK_CLOEXEC
, 0);
179 if (connect(fd
, &sa
.sa
, salen
) < 0)
182 r
= getpeercred(fd
, &ucred
);
186 r
= get_ctty(ucred
.pid
, NULL
, &tty
);
190 v
= vtnr_from_tty(tty
);
198 *vtnr
= (uint32_t) v
;
203 static int export_legacy_dbus_address(
204 pam_handle_t
*handle
,
206 const char *runtime
) {
209 _cleanup_free_
char *t
= NULL
;
212 /* We need to export $DBUS_SESSION_BUS_ADDRESS because various applications will not connect
213 * correctly to the bus without it. This setting matches what dbus.socket does for the user
214 * session using 'systemctl --user set-environment'. We want to have the same configuration
215 * in processes started from the PAM session.
217 * The setting of the address is guarded by the access() check because it is also possible to compile
218 * dbus without --enable-user-session, in which case this socket is not used, and
219 * $DBUS_SESSION_BUS_ADDRESS should not be set. An alternative approach would to not do the access()
220 * check here, and let applications try on their own, by using "unix:path=%s/bus;autolaunch:". But we
221 * expect the socket to be present by the time we do this check, so we can just as well check once
224 s
= strjoina(runtime
, "/bus");
225 if (access(s
, F_OK
) < 0)
228 if (asprintf(&t
, DEFAULT_USER_BUS_ADDRESS_FMT
, runtime
) < 0)
231 r
= pam_misc_setenv(handle
, "DBUS_SESSION_BUS_ADDRESS", t
, 0);
232 if (r
!= PAM_SUCCESS
)
238 pam_syslog(handle
, LOG_ERR
, "Failed to set bus variable.");
242 static int append_session_memory_max(pam_handle_t
*handle
, sd_bus_message
*m
, const char *limit
) {
249 if (streq(limit
, "infinity")) {
250 r
= sd_bus_message_append(m
, "(sv)", "MemoryMax", "t", (uint64_t)-1);
252 pam_syslog(handle
, LOG_ERR
, "Failed to append to bus message: %s", strerror(-r
));
256 r
= parse_permille(limit
);
258 r
= sd_bus_message_append(m
, "(sv)", "MemoryMaxScale", "u", (uint32_t) (((uint64_t) r
* UINT32_MAX
) / 1000U));
260 pam_syslog(handle
, LOG_ERR
, "Failed to append to bus message: %s", strerror(-r
));
264 r
= parse_size(limit
, 1024, &val
);
266 r
= sd_bus_message_append(m
, "(sv)", "MemoryMax", "t", val
);
268 pam_syslog(handle
, LOG_ERR
, "Failed to append to bus message: %s", strerror(-r
));
272 pam_syslog(handle
, LOG_WARNING
, "Failed to parse systemd.limit: %s, ignoring.", limit
);
279 static int append_session_tasks_max(pam_handle_t
*handle
, sd_bus_message
*m
, const char *limit
) {
283 /* No need to parse "infinity" here, it will be set unconditionally later in manager_start_scope() */
284 if (isempty(limit
) || streq(limit
, "infinity"))
287 r
= safe_atou64(limit
, &val
);
289 r
= sd_bus_message_append(m
, "(sv)", "TasksMax", "t", val
);
291 pam_syslog(handle
, LOG_ERR
, "Failed to append to bus message: %s", strerror(-r
));
295 pam_syslog(handle
, LOG_WARNING
, "Failed to parse systemd.limit: %s, ignoring.", limit
);
300 static int append_session_cg_weight(pam_handle_t
*handle
, sd_bus_message
*m
, const char *limit
, const char *field
) {
307 r
= cg_weight_parse(limit
, &val
);
309 r
= sd_bus_message_append(m
, "(sv)", field
, "t", val
);
311 pam_syslog(handle
, LOG_ERR
, "Failed to append to bus message: %s", strerror(-r
));
314 } else if (streq(field
, "CPUWeight"))
315 pam_syslog(handle
, LOG_WARNING
, "Failed to parse systemd.cpu_weight: %s, ignoring.", limit
);
317 pam_syslog(handle
, LOG_WARNING
, "Failed to parse systemd.io_weight: %s, ignoring.", limit
);
322 static const char* getenv_harder(pam_handle_t
*handle
, const char *key
, const char *fallback
) {
328 /* Looks for an environment variable, preferrably in the environment block associated with the specified PAM
329 * handle, falling back to the process' block instead. */
331 v
= pam_getenv(handle
, key
);
342 static int update_environment(pam_handle_t
*handle
, const char *key
, const char *value
) {
348 /* Updates the environment, but only if there's actually a value set. Also, log about errors */
353 r
= pam_misc_setenv(handle
, key
, value
, 0);
354 if (r
!= PAM_SUCCESS
)
355 pam_syslog(handle
, LOG_ERR
, "Failed to set environment variable %s.", key
);
360 static bool validate_runtime_directory(pam_handle_t
*handle
, const char *path
, uid_t uid
) {
365 /* Just some extra paranoia: let's not set $XDG_RUNTIME_DIR if the directory we'd set it to isn't actually set
366 * up properly for us. */
368 if (lstat(path
, &st
) < 0) {
369 pam_syslog(handle
, LOG_ERR
, "Failed to stat() runtime directory '%s': %s", path
, strerror(errno
));
373 if (!S_ISDIR(st
.st_mode
)) {
374 pam_syslog(handle
, LOG_ERR
, "Runtime directory '%s' is not actually a directory.", path
);
378 if (st
.st_uid
!= uid
) {
379 pam_syslog(handle
, LOG_ERR
, "Runtime directory '%s' is not owned by UID " UID_FMT
", as it should.", path
, uid
);
386 pam_syslog(handle
, LOG_WARNING
, "Not setting $XDG_RUNTIME_DIR, as the directory is not in order.");
390 _public_ PAM_EXTERN
int pam_sm_open_session(
391 pam_handle_t
*handle
,
393 int argc
, const char **argv
) {
395 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
396 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
398 *username
, *id
, *object_path
, *runtime_path
,
400 *tty
= NULL
, *display
= NULL
,
401 *remote_user
= NULL
, *remote_host
= NULL
,
403 *type
= NULL
, *class = NULL
,
404 *class_pam
= NULL
, *type_pam
= NULL
, *cvtnr
= NULL
, *desktop
= NULL
, *desktop_pam
= NULL
,
405 *memory_max
= NULL
, *tasks_max
= NULL
, *cpu_weight
= NULL
, *io_weight
= NULL
;
406 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
407 int session_fd
= -1, existing
, r
;
408 bool debug
= false, remote
;
415 /* Make this a NOP on non-logind systems */
416 if (!logind_running())
419 if (parse_argv(handle
,
425 return PAM_SESSION_ERR
;
428 pam_syslog(handle
, LOG_DEBUG
, "pam-systemd initializing");
430 r
= get_user_data(handle
, &username
, &pw
);
431 if (r
!= PAM_SUCCESS
) {
432 pam_syslog(handle
, LOG_ERR
, "Failed to get user data.");
436 /* Make sure we don't enter a loop by talking to
437 * systemd-logind when it is actually waiting for the
438 * background to finish start-up. If the service is
439 * "systemd-user" we simply set XDG_RUNTIME_DIR and
442 pam_get_item(handle
, PAM_SERVICE
, (const void**) &service
);
443 if (streq_ptr(service
, "systemd-user")) {
444 char rt
[STRLEN("/run/user/") + DECIMAL_STR_MAX(uid_t
)];
446 xsprintf(rt
, "/run/user/"UID_FMT
, pw
->pw_uid
);
447 if (validate_runtime_directory(handle
, rt
, pw
->pw_uid
)) {
448 r
= pam_misc_setenv(handle
, "XDG_RUNTIME_DIR", rt
, 0);
449 if (r
!= PAM_SUCCESS
) {
450 pam_syslog(handle
, LOG_ERR
, "Failed to set runtime dir.");
455 r
= export_legacy_dbus_address(handle
, pw
->pw_uid
, rt
);
456 if (r
!= PAM_SUCCESS
)
462 /* Otherwise, we ask logind to create a session for us */
464 pam_get_item(handle
, PAM_XDISPLAY
, (const void**) &display
);
465 pam_get_item(handle
, PAM_TTY
, (const void**) &tty
);
466 pam_get_item(handle
, PAM_RUSER
, (const void**) &remote_user
);
467 pam_get_item(handle
, PAM_RHOST
, (const void**) &remote_host
);
469 seat
= getenv_harder(handle
, "XDG_SEAT", NULL
);
470 cvtnr
= getenv_harder(handle
, "XDG_VTNR", NULL
);
471 type
= getenv_harder(handle
, "XDG_SESSION_TYPE", type_pam
);
472 class = getenv_harder(handle
, "XDG_SESSION_CLASS", class_pam
);
473 desktop
= getenv_harder(handle
, "XDG_SESSION_DESKTOP", desktop_pam
);
477 if (strchr(tty
, ':')) {
478 /* A tty with a colon is usually an X11 display, placed there to show up in utmp. We rearrange things
479 * and don't pretend that an X display was a tty. */
480 if (isempty(display
))
484 } else if (streq(tty
, "cron")) {
485 /* cron is setting PAM_TTY to "cron" for some reason (the commit carries no information why, but
486 * probably because it wants to set it to something as pam_time/pam_access/… require PAM_TTY to be set
487 * (as they otherwise even try to update it!) — but cron doesn't actually allocate a TTY for its forked
489 type
= "unspecified";
490 class = "background";
493 } else if (streq(tty
, "ssh")) {
494 /* ssh has been setting PAM_TTY to "ssh" (for the same reason as cron does this, see above. For further
495 * details look for "PAM_TTY_KLUDGE" in the openssh sources). */
498 tty
= NULL
; /* This one is particularly sad, as this means that ssh sessions — even though usually
499 * associated with a pty — won't be tracked by their tty in logind. This is because ssh
500 * does the PAM session registration early for new connections, and registers a pty only
501 * much later (this is because it doesn't know yet if it needs one at all, as whether to
502 * register a pty or not is negotiated much later in the protocol). */
505 /* Chop off leading /dev prefix that some clients specify, but others do not. */
506 tty
= skip_dev_prefix(tty
);
508 /* If this fails vtnr will be 0, that's intended */
510 (void) safe_atou32(cvtnr
, &vtnr
);
512 if (!isempty(display
) && !vtnr
) {
514 (void) get_seat_from_display(display
, &seat
, &vtnr
);
515 else if (streq(seat
, "seat0"))
516 (void) get_seat_from_display(display
, NULL
, &vtnr
);
519 if (seat
&& !streq(seat
, "seat0") && vtnr
!= 0) {
521 pam_syslog(handle
, LOG_DEBUG
, "Ignoring vtnr %"PRIu32
" for %s which is not seat0", vtnr
, seat
);
526 type
= !isempty(display
) ? "x11" :
527 !isempty(tty
) ? "tty" : "unspecified";
530 class = streq(type
, "unspecified") ? "background" : "user";
532 remote
= !isempty(remote_host
) && !is_localhost(remote_host
);
534 (void) pam_get_data(handle
, "systemd.memory_max", (const void **)&memory_max
);
535 (void) pam_get_data(handle
, "systemd.tasks_max", (const void **)&tasks_max
);
536 (void) pam_get_data(handle
, "systemd.cpu_weight", (const void **)&cpu_weight
);
537 (void) pam_get_data(handle
, "systemd.io_weight", (const void **)&io_weight
);
539 /* Talk to logind over the message bus */
541 r
= sd_bus_open_system(&bus
);
543 pam_syslog(handle
, LOG_ERR
, "Failed to connect to system bus: %s", strerror(-r
));
544 return PAM_SESSION_ERR
;
548 pam_syslog(handle
, LOG_DEBUG
, "Asking logind to create session: "
549 "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",
550 pw
->pw_uid
, getpid_cached(),
552 type
, class, strempty(desktop
),
553 strempty(seat
), vtnr
, strempty(tty
), strempty(display
),
554 yes_no(remote
), strempty(remote_user
), strempty(remote_host
));
555 pam_syslog(handle
, LOG_DEBUG
, "Session limits: "
556 "memory_max=%s tasks_max=%s cpu_weight=%s io_weight=%s",
557 strna(memory_max
), strna(tasks_max
), strna(cpu_weight
), strna(io_weight
));
560 r
= sd_bus_message_new_method_call(
563 "org.freedesktop.login1",
564 "/org/freedesktop/login1",
565 "org.freedesktop.login1.Manager",
568 pam_syslog(handle
, LOG_ERR
, "Failed to create CreateSession method call: %s", strerror(-r
));
569 return PAM_SESSION_ERR
;
572 r
= sd_bus_message_append(m
, "uusssssussbss",
573 (uint32_t) pw
->pw_uid
,
587 pam_syslog(handle
, LOG_ERR
, "Failed to append to bus message: %s", strerror(-r
));
588 return PAM_SESSION_ERR
;
591 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
593 pam_syslog(handle
, LOG_ERR
, "Failed to open message container: %s", strerror(-r
));
594 return PAM_SYSTEM_ERR
;
597 r
= append_session_memory_max(handle
, m
, memory_max
);
599 return PAM_SESSION_ERR
;
601 r
= append_session_tasks_max(handle
, m
, tasks_max
);
603 return PAM_SESSION_ERR
;
605 r
= append_session_cg_weight(handle
, m
, cpu_weight
, "CPUWeight");
607 return PAM_SESSION_ERR
;
609 r
= append_session_cg_weight(handle
, m
, io_weight
, "IOWeight");
611 return PAM_SESSION_ERR
;
613 r
= sd_bus_message_close_container(m
);
615 pam_syslog(handle
, LOG_ERR
, "Failed to close message container: %s", strerror(-r
));
616 return PAM_SYSTEM_ERR
;
619 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
621 if (sd_bus_error_has_name(&error
, BUS_ERROR_SESSION_BUSY
)) {
623 pam_syslog(handle
, LOG_DEBUG
, "Not creating session: %s", bus_error_message(&error
, r
));
626 pam_syslog(handle
, LOG_ERR
, "Failed to create session: %s", bus_error_message(&error
, r
));
627 return PAM_SYSTEM_ERR
;
631 r
= sd_bus_message_read(reply
,
642 pam_syslog(handle
, LOG_ERR
, "Failed to parse message: %s", strerror(-r
));
643 return PAM_SESSION_ERR
;
647 pam_syslog(handle
, LOG_DEBUG
, "Reply from logind: "
648 "id=%s object_path=%s runtime_path=%s session_fd=%d seat=%s vtnr=%u original_uid=%u",
649 id
, object_path
, runtime_path
, session_fd
, seat
, vtnr
, original_uid
);
651 r
= update_environment(handle
, "XDG_SESSION_ID", id
);
652 if (r
!= PAM_SUCCESS
)
655 if (original_uid
== pw
->pw_uid
) {
656 /* Don't set $XDG_RUNTIME_DIR if the user we now
657 * authenticated for does not match the original user
658 * of the session. We do this in order not to result
659 * in privileged apps clobbering the runtime directory
662 if (validate_runtime_directory(handle
, runtime_path
, pw
->pw_uid
)) {
663 r
= update_environment(handle
, "XDG_RUNTIME_DIR", runtime_path
);
664 if (r
!= PAM_SUCCESS
)
668 r
= export_legacy_dbus_address(handle
, pw
->pw_uid
, runtime_path
);
669 if (r
!= PAM_SUCCESS
)
673 /* Most likely we got the session/type/class from environment variables, but might have gotten the data
674 * somewhere else (for example PAM module parameters). Let's now update the environment variables, so that this
675 * data is inherited into the session processes, and programs can rely on them to be initialized. */
677 r
= update_environment(handle
, "XDG_SESSION_TYPE", type
);
678 if (r
!= PAM_SUCCESS
)
681 r
= update_environment(handle
, "XDG_SESSION_CLASS", class);
682 if (r
!= PAM_SUCCESS
)
685 r
= update_environment(handle
, "XDG_SESSION_DESKTOP", desktop
);
686 if (r
!= PAM_SUCCESS
)
689 r
= update_environment(handle
, "XDG_SEAT", seat
);
690 if (r
!= PAM_SUCCESS
)
694 char buf
[DECIMAL_STR_MAX(vtnr
)];
695 sprintf(buf
, "%u", vtnr
);
697 r
= update_environment(handle
, "XDG_VTNR", buf
);
698 if (r
!= PAM_SUCCESS
)
702 r
= pam_set_data(handle
, "systemd.existing", INT_TO_PTR(!!existing
), NULL
);
703 if (r
!= PAM_SUCCESS
) {
704 pam_syslog(handle
, LOG_ERR
, "Failed to install existing flag.");
708 if (session_fd
>= 0) {
709 session_fd
= fcntl(session_fd
, F_DUPFD_CLOEXEC
, 3);
710 if (session_fd
< 0) {
711 pam_syslog(handle
, LOG_ERR
, "Failed to dup session fd: %m");
712 return PAM_SESSION_ERR
;
715 r
= pam_set_data(handle
, "systemd.session-fd", FD_TO_PTR(session_fd
), NULL
);
716 if (r
!= PAM_SUCCESS
) {
717 pam_syslog(handle
, LOG_ERR
, "Failed to install session fd.");
718 safe_close(session_fd
);
726 _public_ PAM_EXTERN
int pam_sm_close_session(
727 pam_handle_t
*handle
,
729 int argc
, const char **argv
) {
731 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
732 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
733 const void *existing
= NULL
;
739 /* Only release session if it wasn't pre-existing when we
740 * tried to create it */
741 (void) pam_get_data(handle
, "systemd.existing", &existing
);
743 id
= pam_getenv(handle
, "XDG_SESSION_ID");
744 if (id
&& !existing
) {
746 /* Before we go and close the FIFO we need to tell
747 * logind that this is a clean session shutdown, so
748 * that it doesn't just go and slaughter us
749 * immediately after closing the fd */
751 r
= sd_bus_open_system(&bus
);
753 pam_syslog(handle
, LOG_ERR
, "Failed to connect to system bus: %s", strerror(-r
));
754 return PAM_SESSION_ERR
;
757 r
= sd_bus_call_method(bus
,
758 "org.freedesktop.login1",
759 "/org/freedesktop/login1",
760 "org.freedesktop.login1.Manager",
767 pam_syslog(handle
, LOG_ERR
, "Failed to release session: %s", bus_error_message(&error
, r
));
768 return PAM_SESSION_ERR
;
772 /* Note that we are knowingly leaking the FIFO fd here. This
773 * way, logind can watch us die. If we closed it here it would
774 * not have any clue when that is completed. Given that one
775 * cannot really have multiple PAM sessions open from the same
776 * process this means we will leak one FD at max. */