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