1 /*        $NetBSD: pam_ssh.c,v 1.30 2022/06/15 08:31:34 hannken Exp $ */
2 
3 /*-
4  * Copyright (c) 2003 Networks Associates Technology, Inc.
5  * All rights reserved.
6  *
7  * This software was developed for the FreeBSD Project by ThinkSec AS and
8  * NAI Labs, the Security Research Division of Network Associates, Inc.
9  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
10  * DARPA CHATS research program.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. The name of the author may not be used to endorse or promote
21  *    products derived from this software without specific prior written
22  *    permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 #ifdef __FreeBSD__
39 __FBSDID("$FreeBSD: src/lib/libpam/modules/pam_ssh/pam_ssh.c,v 1.40 2004/02/10 10:13:21 des Exp $");
40 #else
41 __RCSID("$NetBSD: pam_ssh.c,v 1.30 2022/06/15 08:31:34 hannken Exp $");
42 #endif
43 
44 #include <sys/param.h>
45 #include <sys/wait.h>
46 
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <paths.h>
50 #include <pwd.h>
51 #include <signal.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <unistd.h>
55 
56 #define PAM_SM_AUTH
57 #define PAM_SM_SESSION
58 
59 #include <security/pam_appl.h>
60 #include <security/pam_modules.h>
61 #include <security/openpam.h>
62 
63 #include <openssl/evp.h>
64 
65 #include "sshkey.h"
66 #include "sshbuf.h"
67 #include "authfd.h"
68 #include "authfile.h"
69 
70 #define ssh_add_identity(auth, key, comment) \
71     ssh_add_identity_constrained(auth, key, comment, 0, 0, 0, NULL, NULL, 00)
72 
73 extern char **environ;
74 
75 struct pam_ssh_key {
76           struct sshkey       *key;
77           char      *comment;
78 };
79 
80 static const char *pam_ssh_prompt = "SSH passphrase: ";
81 static const char *pam_ssh_have_keys = "pam_ssh_have_keys";
82 
83 static const char *pam_ssh_keyfiles[] = {
84           ".ssh/identity",    /* SSH1 RSA key */
85           ".ssh/id_rsa",                /* SSH2 RSA key */
86           ".ssh/id_dsa",                /* SSH2 DSA key */
87           ".ssh/id_ecdsa",    /* SSH2 ECDSA key */
88           NULL
89 };
90 
91 static const char *pam_ssh_agent = "/usr/bin/ssh-agent";
92 static const char *const pam_ssh_agent_argv[] = { "ssh_agent", "-s", NULL };
93 static const char *const pam_ssh_agent_envp[] = { NULL };
94 
95 /*
96  * Attempts to load a private key from the specified file in the specified
97  * directory, using the specified passphrase.  If successful, returns a
98  * struct pam_ssh_key containing the key and its comment.
99  */
100 static struct pam_ssh_key *
pam_ssh_load_key(const char * dir,const char * kfn,const char * passphrase,int nullok)101 pam_ssh_load_key(const char *dir, const char *kfn, const char *passphrase,
102     int nullok)
103 {
104           struct pam_ssh_key *psk;
105           char fn[PATH_MAX];
106           int r;
107           char *comment;
108           struct sshkey *key;
109 
110           if (snprintf(fn, sizeof(fn), "%s/%s", dir, kfn) > (int)sizeof(fn))
111                     return (NULL);
112           comment = NULL;
113           /*
114            * If the key is unencrypted, OpenSSL ignores the passphrase, so
115            * it will seem like the user typed in the right one.  This allows
116            * a user to circumvent nullok by providing a dummy passphrase.
117            * Verify that the key really *is* encrypted by trying to load it
118            * with an empty passphrase, and if the key is not encrypted,
119            * accept only an empty passphrase.
120            */
121           r = sshkey_load_private(fn, "", &key, &comment);
122           if (r == 0 && !(*passphrase == '\0' && nullok)) {
123                     openpam_log(PAM_LOG_DEBUG, "rejected unencrypted key from %s", fn);
124                     sshkey_free(key);
125                     free(comment);
126                     return (NULL);
127           }
128           if (r)
129                     r = sshkey_load_private(fn, passphrase, &key, &comment);
130           if (r) {
131                     openpam_log(PAM_LOG_DEBUG, "failed to load key from %s", fn);
132                     if (comment != NULL)
133                               free(comment);
134                     return (NULL);
135           }
136 
137           openpam_log(PAM_LOG_DEBUG, "loaded '%s' from %s", comment, fn);
138           if ((psk = malloc(sizeof(*psk))) == NULL) {
139                     sshkey_free(key);
140                     free(comment);
141                     return (NULL);
142           }
143           psk->key = key;
144           psk->comment = comment;
145           return (psk);
146 }
147 
148 /*
149  * Wipes a private key and frees the associated resources.
150  */
151 static void
pam_ssh_free_key(pam_handle_t * pamh __unused,void * data,int pam_err __unused)152 pam_ssh_free_key(pam_handle_t *pamh __unused,
153     void *data, int pam_err __unused)
154 {
155           struct pam_ssh_key *psk;
156 
157           psk = data;
158           sshkey_free(psk->key);
159           free(psk->comment);
160           free(psk);
161 }
162 
163 PAM_EXTERN int
pam_sm_authenticate(pam_handle_t * pamh,int flags __unused,int argc __unused,const char * argv[]__unused)164 pam_sm_authenticate(pam_handle_t *pamh, int flags __unused,
165     int argc __unused, const char *argv[] __unused)
166 {
167           const char **kfn, *passphrase, *user;
168           const void *item;
169           struct passwd *pwd, pwres;
170           struct pam_ssh_key *psk;
171           int nkeys, nullok, pam_err, pass;
172           char pwbuf[1024];
173 
174           nullok = (openpam_get_option(pamh, "nullok") != NULL);
175 
176           /* PEM is not loaded by default */
177           OpenSSL_add_all_algorithms();
178 
179           /* get user name and home directory */
180           pam_err = pam_get_user(pamh, &user, NULL);
181           if (pam_err != PAM_SUCCESS)
182                     return (pam_err);
183           if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
184               pwd == NULL)
185                     return (PAM_USER_UNKNOWN);
186           if (pwd->pw_dir == NULL)
187                     return (PAM_AUTH_ERR);
188 
189           nkeys = 0;
190           pass = (pam_get_item(pamh, PAM_AUTHTOK, &item) == PAM_SUCCESS &&
191               item != NULL);
192  load_keys:
193           /* get passphrase */
194           pam_err = pam_get_authtok(pamh, PAM_AUTHTOK,
195               &passphrase, pam_ssh_prompt);
196           if (pam_err != PAM_SUCCESS)
197                     return (pam_err);
198 
199           /* switch to user credentials */
200           pam_err = openpam_borrow_cred(pamh, pwd);
201           if (pam_err != PAM_SUCCESS)
202                     return (pam_err);
203 
204           /* try to load keys from all keyfiles we know of */
205           for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
206                     psk = pam_ssh_load_key(pwd->pw_dir, *kfn, passphrase, nullok);
207                     if (psk != NULL) {
208                               pam_set_data(pamh, *kfn, psk, pam_ssh_free_key);
209                               ++nkeys;
210                     }
211           }
212 
213           /* switch back to arbitrator credentials */
214           openpam_restore_cred(pamh);
215 
216           /*
217            * If we tried an old token and didn't get anything, and
218            * try_first_pass was specified, try again after prompting the
219            * user for a new passphrase.
220            */
221           if (nkeys == 0 && pass == 1 &&
222               openpam_get_option(pamh, "try_first_pass") != NULL) {
223                     pam_set_item(pamh, PAM_AUTHTOK, NULL);
224                     pass = 0;
225                     goto load_keys;
226           }
227 
228           /* no keys? */
229           if (nkeys == 0)
230                     return (PAM_AUTH_ERR);
231 
232           pam_set_data(pamh, pam_ssh_have_keys, NULL, NULL);
233           return (PAM_SUCCESS);
234 }
235 
236 PAM_EXTERN int
pam_sm_setcred(pam_handle_t * pamh __unused,int flags __unused,int argc __unused,const char * argv[]__unused)237 pam_sm_setcred(pam_handle_t *pamh __unused, int flags __unused,
238     int argc __unused, const char *argv[] __unused)
239 {
240 
241           return (PAM_SUCCESS);
242 }
243 
244 /*
245  * Parses a line from ssh-agent's output.
246  */
247 static void
pam_ssh_process_agent_output(pam_handle_t * pamh,FILE * f)248 pam_ssh_process_agent_output(pam_handle_t *pamh, FILE *f)
249 {
250           char *line, *p, *key, *val;
251           size_t len;
252 
253           while ((line = fgetln(f, &len)) != NULL) {
254                     if (len < 4 || strncmp(line, "SSH_", 4) != 0)
255                               continue;
256 
257                     /* find equal sign at end of key */
258                     for (p = key = line; p < line + len; ++p)
259                               if (*p == '=')
260                                         break;
261                     if (p == line + len || *p != '=')
262                               continue;
263                     *p = '\0';
264 
265                     /* find semicolon at end of value */
266                     for (val = ++p; p < line + len; ++p)
267                               if (*p == ';')
268                                         break;
269                     if (p == line + len || *p != ';')
270                               continue;
271                     *p = '\0';
272 
273                     /* store key-value pair in environment */
274                     openpam_log(PAM_LOG_DEBUG, "got %s: %s", key, val);
275                     pam_setenv(pamh, key, val, 1);
276           }
277 }
278 
279 /*
280  * Starts an ssh agent and stores the environment variables derived from
281  * its output.
282  */
283 static int
pam_ssh_start_agent(pam_handle_t * pamh,struct passwd * pwd)284 pam_ssh_start_agent(pam_handle_t *pamh, struct passwd *pwd)
285 {
286           int agent_pipe[2];
287           pid_t pid;
288           FILE *f;
289 
290           /* get a pipe which we will use to read the agent's output */
291           if (pipe(agent_pipe) == -1)
292                     return (PAM_SYSTEM_ERR);
293 
294           /* start the agent */
295           openpam_log(PAM_LOG_DEBUG, "starting an ssh agent");
296           pid = fork();
297           if (pid == (pid_t)-1) {
298                     /* failed */
299                     close(agent_pipe[0]);
300                     close(agent_pipe[1]);
301                     return (PAM_SYSTEM_ERR);
302           }
303           if (pid == 0) {
304 #ifndef F_CLOSEM
305                     int fd;
306 #endif
307                     /* child: drop privs, close fds and start agent */
308                     if (setgid(pwd->pw_gid) == -1) {
309                               openpam_log(PAM_LOG_DEBUG, "%s: Cannot setgid %d (%s)",
310                                   __func__, (int)pwd->pw_gid, strerror(errno));
311                               goto done;
312                     }
313                     if (initgroups(pwd->pw_name, pwd->pw_gid) == -1) {
314                               openpam_log(PAM_LOG_DEBUG,
315                                   "%s: Cannot initgroups for %s (%s)",
316                                   __func__, pwd->pw_name, strerror(errno));
317                               goto done;
318                     }
319                     if (setuid(pwd->pw_uid) == -1) {
320                               openpam_log(PAM_LOG_DEBUG, "%s: Cannot setuid %d (%s)",
321                                   __func__, (int)pwd->pw_uid, strerror(errno));
322                               goto done;
323                     }
324                     (void)close(STDIN_FILENO);
325                     (void)open(_PATH_DEVNULL, O_RDONLY);
326                     (void)dup2(agent_pipe[1], STDOUT_FILENO);
327                     (void)dup2(agent_pipe[1], STDERR_FILENO);
328 #ifdef F_CLOSEM
329                     (void)fcntl(3, F_CLOSEM, 0);
330 #else
331                     for (fd = 3; fd < getdtablesize(); ++fd)
332                               (void)close(fd);
333 #endif
334                     (void)execve(pam_ssh_agent,
335                         (char **)__UNCONST(pam_ssh_agent_argv),
336                         (char **)__UNCONST(pam_ssh_agent_envp));
337 done:
338                     _exit(127);
339           }
340 
341           /* parent */
342           close(agent_pipe[1]);
343           if ((f = fdopen(agent_pipe[0], "r")) == NULL)
344                     return (PAM_SYSTEM_ERR);
345           pam_ssh_process_agent_output(pamh, f);
346           fclose(f);
347 
348           return (PAM_SUCCESS);
349 }
350 
351 /*
352  * Adds previously stored keys to a running agent.
353  */
354 static int
pam_ssh_add_keys_to_agent(pam_handle_t * pamh)355 pam_ssh_add_keys_to_agent(pam_handle_t *pamh)
356 {
357           const struct pam_ssh_key *psk;
358           const char **kfn;
359           char **envlist, **env;
360           int pam_err;
361           int agent_fd;
362 
363           /* switch to PAM environment */
364           envlist = environ;
365           if ((environ = pam_getenvlist(pamh)) == NULL) {
366                     openpam_log(PAM_LOG_DEBUG, "%s: cannot get envlist",
367                         __func__);
368                     environ = envlist;
369                     return (PAM_SYSTEM_ERR);
370           }
371 
372           /* get a connection to the agent */
373           if (ssh_get_authentication_socket(&agent_fd) != 0) {
374                     openpam_log(PAM_LOG_DEBUG,
375                         "%s: cannot get authentication connection",
376                         __func__);
377                     pam_err = PAM_SYSTEM_ERR;
378                     agent_fd = -1;
379                     goto end;
380           }
381 
382           /* look for keys to add to it */
383           for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
384                     const void *vp;
385                     pam_err = pam_get_data(pamh, *kfn, &vp);
386                     psk = vp;
387                     if (pam_err == PAM_SUCCESS && psk != NULL) {
388                               if (ssh_add_identity(agent_fd, psk->key, psk->comment))
389                                         openpam_log(PAM_LOG_DEBUG,
390                                             "added %s to ssh agent", psk->comment);
391                               else
392                                         openpam_log(PAM_LOG_DEBUG, "failed "
393                                             "to add %s to ssh agent", psk->comment);
394                               /* we won't need the key again, so wipe it */
395                               pam_set_data(pamh, *kfn, NULL, NULL);
396                     }
397           }
398           pam_err = PAM_SUCCESS;
399  end:
400           /* disconnect from agent */
401           if (agent_fd != -1)
402                     ssh_close_authentication_socket(agent_fd);
403 
404           /* switch back to original environment */
405           for (env = environ; *env != NULL; ++env)
406                     free(*env);
407           free(environ);
408           environ = envlist;
409 
410           return (pam_err);
411 }
412 
413 PAM_EXTERN int
pam_sm_open_session(pam_handle_t * pamh,int flags __unused,int argc __unused,const char * argv[]__unused)414 pam_sm_open_session(pam_handle_t *pamh, int flags __unused,
415     int argc __unused, const char *argv[] __unused)
416 {
417           struct passwd *pwd, pwres;
418           const char *user;
419           const void *data;
420           int pam_err = PAM_SUCCESS;
421           char pwbuf[1024];
422 
423           /* no keys, no work */
424           if (pam_get_data(pamh, pam_ssh_have_keys, &data) != PAM_SUCCESS &&
425               openpam_get_option(pamh, "want_agent") == NULL)
426                     return (PAM_SUCCESS);
427 
428           /* switch to user credentials */
429           pam_err = pam_get_user(pamh, &user, NULL);
430           if (pam_err != PAM_SUCCESS)
431                     return (pam_err);
432           if (getpwnam_r(user, &pwres, pwbuf, sizeof(pwbuf), &pwd) != 0 ||
433               pwd == NULL)
434                     return (PAM_USER_UNKNOWN);
435 
436           /* start the agent */
437           pam_err = pam_ssh_start_agent(pamh, pwd);
438           if (pam_err != PAM_SUCCESS)
439                     return pam_err;
440 
441           pam_err = openpam_borrow_cred(pamh, pwd);
442           if (pam_err != PAM_SUCCESS)
443                     return pam_err;
444 
445           /* we have an agent, see if we can add any keys to it */
446           pam_err = pam_ssh_add_keys_to_agent(pamh);
447           if (pam_err != PAM_SUCCESS) {
448                     /* XXX ignore failures */
449                     openpam_log(PAM_LOG_DEBUG, "failed adding keys to ssh agent");
450                     pam_err = PAM_SUCCESS;
451           }
452 
453           openpam_restore_cred(pamh);
454           return pam_err;
455 }
456 
457 PAM_EXTERN int
pam_sm_close_session(pam_handle_t * pamh,int flags __unused,int argc __unused,const char * argv[]__unused)458 pam_sm_close_session(pam_handle_t *pamh, int flags __unused,
459     int argc __unused, const char *argv[] __unused)
460 {
461           const char *ssh_agent_pid;
462           char *end;
463           int status;
464           pid_t pid;
465 
466           if ((ssh_agent_pid = pam_getenv(pamh, "SSH_AGENT_PID")) == NULL) {
467                     openpam_log(PAM_LOG_DEBUG, "no ssh agent");
468                     return (PAM_SUCCESS);
469           }
470           pid = (pid_t)strtol(ssh_agent_pid, &end, 10);
471           if (*ssh_agent_pid == '\0' || *end != '\0') {
472                     openpam_log(PAM_LOG_DEBUG, "invalid ssh agent pid");
473                     return (PAM_SESSION_ERR);
474           }
475           openpam_log(PAM_LOG_DEBUG, "killing ssh agent %d", (int)pid);
476           if (kill(pid, SIGTERM) == -1 ||
477               (waitpid(pid, &status, 0) == -1 && errno != ECHILD))
478                     return (PAM_SYSTEM_ERR);
479           return (PAM_SUCCESS);
480 }
481 
482 PAM_MODULE_ENTRY("pam_ssh");
483