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