HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/login/pam_systemd.c

81,007 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 6b5ee9afbaad6bbf19d693c41ea6f803d7491556

Lines 1001–1992 of 1,992

        if (!isempty(c->area) && !filename_is_valid(c->area)) {
                sym_pam_syslog(pamh, LOG_WARNING, "Specified area '%s' is not a valid filename, ignoring area request.", c->area);
                c->area = NULL;
        }
 
        if (isempty(c->class)) {
                c->class = streq(c->type, "unspecified") ? "background" : "user";
 
                /* For non-regular users tweak the type a bit:
                 *
                 * - Allow root tty logins *before* systemd-user-sessions.service is run, to allow early boot
                 *   logins to debug things.
                 *
                 * - Non-graphical sessions shall be invoked without service manager.
                 *
                 * (Note that this somewhat replicates the class mangling logic on systemd-logind.service's
                 * server side to some degree, in case clients allocate a session and don't specify a
                 * class. This is somewhat redundant, but we need the class set up properly below.)
                 *
                 * For regular users also tweak the type a bit: if an area is specified at login time, switch
                 * to light mode too. (Mostly because at the moment we do no support a per-area service
                 * manager. Once we do, we should change this.).
                 */
 
                switch (user_record_disposition(ur)) {
 
                case USER_INTRINSIC:
                case USER_SYSTEM:
                case USER_DYNAMIC:
                        if (streq(c->class, "user"))
                                c->class = user_record_is_root(ur) ? "user-early" :
                                        (STR_IN_SET(c->type, "x11", "wayland", "mir") ? "user" : "user-light");
                        else if (streq(c->class, "background"))
                                c->class = "background-light";
                        break;
 
                case USER_REGULAR:
                        if (!isempty(c->area)) {
                                if (streq(c->class, "user"))
                                        c->class = "user-light";
                                else if (streq(c->class, "background"))
                                        c->class = "background-light";
                        }
 
                        break;
 
                default:
                        ;
                }
 
                pam_debug_syslog(pamh, debug, "Automatically chose session class '%s'.", c->class);
        }
 
        if (c->incomplete) {
                if (streq(c->class, "user"))
                        c->class = "user-incomplete";
                else
                        sym_pam_syslog(pamh, LOG_WARNING, "PAM session of class '%s' is incomplete, which is not supported, ignoring.", c->class);
        }
 
        c->remote = !isempty(c->remote_host) && !is_localhost(c->remote_host);
}
 
static bool can_use_varlink(const SessionContext *c) {
        /* Since PID 1 currently doesn't do Varlink right now, we cannot directly set properties for the
         * scope, for now. */
        return !c->memory_max &&
                !c->runtime_max_sec &&
                !c->tasks_max &&
                !c->cpu_weight &&
                !c->io_weight;
}
 
static int register_session(
                pam_handle_t *pamh,
                SessionContext *c,
                UserRecord *ur,
                bool debug,
                char **ret_seat,
                char **ret_type,
                char **ret_runtime_dir) {
 
        int r;
 
        assert(pamh);
        assert(c);
        assert(ur);
        assert(ret_seat);
        assert(ret_type);
        assert(ret_runtime_dir);
 
        /* We don't register session class none with logind */
        if (streq(c->class, "none")) {
                pam_debug_syslog(pamh, debug, "Skipping logind registration for session class none.");
                *ret_seat = *ret_type = *ret_runtime_dir = NULL;
                return PAM_SUCCESS;
        }
 
        /* Make most of this a NOP on non-logind systems */
        if (!logind_running()) {
                pam_debug_syslog(pamh, debug, "Skipping logind registration as logind is not running.");
                *ret_seat = *ret_type = *ret_runtime_dir = NULL;
                return PAM_SUCCESS;
        }
 
        pam_debug_syslog(pamh, debug,
                         "Asking logind to create session: "
                         "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",
                         ur->uid, getpid_cached(),
                         strempty(c->service),
                         c->type, c->class, strempty(c->desktop),
                         strempty(c->seat), c->vtnr, strempty(c->tty), strempty(c->display),
                         yes_no(c->remote), strempty(c->remote_user), strempty(c->remote_host));
        pam_debug_syslog(pamh, debug,
                         "Session limits: "
                         "memory_max=%s tasks_max=%s cpu_weight=%s io_weight=%s runtime_max_sec=%s",
                         strna(c->memory_max), strna(c->tasks_max), strna(c->cpu_weight), strna(c->io_weight), strna(c->runtime_max_sec));
 
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL; /* the following variables point into this message, hence pin it for longer */
        _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL; /* similar */
        const char *id = NULL, *object_path = NULL, *runtime_path = NULL, *real_seat = NULL;
        uint32_t original_uid = UID_INVALID, real_vtnr = 0;
 
        bool done = false;
        if (can_use_varlink(c)) {
 
                r = sd_varlink_connect_address(&vl, "/run/systemd/io.systemd.Login");
                if (r < 0)
                        pam_debug_syslog_errno(pamh, debug, r, "Failed to connect to logind via Varlink, falling back to D-Bus: %m");
                else {
                        r = sd_varlink_set_allow_fd_passing_output(vl, true);
                        if (r < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to enable output fd passing on Varlink socket: %m");
 
                        r = sd_varlink_set_relative_timeout(vl, LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC);
                        if (r < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to set relative timeout on Varlink socket: %m");
 
                        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
                        r = pidref_set_self(&pidref);
                        if (r < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to acquire PID reference on ourselves: %m");
 
                        sd_json_variant *vreply = NULL;
                        const char *error_id = NULL;
                        r = sd_varlink_callbo(
                                        vl,
                                        "io.systemd.Login.CreateSession",
                                        &vreply,
                                        &error_id,
                                        SD_JSON_BUILD_PAIR_UNSIGNED("UID", ur->uid),
                                        JSON_BUILD_PAIR_PIDREF("PID", &pidref),
                                        JSON_BUILD_PAIR_STRING_NON_EMPTY("Service", c->service),
                                        JSON_BUILD_PAIR_ENUM("Type", c->type),
                                        JSON_BUILD_PAIR_ENUM("Class", c->class),
                                        JSON_BUILD_PAIR_STRING_NON_EMPTY("Desktop", c->desktop),
                                        JSON_BUILD_PAIR_STRING_NON_EMPTY("Seat", c->seat),
                                        JSON_BUILD_PAIR_UNSIGNED_NON_ZERO("VTNr", c->vtnr),
                                        JSON_BUILD_PAIR_STRING_NON_EMPTY("TTY", c->tty),
                                        JSON_BUILD_PAIR_STRING_NON_EMPTY("Display", c->display),
                                        SD_JSON_BUILD_PAIR_BOOLEAN("Remote", c->remote),
                                        JSON_BUILD_PAIR_STRING_NON_EMPTY("RemoteUser", c->remote_user),
                                        JSON_BUILD_PAIR_STRING_NON_EMPTY("RemoteHost", c->remote_host),
                                        JSON_BUILD_PAIR_CONDITION_STRV(!strv_isempty(c->extra_device_access), "ExtraDeviceAccess", c->extra_device_access));
                        if (r < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, r,
                                                        "Failed to issue io.systemd.Login.CreateSession varlink call: %m");
                        if (streq_ptr(error_id, "io.systemd.Login.AlreadySessionMember")) {
                                /* We are already in a session, don't do anything */
                                pam_debug_syslog(pamh, debug, "Not creating session: %s", error_id);
                                *ret_seat = *ret_type= *ret_runtime_dir = NULL;
                                return PAM_SUCCESS;
                        }
                        if (error_id)
                                return pam_syslog_errno(pamh, LOG_ERR, sd_varlink_error_to_errno(error_id, vreply),
                                                        "Varlink call io.systemd.Login.CreateSession failed: %s", error_id);
 
                        struct {
                                const char *id;
                                const char *runtime_path;
                                uid_t uid;
                                const char *seat;
                                unsigned vtnr;
                        } p = {
                                .uid = UID_INVALID,
                        };
 
                        static const sd_json_dispatch_field dispatch_table[] = {
                                { "Id",                    SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string, voffsetof(p, id),             SD_JSON_MANDATORY },
                                { "RuntimePath",           SD_JSON_VARIANT_STRING,        json_dispatch_const_path,      voffsetof(p, runtime_path),   SD_JSON_MANDATORY },
                                { "UID",                   _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,      voffsetof(p, uid),            SD_JSON_MANDATORY },
                                { "Seat",                  SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string, voffsetof(p, seat),           0                 },
                                { "VTNr",                  _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint,         voffsetof(p, vtnr),           0                 },
                                {}
                        };
 
                        r = sd_json_dispatch(vreply, dispatch_table, SD_JSON_ALLOW_EXTENSIONS, &p);
                        if (r < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to parse CreateSession() reply: %m");
 
                        id = p.id;
                        runtime_path = p.runtime_path;
                        original_uid = p.uid;
                        real_seat = p.seat;
                        real_vtnr = p.vtnr;
 
                        done = true;
                }
        }
 
        if (!done) {
                /* Let's release the D-Bus connection once we are done here, after all the session might live
                 * quite a long time, and we are not going to process the bus connection in that time, so
                 * let's better close before the daemon kicks us off because we are not processing
                 * anything. */
                _cleanup_(pam_bus_data_disconnectp) PamBusData *d = NULL;
                _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
 
                /* Talk to logind over the message bus */
                r = pam_acquire_bus_connection(pamh, "pam-systemd", debug, &bus, &d);
                if (r != PAM_SUCCESS)
                        return r;
 
                _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
                r = create_session_message(
                                bus,
                                pamh,
                                ur,
                                c,
                                /* avoid_pidfd= */ false,
                                &m);
                if (r < 0)
                        return pam_bus_log_create_error(pamh, r);
 
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
                r = sd_bus_call(bus, m, LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC, &error, &reply);
                if (r < 0 && sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
                        sd_bus_error_free(&error);
                        pam_debug_syslog(pamh, debug,
                                         "CreateSessionWithPIDFD() API is not available, retrying with CreateSession().");
 
                        m = sd_bus_message_unref(m);
                        r = create_session_message(bus,
                                                   pamh,
                                                   ur,
                                                   c,
                                                   /* avoid_pidfd= */ true,
                                                   &m);
                        if (r < 0)
                                return pam_bus_log_create_error(pamh, r);
 
                        r = sd_bus_call(bus, m, LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC, &error, &reply);
                }
                if (r < 0) {
                        if (sd_bus_error_has_name(&error, BUS_ERROR_SESSION_BUSY)) {
                                /* We are already in a session, don't do anything */
                                pam_debug_syslog(pamh, debug,
                                                 "Not creating session: %s", bus_error_message(&error, r));
                                *ret_seat = *ret_type = *ret_runtime_dir = NULL;
                                return PAM_SUCCESS;
                        }
 
                        sym_pam_syslog(pamh, LOG_ERR, "Failed to create session: %s", bus_error_message(&error, r));
                        return PAM_SESSION_ERR;
                }
 
                int session_fd;
                r = sd_bus_message_read(
                                reply,
                                "soshusub",
                                &id,
                                &object_path,
                                &runtime_path,
                                &session_fd,
                                &original_uid,
                                &real_seat,
                                &real_vtnr,
                                /* existing = */ NULL); /* deprecated in b80120c4cba7d134b5437a58437a23fdf7ab2084 */
                if (r < 0)
                        return pam_bus_log_parse_error(pamh, r);
 
                /* Since v258, logind fully relies on pidfd to monitor the lifetime of the session leader
                 * process and returns a dummy session_fd (no longer a fifo). However because logind cannot
                 * be restarted (known long-standing issue), we must still be prepared to receive a fifo fd
                 * from a running logind older than v258. */
                if (sd_is_fifo(session_fd, NULL) > 0) {
                        _cleanup_close_ int fd = fcntl(session_fd, F_DUPFD_CLOEXEC, 3);
                        if (fd < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, errno, "Failed to dup session fd: %m");
 
                        r = sym_pam_set_data(pamh, "systemd.session-fd", FD_TO_PTR(fd), NULL);
                        if (r != PAM_SUCCESS)
                                return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to install session fd: @PAMERR@");
                        TAKE_FD(fd);
                }
        }
 
        pam_debug_syslog(pamh, debug,
                         "Reply from logind: "
                         "id=%s object_path=%s runtime_path=%s seat=%s vtnr=%u original_uid=%u",
                         id, strna(object_path), runtime_path, real_seat, real_vtnr, original_uid);
 
        /* Please update manager_default_environment() in core/manager.c accordingly if more session envvars
         * shall be added. */
 
        r = update_environment(pamh, "XDG_SESSION_ID", id);
        if (r != PAM_SUCCESS)
                return r;
 
        /* Most likely we got the session/type/class from environment variables, but might have gotten the data
         * somewhere else (for example PAM module parameters). Let's now update the environment variables, so that this
         * data is inherited into the session processes, and programs can rely on them to be initialized. */
 
        _cleanup_free_ char *real_type = strdup(c->type); /* make copy because this might point to env block, which we are going to update shortly */
        if (!real_type)
                return pam_log_oom(pamh);
 
        r = update_environment(pamh, "XDG_SESSION_TYPE", c->type);
        if (r != PAM_SUCCESS)
                return r;
 
        r = update_environment(pamh, "XDG_SESSION_CLASS", c->class);
        if (r != PAM_SUCCESS)
                return r;
 
        r = update_environment(pamh, "XDG_SESSION_DESKTOP", c->desktop);
        if (r != PAM_SUCCESS)
                return r;
 
        _cleanup_free_ char *extra_devices = strv_join(c->extra_device_access, ":");
        if (!extra_devices)
                return pam_log_oom(pamh);
 
        r = update_environment(pamh, "XDG_SESSION_EXTRA_DEVICE_ACCESS", extra_devices);
        if (r != PAM_SUCCESS)
                return r;
 
        r = update_environment(pamh, "XDG_SEAT", real_seat);
        if (r != PAM_SUCCESS)
                return r;
 
        if (real_vtnr > 0) {
                char buf[DECIMAL_STR_MAX(real_vtnr)];
                xsprintf(buf, "%u", real_vtnr);
 
                r = update_environment(pamh, "XDG_VTNR", buf);
                if (r != PAM_SUCCESS)
                        return r;
        }
 
        /* Don't set $XDG_RUNTIME_DIR if the user we now authenticated for does not match the
         * original user of the session. We do this in order not to result in privileged apps
         * clobbering the runtime directory unnecessarily. */
        _cleanup_free_ char *rt = NULL;
        if (original_uid == ur->uid && validate_runtime_directory(pamh, runtime_path, ur->uid))
                if (strdup_to(&rt, runtime_path) < 0)
                        return pam_log_oom(pamh);
 
        /* Everything worked, hence let's patch in the data we learned. Since 'real_set' points into the
         * D-Bus message, let's copy it and return it as a buffer */
        _cleanup_free_ char *rs = NULL;
        if (strdup_to(&rs, real_seat) < 0)
                return pam_log_oom(pamh);
 
        c->vtnr = real_vtnr;
        c->seat = *ret_seat = TAKE_PTR(rs);
        c->type = *ret_type = TAKE_PTR(real_type);
        *ret_runtime_dir = TAKE_PTR(rt);
 
        return PAM_SUCCESS;
}
 
static int import_shell_credentials(pam_handle_t *pamh, bool debug) {
 
        static const char *const propagate[] = {
                "shell.prompt.prefix", "SHELL_PROMPT_PREFIX",
                "shell.prompt.suffix", "SHELL_PROMPT_SUFFIX",
                "shell.welcome",       "SHELL_WELCOME",
                NULL
        };
        int r;
 
        assert(pamh);
 
        STRV_FOREACH_PAIR(k, v, propagate) {
                r = propagate_credential_to_environment(pamh, debug, *k, *v);
                if (r != PAM_SUCCESS)
                        return r;
        }
 
        return PAM_SUCCESS;
}
 
static int mkdir_chown_open_directory(
                int parent_fd,
                const char *name,
                uid_t uid,
                gid_t gid,
                mode_t mode) {
 
        _cleanup_free_ char *t = NULL;
        int r;
 
        assert(parent_fd >= 0);
        assert(name);
        assert(uid_is_valid(uid));
        assert(gid_is_valid(gid));
        assert(mode != MODE_INVALID);
 
        for (unsigned attempt = 0;; attempt++) {
                _cleanup_close_ int fd = openat(parent_fd, name, O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
                if (fd >= 0)
                        return TAKE_FD(fd);
                if (errno != ENOENT)
                        return -errno;
 
                /* Let's create the directory under a temporary name first, since we want to make sure that
                 * once it appears under the right name it has the right ownership */
                r = tempfn_random(name, /* extra= */ NULL, &t);
                if (r < 0)
                        return r;
 
                fd = open_mkdir_at(parent_fd, t, O_CLOEXEC|O_EXCL, 0700); /* Use restrictive mode until ownership is in order */
                if (fd < 0)
                        return fd;
 
                r = RET_NERRNO(fchown(fd, uid, gid));
                if (r < 0)
                        goto fail;
 
                r = RET_NERRNO(fchmod(fd, mode));
                if (r < 0)
                        goto fail;
 
                r = rename_noreplace(parent_fd, t, parent_fd, name);
                if (r >= 0)
                        return TAKE_FD(fd);
                if (r != -EEXIST || attempt >= 5)
                        goto fail;
 
                /* Maybe some other login attempt created the directory at the same time? Let's retry */
                (void) unlinkat(parent_fd, t, AT_REMOVEDIR);
                t = mfree(t);
        }
 
fail:
        (void) unlinkat(parent_fd, ASSERT_PTR(t), AT_REMOVEDIR);
        return r;
}
 
static int make_area_runtime_directory(
                pam_handle_t *pamh,
                UserRecord *ur,
                const char *runtime_directory,
                const char *area,
                char **ret) {
 
        assert(pamh);
        assert(ur);
        assert(runtime_directory);
        assert(area);
        assert(ret);
 
        /* Let's be careful with creating these directories, the runtime directory is owned by the user after all,
         * and they might play symlink games with us. */
 
        _cleanup_close_ int fd = open(runtime_directory, O_CLOEXEC|O_PATH|O_DIRECTORY);
        if (fd < 0)
                return pam_syslog_errno(pamh, LOG_ERR, errno, "Unable to open runtime directory '%s': %m", runtime_directory);
 
        _cleanup_close_ int fd_areas = mkdir_chown_open_directory(fd, "Areas", ur->uid, user_record_gid(ur), 0755);
        if (fd_areas < 0)
                return pam_syslog_errno(pamh, LOG_ERR, fd_areas, "Unable to create 'Areas' directory below '%s': %m", runtime_directory);
 
        _cleanup_close_ int fd_area = mkdir_chown_open_directory(fd_areas, area, ur->uid, user_record_gid(ur), 0755);
        if (fd_area < 0)
                return pam_syslog_errno(pamh, LOG_ERR, fd_area, "Unable to create '%s' directory below '%s/Areas': %m", area, runtime_directory);
 
        char *j = path_join(runtime_directory, "Areas", area);
        if (!j)
                return pam_log_oom(pamh);
 
        *ret = j;
        return 0;
}
 
static int export_legacy_dbus_address(pam_handle_t *pamh, const char *runtime) {
 
        assert(pamh);
        assert(runtime);
 
        /* We need to export $DBUS_SESSION_BUS_ADDRESS because various applications will not connect
         * correctly to the bus without it. This setting matches what dbus.socket does for the user session
         * using 'systemctl --user set-environment'. We want to have the same configuration in processes
         * started from the PAM session.
         *
         * The setting of the address is guarded by the access() check because it is also possible to compile
         * dbus without --enable-user-session, in which case this socket is not used, and
         * $DBUS_SESSION_BUS_ADDRESS should not be set. An alternative approach would to not do the access()
         * check here, and let applications try on their own, by using "unix:path=%s/bus;autolaunch:". But we
         * expect the socket to be present by the time we do this check, so we can just as well check once
         * here. */
 
        const char *s = strjoina(runtime, "/bus");
        if (access(s, F_OK) < 0) {
                if (errno != ENOENT)
                        pam_syslog_errno(pamh, LOG_WARNING, errno, "Failed to check if %s/bus exists, ignoring: %m", runtime);
 
                return PAM_SUCCESS;
        }
 
        _cleanup_free_ char *t = NULL;
        if (asprintf(&t, DEFAULT_USER_BUS_ADDRESS_FMT, runtime) < 0)
                return pam_log_oom(pamh);
 
        return update_environment(pamh, "DBUS_SESSION_BUS_ADDRESS", t);
}
 
static int setup_runtime_directory(
                pam_handle_t *pamh,
                UserRecord *ur,
                const char *runtime_directory,
                const char *area) {
 
        int r;
 
        assert(pamh);
        assert(ur);
 
        if (!runtime_directory) {
                /* If this is an area switch request, always reset $XDG_RUNTIME_DIR if we got nothing
                 * to ensure the main runtime dir won't be clobbered. */
                if (area)
                        return update_environment(pamh, "XDG_RUNTIME_DIR", NULL);
 
                return PAM_SUCCESS;
        }
 
        /* Also create a per-area subdirectory for $XDG_RUNTIME_DIR, so that each area has their own
         * set of runtime services. We follow the same directory structure as for $HOME. Note that we
         * do not define any form of automatic clean-up for the per-area subdirs beyond the regular
         * clean-up of the whole $XDG_RUNTIME_DIR hierarchy when the user finally logs out. */
        _cleanup_free_ char *per_area_runtime_directory = NULL;
        if (area) {
                r = make_area_runtime_directory(pamh, ur, runtime_directory, area, &per_area_runtime_directory);
                if (r != PAM_SUCCESS)
                        return r;
 
                runtime_directory = per_area_runtime_directory;
        }
 
        r = update_environment(pamh, "XDG_RUNTIME_DIR", runtime_directory);
        if (r != PAM_SUCCESS)
                return r;
 
        return export_legacy_dbus_address(pamh, runtime_directory);
}
 
static int setup_environment(
                pam_handle_t *pamh,
                UserRecord *ur,
                const char *runtime_directory,
                const char *area,
                bool debug) {
 
        int r;
 
        assert(pamh);
        assert(ur);
 
        const char *h = ASSERT_PTR(user_record_home_directory(ur));
 
        /* If an empty area string is specified, this means an explicit: do not use the area logic, normalize this here */
        area = empty_to_null(area);
 
        _cleanup_free_ char *ha = NULL, *area_copy = NULL;
        if (area) {
                _cleanup_free_ char *j = path_join(h, "Areas", area);
                if (!j)
                        return pam_log_oom(pamh);
 
                _cleanup_close_ int fd = -EBADF;
                r = chase(j, /* root= */ NULL, CHASE_MUST_BE_DIRECTORY, &ha, &fd);
                if (r < 0) {
                        /* Log the precise error */
                        pam_syslog_errno(pamh, LOG_WARNING, r, "Path '%s' of requested user area '%s' is not accessible, reverting to regular home directory: %m", j, area);
 
                        /* Also tell the user directly at login, but a bit more vague */
                        sym_pam_info(pamh, "Path '%s' of requested user area '%s' is not accessible, reverting to regular home directory.", j, area);
                        area = NULL;
                } else {
                        /* Validate that the target is definitely owned by user */
                        struct stat st;
                        if (fstat(fd, &st) < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, errno, "Unable to fstat() target area directory '%s': %m", ha);
 
                        if (st.st_uid != ur->uid) {
                                sym_pam_syslog(pamh, LOG_ERR, "Path '%s' of requested user area '%s' is not owned by user, reverting to regular home directory.", ha, area);
 
                                /* Also tell the user directly at login. */
                                sym_pam_info(pamh, "Path '%s' of requested user area '%s' is not owned by user, reverting to regular home directory.", ha, area);
                                area = NULL;
                        } else {
                                /* All good, now make a copy of the area string, since we quite likely are
                                 * going to invalidate it (if it points into the environment block), via the
                                 * update_environment() call below */
                                area_copy = strdup(area);
                                if (!area_copy)
                                        return pam_log_oom(pamh);
 
                                pam_debug_syslog(pamh, debug, "Area '%s' selected, setting $HOME to '%s'.", area, ha);
                                h = ha;
                                area = area_copy;
                        }
                }
        }
 
        r = update_environment(pamh, "XDG_AREA", area);
        if (r != PAM_SUCCESS)
                return r;
 
        r = update_environment(pamh, "HOME", h);
        if (r != PAM_SUCCESS)
                return r;
 
        return setup_runtime_directory(pamh, ur, runtime_directory, area);
}
 
static int open_osc_context(pam_handle_t *pamh, const char *session_type, UserRecord *ur, bool debug) {
        int r;
 
        assert(pamh);
        assert(ur);
 
        /* If this is a TTY session, then output the session start OSC sequence */
 
        if (!streq_ptr(session_type, "tty"))
                return PAM_SUCCESS;
 
        const char *e = sym_pam_getenv(pamh, "TERM");
        if (!e)
                e = getenv("TERM");
        if (streq_ptr(e, "dumb"))
                return PAM_SUCCESS;
 
        /* NB: we output directly to stdout, instead of going via sym_pam_info() or so, because that's too
         * high-level for us, as it suffixes the output with a newline, expecting a full blown text message
         * as prompt string, not just an ANSI sequence. Note that PAM's conv_misc() actually goes to stdout
         * anyway, hence let's do so here too, but only after careful validation. */
        if (!isatty_safe(STDOUT_FILENO))
                return PAM_SUCCESS;
 
        /* Keep a reference to the TTY we are operating on, so that we can issue the OSC close sequence also
         * if the TTY is already closed. We use an O_PATH reference here, rather than a properly opened fd,
         * so that we don't delay tty hang-up. */
        _cleanup_close_ int tty_opath_fd = fd_reopen(STDOUT_FILENO, O_PATH|O_CLOEXEC);
        if (tty_opath_fd < 0)
                pam_debug_syslog_errno(pamh, debug, tty_opath_fd, "Failed to pin TTY, ignoring: %m");
        else
                tty_opath_fd = fd_move_above_stdio(tty_opath_fd);
 
        _cleanup_free_ char *osc = NULL;
        sd_id128_t osc_id;
        r = osc_context_open_session(
                        ur->user_name,
                        sym_pam_getenv(pamh, "XDG_SESSION_ID"),
                        &osc,
                        &osc_id);
        if (r < 0)
                return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to prepare OSC sequence: %m");
 
        r = loop_write(STDOUT_FILENO, osc, SIZE_MAX);
        if (r < 0)
                return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to write OSC sequence to TTY: %m");
 
        /* Remember the OSC context id, so that we can close it cleanly later */
        _cleanup_free_ sd_id128_t *osc_id_copy = newdup(sd_id128_t, &osc_id, 1);
        if (!osc_id_copy)
                return pam_log_oom(pamh);
 
        r = sym_pam_set_data(pamh, "systemd.osc-context-id", osc_id_copy, pam_cleanup_free);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r,
                                            "Failed to set PAM OSC sequence ID data: @PAMERR@");
 
        TAKE_PTR(osc_id_copy);
 
        if (tty_opath_fd >= 0) {
                r = sym_pam_set_data(pamh, "systemd.osc-context-fd", FD_TO_PTR(tty_opath_fd), pam_cleanup_close);
                if (r != PAM_SUCCESS)
                        return pam_syslog_pam_error(pamh, LOG_ERR, r,
                                                    "Failed to set PAM OSC sequence fd data: @PAMERR@");
 
                TAKE_FD(tty_opath_fd);
        }
 
        return PAM_SUCCESS;
}
 
static int close_osc_context(pam_handle_t *pamh, bool debug) {
        int r;
 
        assert(pamh);
 
        const void *p;
        int tty_opath_fd = -EBADF;
        r = sym_pam_get_data(pamh, "systemd.osc-context-fd", &p);
        if (r == PAM_SUCCESS)
                tty_opath_fd = PTR_TO_FD(p);
        else if (r != PAM_NO_MODULE_DATA)
                return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to get PAM OSC context fd: @PAMERR@");
        if (tty_opath_fd < 0)
                return PAM_SUCCESS;
 
        const sd_id128_t *osc_id = NULL;
        r = sym_pam_get_data(pamh, "systemd.osc-context-id", (const void**) &osc_id);
        if (!IN_SET(r, PAM_SUCCESS, PAM_NO_MODULE_DATA))
                return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to get PAM OSC context id data: @PAMERR@");
        if (!osc_id)
                return PAM_SUCCESS;
 
        /* Now open the original TTY again, so that we can write on it */
        _cleanup_close_ int fd = fd_reopen(tty_opath_fd, O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
        if (fd < 0) {
                pam_debug_syslog_errno(pamh, debug, fd, "Failed to reopen TTY, ignoring: %m");
                return PAM_SUCCESS;
        }
 
        /* /bin/login calls us with fds 0, 1, 2 closed, which is just weird. Let's step outside of that
         * range, just in case sym_pam_syslog() or so logs to stderr */
        fd = fd_move_above_stdio(fd);
 
        /* Safety check, let's verify this is a valid TTY we just opened */
        if (!isatty_safe(fd))
                return PAM_SUCCESS;
 
        _cleanup_free_ char *osc = NULL;
        r = osc_context_close(*osc_id, &osc);
        if (r < 0)
                return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to prepare OSC sequence: %m");
 
        /* When we are closing things, the TTY might not take our writes anymore. Accept that gracefully. */
        r = loop_write(fd, osc, SIZE_MAX);
        if (r < 0)
                pam_debug_syslog_errno(pamh, debug, r, "Failed to write OSC sequence to TTY, ignoring: %m");
 
        return PAM_SUCCESS;
}
 
static int acquire_inhibit_lock(
                pam_handle_t *pamh,
                const char *inhibit_what,
                const char *inhibit_why,
                bool debug) {
 
        _cleanup_(pam_bus_data_disconnectp) PamBusData *d = NULL;
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
        const char *service = NULL;
        int r;
 
        assert(pamh);
        assert(inhibit_what);
 
        r = pam_acquire_bus_connection(pamh, "pam-systemd", debug, &bus, &d);
        if (r != PAM_SUCCESS)
                return r;
 
        (void) sym_pam_get_item(pamh, PAM_SERVICE, (const void **) &service);
 
        r = bus_call_method(bus, bus_login_mgr, "Inhibit", &error, &reply, "ssss",
                            inhibit_what,
                            service ?: "pam_systemd",
                            inhibit_why ?: "Active PAM session",
                            "block");
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING, "Failed to acquire inhibit lock: %s", bus_error_message(&error, r));
                return PAM_SESSION_ERR;
        }
 
        int raw_fd;
        r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_UNIX_FD, &raw_fd);
        if (r < 0)
                return pam_bus_log_parse_error(pamh, r);
 
        _cleanup_close_ int fd = fcntl(raw_fd, F_DUPFD_CLOEXEC, 3);
        if (fd < 0)
                return pam_syslog_errno(pamh, LOG_ERR, errno, "Failed to dup inhibit lock fd: %m");
 
        r = sym_pam_set_data(pamh, "systemd.inhibit-fd", FD_TO_PTR(fd), pam_cleanup_close);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r,
                                            "Failed to store inhibit lock fd: @PAMERR@");
        TAKE_FD(fd);
 
        pam_debug_syslog(pamh, debug, "Acquired inhibit lock for '%s'.", inhibit_what);
        return PAM_SUCCESS;
}
 
_public_ PAM_EXTERN int pam_sm_open_session(
                pam_handle_t *pamh,
                int flags,
                int argc, const char **argv) {
 
        int r;
 
        assert(pamh);
 
        LIBPAM_NOTE(required);
        r = dlopen_libpam(LOG_DEBUG);
        if (r < 0)
                return PAM_SERVICE_ERR;
 
        pam_log_setup();
 
        uint64_t default_capability_bounding_set = CAP_MASK_UNSET, default_capability_ambient_set = CAP_MASK_UNSET;
        const char *class_pam = NULL, *type_pam = NULL, *desktop_pam = NULL, *area_pam = NULL, *inhibit_what = NULL, *inhibit_why = NULL;
        bool debug = false;
        if (parse_argv(pamh,
                       argc, argv,
                       &class_pam,
                       &type_pam,
                       &desktop_pam,
                       &area_pam,
                       &inhibit_what,
                       &inhibit_why,
                       &debug,
                       &default_capability_bounding_set,
                       &default_capability_ambient_set) < 0)
                return PAM_SESSION_ERR;
 
        pam_debug_syslog(pamh, debug, "pam-systemd: initializing...");
 
        _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
        r = acquire_user_record(pamh, &ur);
        if (r != PAM_SUCCESS)
                return r;
 
        _cleanup_(session_context_done) SessionContext c = {};
        r = pam_get_item_many(
                        pamh,
                        PAM_SERVICE,  &c.service,
                        PAM_XDISPLAY, &c.display,
                        PAM_TTY,      &c.tty,
                        PAM_RUSER,    &c.remote_user,
                        PAM_RHOST,    &c.remote_host);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to get PAM items: @PAMERR@");
 
        c.seat = getenv_harder(pamh, "XDG_SEAT", NULL);
        c.vtnr = getenv_harder_uint32(pamh, "XDG_VTNR", 0);
        c.type = getenv_harder(pamh, "XDG_SESSION_TYPE", type_pam);
        c.class = getenv_harder(pamh, "XDG_SESSION_CLASS", class_pam);
        c.desktop = getenv_harder(pamh, "XDG_SESSION_DESKTOP", desktop_pam);
        c.area = getenv_harder(pamh, "XDG_AREA", area_pam);
        c.incomplete = getenv_harder_bool(pamh, "XDG_SESSION_INCOMPLETE", false);
        inhibit_what = getenv_harder(pamh, "XDG_SESSION_INHIBIT", inhibit_what);
        inhibit_why = getenv_harder(pamh, "XDG_SESSION_INHIBIT_WHY", inhibit_why);
 
        const char *extra_device_access = getenv_harder(pamh, "XDG_SESSION_EXTRA_DEVICE_ACCESS", NULL);
        if (extra_device_access) {
                c.extra_device_access = strv_split(extra_device_access, ":");
                if (!c.extra_device_access)
                        return pam_log_oom(pamh);
        }
 
        r = pam_get_data_many(
                        pamh,
                        "systemd.memory_max",      &c.memory_max,
                        "systemd.tasks_max",       &c.tasks_max,
                        "systemd.cpu_weight",      &c.cpu_weight,
                        "systemd.io_weight",       &c.io_weight,
                        "systemd.runtime_max_sec", &c.runtime_max_sec);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to get PAM data: @PAMERR@");
 
        session_context_mangle(pamh, &c, ur, debug);
 
        _cleanup_free_ char *seat_buffer = NULL, *type_buffer = NULL, *runtime_dir = NULL;
        r = register_session(pamh, &c, ur, debug, &seat_buffer, &type_buffer, &runtime_dir);
        if (r != PAM_SUCCESS)
                return r;
 
        if (inhibit_what)
                /* Failure to acquire the inhibit lock is not fatal, session setup should proceed
                 * regardless. */
                (void) acquire_inhibit_lock(pamh, inhibit_what, inhibit_why, debug);
 
        r = import_shell_credentials(pamh, debug);
        if (r != PAM_SUCCESS)
                return r;
 
        r = setup_environment(pamh, ur, runtime_dir, c.area, debug);
        if (r != PAM_SUCCESS)
                return r;
 
        if (default_capability_ambient_set == CAP_MASK_UNSET)
                default_capability_ambient_set = pick_default_capability_ambient_set(ur, c.service, c.seat);
 
        r = apply_user_record_settings(pamh, ur, debug, default_capability_bounding_set, default_capability_ambient_set);
        if (r != PAM_SUCCESS)
                return r;
 
        return open_osc_context(pamh, c.type, ur, debug);
}
 
_public_ PAM_EXTERN int pam_sm_close_session(
                pam_handle_t *pamh,
                int flags,
                int argc, const char **argv) {
 
        bool debug = false;
        const char *id;
        int r;
 
        assert(pamh);
 
        r = dlopen_libpam(LOG_DEBUG);
        if (r < 0)
                return PAM_SERVICE_ERR;
 
        pam_log_setup();
 
        if (parse_argv(pamh,
                       argc, argv,
                       /* class= */ NULL,
                       /* type= */ NULL,
                       /* desktop= */ NULL,
                       /* area= */ NULL,
                       /* inhibit_what= */ NULL,
                       /* inhibit_why= */ NULL,
                       &debug,
                       /* default_capability_bounding_set= */ NULL,
                       /* default_capability_ambient_set= */ NULL) < 0)
                return PAM_SESSION_ERR;
 
        pam_debug_syslog(pamh, debug, "pam-systemd: shutting down...");
 
        (void) close_osc_context(pamh, debug);
 
        (void) sym_pam_set_data(pamh, "systemd.inhibit-fd", NULL, NULL);
 
        id = sym_pam_getenv(pamh, "XDG_SESSION_ID");
        if (id) {
                _cleanup_(sd_varlink_unrefp) sd_varlink *vl = NULL;
                bool done = false;
 
                r = sd_varlink_connect_address(&vl, "/run/systemd/io.systemd.Login");
                if (r < 0)
                        pam_debug_syslog_errno(pamh, debug, r, "Failed to connect to logind via Varlink, falling back to D-Bus: %m");
                else {
                        _cleanup_(sd_json_variant_unrefp) sd_json_variant *vreply = NULL;
                        const char *error_id = NULL;
                        r = sd_varlink_callbo(
                                        vl,
                                        "io.systemd.Login.ReleaseSession",
                                        /* ret_reply= */ NULL,
                                        &error_id,
                                        SD_JSON_BUILD_PAIR_STRING("Id", id));
                        if (r < 0)
                                return pam_syslog_errno(pamh, LOG_ERR, r,
                                                        "Failed to issue io.systemd.Login.ReleaseSession varlink call: %m");
                        if (error_id)
                                return pam_syslog_errno(pamh, LOG_ERR, sd_varlink_error_to_errno(error_id, vreply),
                                                        "Varlink call io.systemd.Login.ReleaseSession failed: %s", error_id);
 
                        done = true;
                }
 
                if (!done) {
                        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
                        _cleanup_(pam_bus_data_disconnectp) PamBusData *d = NULL;
                        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
 
                        /* Before we go and close the FIFO we need to tell logind that this is a clean session
                         * shutdown, so that it doesn't just go and slaughter us immediately after closing the fd */
 
                        r = pam_acquire_bus_connection(pamh, "pam-systemd", debug, &bus, &d);
                        if (r != PAM_SUCCESS)
                                return r;
 
                        r = bus_call_method(bus, bus_login_mgr, "ReleaseSession", &error, NULL, "s", id);
                        if (r < 0)
                                return pam_syslog_pam_error(pamh, LOG_ERR, PAM_SESSION_ERR,
                                                            "Failed to release session: %s", bus_error_message(&error, r));
                }
        }
 
        return PAM_SUCCESS;
}