- stevesk@cvs.openbsd.org 2006/08/01 23:36:12
[openssh-git.git] / auth-pam.c
blob6ce9db12b2fa9e774b295a3c9f460d2006365711
1 /*-
2 * Copyright (c) 2002 Networks Associates Technology, Inc.
3 * All rights reserved.
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.
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.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
32 * Copyright (c) 2003,2004 Damien Miller <djm@mindrot.org>
33 * Copyright (c) 2003,2004 Darren Tucker <dtucker@zip.com.au>
35 * Permission to use, copy, modify, and distribute this software for any
36 * purpose with or without fee is hereby granted, provided that the above
37 * copyright notice and this permission notice appear in all copies.
39 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
40 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
41 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
42 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
43 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
44 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
45 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
48 /* Based on $FreeBSD: src/crypto/openssh/auth2-pam-freebsd.c,v 1.11 2003/03/31 13:48:18 des Exp $ */
49 #include "includes.h"
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <sys/wait.h>
55 #include <errno.h>
56 #include <signal.h>
57 #include <string.h>
58 #include <unistd.h>
60 #ifdef USE_PAM
61 #if defined(HAVE_SECURITY_PAM_APPL_H)
62 #include <security/pam_appl.h>
63 #elif defined (HAVE_PAM_PAM_APPL_H)
64 #include <pam/pam_appl.h>
65 #endif
67 /* OpenGroup RFC86.0 and XSSO specify no "const" on arguments */
68 #ifdef PAM_SUN_CODEBASE
69 # define sshpam_const /* Solaris, HP-UX, AIX */
70 #else
71 # define sshpam_const const /* LinuxPAM, OpenPAM */
72 #endif
74 #include "auth.h"
75 #include "auth-pam.h"
76 #include "buffer.h"
77 #include "bufaux.h"
78 #include "canohost.h"
79 #include "log.h"
80 #include "monitor_wrap.h"
81 #include "msg.h"
82 #include "packet.h"
83 #include "misc.h"
84 #include "servconf.h"
85 #include "ssh2.h"
86 #include "xmalloc.h"
87 #include "auth-options.h"
89 extern ServerOptions options;
90 extern Buffer loginmsg;
91 extern int compat20;
92 extern u_int utmp_len;
94 /* so we don't silently change behaviour */
95 #ifdef USE_POSIX_THREADS
96 # error "USE_POSIX_THREADS replaced by UNSUPPORTED_POSIX_THREADS_HACK"
97 #endif
100 * Formerly known as USE_POSIX_THREADS, using this is completely unsupported
101 * and generally a bad idea. Use at own risk and do not expect support if
102 * this breaks.
104 #ifdef UNSUPPORTED_POSIX_THREADS_HACK
105 #include <pthread.h>
107 * Avoid namespace clash when *not* using pthreads for systems *with*
108 * pthreads, which unconditionally define pthread_t via sys/types.h
109 * (e.g. Linux)
111 typedef pthread_t sp_pthread_t;
112 #else
113 typedef pid_t sp_pthread_t;
114 #endif
116 struct pam_ctxt {
117 sp_pthread_t pam_thread;
118 int pam_psock;
119 int pam_csock;
120 int pam_done;
123 static void sshpam_free_ctx(void *);
124 static struct pam_ctxt *cleanup_ctxt;
126 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
128 * Simulate threads with processes.
131 static int sshpam_thread_status = -1;
132 static mysig_t sshpam_oldsig;
134 static void
135 sshpam_sigchld_handler(int sig)
137 signal(SIGCHLD, SIG_DFL);
138 if (cleanup_ctxt == NULL)
139 return; /* handler called after PAM cleanup, shouldn't happen */
140 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, WNOHANG)
141 <= 0) {
142 /* PAM thread has not exitted, privsep slave must have */
143 kill(cleanup_ctxt->pam_thread, SIGTERM);
144 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, 0)
145 <= 0)
146 return; /* could not wait */
148 if (WIFSIGNALED(sshpam_thread_status) &&
149 WTERMSIG(sshpam_thread_status) == SIGTERM)
150 return; /* terminated by pthread_cancel */
151 if (!WIFEXITED(sshpam_thread_status))
152 fatal("PAM: authentication thread exited unexpectedly");
153 if (WEXITSTATUS(sshpam_thread_status) != 0)
154 fatal("PAM: authentication thread exited uncleanly");
157 /* ARGSUSED */
158 static void
159 pthread_exit(void *value)
161 _exit(0);
164 /* ARGSUSED */
165 static int
166 pthread_create(sp_pthread_t *thread, const void *attr,
167 void *(*thread_start)(void *), void *arg)
169 pid_t pid;
170 struct pam_ctxt *ctx = arg;
172 sshpam_thread_status = -1;
173 switch ((pid = fork())) {
174 case -1:
175 error("fork(): %s", strerror(errno));
176 return (-1);
177 case 0:
178 close(ctx->pam_psock);
179 ctx->pam_psock = -1;
180 thread_start(arg);
181 _exit(1);
182 default:
183 *thread = pid;
184 close(ctx->pam_csock);
185 ctx->pam_csock = -1;
186 sshpam_oldsig = signal(SIGCHLD, sshpam_sigchld_handler);
187 return (0);
191 static int
192 pthread_cancel(sp_pthread_t thread)
194 signal(SIGCHLD, sshpam_oldsig);
195 return (kill(thread, SIGTERM));
198 /* ARGSUSED */
199 static int
200 pthread_join(sp_pthread_t thread, void **value)
202 int status;
204 if (sshpam_thread_status != -1)
205 return (sshpam_thread_status);
206 signal(SIGCHLD, sshpam_oldsig);
207 waitpid(thread, &status, 0);
208 return (status);
210 #endif
213 static pam_handle_t *sshpam_handle = NULL;
214 static int sshpam_err = 0;
215 static int sshpam_authenticated = 0;
216 static int sshpam_session_open = 0;
217 static int sshpam_cred_established = 0;
218 static int sshpam_account_status = -1;
219 static char **sshpam_env = NULL;
220 static Authctxt *sshpam_authctxt = NULL;
221 static const char *sshpam_password = NULL;
222 static char badpw[] = "\b\n\r\177INCORRECT";
224 /* Some PAM implementations don't implement this */
225 #ifndef HAVE_PAM_GETENVLIST
226 static char **
227 pam_getenvlist(pam_handle_t *pamh)
230 * XXX - If necessary, we can still support envrionment passing
231 * for platforms without pam_getenvlist by searching for known
232 * env vars (e.g. KRB5CCNAME) from the PAM environment.
234 return NULL;
236 #endif
239 * Some platforms, notably Solaris, do not enforce password complexity
240 * rules during pam_chauthtok() if the real uid of the calling process
241 * is 0, on the assumption that it's being called by "passwd" run by root.
242 * This wraps pam_chauthtok and sets/restore the real uid so PAM will do
243 * the right thing.
245 #ifdef SSHPAM_CHAUTHTOK_NEEDS_RUID
246 static int
247 sshpam_chauthtok_ruid(pam_handle_t *pamh, int flags)
249 int result;
251 if (sshpam_authctxt == NULL)
252 fatal("PAM: sshpam_authctxt not initialized");
253 if (setreuid(sshpam_authctxt->pw->pw_uid, -1) == -1)
254 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
255 result = pam_chauthtok(pamh, flags);
256 if (setreuid(0, -1) == -1)
257 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
258 return result;
260 # define pam_chauthtok(a,b) (sshpam_chauthtok_ruid((a), (b)))
261 #endif
263 void
264 sshpam_password_change_required(int reqd)
266 debug3("%s %d", __func__, reqd);
267 if (sshpam_authctxt == NULL)
268 fatal("%s: PAM authctxt not initialized", __func__);
269 sshpam_authctxt->force_pwchange = reqd;
270 if (reqd) {
271 no_port_forwarding_flag |= 2;
272 no_agent_forwarding_flag |= 2;
273 no_x11_forwarding_flag |= 2;
274 } else {
275 no_port_forwarding_flag &= ~2;
276 no_agent_forwarding_flag &= ~2;
277 no_x11_forwarding_flag &= ~2;
281 /* Import regular and PAM environment from subprocess */
282 static void
283 import_environments(Buffer *b)
285 char *env;
286 u_int i, num_env;
287 int err;
289 debug3("PAM: %s entering", __func__);
291 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
292 /* Import variables set by do_pam_account */
293 sshpam_account_status = buffer_get_int(b);
294 sshpam_password_change_required(buffer_get_int(b));
296 /* Import environment from subprocess */
297 num_env = buffer_get_int(b);
298 if (num_env > 1024)
299 fatal("%s: received %u environment variables, expected <= 1024",
300 __func__, num_env);
301 sshpam_env = xcalloc(num_env + 1, sizeof(*sshpam_env));
302 debug3("PAM: num env strings %d", num_env);
303 for(i = 0; i < num_env; i++)
304 sshpam_env[i] = buffer_get_string(b, NULL);
306 sshpam_env[num_env] = NULL;
308 /* Import PAM environment from subprocess */
309 num_env = buffer_get_int(b);
310 debug("PAM: num PAM env strings %d", num_env);
311 for(i = 0; i < num_env; i++) {
312 env = buffer_get_string(b, NULL);
314 #ifdef HAVE_PAM_PUTENV
315 /* Errors are not fatal here */
316 if ((err = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
317 error("PAM: pam_putenv: %s",
318 pam_strerror(sshpam_handle, sshpam_err));
320 #endif
322 #endif
326 * Conversation function for authentication thread.
328 static int
329 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
330 struct pam_response **resp, void *data)
332 Buffer buffer;
333 struct pam_ctxt *ctxt;
334 struct pam_response *reply;
335 int i;
337 debug3("PAM: %s entering, %d messages", __func__, n);
338 *resp = NULL;
340 if (data == NULL) {
341 error("PAM: conversation function passed a null context");
342 return (PAM_CONV_ERR);
344 ctxt = data;
345 if (n <= 0 || n > PAM_MAX_NUM_MSG)
346 return (PAM_CONV_ERR);
348 if ((reply = calloc(n, sizeof(*reply))) == NULL)
349 return (PAM_CONV_ERR);
351 buffer_init(&buffer);
352 for (i = 0; i < n; ++i) {
353 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
354 case PAM_PROMPT_ECHO_OFF:
355 buffer_put_cstring(&buffer,
356 PAM_MSG_MEMBER(msg, i, msg));
357 if (ssh_msg_send(ctxt->pam_csock,
358 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
359 goto fail;
360 if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
361 goto fail;
362 if (buffer_get_char(&buffer) != PAM_AUTHTOK)
363 goto fail;
364 reply[i].resp = buffer_get_string(&buffer, NULL);
365 break;
366 case PAM_PROMPT_ECHO_ON:
367 buffer_put_cstring(&buffer,
368 PAM_MSG_MEMBER(msg, i, msg));
369 if (ssh_msg_send(ctxt->pam_csock,
370 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
371 goto fail;
372 if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
373 goto fail;
374 if (buffer_get_char(&buffer) != PAM_AUTHTOK)
375 goto fail;
376 reply[i].resp = buffer_get_string(&buffer, NULL);
377 break;
378 case PAM_ERROR_MSG:
379 buffer_put_cstring(&buffer,
380 PAM_MSG_MEMBER(msg, i, msg));
381 if (ssh_msg_send(ctxt->pam_csock,
382 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
383 goto fail;
384 break;
385 case PAM_TEXT_INFO:
386 buffer_put_cstring(&buffer,
387 PAM_MSG_MEMBER(msg, i, msg));
388 if (ssh_msg_send(ctxt->pam_csock,
389 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
390 goto fail;
391 break;
392 default:
393 goto fail;
395 buffer_clear(&buffer);
397 buffer_free(&buffer);
398 *resp = reply;
399 return (PAM_SUCCESS);
401 fail:
402 for(i = 0; i < n; i++) {
403 if (reply[i].resp != NULL)
404 xfree(reply[i].resp);
406 xfree(reply);
407 buffer_free(&buffer);
408 return (PAM_CONV_ERR);
412 * Authentication thread.
414 static void *
415 sshpam_thread(void *ctxtp)
417 struct pam_ctxt *ctxt = ctxtp;
418 Buffer buffer;
419 struct pam_conv sshpam_conv;
420 int flags = (options.permit_empty_passwd == 0 ?
421 PAM_DISALLOW_NULL_AUTHTOK : 0);
422 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
423 extern char **environ;
424 char **env_from_pam;
425 u_int i;
426 const char *pam_user;
427 const char **ptr_pam_user = &pam_user;
429 pam_get_item(sshpam_handle, PAM_USER,
430 (sshpam_const void **)ptr_pam_user);
431 environ[0] = NULL;
433 if (sshpam_authctxt != NULL) {
434 setproctitle("%s [pam]",
435 sshpam_authctxt->valid ? pam_user : "unknown");
437 #endif
439 sshpam_conv.conv = sshpam_thread_conv;
440 sshpam_conv.appdata_ptr = ctxt;
442 if (sshpam_authctxt == NULL)
443 fatal("%s: PAM authctxt not initialized", __func__);
445 buffer_init(&buffer);
446 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
447 (const void *)&sshpam_conv);
448 if (sshpam_err != PAM_SUCCESS)
449 goto auth_fail;
450 sshpam_err = pam_authenticate(sshpam_handle, flags);
451 if (sshpam_err != PAM_SUCCESS)
452 goto auth_fail;
454 if (compat20) {
455 if (!do_pam_account()) {
456 sshpam_err = PAM_ACCT_EXPIRED;
457 goto auth_fail;
459 if (sshpam_authctxt->force_pwchange) {
460 sshpam_err = pam_chauthtok(sshpam_handle,
461 PAM_CHANGE_EXPIRED_AUTHTOK);
462 if (sshpam_err != PAM_SUCCESS)
463 goto auth_fail;
464 sshpam_password_change_required(0);
468 buffer_put_cstring(&buffer, "OK");
470 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
471 /* Export variables set by do_pam_account */
472 buffer_put_int(&buffer, sshpam_account_status);
473 buffer_put_int(&buffer, sshpam_authctxt->force_pwchange);
475 /* Export any environment strings set in child */
476 for(i = 0; environ[i] != NULL; i++)
477 ; /* Count */
478 buffer_put_int(&buffer, i);
479 for(i = 0; environ[i] != NULL; i++)
480 buffer_put_cstring(&buffer, environ[i]);
482 /* Export any environment strings set by PAM in child */
483 env_from_pam = pam_getenvlist(sshpam_handle);
484 for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
485 ; /* Count */
486 buffer_put_int(&buffer, i);
487 for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
488 buffer_put_cstring(&buffer, env_from_pam[i]);
489 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
491 /* XXX - can't do much about an error here */
492 ssh_msg_send(ctxt->pam_csock, sshpam_err, &buffer);
493 buffer_free(&buffer);
494 pthread_exit(NULL);
496 auth_fail:
497 buffer_put_cstring(&buffer,
498 pam_strerror(sshpam_handle, sshpam_err));
499 /* XXX - can't do much about an error here */
500 if (sshpam_err == PAM_ACCT_EXPIRED)
501 ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, &buffer);
502 else
503 ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
504 buffer_free(&buffer);
505 pthread_exit(NULL);
507 return (NULL); /* Avoid warning for non-pthread case */
510 void
511 sshpam_thread_cleanup(void)
513 struct pam_ctxt *ctxt = cleanup_ctxt;
515 debug3("PAM: %s entering", __func__);
516 if (ctxt != NULL && ctxt->pam_thread != 0) {
517 pthread_cancel(ctxt->pam_thread);
518 pthread_join(ctxt->pam_thread, NULL);
519 close(ctxt->pam_psock);
520 close(ctxt->pam_csock);
521 memset(ctxt, 0, sizeof(*ctxt));
522 cleanup_ctxt = NULL;
526 static int
527 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
528 struct pam_response **resp, void *data)
530 debug3("PAM: %s entering, %d messages", __func__, n);
531 return (PAM_CONV_ERR);
534 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
536 static int
537 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
538 struct pam_response **resp, void *data)
540 struct pam_response *reply;
541 int i;
542 size_t len;
544 debug3("PAM: %s called with %d messages", __func__, n);
545 *resp = NULL;
547 if (n <= 0 || n > PAM_MAX_NUM_MSG)
548 return (PAM_CONV_ERR);
550 if ((reply = calloc(n, sizeof(*reply))) == NULL)
551 return (PAM_CONV_ERR);
553 for (i = 0; i < n; ++i) {
554 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
555 case PAM_ERROR_MSG:
556 case PAM_TEXT_INFO:
557 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
558 buffer_append(&loginmsg, PAM_MSG_MEMBER(msg, i, msg), len);
559 buffer_append(&loginmsg, "\n", 1 );
560 reply[i].resp_retcode = PAM_SUCCESS;
561 break;
562 default:
563 goto fail;
566 *resp = reply;
567 return (PAM_SUCCESS);
569 fail:
570 for(i = 0; i < n; i++) {
571 if (reply[i].resp != NULL)
572 xfree(reply[i].resp);
574 xfree(reply);
575 return (PAM_CONV_ERR);
578 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
580 void
581 sshpam_cleanup(void)
583 debug("PAM: cleanup");
584 if (sshpam_handle == NULL)
585 return;
586 pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
587 if (sshpam_cred_established) {
588 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
589 sshpam_cred_established = 0;
591 if (sshpam_session_open) {
592 pam_close_session(sshpam_handle, PAM_SILENT);
593 sshpam_session_open = 0;
595 sshpam_authenticated = 0;
596 pam_end(sshpam_handle, sshpam_err);
597 sshpam_handle = NULL;
600 static int
601 sshpam_init(Authctxt *authctxt)
603 extern char *__progname;
604 const char *pam_rhost, *pam_user, *user = authctxt->user;
605 const char **ptr_pam_user = &pam_user;
607 if (sshpam_handle != NULL) {
608 /* We already have a PAM context; check if the user matches */
609 sshpam_err = pam_get_item(sshpam_handle,
610 PAM_USER, (sshpam_const void **)ptr_pam_user);
611 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
612 return (0);
613 pam_end(sshpam_handle, sshpam_err);
614 sshpam_handle = NULL;
616 debug("PAM: initializing for \"%s\"", user);
617 sshpam_err =
618 pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
619 sshpam_authctxt = authctxt;
621 if (sshpam_err != PAM_SUCCESS) {
622 pam_end(sshpam_handle, sshpam_err);
623 sshpam_handle = NULL;
624 return (-1);
626 pam_rhost = get_remote_name_or_ip(utmp_len, options.use_dns);
627 debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
628 sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
629 if (sshpam_err != PAM_SUCCESS) {
630 pam_end(sshpam_handle, sshpam_err);
631 sshpam_handle = NULL;
632 return (-1);
634 #ifdef PAM_TTY_KLUDGE
636 * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
637 * sshd doesn't set the tty until too late in the auth process and
638 * may not even set one (for tty-less connections)
640 debug("PAM: setting PAM_TTY to \"ssh\"");
641 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
642 if (sshpam_err != PAM_SUCCESS) {
643 pam_end(sshpam_handle, sshpam_err);
644 sshpam_handle = NULL;
645 return (-1);
647 #endif
648 return (0);
651 static void *
652 sshpam_init_ctx(Authctxt *authctxt)
654 struct pam_ctxt *ctxt;
655 int socks[2];
657 debug3("PAM: %s entering", __func__);
659 * Refuse to start if we don't have PAM enabled or do_pam_account
660 * has previously failed.
662 if (!options.use_pam || sshpam_account_status == 0)
663 return NULL;
665 /* Initialize PAM */
666 if (sshpam_init(authctxt) == -1) {
667 error("PAM: initialization failed");
668 return (NULL);
671 ctxt = xmalloc(sizeof *ctxt);
672 memset(ctxt, 0, sizeof(*ctxt));
674 /* Start the authentication thread */
675 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
676 error("PAM: failed create sockets: %s", strerror(errno));
677 xfree(ctxt);
678 return (NULL);
680 ctxt->pam_psock = socks[0];
681 ctxt->pam_csock = socks[1];
682 if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
683 error("PAM: failed to start authentication thread: %s",
684 strerror(errno));
685 close(socks[0]);
686 close(socks[1]);
687 xfree(ctxt);
688 return (NULL);
690 cleanup_ctxt = ctxt;
691 return (ctxt);
694 static int
695 sshpam_query(void *ctx, char **name, char **info,
696 u_int *num, char ***prompts, u_int **echo_on)
698 Buffer buffer;
699 struct pam_ctxt *ctxt = ctx;
700 size_t plen;
701 u_char type;
702 char *msg;
703 size_t len, mlen;
705 debug3("PAM: %s entering", __func__);
706 buffer_init(&buffer);
707 *name = xstrdup("");
708 *info = xstrdup("");
709 *prompts = xmalloc(sizeof(char *));
710 **prompts = NULL;
711 plen = 0;
712 *echo_on = xmalloc(sizeof(u_int));
713 while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
714 type = buffer_get_char(&buffer);
715 msg = buffer_get_string(&buffer, NULL);
716 mlen = strlen(msg);
717 switch (type) {
718 case PAM_PROMPT_ECHO_ON:
719 case PAM_PROMPT_ECHO_OFF:
720 *num = 1;
721 len = plen + mlen + 1;
722 **prompts = xrealloc(**prompts, 1, len);
723 strlcpy(**prompts + plen, msg, len - plen);
724 plen += mlen;
725 **echo_on = (type == PAM_PROMPT_ECHO_ON);
726 xfree(msg);
727 return (0);
728 case PAM_ERROR_MSG:
729 case PAM_TEXT_INFO:
730 /* accumulate messages */
731 len = plen + mlen + 2;
732 **prompts = xrealloc(**prompts, 1, len);
733 strlcpy(**prompts + plen, msg, len - plen);
734 plen += mlen;
735 strlcat(**prompts + plen, "\n", len - plen);
736 plen++;
737 xfree(msg);
738 break;
739 case PAM_ACCT_EXPIRED:
740 sshpam_account_status = 0;
741 /* FALLTHROUGH */
742 case PAM_AUTH_ERR:
743 debug3("PAM: %s", pam_strerror(sshpam_handle, type));
744 if (**prompts != NULL && strlen(**prompts) != 0) {
745 *info = **prompts;
746 **prompts = NULL;
747 *num = 0;
748 **echo_on = 0;
749 ctxt->pam_done = -1;
750 xfree(msg);
751 return 0;
753 /* FALLTHROUGH */
754 case PAM_SUCCESS:
755 if (**prompts != NULL) {
756 /* drain any accumulated messages */
757 debug("PAM: %s", **prompts);
758 buffer_append(&loginmsg, **prompts,
759 strlen(**prompts));
760 xfree(**prompts);
761 **prompts = NULL;
763 if (type == PAM_SUCCESS) {
764 if (!sshpam_authctxt->valid ||
765 (sshpam_authctxt->pw->pw_uid == 0 &&
766 options.permit_root_login != PERMIT_YES))
767 fatal("Internal error: PAM auth "
768 "succeeded when it should have "
769 "failed");
770 import_environments(&buffer);
771 *num = 0;
772 **echo_on = 0;
773 ctxt->pam_done = 1;
774 xfree(msg);
775 return (0);
777 error("PAM: %s for %s%.100s from %.100s", msg,
778 sshpam_authctxt->valid ? "" : "illegal user ",
779 sshpam_authctxt->user,
780 get_remote_name_or_ip(utmp_len, options.use_dns));
781 /* FALLTHROUGH */
782 default:
783 *num = 0;
784 **echo_on = 0;
785 xfree(msg);
786 ctxt->pam_done = -1;
787 return (-1);
790 return (-1);
793 /* XXX - see also comment in auth-chall.c:verify_response */
794 static int
795 sshpam_respond(void *ctx, u_int num, char **resp)
797 Buffer buffer;
798 struct pam_ctxt *ctxt = ctx;
800 debug2("PAM: %s entering, %u responses", __func__, num);
801 switch (ctxt->pam_done) {
802 case 1:
803 sshpam_authenticated = 1;
804 return (0);
805 case 0:
806 break;
807 default:
808 return (-1);
810 if (num != 1) {
811 error("PAM: expected one response, got %u", num);
812 return (-1);
814 buffer_init(&buffer);
815 if (sshpam_authctxt->valid &&
816 (sshpam_authctxt->pw->pw_uid != 0 ||
817 options.permit_root_login == PERMIT_YES))
818 buffer_put_cstring(&buffer, *resp);
819 else
820 buffer_put_cstring(&buffer, badpw);
821 if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer) == -1) {
822 buffer_free(&buffer);
823 return (-1);
825 buffer_free(&buffer);
826 return (1);
829 static void
830 sshpam_free_ctx(void *ctxtp)
832 struct pam_ctxt *ctxt = ctxtp;
834 debug3("PAM: %s entering", __func__);
835 sshpam_thread_cleanup();
836 xfree(ctxt);
838 * We don't call sshpam_cleanup() here because we may need the PAM
839 * handle at a later stage, e.g. when setting up a session. It's
840 * still on the cleanup list, so pam_end() *will* be called before
841 * the server process terminates.
845 KbdintDevice sshpam_device = {
846 "pam",
847 sshpam_init_ctx,
848 sshpam_query,
849 sshpam_respond,
850 sshpam_free_ctx
853 KbdintDevice mm_sshpam_device = {
854 "pam",
855 mm_sshpam_init_ctx,
856 mm_sshpam_query,
857 mm_sshpam_respond,
858 mm_sshpam_free_ctx
862 * This replaces auth-pam.c
864 void
865 start_pam(Authctxt *authctxt)
867 if (!options.use_pam)
868 fatal("PAM: initialisation requested when UsePAM=no");
870 if (sshpam_init(authctxt) == -1)
871 fatal("PAM: initialisation failed");
874 void
875 finish_pam(void)
877 sshpam_cleanup();
880 u_int
881 do_pam_account(void)
883 debug("%s: called", __func__);
884 if (sshpam_account_status != -1)
885 return (sshpam_account_status);
887 sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
888 debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
889 pam_strerror(sshpam_handle, sshpam_err));
891 if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
892 sshpam_account_status = 0;
893 return (sshpam_account_status);
896 if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
897 sshpam_password_change_required(1);
899 sshpam_account_status = 1;
900 return (sshpam_account_status);
903 void
904 do_pam_set_tty(const char *tty)
906 if (tty != NULL) {
907 debug("PAM: setting PAM_TTY to \"%s\"", tty);
908 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, tty);
909 if (sshpam_err != PAM_SUCCESS)
910 fatal("PAM: failed to set PAM_TTY: %s",
911 pam_strerror(sshpam_handle, sshpam_err));
915 void
916 do_pam_setcred(int init)
918 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
919 (const void *)&store_conv);
920 if (sshpam_err != PAM_SUCCESS)
921 fatal("PAM: failed to set PAM_CONV: %s",
922 pam_strerror(sshpam_handle, sshpam_err));
923 if (init) {
924 debug("PAM: establishing credentials");
925 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
926 } else {
927 debug("PAM: reinitializing credentials");
928 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
930 if (sshpam_err == PAM_SUCCESS) {
931 sshpam_cred_established = 1;
932 return;
934 if (sshpam_authenticated)
935 fatal("PAM: pam_setcred(): %s",
936 pam_strerror(sshpam_handle, sshpam_err));
937 else
938 debug("PAM: pam_setcred(): %s",
939 pam_strerror(sshpam_handle, sshpam_err));
942 static int
943 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
944 struct pam_response **resp, void *data)
946 char input[PAM_MAX_MSG_SIZE];
947 struct pam_response *reply;
948 int i;
950 debug3("PAM: %s called with %d messages", __func__, n);
952 *resp = NULL;
954 if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
955 return (PAM_CONV_ERR);
957 if ((reply = calloc(n, sizeof(*reply))) == NULL)
958 return (PAM_CONV_ERR);
960 for (i = 0; i < n; ++i) {
961 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
962 case PAM_PROMPT_ECHO_OFF:
963 reply[i].resp =
964 read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
965 RP_ALLOW_STDIN);
966 reply[i].resp_retcode = PAM_SUCCESS;
967 break;
968 case PAM_PROMPT_ECHO_ON:
969 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
970 fgets(input, sizeof input, stdin);
971 if ((reply[i].resp = strdup(input)) == NULL)
972 goto fail;
973 reply[i].resp_retcode = PAM_SUCCESS;
974 break;
975 case PAM_ERROR_MSG:
976 case PAM_TEXT_INFO:
977 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
978 reply[i].resp_retcode = PAM_SUCCESS;
979 break;
980 default:
981 goto fail;
984 *resp = reply;
985 return (PAM_SUCCESS);
987 fail:
988 for(i = 0; i < n; i++) {
989 if (reply[i].resp != NULL)
990 xfree(reply[i].resp);
992 xfree(reply);
993 return (PAM_CONV_ERR);
996 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
999 * XXX this should be done in the authentication phase, but ssh1 doesn't
1000 * support that
1002 void
1003 do_pam_chauthtok(void)
1005 if (use_privsep)
1006 fatal("Password expired (unable to change with privsep)");
1007 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1008 (const void *)&tty_conv);
1009 if (sshpam_err != PAM_SUCCESS)
1010 fatal("PAM: failed to set PAM_CONV: %s",
1011 pam_strerror(sshpam_handle, sshpam_err));
1012 debug("PAM: changing password");
1013 sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1014 if (sshpam_err != PAM_SUCCESS)
1015 fatal("PAM: pam_chauthtok(): %s",
1016 pam_strerror(sshpam_handle, sshpam_err));
1019 void
1020 do_pam_session(void)
1022 debug3("PAM: opening session");
1023 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1024 (const void *)&store_conv);
1025 if (sshpam_err != PAM_SUCCESS)
1026 fatal("PAM: failed to set PAM_CONV: %s",
1027 pam_strerror(sshpam_handle, sshpam_err));
1028 sshpam_err = pam_open_session(sshpam_handle, 0);
1029 if (sshpam_err == PAM_SUCCESS)
1030 sshpam_session_open = 1;
1031 else {
1032 sshpam_session_open = 0;
1033 disable_forwarding();
1034 error("PAM: pam_open_session(): %s",
1035 pam_strerror(sshpam_handle, sshpam_err));
1041 is_pam_session_open(void)
1043 return sshpam_session_open;
1047 * Set a PAM environment string. We need to do this so that the session
1048 * modules can handle things like Kerberos/GSI credentials that appear
1049 * during the ssh authentication process.
1052 do_pam_putenv(char *name, char *value)
1054 int ret = 1;
1055 #ifdef HAVE_PAM_PUTENV
1056 char *compound;
1057 size_t len;
1059 len = strlen(name) + strlen(value) + 2;
1060 compound = xmalloc(len);
1062 snprintf(compound, len, "%s=%s", name, value);
1063 ret = pam_putenv(sshpam_handle, compound);
1064 xfree(compound);
1065 #endif
1067 return (ret);
1070 char **
1071 fetch_pam_child_environment(void)
1073 return sshpam_env;
1076 char **
1077 fetch_pam_environment(void)
1079 return (pam_getenvlist(sshpam_handle));
1082 void
1083 free_pam_environment(char **env)
1085 char **envp;
1087 if (env == NULL)
1088 return;
1090 for (envp = env; *envp; envp++)
1091 xfree(*envp);
1092 xfree(env);
1096 * "Blind" conversation function for password authentication. Assumes that
1097 * echo-off prompts are for the password and stores messages for later
1098 * display.
1100 static int
1101 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1102 struct pam_response **resp, void *data)
1104 struct pam_response *reply;
1105 int i;
1106 size_t len;
1108 debug3("PAM: %s called with %d messages", __func__, n);
1110 *resp = NULL;
1112 if (n <= 0 || n > PAM_MAX_NUM_MSG)
1113 return (PAM_CONV_ERR);
1115 if ((reply = malloc(n * sizeof(*reply))) == NULL)
1116 return (PAM_CONV_ERR);
1117 memset(reply, 0, n * sizeof(*reply));
1119 for (i = 0; i < n; ++i) {
1120 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1121 case PAM_PROMPT_ECHO_OFF:
1122 if (sshpam_password == NULL)
1123 goto fail;
1124 if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1125 goto fail;
1126 reply[i].resp_retcode = PAM_SUCCESS;
1127 break;
1128 case PAM_ERROR_MSG:
1129 case PAM_TEXT_INFO:
1130 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1131 if (len > 0) {
1132 buffer_append(&loginmsg,
1133 PAM_MSG_MEMBER(msg, i, msg), len);
1134 buffer_append(&loginmsg, "\n", 1);
1136 if ((reply[i].resp = strdup("")) == NULL)
1137 goto fail;
1138 reply[i].resp_retcode = PAM_SUCCESS;
1139 break;
1140 default:
1141 goto fail;
1144 *resp = reply;
1145 return (PAM_SUCCESS);
1147 fail:
1148 for(i = 0; i < n; i++) {
1149 if (reply[i].resp != NULL)
1150 xfree(reply[i].resp);
1152 xfree(reply);
1153 return (PAM_CONV_ERR);
1156 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1159 * Attempt password authentication via PAM
1162 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1164 int flags = (options.permit_empty_passwd == 0 ?
1165 PAM_DISALLOW_NULL_AUTHTOK : 0);
1167 if (!options.use_pam || sshpam_handle == NULL)
1168 fatal("PAM: %s called when PAM disabled or failed to "
1169 "initialise.", __func__);
1171 sshpam_password = password;
1172 sshpam_authctxt = authctxt;
1175 * If the user logging in is invalid, or is root but is not permitted
1176 * by PermitRootLogin, use an invalid password to prevent leaking
1177 * information via timing (eg if the PAM config has a delay on fail).
1179 if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1180 options.permit_root_login != PERMIT_YES))
1181 sshpam_password = badpw;
1183 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1184 (const void *)&passwd_conv);
1185 if (sshpam_err != PAM_SUCCESS)
1186 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1187 pam_strerror(sshpam_handle, sshpam_err));
1189 sshpam_err = pam_authenticate(sshpam_handle, flags);
1190 sshpam_password = NULL;
1191 if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1192 debug("PAM: password authentication accepted for %.100s",
1193 authctxt->user);
1194 return 1;
1195 } else {
1196 debug("PAM: password authentication failed for %.100s: %s",
1197 authctxt->valid ? authctxt->user : "an illegal user",
1198 pam_strerror(sshpam_handle, sshpam_err));
1199 return 0;
1202 #endif /* USE_PAM */