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