Debian Codegraph @

src/login/pam_systemd_loadkey.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "keyring-util.h"
4 #include "nulstr-util.h"
5 #include "pam-util.h"
6 #include "string-util.h"
7 #include "strv.h"
8
9 /* By default, this module retrieves the key stored by systemd-cryptsetup.
10 * This can be overridden by the keyname= parameter. */
11 static const char DEFAULT_KEYNAME[] = "cryptsetup";
12
13 _public_ PAM_EXTERN int pam_sm_authenticate(
14 pam_handle_t *pamh,
15 int flags,
16 int argc, const char **argv) {
17
18 int r;
19
20 assert(pamh);
21
22 r = DLOPEN_LIBPAM(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_REQUIRED);
23 if (r < 0)
24 return PAM_SERVICE_ERR;
25
26 pam_log_setup();
27
28 /* Parse argv. */
29
30 assert(argc >= 0);
31 assert(argc == 0 || argv);
32
33 const char *keyname = DEFAULT_KEYNAME;
34 bool debug = false;
35
36 for (int i = 0; i < argc; i++) {
37 const char *p;
38
39 if ((p = startswith(argv[i], "keyname=")))
40 keyname = p;
41 else if (streq(argv[i], "debug"))
42 debug = true;
43 else
44 sym_pam_syslog(pamh, LOG_WARNING, "Unknown parameter '%s', ignoring.", argv[i]);
45 }
46
47 pam_debug_syslog(pamh, debug, "pam-systemd-loadkey: initializing...");
48
49 /* Retrieve the key. */
50
51 key_serial_t serial;
52 serial = request_key("user", keyname, NULL, 0);
53 if (serial < 0) {
54 if (errno == ENOKEY) {
55 pam_debug_syslog(pamh, debug, "Key not found: %s", keyname);
56 return PAM_AUTHINFO_UNAVAIL;
57 } else if (errno == EKEYEXPIRED) {
58 pam_debug_syslog(pamh, debug, "Key expired: %s", keyname);
59 return PAM_AUTHINFO_UNAVAIL;
60 } else
61 return pam_syslog_errno(pamh, LOG_ERR, errno, "Failed to look up the key: %m");
62 }
63
64 _cleanup_(erase_and_freep) void *p = NULL;
65 size_t n;
66
67 r = keyring_read(serial, &p, &n);
68 if (r < 0)
69 return pam_syslog_errno(pamh, LOG_ERR, r, "Failed to read the key: %m");
70
71 /* Split the key by NUL. Set the last item as authtok. */
72
73 _cleanup_strv_free_erase_ char **passwords = strv_parse_nulstr(p, n);
74 if (!passwords)
75 return pam_log_oom(pamh);
76
77 size_t passwords_len = strv_length(passwords);
78 if (passwords_len == 0) {
79 pam_debug_syslog(pamh, debug, "Key is empty.");
80 return PAM_AUTHINFO_UNAVAIL;
81 } else if (passwords_len > 1)
82 pam_debug_syslog(pamh, debug, "Multiple passwords found in the key. Using the last one.");
83
84 r = sym_pam_set_item(pamh, PAM_AUTHTOK, passwords[passwords_len - 1]);
85 if (r != PAM_SUCCESS)
86 return pam_syslog_pam_error(pamh, LOG_ERR, r, "Failed to set PAM auth token: @PAMERR@");
87
88 return PAM_SUCCESS;
89 }
90
91 _public_ PAM_EXTERN int pam_sm_setcred(
92 pam_handle_t *pamh,
93 int flags,
94 int argc, const char **argv) {
95
96 return PAM_SUCCESS;
97 }