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