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