Merge from vendor branch GDB:
[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.40 2004/02/10 10:13:21 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 "authfd.h"
62 #include "authfile.h"
63
64 extern char **environ;
65
66 struct pam_ssh_key {
67         Key     *key;
68         char    *comment;
69 };
70
71 static const char *pam_ssh_prompt = "SSH passphrase: ";
72 static const char *pam_ssh_have_keys = "pam_ssh_have_keys";
73
74 static const char *pam_ssh_keyfiles[] = {
75         ".ssh/identity",        /* SSH1 RSA key */
76         ".ssh/id_rsa",          /* SSH2 RSA key */
77         ".ssh/id_dsa",          /* SSH2 DSA key */
78         NULL
79 };
80
81 static const char *pam_ssh_agent = "/usr/bin/ssh-agent";
82 static const char *pam_ssh_agent_argv[] = { "ssh_agent", "-s", NULL };
83 static char *const pam_ssh_agent_envp[] = { NULL };
84
85 /*
86  * Attempts to load a private key from the specified file in the specified
87  * directory, using the specified passphrase.  If successful, returns a
88  * struct pam_ssh_key containing the key and its comment.
89  */
90 static struct pam_ssh_key *
91 pam_ssh_load_key(const char *dir, const char *kfn, const char *passphrase)
92 {
93         struct pam_ssh_key *psk;
94         char fn[PATH_MAX];
95         char *comment;
96         Key *key;
97
98         if (snprintf(fn, sizeof(fn), "%s/%s", dir, kfn) > (int)sizeof(fn))
99                 return (NULL);
100         comment = NULL;
101         key = key_load_private(fn, passphrase, &comment);
102         if (key == NULL) {
103                 openpam_log(PAM_LOG_DEBUG, "failed to load key from %s\n", fn);
104                 return (NULL);
105         }
106
107         openpam_log(PAM_LOG_DEBUG, "loaded '%s' from %s\n", comment, fn);
108         if ((psk = malloc(sizeof(*psk))) == NULL) {
109                 key_free(key);
110                 free(comment);
111                 return (NULL);
112         }
113         psk->key = key;
114         psk->comment = comment;
115         return (psk);
116 }
117
118 /*
119  * Wipes a private key and frees the associated resources.
120  */
121 static void
122 pam_ssh_free_key(pam_handle_t *pamh __unused,
123     void *data, int pam_err __unused)
124 {
125         struct pam_ssh_key *psk;
126
127         psk = data;
128         key_free(psk->key);
129         free(psk->comment);
130         free(psk);
131 }
132
133 PAM_EXTERN int
134 pam_sm_authenticate(pam_handle_t *pamh, int flags __unused,
135     int argc __unused, const char *argv[] __unused)
136 {
137         const char **kfn, *passphrase, *user;
138         struct passwd *pwd;
139         struct pam_ssh_key *psk;
140         int nkeys, pam_err, pass;
141
142         /* PEM is not loaded by default */
143         OpenSSL_add_all_algorithms();
144
145         /* get user name and home directory */
146         pam_err = pam_get_user(pamh, &user, NULL);
147         if (pam_err != PAM_SUCCESS)
148                 return (pam_err);
149         pwd = getpwnam(user);
150         if (pwd == NULL)
151                 return (PAM_USER_UNKNOWN);
152         if (pwd->pw_dir == NULL)
153                 return (PAM_AUTH_ERR);
154
155         /* switch to user credentials */
156         pam_err = openpam_borrow_cred(pamh, pwd);
157         if (pam_err != PAM_SUCCESS)
158                 return (pam_err);
159
160         pass = (pam_get_item(pamh, PAM_AUTHTOK,
161             (const void **)&passphrase) == PAM_SUCCESS);
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                 openpam_restore_cred(pamh);
168                 return (pam_err);
169         }
170
171         /* try to load keys from all keyfiles we know of */
172         nkeys = 0;
173         for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
174                 psk = pam_ssh_load_key(pwd->pw_dir, *kfn, passphrase);
175                 if (psk != NULL) {
176                         pam_set_data(pamh, *kfn, psk, pam_ssh_free_key);
177                         ++nkeys;
178                 }
179         }
180
181         /*
182          * If we tried an old token and didn't get anything, and
183          * try_first_pass was specified, try again after prompting the
184          * user for a new passphrase.
185          */
186         if (nkeys == 0 && pass == 1 &&
187             openpam_get_option(pamh, "try_first_pass") != NULL) {
188                 pam_set_item(pamh, PAM_AUTHTOK, NULL);
189                 pass = 0;
190                 goto load_keys;
191         }
192
193         /* switch back to arbitrator credentials before returning */
194         openpam_restore_cred(pamh);
195
196         /* no keys? */
197         if (nkeys == 0)
198                 return (PAM_AUTH_ERR);
199
200         pam_set_data(pamh, pam_ssh_have_keys, NULL, NULL);
201         return (PAM_SUCCESS);
202 }
203
204 PAM_EXTERN int
205 pam_sm_setcred(pam_handle_t *pamh __unused, int flags __unused,
206     int argc __unused, const char *argv[] __unused)
207 {
208
209         return (PAM_SUCCESS);
210 }
211
212 /*
213  * Parses a line from ssh-agent's output.
214  */
215 static void
216 pam_ssh_process_agent_output(pam_handle_t *pamh, FILE *f)
217 {
218         char *line, *p, *key, *val;
219         size_t len;
220
221         while ((line = fgetln(f, &len)) != NULL) {
222                 if (len < 4 || strncmp(line, "SSH_", 4) != 0)
223                         continue;
224
225                 /* find equal sign at end of key */
226                 for (p = key = line; p < line + len; ++p)
227                         if (*p == '=')
228                                 break;
229                 if (p == line + len || *p != '=')
230                         continue;
231                 *p = '\0';
232
233                 /* find semicolon at end of value */
234                 for (val = ++p; p < line + len; ++p)
235                         if (*p == ';')
236                                 break;
237                 if (p == line + len || *p != ';')
238                         continue;
239                 *p = '\0';
240
241                 /* store key-value pair in environment */
242                 openpam_log(PAM_LOG_DEBUG, "got %s: %s", key, val);
243                 pam_setenv(pamh, key, val, 1);
244         }
245 }
246
247 /*
248  * Starts an ssh agent and stores the environment variables derived from
249  * its output.
250  */
251 static int
252 pam_ssh_start_agent(pam_handle_t *pamh)
253 {
254         int agent_pipe[2];
255         pid_t pid;
256         FILE *f;
257
258         /* get a pipe which we will use to read the agent's output */
259         if (pipe(agent_pipe) == -1) {
260                 openpam_restore_cred(pamh);
261                 return (PAM_SYSTEM_ERR);
262         }
263
264         /* start the agent */
265         openpam_log(PAM_LOG_DEBUG, "starting an ssh agent");
266         pid = fork();
267         if (pid == (pid_t)-1) {
268                 /* failed */
269                 close(agent_pipe[0]);
270                 close(agent_pipe[1]);
271                 return (PAM_SYSTEM_ERR);
272         }
273         if (pid == 0) {
274                 int fd;
275
276                 /* child: drop privs, close fds and start agent */
277                 setgid(getegid());
278                 setuid(geteuid());
279                 close(STDIN_FILENO);
280                 open(_PATH_DEVNULL, O_RDONLY);
281                 dup2(agent_pipe[1], STDOUT_FILENO);
282                 dup2(agent_pipe[1], STDERR_FILENO);
283                 for (fd = 3; fd < getdtablesize(); ++fd)
284                         close(fd);
285                 execve(pam_ssh_agent,
286                     __DECONST(char * const *, pam_ssh_agent_argv),
287                     pam_ssh_agent_envp);
288                 _exit(127);
289         }
290
291         /* parent */
292         close(agent_pipe[1]);
293         if ((f = fdopen(agent_pipe[0], "r")) == NULL)
294                 return (PAM_SYSTEM_ERR);
295         pam_ssh_process_agent_output(pamh, f);
296         fclose(f);
297
298         return (PAM_SUCCESS);
299 }
300
301 /*
302  * Adds previously stored keys to a running agent.
303  */
304 static int
305 pam_ssh_add_keys_to_agent(pam_handle_t *pamh)
306 {
307         AuthenticationConnection *ac;
308         struct pam_ssh_key *psk;
309         const char **kfn;
310         char **envlist, **env;
311         int pam_err;
312
313         /* switch to PAM environment */
314         envlist = environ;
315         if ((environ = pam_getenvlist(pamh)) == NULL) {
316                 environ = envlist;
317                 return (PAM_SYSTEM_ERR);
318         }
319
320         /* get a connection to the agent */
321         if ((ac = ssh_get_authentication_connection()) == NULL) {
322                 pam_err = PAM_SYSTEM_ERR;
323                 goto end;
324         }
325
326         /* look for keys to add to it */
327         for (kfn = pam_ssh_keyfiles; *kfn != NULL; ++kfn) {
328                 pam_err = pam_get_data(pamh, *kfn, (void **)&psk);
329                 if (pam_err == PAM_SUCCESS && psk != NULL) {
330                         if (ssh_add_identity(ac, psk->key, psk->comment))
331                                 openpam_log(PAM_LOG_DEBUG,
332                                     "added %s to ssh agent", psk->comment);
333                         else
334                                 openpam_log(PAM_LOG_DEBUG, "failed "
335                                     "to add %s to ssh agent", psk->comment);
336                         /* we won't need the key again, so wipe it */
337                         pam_set_data(pamh, *kfn, NULL, NULL);
338                 }
339         }
340         pam_err = PAM_SUCCESS;
341  end:
342         /* disconnect from agent */
343         if (ac != NULL)
344                 ssh_close_authentication_connection(ac);
345
346         /* switch back to original environment */
347         for (env = environ; *env != NULL; ++env)
348                 free(*env);
349         free(environ);
350         environ = envlist;
351
352         return (pam_err);
353 }
354
355 PAM_EXTERN int
356 pam_sm_open_session(pam_handle_t *pamh, int flags __unused,
357     int argc __unused, const char *argv[] __unused)
358 {
359         struct passwd *pwd;
360         const char *user;
361         void *data;
362         int pam_err;
363
364         /* no keys, no work */
365         if (pam_get_data(pamh, pam_ssh_have_keys, &data) != PAM_SUCCESS &&
366             openpam_get_option(pamh, "want_agent") == NULL)
367                 return (PAM_SUCCESS);
368
369         /* switch to user credentials */
370         pam_err = pam_get_user(pamh, &user, NULL);
371         if (pam_err != PAM_SUCCESS)
372                 return (pam_err);
373         pwd = getpwnam(user);
374         if (pwd == NULL)
375                 return (PAM_USER_UNKNOWN);
376         pam_err = openpam_borrow_cred(pamh, pwd);
377         if (pam_err != PAM_SUCCESS)
378                 return (pam_err);
379
380         /* start the agent */
381         pam_err = pam_ssh_start_agent(pamh);
382         if (pam_err != PAM_SUCCESS) {
383                 openpam_restore_cred(pamh);
384                 return (pam_err);
385         }
386
387         /* we have an agent, see if we can add any keys to it */
388         pam_err = pam_ssh_add_keys_to_agent(pamh);
389         if (pam_err != PAM_SUCCESS) {
390                 /* XXX ignore failures */
391         }
392
393         openpam_restore_cred(pamh);
394         return (PAM_SUCCESS);
395 }
396
397 PAM_EXTERN int
398 pam_sm_close_session(pam_handle_t *pamh, int flags __unused,
399     int argc __unused, const char *argv[] __unused)
400 {
401         const char *ssh_agent_pid;
402         char *end;
403         int status;
404         pid_t pid;
405
406         if ((ssh_agent_pid = pam_getenv(pamh, "SSH_AGENT_PID")) == NULL) {
407                 openpam_log(PAM_LOG_DEBUG, "no ssh agent");
408                 return (PAM_SUCCESS);
409         }
410         pid = (pid_t)strtol(ssh_agent_pid, &end, 10);
411         if (*ssh_agent_pid == '\0' || *end != '\0') {
412                 openpam_log(PAM_LOG_DEBUG, "invalid ssh agent pid");
413                 return (PAM_SESSION_ERR);
414         }
415         openpam_log(PAM_LOG_DEBUG, "killing ssh agent %d", (int)pid);
416         if (kill(pid, SIGTERM) == -1 ||
417             (waitpid(pid, &status, 0) == -1 && errno != ECHILD))
418                 return (PAM_SYSTEM_ERR);
419         return (PAM_SUCCESS);
420 }
421
422 PAM_MODULE_ENTRY("pam_ssh");