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 1–1000 of 1,992

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <endian.h>
#include <fcntl.h>
#include <pwd.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h>
 
#include "sd-bus.h"
#include "sd-daemon.h"
#include "sd-varlink.h"
 
#include "alloc-util.h"
#include "bus-common-errors.h"
#include "bus-error.h"
#include "bus-internal.h"
#include "bus-locator.h"
#include "capability-list.h"
#include "capability-util.h"
#include "cgroup-setup.h"
#include "chase.h"
#include "creds-util.h"
#include "devnum-util.h"
#include "errno-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "format-util.h"
#include "fs-util.h"
#include "hostname-util.h"
#include "io-util.h"
#include "json-util.h"
#include "locale-util.h"
#include "login-util.h"
#include "osc-context.h"
#include "pam-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "percent-util.h"
#include "pidfd-util.h"
#include "pidref.h"
#include "process-util.h"
#include "rlimit-util.h"
#include "socket-util.h"
#include "stdio-util.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "time-util.h"
#include "tmpfile-util.h"
#include "user-util.h"
#include "userdb.h"
 
#define LOGIN_SLOW_BUS_CALL_TIMEOUT_USEC (2*USEC_PER_MINUTE)
 
static int parse_caps(
                pam_handle_t *pamh,
                const char *value,
                uint64_t *caps) {
 
        bool subtract;
        int r;
 
        assert(pamh);
        assert(value);
 
        if (value[0] == '~') {
                subtract = true;
                value++;
        } else
                subtract = false;
 
        for (;;) {
                _cleanup_free_ char *s = NULL;
                uint64_t b, m;
                int c;
 
                /* We can't use spaces as separators here, as PAM's simplistic argument parser doesn't allow
                 * spaces inside of arguments. We use commas instead (which is similar to cap_from_text(),
                 * which also uses commas). */
                r = extract_first_word(&value, &s, ",", EXTRACT_DONT_COALESCE_SEPARATORS);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                c = capability_from_name(s);
                if (c < 0) {
                        sym_pam_syslog(pamh, LOG_WARNING, "Unknown capability, ignoring: %s", s);
                        continue;
                }
 
                m = UINT64_C(1) << c;
 
                if (!caps)
                        continue;
 
                if (*caps == CAP_MASK_UNSET)
                        b = subtract ? all_capabilities() : 0;
                else
                        b = *caps;
 
                if (subtract)
                        *caps = b & ~m;
                else
                        *caps = b | m;
        }
 
        return 0;
}
 
static int parse_argv(
                pam_handle_t *pamh,
                int argc, const char **argv,
                const char **class,
                const char **type,
                const char **desktop,
                const char **area,
                const char **inhibit_what,
                const char **inhibit_why,
                bool *debug,
                uint64_t *default_capability_bounding_set,
                uint64_t *default_capability_ambient_set) {
 
        int r;
 
        assert(pamh);
        assert(argc >= 0);
        assert(argc == 0 || argv);
 
        for (int i = 0; i < argc; i++) {
                const char *p;
 
                if ((p = startswith(argv[i], "class="))) {
                        if (class)
                                *class = p;
 
                } else if ((p = startswith(argv[i], "type="))) {
                        if (type)
                                *type = p;
 
                } else if ((p = startswith(argv[i], "desktop="))) {
                        if (desktop)
                                *desktop = p;
 
                } else if ((p = startswith(argv[i], "area="))) {
 
                        if (!isempty(p) && !filename_is_valid(p))
                                sym_pam_syslog(pamh, LOG_WARNING, "Area name specified among PAM module parameters is not valid, ignoring: %s", p);
                        else if (area)
                                *area = p;
                } else if ((p = startswith(argv[i], "inhibit="))) {
                        if (inhibit_what)
                                *inhibit_what = p;
                } else if ((p = startswith(argv[i], "inhibit-why="))) {
                        if (inhibit_why)
                                *inhibit_why = p;
 
                } else if (streq(argv[i], "debug")) {
                        if (debug)
                                *debug = true;
 
                } else if ((p = startswith(argv[i], "debug="))) {
                        r = parse_boolean(p);
                        if (r < 0)
                                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse debug= argument, ignoring: %s", p);
                        else if (debug)
                                *debug = r;
 
                } else if ((p = startswith(argv[i], "default-capability-bounding-set="))) {
                        r = parse_caps(pamh, p, default_capability_bounding_set);
                        if (r < 0)
                                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse default-capability-bounding-set= argument, ignoring: %s", p);
 
                } else if ((p = startswith(argv[i], "default-capability-ambient-set="))) {
                        r = parse_caps(pamh, p, default_capability_ambient_set);
                        if (r < 0)
                                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse default-capability-ambient-set= argument, ignoring: %s", p);
 
                } else
                        sym_pam_syslog(pamh, LOG_WARNING, "Unknown parameter '%s', ignoring.", argv[i]);
        }
 
        return 0;
}
 
static int acquire_user_record(pam_handle_t *pamh, UserRecord **ret_record) {
        int r;
 
        assert(pamh);
 
        const char *username = NULL;
        r = sym_pam_get_user(pamh, &username, NULL);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to get user name: @PAMERR@");
        if (isempty(username))
                return pam_syslog_pam_error(pamh, LOG_ERR, PAM_SERVICE_ERR, "User name not valid.");
 
        /* If pam_systemd_homed (or some other module) already acquired the user record we can reuse it
         * here. */
        _cleanup_free_ char *field = strjoin("systemd-user-record-", username);
        if (!field)
                return pam_log_oom(pamh);
 
        _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
        const char *json = NULL;
        r = sym_pam_get_data(pamh, field, (const void**) &json);
        if (!IN_SET(r, PAM_SUCCESS, PAM_NO_MODULE_DATA))
                return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to get PAM user record data: @PAMERR@");
        if (r == PAM_SUCCESS && json) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
 
                /* Parse cached record */
                r = sd_json_parse(json, SD_JSON_PARSE_MUST_BE_OBJECT|SD_JSON_PARSE_SENSITIVE, &v, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
                if (r < 0)
                        return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to parse JSON user record: %m");
 
                ur = user_record_new();
                if (!ur)
                        return pam_log_oom(pamh);
 
                r = user_record_load(ur, v, USER_RECORD_LOAD_REFUSE_SECRET|USER_RECORD_PERMISSIVE);
                if (r < 0)
                        return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to load user record: %m");
 
                /* Safety check if cached record actually matches what we are looking for */
                if (!user_record_matches_user_name(ur, username))
                        return pam_syslog_pam_error(pamh, LOG_ERR, PAM_SERVICE_ERR,
                                                    "Acquired user record does not match user name.");
        } else {
                _cleanup_free_ char *formatted = NULL;
 
                /* Request the record ourselves */
                r = userdb_by_name(username, /* match= */ NULL, /* flags= */ 0, &ur);
                if (r < 0) {
                        pam_syslog_errno(pamh, LOG_ERR, r, "Failed to get user record: %m");
                        return PAM_USER_UNKNOWN;
                }
 
                if (!uid_is_valid(ur->uid))
                        return pam_syslog_pam_error(pamh, LOG_ERR, PAM_USER_UNKNOWN,
                                                    "User record of user '%s' has no UID, refusing.", username);
 
                r = sd_json_variant_format(ur->json, 0, &formatted);
                if (r < 0)
                        return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to format user JSON: %m");
 
                /* And cache it for everyone else */
                r = sym_pam_set_data(pamh, field, formatted, pam_cleanup_free);
                if (r != PAM_SUCCESS)
                        return pam_syslog_pam_error(pamh, LOG_ERR, r,
                                                    "Failed to set PAM user record data '%s': @PAMERR@", field);
                TAKE_PTR(formatted);
        }
 
        if (!uid_is_valid(ur->uid))
                return pam_syslog_pam_error(pamh, LOG_ERR, PAM_SERVICE_ERR,
                                            "Acquired user record does not have a UID.");
 
        if (ret_record)
                *ret_record = TAKE_PTR(ur);
 
        return PAM_SUCCESS;
}
 
static bool display_is_local(const char *display) {
        assert(display);
 
        return
                display[0] == ':' &&
                ascii_isdigit(display[1]);
}
 
static int socket_from_display(const char *display) {
        _cleanup_free_ char *f = NULL;
        size_t k;
        char *c;
        union sockaddr_union sa;
        socklen_t sa_len;
        _cleanup_close_ int fd = -EBADF;
        int r;
 
        assert(display);
 
        if (!display_is_local(display))
                return -EINVAL;
 
        k = strspn(display + 1, DIGITS);
 
        /* Try abstract socket first. */
        f = new(char, STRLEN("@/tmp/.X11-unix/X") + k + 1);
        if (!f)
                return -ENOMEM;
 
        c = stpcpy(f, "@/tmp/.X11-unix/X");
        memcpy(c, display+1, k);
        c[k] = 0;
 
        r = sockaddr_un_set_path(&sa.un, f);
        if (r < 0)
                return r;
        sa_len = r;
 
        fd = RET_NERRNO(socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0));
        if (fd < 0)
                return fd;
 
        r = RET_NERRNO(connect(fd, &sa.sa, sa_len));
        if (r >= 0)
                return TAKE_FD(fd);
        if (r != -ECONNREFUSED)
                return r;
 
        /* Try also non-abstract socket. */
        r = sockaddr_un_set_path(&sa.un, f + 1);
        if (r < 0)
                return r;
        sa_len = r;
 
        r = RET_NERRNO(connect(fd, &sa.sa, sa_len));
        if (r >= 0)
                return TAKE_FD(fd);
        return r;
}
 
static int get_seat_from_display(const char *display, const char **seat, uint32_t *vtnr) {
        _cleanup_free_ char *sys_path = NULL, *tty = NULL;
        _cleanup_close_ int fd = -EBADF;
        struct ucred ucred;
        int v, r;
        dev_t display_ctty;
 
        assert(display);
        assert(vtnr);
 
        /* We deduce the X11 socket from the display name, then use
         * SO_PEERCRED to determine the X11 server process, ask for
         * the controlling tty of that and if it's a VC then we know
         * the seat and the virtual terminal. Sounds ugly, is only
         * semi-ugly. */
 
        fd = socket_from_display(display);
        if (fd < 0)
                return fd;
 
        r = getpeercred(fd, &ucred);
        if (r < 0)
                return r;
 
        r = get_ctty_devnr(ucred.pid, &display_ctty);
        if (r < 0)
                return r;
 
        if (asprintf(&sys_path, "/sys/dev/char/" DEVNUM_FORMAT_STR, DEVNUM_FORMAT_VAL(display_ctty)) < 0)
                return -ENOMEM;
        r = readlink_value(sys_path, &tty);
        if (r < 0)
                return r;
 
        v = vtnr_from_tty(tty);
        if (v < 0)
                return v;
        assert(v > 0);
 
        if (seat)
                *seat = "seat0";
        *vtnr = (uint32_t) v;
 
        return 0;
}
 
static int append_session_memory_max(pam_handle_t *pamh, sd_bus_message *m, const char *limit) {
        int r;
 
        assert(pamh);
        assert(m);
 
        if (isempty(limit))
                return 0;
 
        if (streq(limit, "infinity"))
                return sd_bus_message_append(m, "(sv)", "MemoryMax", "t", UINT64_MAX);
 
        r = parse_permyriad(limit);
        if (r >= 0)
                return sd_bus_message_append(m, "(sv)", "MemoryMaxScale", "u", UINT32_SCALE_FROM_PERMYRIAD(r));
 
        uint64_t val;
        r = parse_size(limit, 1024, &val);
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse systemd.memory_max, ignoring: %s", limit);
                return 0;
        }
 
        return sd_bus_message_append(m, "(sv)", "MemoryMax", "t", val);
}
 
static int append_session_runtime_max_sec(pam_handle_t *pamh, sd_bus_message *m, const char *limit) {
        int r;
 
        assert(pamh);
        assert(m);
 
        /* No need to parse "infinity" here, it will be set by default later in scope_init() */
        if (isempty(limit) || streq(limit, "infinity"))
                return 0;
 
        usec_t val;
        r = parse_sec(limit, &val);
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse systemd.runtime_max_sec: %s, ignoring.", limit);
                return 0;
        }
 
        return sd_bus_message_append(m, "(sv)", "RuntimeMaxUSec", "t", (uint64_t) val);
}
 
static int append_session_tasks_max(pam_handle_t *pamh, sd_bus_message *m, const char *limit) {
        int r;
 
        assert(pamh);
        assert(m);
 
        /* No need to parse "infinity" here, it will be set unconditionally later in manager_start_scope() */
        if (isempty(limit) || streq(limit, "infinity"))
                return 0;
 
        uint64_t val;
        r = safe_atou64(limit, &val);
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse systemd.tasks_max, ignoring: %s", limit);
                return 0;
        }
 
        return sd_bus_message_append(m, "(sv)", "TasksMax", "t", val);
}
 
static int append_session_cpu_weight(pam_handle_t *pamh, sd_bus_message *m, const char *limit) {
        int r;
 
        assert(pamh);
        assert(m);
 
        if (isempty(limit))
                return 0;
 
        uint64_t val;
        r = cg_cpu_weight_parse(limit, &val);
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse systemd.cpu_weight, ignoring: %s", limit);
                return 0;
        }
 
        return sd_bus_message_append(m, "(sv)", "CPUWeight", "t", val);
}
 
static int append_session_io_weight(pam_handle_t *pamh, sd_bus_message *m, const char *limit) {
        int r;
 
        assert(pamh);
        assert(m);
 
        if (isempty(limit))
                return 0;
 
        uint64_t val;
        r = cg_weight_parse(limit, &val);
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING, "Failed to parse systemd.io_weight, ignoring: %s", limit);
                return 0;
        }
 
        return sd_bus_message_append(m, "(sv)", "IOWeight", "t", val);
}
 
static const char* getenv_harder(pam_handle_t *pamh, const char *key, const char *fallback) {
        const char *v;
 
        assert(pamh);
        assert(key);
 
        /* Looks for an environment variable, preferably in the environment block associated with the
         * specified PAM handle, falling back to the process' block instead. Why check both? Because we want
         * to permit configuration of session properties from unit files that invoke PAM services, so that
         * PAM services don't have to be reworked to set systemd-specific properties, but these properties
         * can still be set from the unit file Environment= block. */
 
        v = sym_pam_getenv(pamh, key);
        if (!isempty(v))
                return v;
 
        /* We use secure_getenv() here, since we might get loaded into su/sudo, which are SUID. Ideally
         * they'd clean up the environment before invoking foreign code (such as PAM modules), but alas they
         * currently don't (to be precise, they clean up the environment they pass to their children, but
         * not their own environ[]). */
        v = secure_getenv(key);
        if (!isempty(v))
                return v;
 
        return fallback;
}
 
static bool getenv_harder_bool(pam_handle_t *pamh, const char *key, bool fallback) {
        const char *v;
        int r;
 
        assert(pamh);
        assert(key);
 
        v = getenv_harder(pamh, key, NULL);
        if (isempty(v))
                return fallback;
 
        r = parse_boolean(v);
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING,
                               "Failed to parse environment variable value '%s' of '%s', falling back to using '%s'.",
                               v, key, true_false(fallback));
                return fallback;
        }
 
        return r;
}
 
static uint32_t getenv_harder_uint32(pam_handle_t *pamh, const char *key, uint32_t fallback) {
        int r;
 
        assert(pamh);
        assert(key);
 
        const char *v = getenv_harder(pamh, key, NULL);
        if (isempty(v))
                return fallback;
 
        uint32_t u;
        r = safe_atou32(v, &u);
        if (r < 0) {
                sym_pam_syslog(pamh, LOG_WARNING,
                               "Failed to parse environment variable value '%s' of '%s' as unsigned integer, falling back to using %" PRIu32 ".",
                               v, key, fallback);
                return fallback;
        }
 
        return u;
}
 
static int update_environment(pam_handle_t *pamh, const char *key, const char *value) {
        int r;
 
        assert(pamh);
        assert(key);
 
        /* Updates the environment, and removes environment variables if value is NULL or empty. Also, log
         * about errors. */
 
        if (isempty(value)) {
                /* Unset the variable if set. Note that sym_pam_putenv() would log nastily behind our back if we
                 * call it without the variable actually being set. Hence we check explicitly if it's set
                 * before. */
 
                if (!sym_pam_getenv(pamh, key))
                        return PAM_SUCCESS;
 
                r = sym_pam_putenv(pamh, key);
                if (!IN_SET(r, PAM_SUCCESS, PAM_BAD_ITEM))
                        return pam_syslog_pam_error(pamh, LOG_WARNING, r,
                                                    "Failed to unset %s environment variable: @PAMERR@", key);
 
                return PAM_SUCCESS;
        }
 
        r = pam_putenv_assign(pamh, key, value);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r,
                                            "Failed to set environment variable %s: @PAMERR@", key);
 
        return PAM_SUCCESS;
}
 
static int propagate_credential_to_environment(pam_handle_t *pamh, bool debug, const char *credential, const char *varname) {
        int r;
 
        assert(pamh);
        assert(credential);
        assert(varname);
 
        _cleanup_free_ char *value = NULL;
 
        /* Read a service credential, and propagate it into an environment variable */
 
        r = read_credential(credential, (void**) &value, /* ret_size= */ NULL);
        if (r < 0) {
                pam_debug_syslog_errno(pamh, debug, r, "Failed to read credential '%s', ignoring: %m", credential);
                return PAM_SUCCESS;
        }
 
        r = pam_putenv_assign(pamh, varname, value);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r,
                                            "Failed to set environment variable %s: @PAMERR@", varname);
 
        return PAM_SUCCESS;
}
 
static bool validate_runtime_directory(pam_handle_t *pamh, const char *path, uid_t uid) {
        struct stat st;
 
        assert(pamh);
        assert(path);
 
        /* Some extra paranoia: let's not set $XDG_RUNTIME_DIR if the directory we'd set it to isn't actually
         * set up properly for us. This is supposed to provide a careful safety net for supporting su/sudo
         * type transitions: in that case the UID changes, but the session and thus the user owning it
         * doesn't change. Since the $XDG_RUNTIME_DIR lifecycle is bound to the session's user being logged
         * in at least once we should be particularly careful when setting the environment variable, since
         * otherwise we might end up setting $XDG_RUNTIME_DIR to some directory owned by the wrong user. */
 
        if (!path_is_absolute(path)) {
                sym_pam_syslog(pamh, LOG_ERR, "Provided runtime directory '%s' is not absolute.", path);
                goto fail;
        }
 
        if (lstat(path, &st) < 0) {
                pam_syslog_errno(pamh, LOG_ERR, errno, "Failed to stat() runtime directory '%s': %m", path);
                goto fail;
        }
 
        if (!S_ISDIR(st.st_mode)) {
                sym_pam_syslog(pamh, LOG_ERR, "Runtime directory '%s' is not actually a directory.", path);
                goto fail;
        }
 
        if (st.st_uid != uid) {
                sym_pam_syslog(pamh, LOG_ERR, "Runtime directory '%s' is not owned by UID " UID_FMT ", as it should.", path, uid);
                goto fail;
        }
 
        return true;
 
fail:
        sym_pam_syslog(pamh, LOG_WARNING, "Not setting $XDG_RUNTIME_DIR, as the directory is not in order.");
        return false;
}
 
static int pam_putenv_and_log(pam_handle_t *pamh, const char *e, bool debug) {
        int r;
 
        assert(pamh);
        assert(e);
 
        r = sym_pam_putenv(pamh, e);
        if (r != PAM_SUCCESS)
                return pam_syslog_pam_error(pamh, LOG_ERR, r,
                                            "Failed to set PAM environment variable %s: @PAMERR@", e);
 
        pam_debug_syslog(pamh, debug, "PAM environment variable %s set based on user record.", e);
        return PAM_SUCCESS;
}
 
static int apply_user_record_settings(
                pam_handle_t *pamh,
                UserRecord *ur,
                bool debug,
                uint64_t default_capability_bounding_set,
                uint64_t default_capability_ambient_set) {
        _cleanup_strv_free_ char **langs = NULL;
        int r;
 
        assert(pamh);
        assert(ur);
 
        if (ur->umask != MODE_INVALID) {
                umask(ur->umask);
                pam_debug_syslog(pamh, debug, "Set user umask to %04o based on user record.", ur->umask);
        }
 
        STRV_FOREACH(i, ur->environment) {
                r = pam_putenv_and_log(pamh, *i, debug);
                if (r != PAM_SUCCESS)
                        return r;
        }
 
        if (ur->email_address) {
                _cleanup_free_ char *joined = NULL;
 
                joined = strjoin("EMAIL=", ur->email_address);
                if (!joined)
                        return pam_log_oom(pamh);
 
                r = pam_putenv_and_log(pamh, joined, debug);
                if (r != PAM_SUCCESS)
                        return r;
        }
 
        if (ur->time_zone) {
                if (!timezone_is_valid(ur->time_zone, LOG_DEBUG))
                        pam_debug_syslog(pamh, debug,
                                         "Time zone specified in user record is not valid locally, not setting $TZ.");
                else {
                        _cleanup_free_ char *joined = NULL;
 
                        joined = strjoin("TZ=:", ur->time_zone);
                        if (!joined)
                                return pam_log_oom(pamh);
 
                        r = pam_putenv_and_log(pamh, joined, debug);
                        if (r != PAM_SUCCESS)
                                return r;
                }
        }
 
        r = user_record_languages(ur, &langs);
        if (r < 0)
                pam_syslog_errno(pamh, LOG_ERR, r,
                                 "Failed to acquire user's language preferences, ignoring: %m");
        else if (strv_isempty(langs))
                ; /* User has no preference set so we do nothing */
        else if (locale_is_installed(langs[0]) <= 0)
                pam_debug_syslog(pamh, debug,
                                 "Preferred languages specified in user record are not installed locally, not setting $LANG or $LANGUAGE.");
        else {
                _cleanup_free_ char *lang = NULL;
 
                lang = strjoin("LANG=", langs[0]);
                if (!lang)
                        return pam_log_oom(pamh);
 
                r = pam_putenv_and_log(pamh, lang, debug);
                if (r != PAM_SUCCESS)
                        return r;
 
                if (strv_length(langs) > 1) {
                        _cleanup_free_ char *joined = NULL, *language = NULL;
 
                        joined = strv_join(langs, ":");
                        if (!joined)
                                return pam_log_oom(pamh);
 
                        language = strjoin("LANGUAGE=", joined);
                        if (!language)
                                return pam_log_oom(pamh);
 
                        r = pam_putenv_and_log(pamh, language, debug);
                        if (r != PAM_SUCCESS)
                                return r;
                }
        }
 
        if (nice_is_valid(ur->nice_level)) {
                if (nice(ur->nice_level) < 0)
                        pam_syslog_errno(pamh, LOG_WARNING, errno,
                                         "Failed to set nice level to %i, ignoring: %m", ur->nice_level);
                else
                        pam_debug_syslog(pamh, debug,
                                         "Nice level set to %i, based on user record.", ur->nice_level);
        }
 
        for (int rl = 0; rl < _RLIMIT_MAX; rl++) {
                if (!ur->rlimits[rl])
                        continue;
 
                r = setrlimit_closest(rl, ur->rlimits[rl]);
                if (r < 0)
                        pam_syslog_errno(pamh, LOG_ERR, r,
                                         "Failed to set resource limit %s, ignoring: %m", rlimit_to_string(rl));
                else
                        pam_debug_syslog(pamh, debug,
                                         "Resource limit %s set, based on user record.", rlimit_to_string(rl));
        }
 
        uint64_t a, b;
        a = user_record_capability_ambient_set(ur);
        if (a == CAP_MASK_UNSET)
                a = default_capability_ambient_set;
 
        b = user_record_capability_bounding_set(ur);
        if (b == CAP_MASK_UNSET)
                b = default_capability_bounding_set;
 
        if (a != CAP_MASK_UNSET && a != 0) {
                a &= b;
 
                r = capability_ambient_set_apply(a, /* also_inherit= */ true);
                if (r < 0)
                        pam_syslog_errno(pamh, LOG_ERR, r,
                                         "Failed to set ambient capabilities, ignoring: %m");
        }
 
        if (b != CAP_MASK_UNSET && !cap_test_all(b)) {
                r = capability_bounding_set_drop(b, /* right_now= */ false);
                if (r < 0)
                        pam_syslog_errno(pamh, LOG_ERR, r,
                                         "Failed to set bounding capabilities, ignoring: %m");
        }
 
        return PAM_SUCCESS;
}
 
static uint64_t pick_default_capability_ambient_set(
                UserRecord *ur,
                const char *service,
                const char *seat) {
 
        /* If not configured otherwise, let's enable CAP_WAKE_ALARM for regular users when logging in on a
         * seat (i.e. when they are present physically on the device), or when invoked for the systemd --user
         * instances. This allows desktops to install CAP_WAKE_ALARM to implement alarm clock apps without
         * much fuss. */
 
        return ur &&
                user_record_disposition(ur) == USER_REGULAR &&
                (streq_ptr(service, "systemd-user") || !isempty(seat)) ? (UINT64_C(1) << CAP_WAKE_ALARM) : CAP_MASK_UNSET;
}
 
typedef struct SessionContext {
        const char *service;
        const char *type;
        const char *class;
        const char *desktop;
        const char *seat;
        uint32_t vtnr;
        const char *tty;
        const char *display;
        char **extra_device_access;
        bool remote;
        const char *remote_user;
        const char *remote_host;
        const char *memory_max;
        const char *tasks_max;
        const char *cpu_weight;
        const char *io_weight;
        const char *runtime_max_sec;
        const char *area;
        bool incomplete;
} SessionContext;
 
static void session_context_done(SessionContext *c) {
        strv_free(c->extra_device_access);
}
 
static int create_session_message(
                sd_bus *bus,
                pam_handle_t *pamh,
                UserRecord *ur,
                const SessionContext *context,
                bool avoid_pidfd,
                sd_bus_message **ret) {
 
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        _cleanup_close_ int pidfd = -EBADF;
        int r;
 
        assert(bus);
        assert(pamh);
        assert(ur);
        assert(context);
        assert(ret);
 
        if (!avoid_pidfd) {
                pidfd = pidfd_open(getpid_cached(), 0);
                if (pidfd < 0)
                        return -errno;
        }
 
        r = bus_message_new_method_call(bus, &m, bus_login_mgr, pidfd >= 0 ? "CreateSessionWithPIDFD" : "CreateSession");
        if (r < 0)
                return r;
 
        r = sd_bus_message_append(
                        m,
                        pidfd >= 0 ? "uhsssssussbss" : "uusssssussbss",
                        (uint32_t) ur->uid,
                        pidfd >= 0 ? pidfd : 0,
                        context->service,
                        context->type,
                        context->class,
                        context->desktop,
                        context->seat,
                        context->vtnr,
                        context->tty,
                        context->display,
                        context->remote,
                        context->remote_user,
                        context->remote_host);
        if (r < 0)
                return r;
 
        if (pidfd >= 0) {
                r = sd_bus_message_append(m, "t", UINT64_C(0));
                if (r < 0)
                        return r;
        }
 
        r = sd_bus_message_open_container(m, 'a', "(sv)");
        if (r < 0)
                return r;
 
        r = append_session_memory_max(pamh, m, context->memory_max);
        if (r < 0)
                return r;
 
        r = append_session_runtime_max_sec(pamh, m, context->runtime_max_sec);
        if (r < 0)
                return r;
 
        r = append_session_tasks_max(pamh, m, context->tasks_max);
        if (r < 0)
                return r;
 
        r = append_session_cpu_weight(pamh, m, context->cpu_weight);
        if (r < 0)
                return r;
 
        r = append_session_io_weight(pamh, m, context->io_weight);
        if (r < 0)
                return r;
 
        r = sd_bus_message_close_container(m);
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(m);
        return 0;
}
 
static void session_context_mangle(
                pam_handle_t *pamh,
                SessionContext *c,
                UserRecord *ur,
                bool debug) {
 
        assert(pamh);
        assert(c);
        assert(ur);
 
        /* The session class can be overridden via the PAM environment, and we try to honor that selection. */
        if (streq_ptr(c->service, "systemd-user")) {
                /* If we detect that we are running in the "systemd-user" PAM stack, then let's patch the class to
                 * 'manager' if not set, simply for robustness reasons. */
                c->type = "unspecified";
                if (isempty(c->class))
                        c->class = IN_SET(user_record_disposition(ur), USER_INTRINSIC, USER_SYSTEM, USER_DYNAMIC) ?
                                "manager-early" : "manager";
                c->tty = NULL;
 
        } else if (c->tty && strchr(c->tty, ':')) {
                /* A tty with a colon is usually an X11 display, placed there to show up in utmp. We rearrange things
                 * and don't pretend that an X display was a tty. */
                if (isempty(c->display))
                        c->display = c->tty;
                c->tty = NULL;
 
        } else if (streq_ptr(c->tty, "cron")) {
                /* cron is setting PAM_TTY to "cron" for some reason (the commit carries no information why, but
                 * probably because it wants to set it to something as pam_time/pam_access/… require PAM_TTY to be set
                 * (as they otherwise even try to update it!) — but cron doesn't actually allocate a TTY for its forked
                 * off processes.) */
                c->type = "unspecified";
                if (isempty(c->class))
                        c->class = "background";
                c->tty = NULL;
 
        } else if (streq_ptr(c->tty, "ssh")) {
                /* ssh has been setting PAM_TTY to "ssh" (for the same reason as cron does this, see above. For further
                 * details look for "PAM_TTY_KLUDGE" in the openssh sources). */
                c->type = "tty";
                if (isempty(c->class))
                        c->class = "user";
                c->tty = NULL; /* This one is particularly sad, as this means that ssh sessions — even though
                               * usually associated with a pty — won't be tracked by their tty in
                               * logind. This is because ssh does the PAM session registration early for new
                               * connections, and registers a pty only much later (this is because it doesn't
                               * know yet if it needs one at all, as whether to register a pty or not is
                               * negotiated much later in the protocol). */
 
        } else if (c->tty)
                /* Chop off leading /dev prefix that some clients specify, but others do not. */
                c->tty = skip_dev_prefix(c->tty);
 
        if (!isempty(c->display) && !c->vtnr) {
                if (isempty(c->seat))
                        (void) get_seat_from_display(c->display, &c->seat, &c->vtnr);
                else if (streq(c->seat, "seat0"))
                        (void) get_seat_from_display(c->display, /* seat= */ NULL, &c->vtnr);
        }
 
        if (c->seat && !streq(c->seat, "seat0") && c->vtnr != 0) {
                pam_debug_syslog(pamh, debug, "Ignoring vtnr %"PRIu32" for %s which is not seat0.", c->vtnr, c->seat);
                c->vtnr = 0;
        }
 
        if (isempty(c->type)) {
                c->type = !isempty(c->display) ? "x11" :
                              !isempty(c->tty) ? "tty" : "unspecified";
                pam_debug_syslog(pamh, debug, "Automatically chose session type '%s'.", c->type);
        }
 
        if (!c->area)
                c->area = ur->default_area;