- jmc@cvs.openbsd.org 2006/07/18 08:03:09
[openssh-git.git] / auth-pam.c
blobcb8754ec7d95653fb9050215dc764443ea00b836
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>
58 #ifdef USE_PAM
59 #if defined(HAVE_SECURITY_PAM_APPL_H)
60 #include <security/pam_appl.h>
61 #elif defined (HAVE_PAM_PAM_APPL_H)
62 #include <pam/pam_appl.h>
63 #endif
65 /* OpenGroup RFC86.0 and XSSO specify no "const" on arguments */
66 #ifdef PAM_SUN_CODEBASE
67 # define sshpam_const /* Solaris, HP-UX, AIX */
68 #else
69 # define sshpam_const const /* LinuxPAM, OpenPAM */
70 #endif
72 #include "auth.h"
73 #include "auth-pam.h"
74 #include "buffer.h"
75 #include "bufaux.h"
76 #include "canohost.h"
77 #include "log.h"
78 #include "monitor_wrap.h"
79 #include "msg.h"
80 #include "packet.h"
81 #include "misc.h"
82 #include "servconf.h"
83 #include "ssh2.h"
84 #include "xmalloc.h"
85 #include "auth-options.h"
87 extern ServerOptions options;
88 extern Buffer loginmsg;
89 extern int compat20;
90 extern u_int utmp_len;
92 /* so we don't silently change behaviour */
93 #ifdef USE_POSIX_THREADS
94 # error "USE_POSIX_THREADS replaced by UNSUPPORTED_POSIX_THREADS_HACK"
95 #endif
98 * Formerly known as USE_POSIX_THREADS, using this is completely unsupported
99 * and generally a bad idea. Use at own risk and do not expect support if
100 * this breaks.
102 #ifdef UNSUPPORTED_POSIX_THREADS_HACK
103 #include <pthread.h>
105 * Avoid namespace clash when *not* using pthreads for systems *with*
106 * pthreads, which unconditionally define pthread_t via sys/types.h
107 * (e.g. Linux)
109 typedef pthread_t sp_pthread_t;
110 #else
111 typedef pid_t sp_pthread_t;
112 #endif
114 struct pam_ctxt {
115 sp_pthread_t pam_thread;
116 int pam_psock;
117 int pam_csock;
118 int pam_done;
121 static void sshpam_free_ctx(void *);
122 static struct pam_ctxt *cleanup_ctxt;
124 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
126 * Simulate threads with processes.
129 static int sshpam_thread_status = -1;
130 static mysig_t sshpam_oldsig;
132 static void
133 sshpam_sigchld_handler(int sig)
135 signal(SIGCHLD, SIG_DFL);
136 if (cleanup_ctxt == NULL)
137 return; /* handler called after PAM cleanup, shouldn't happen */
138 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, WNOHANG)
139 <= 0) {
140 /* PAM thread has not exitted, privsep slave must have */
141 kill(cleanup_ctxt->pam_thread, SIGTERM);
142 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, 0)
143 <= 0)
144 return; /* could not wait */
146 if (WIFSIGNALED(sshpam_thread_status) &&
147 WTERMSIG(sshpam_thread_status) == SIGTERM)
148 return; /* terminated by pthread_cancel */
149 if (!WIFEXITED(sshpam_thread_status))
150 fatal("PAM: authentication thread exited unexpectedly");
151 if (WEXITSTATUS(sshpam_thread_status) != 0)
152 fatal("PAM: authentication thread exited uncleanly");
155 static void
156 pthread_exit(void *value __unused)
158 _exit(0);
161 static int
162 pthread_create(sp_pthread_t *thread, const void *attr __unused,
163 void *(*thread_start)(void *), void *arg)
165 pid_t pid;
166 struct pam_ctxt *ctx = arg;
168 sshpam_thread_status = -1;
169 switch ((pid = fork())) {
170 case -1:
171 error("fork(): %s", strerror(errno));
172 return (-1);
173 case 0:
174 close(ctx->pam_psock);
175 ctx->pam_psock = -1;
176 thread_start(arg);
177 _exit(1);
178 default:
179 *thread = pid;
180 close(ctx->pam_csock);
181 ctx->pam_csock = -1;
182 sshpam_oldsig = signal(SIGCHLD, sshpam_sigchld_handler);
183 return (0);
187 static int
188 pthread_cancel(sp_pthread_t thread)
190 signal(SIGCHLD, sshpam_oldsig);
191 return (kill(thread, SIGTERM));
194 static int
195 pthread_join(sp_pthread_t thread, void **value __unused)
197 int status;
199 if (sshpam_thread_status != -1)
200 return (sshpam_thread_status);
201 signal(SIGCHLD, sshpam_oldsig);
202 waitpid(thread, &status, 0);
203 return (status);
205 #endif
208 static pam_handle_t *sshpam_handle = NULL;
209 static int sshpam_err = 0;
210 static int sshpam_authenticated = 0;
211 static int sshpam_session_open = 0;
212 static int sshpam_cred_established = 0;
213 static int sshpam_account_status = -1;
214 static char **sshpam_env = NULL;
215 static Authctxt *sshpam_authctxt = NULL;
216 static const char *sshpam_password = NULL;
217 static char badpw[] = "\b\n\r\177INCORRECT";
219 /* Some PAM implementations don't implement this */
220 #ifndef HAVE_PAM_GETENVLIST
221 static char **
222 pam_getenvlist(pam_handle_t *pamh)
225 * XXX - If necessary, we can still support envrionment passing
226 * for platforms without pam_getenvlist by searching for known
227 * env vars (e.g. KRB5CCNAME) from the PAM environment.
229 return NULL;
231 #endif
234 * Some platforms, notably Solaris, do not enforce password complexity
235 * rules during pam_chauthtok() if the real uid of the calling process
236 * is 0, on the assumption that it's being called by "passwd" run by root.
237 * This wraps pam_chauthtok and sets/restore the real uid so PAM will do
238 * the right thing.
240 #ifdef SSHPAM_CHAUTHTOK_NEEDS_RUID
241 static int
242 sshpam_chauthtok_ruid(pam_handle_t *pamh, int flags)
244 int result;
246 if (sshpam_authctxt == NULL)
247 fatal("PAM: sshpam_authctxt not initialized");
248 if (setreuid(sshpam_authctxt->pw->pw_uid, -1) == -1)
249 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
250 result = pam_chauthtok(pamh, flags);
251 if (setreuid(0, -1) == -1)
252 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
253 return result;
255 # define pam_chauthtok(a,b) (sshpam_chauthtok_ruid((a), (b)))
256 #endif
258 void
259 sshpam_password_change_required(int reqd)
261 debug3("%s %d", __func__, reqd);
262 if (sshpam_authctxt == NULL)
263 fatal("%s: PAM authctxt not initialized", __func__);
264 sshpam_authctxt->force_pwchange = reqd;
265 if (reqd) {
266 no_port_forwarding_flag |= 2;
267 no_agent_forwarding_flag |= 2;
268 no_x11_forwarding_flag |= 2;
269 } else {
270 no_port_forwarding_flag &= ~2;
271 no_agent_forwarding_flag &= ~2;
272 no_x11_forwarding_flag &= ~2;
276 /* Import regular and PAM environment from subprocess */
277 static void
278 import_environments(Buffer *b)
280 char *env;
281 u_int i, num_env;
282 int err;
284 debug3("PAM: %s entering", __func__);
286 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
287 /* Import variables set by do_pam_account */
288 sshpam_account_status = buffer_get_int(b);
289 sshpam_password_change_required(buffer_get_int(b));
291 /* Import environment from subprocess */
292 num_env = buffer_get_int(b);
293 if (num_env > 1024)
294 fatal("%s: received %u environment variables, expected <= 1024",
295 __func__, num_env);
296 sshpam_env = xcalloc(num_env + 1, sizeof(*sshpam_env));
297 debug3("PAM: num env strings %d", num_env);
298 for(i = 0; i < num_env; i++)
299 sshpam_env[i] = buffer_get_string(b, NULL);
301 sshpam_env[num_env] = NULL;
303 /* Import PAM environment from subprocess */
304 num_env = buffer_get_int(b);
305 debug("PAM: num PAM env strings %d", num_env);
306 for(i = 0; i < num_env; i++) {
307 env = buffer_get_string(b, NULL);
309 #ifdef HAVE_PAM_PUTENV
310 /* Errors are not fatal here */
311 if ((err = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
312 error("PAM: pam_putenv: %s",
313 pam_strerror(sshpam_handle, sshpam_err));
315 #endif
317 #endif
321 * Conversation function for authentication thread.
323 static int
324 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
325 struct pam_response **resp, void *data)
327 Buffer buffer;
328 struct pam_ctxt *ctxt;
329 struct pam_response *reply;
330 int i;
332 debug3("PAM: %s entering, %d messages", __func__, n);
333 *resp = NULL;
335 if (data == NULL) {
336 error("PAM: conversation function passed a null context");
337 return (PAM_CONV_ERR);
339 ctxt = data;
340 if (n <= 0 || n > PAM_MAX_NUM_MSG)
341 return (PAM_CONV_ERR);
343 if ((reply = calloc(n, sizeof(*reply))) == NULL)
344 return (PAM_CONV_ERR);
346 buffer_init(&buffer);
347 for (i = 0; i < n; ++i) {
348 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
349 case PAM_PROMPT_ECHO_OFF:
350 buffer_put_cstring(&buffer,
351 PAM_MSG_MEMBER(msg, i, msg));
352 if (ssh_msg_send(ctxt->pam_csock,
353 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
354 goto fail;
355 if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
356 goto fail;
357 if (buffer_get_char(&buffer) != PAM_AUTHTOK)
358 goto fail;
359 reply[i].resp = buffer_get_string(&buffer, NULL);
360 break;
361 case PAM_PROMPT_ECHO_ON:
362 buffer_put_cstring(&buffer,
363 PAM_MSG_MEMBER(msg, i, msg));
364 if (ssh_msg_send(ctxt->pam_csock,
365 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
366 goto fail;
367 if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
368 goto fail;
369 if (buffer_get_char(&buffer) != PAM_AUTHTOK)
370 goto fail;
371 reply[i].resp = buffer_get_string(&buffer, NULL);
372 break;
373 case PAM_ERROR_MSG:
374 buffer_put_cstring(&buffer,
375 PAM_MSG_MEMBER(msg, i, msg));
376 if (ssh_msg_send(ctxt->pam_csock,
377 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
378 goto fail;
379 break;
380 case PAM_TEXT_INFO:
381 buffer_put_cstring(&buffer,
382 PAM_MSG_MEMBER(msg, i, msg));
383 if (ssh_msg_send(ctxt->pam_csock,
384 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
385 goto fail;
386 break;
387 default:
388 goto fail;
390 buffer_clear(&buffer);
392 buffer_free(&buffer);
393 *resp = reply;
394 return (PAM_SUCCESS);
396 fail:
397 for(i = 0; i < n; i++) {
398 if (reply[i].resp != NULL)
399 xfree(reply[i].resp);
401 xfree(reply);
402 buffer_free(&buffer);
403 return (PAM_CONV_ERR);
407 * Authentication thread.
409 static void *
410 sshpam_thread(void *ctxtp)
412 struct pam_ctxt *ctxt = ctxtp;
413 Buffer buffer;
414 struct pam_conv sshpam_conv;
415 int flags = (options.permit_empty_passwd == 0 ?
416 PAM_DISALLOW_NULL_AUTHTOK : 0);
417 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
418 extern char **environ;
419 char **env_from_pam;
420 u_int i;
421 const char *pam_user;
422 const char **ptr_pam_user = &pam_user;
424 pam_get_item(sshpam_handle, PAM_USER,
425 (sshpam_const void **)ptr_pam_user);
426 environ[0] = NULL;
428 if (sshpam_authctxt != NULL) {
429 setproctitle("%s [pam]",
430 sshpam_authctxt->valid ? pam_user : "unknown");
432 #endif
434 sshpam_conv.conv = sshpam_thread_conv;
435 sshpam_conv.appdata_ptr = ctxt;
437 if (sshpam_authctxt == NULL)
438 fatal("%s: PAM authctxt not initialized", __func__);
440 buffer_init(&buffer);
441 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
442 (const void *)&sshpam_conv);
443 if (sshpam_err != PAM_SUCCESS)
444 goto auth_fail;
445 sshpam_err = pam_authenticate(sshpam_handle, flags);
446 if (sshpam_err != PAM_SUCCESS)
447 goto auth_fail;
449 if (compat20) {
450 if (!do_pam_account()) {
451 sshpam_err = PAM_ACCT_EXPIRED;
452 goto auth_fail;
454 if (sshpam_authctxt->force_pwchange) {
455 sshpam_err = pam_chauthtok(sshpam_handle,
456 PAM_CHANGE_EXPIRED_AUTHTOK);
457 if (sshpam_err != PAM_SUCCESS)
458 goto auth_fail;
459 sshpam_password_change_required(0);
463 buffer_put_cstring(&buffer, "OK");
465 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
466 /* Export variables set by do_pam_account */
467 buffer_put_int(&buffer, sshpam_account_status);
468 buffer_put_int(&buffer, sshpam_authctxt->force_pwchange);
470 /* Export any environment strings set in child */
471 for(i = 0; environ[i] != NULL; i++)
472 ; /* Count */
473 buffer_put_int(&buffer, i);
474 for(i = 0; environ[i] != NULL; i++)
475 buffer_put_cstring(&buffer, environ[i]);
477 /* Export any environment strings set by PAM in child */
478 env_from_pam = pam_getenvlist(sshpam_handle);
479 for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
480 ; /* Count */
481 buffer_put_int(&buffer, i);
482 for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
483 buffer_put_cstring(&buffer, env_from_pam[i]);
484 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
486 /* XXX - can't do much about an error here */
487 ssh_msg_send(ctxt->pam_csock, sshpam_err, &buffer);
488 buffer_free(&buffer);
489 pthread_exit(NULL);
491 auth_fail:
492 buffer_put_cstring(&buffer,
493 pam_strerror(sshpam_handle, sshpam_err));
494 /* XXX - can't do much about an error here */
495 if (sshpam_err == PAM_ACCT_EXPIRED)
496 ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, &buffer);
497 else
498 ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
499 buffer_free(&buffer);
500 pthread_exit(NULL);
502 return (NULL); /* Avoid warning for non-pthread case */
505 void
506 sshpam_thread_cleanup(void)
508 struct pam_ctxt *ctxt = cleanup_ctxt;
510 debug3("PAM: %s entering", __func__);
511 if (ctxt != NULL && ctxt->pam_thread != 0) {
512 pthread_cancel(ctxt->pam_thread);
513 pthread_join(ctxt->pam_thread, NULL);
514 close(ctxt->pam_psock);
515 close(ctxt->pam_csock);
516 memset(ctxt, 0, sizeof(*ctxt));
517 cleanup_ctxt = NULL;
521 static int
522 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
523 struct pam_response **resp, void *data)
525 debug3("PAM: %s entering, %d messages", __func__, n);
526 return (PAM_CONV_ERR);
529 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
531 static int
532 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
533 struct pam_response **resp, void *data)
535 struct pam_response *reply;
536 int i;
537 size_t len;
539 debug3("PAM: %s called with %d messages", __func__, n);
540 *resp = NULL;
542 if (n <= 0 || n > PAM_MAX_NUM_MSG)
543 return (PAM_CONV_ERR);
545 if ((reply = calloc(n, sizeof(*reply))) == NULL)
546 return (PAM_CONV_ERR);
548 for (i = 0; i < n; ++i) {
549 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
550 case PAM_ERROR_MSG:
551 case PAM_TEXT_INFO:
552 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
553 buffer_append(&loginmsg, PAM_MSG_MEMBER(msg, i, msg), len);
554 buffer_append(&loginmsg, "\n", 1 );
555 reply[i].resp_retcode = PAM_SUCCESS;
556 break;
557 default:
558 goto fail;
561 *resp = reply;
562 return (PAM_SUCCESS);
564 fail:
565 for(i = 0; i < n; i++) {
566 if (reply[i].resp != NULL)
567 xfree(reply[i].resp);
569 xfree(reply);
570 return (PAM_CONV_ERR);
573 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
575 void
576 sshpam_cleanup(void)
578 debug("PAM: cleanup");
579 if (sshpam_handle == NULL)
580 return;
581 pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
582 if (sshpam_cred_established) {
583 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
584 sshpam_cred_established = 0;
586 if (sshpam_session_open) {
587 pam_close_session(sshpam_handle, PAM_SILENT);
588 sshpam_session_open = 0;
590 sshpam_authenticated = 0;
591 pam_end(sshpam_handle, sshpam_err);
592 sshpam_handle = NULL;
595 static int
596 sshpam_init(Authctxt *authctxt)
598 extern char *__progname;
599 const char *pam_rhost, *pam_user, *user = authctxt->user;
600 const char **ptr_pam_user = &pam_user;
602 if (sshpam_handle != NULL) {
603 /* We already have a PAM context; check if the user matches */
604 sshpam_err = pam_get_item(sshpam_handle,
605 PAM_USER, (sshpam_const void **)ptr_pam_user);
606 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
607 return (0);
608 pam_end(sshpam_handle, sshpam_err);
609 sshpam_handle = NULL;
611 debug("PAM: initializing for \"%s\"", user);
612 sshpam_err =
613 pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
614 sshpam_authctxt = authctxt;
616 if (sshpam_err != PAM_SUCCESS) {
617 pam_end(sshpam_handle, sshpam_err);
618 sshpam_handle = NULL;
619 return (-1);
621 pam_rhost = get_remote_name_or_ip(utmp_len, options.use_dns);
622 debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
623 sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
624 if (sshpam_err != PAM_SUCCESS) {
625 pam_end(sshpam_handle, sshpam_err);
626 sshpam_handle = NULL;
627 return (-1);
629 #ifdef PAM_TTY_KLUDGE
631 * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
632 * sshd doesn't set the tty until too late in the auth process and
633 * may not even set one (for tty-less connections)
635 debug("PAM: setting PAM_TTY to \"ssh\"");
636 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
637 if (sshpam_err != PAM_SUCCESS) {
638 pam_end(sshpam_handle, sshpam_err);
639 sshpam_handle = NULL;
640 return (-1);
642 #endif
643 return (0);
646 static void *
647 sshpam_init_ctx(Authctxt *authctxt)
649 struct pam_ctxt *ctxt;
650 int socks[2];
652 debug3("PAM: %s entering", __func__);
654 * Refuse to start if we don't have PAM enabled or do_pam_account
655 * has previously failed.
657 if (!options.use_pam || sshpam_account_status == 0)
658 return NULL;
660 /* Initialize PAM */
661 if (sshpam_init(authctxt) == -1) {
662 error("PAM: initialization failed");
663 return (NULL);
666 ctxt = xmalloc(sizeof *ctxt);
667 memset(ctxt, 0, sizeof(*ctxt));
669 /* Start the authentication thread */
670 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
671 error("PAM: failed create sockets: %s", strerror(errno));
672 xfree(ctxt);
673 return (NULL);
675 ctxt->pam_psock = socks[0];
676 ctxt->pam_csock = socks[1];
677 if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
678 error("PAM: failed to start authentication thread: %s",
679 strerror(errno));
680 close(socks[0]);
681 close(socks[1]);
682 xfree(ctxt);
683 return (NULL);
685 cleanup_ctxt = ctxt;
686 return (ctxt);
689 static int
690 sshpam_query(void *ctx, char **name, char **info,
691 u_int *num, char ***prompts, u_int **echo_on)
693 Buffer buffer;
694 struct pam_ctxt *ctxt = ctx;
695 size_t plen;
696 u_char type;
697 char *msg;
698 size_t len, mlen;
700 debug3("PAM: %s entering", __func__);
701 buffer_init(&buffer);
702 *name = xstrdup("");
703 *info = xstrdup("");
704 *prompts = xmalloc(sizeof(char *));
705 **prompts = NULL;
706 plen = 0;
707 *echo_on = xmalloc(sizeof(u_int));
708 while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
709 type = buffer_get_char(&buffer);
710 msg = buffer_get_string(&buffer, NULL);
711 mlen = strlen(msg);
712 switch (type) {
713 case PAM_PROMPT_ECHO_ON:
714 case PAM_PROMPT_ECHO_OFF:
715 *num = 1;
716 len = plen + mlen + 1;
717 **prompts = xrealloc(**prompts, 1, len);
718 strlcpy(**prompts + plen, msg, len - plen);
719 plen += mlen;
720 **echo_on = (type == PAM_PROMPT_ECHO_ON);
721 xfree(msg);
722 return (0);
723 case PAM_ERROR_MSG:
724 case PAM_TEXT_INFO:
725 /* accumulate messages */
726 len = plen + mlen + 2;
727 **prompts = xrealloc(**prompts, 1, len);
728 strlcpy(**prompts + plen, msg, len - plen);
729 plen += mlen;
730 strlcat(**prompts + plen, "\n", len - plen);
731 plen++;
732 xfree(msg);
733 break;
734 case PAM_ACCT_EXPIRED:
735 sshpam_account_status = 0;
736 /* FALLTHROUGH */
737 case PAM_AUTH_ERR:
738 debug3("PAM: %s", pam_strerror(sshpam_handle, type));
739 if (**prompts != NULL && strlen(**prompts) != 0) {
740 *info = **prompts;
741 **prompts = NULL;
742 *num = 0;
743 **echo_on = 0;
744 ctxt->pam_done = -1;
745 xfree(msg);
746 return 0;
748 /* FALLTHROUGH */
749 case PAM_SUCCESS:
750 if (**prompts != NULL) {
751 /* drain any accumulated messages */
752 debug("PAM: %s", **prompts);
753 buffer_append(&loginmsg, **prompts,
754 strlen(**prompts));
755 xfree(**prompts);
756 **prompts = NULL;
758 if (type == PAM_SUCCESS) {
759 if (!sshpam_authctxt->valid ||
760 (sshpam_authctxt->pw->pw_uid == 0 &&
761 options.permit_root_login != PERMIT_YES))
762 fatal("Internal error: PAM auth "
763 "succeeded when it should have "
764 "failed");
765 import_environments(&buffer);
766 *num = 0;
767 **echo_on = 0;
768 ctxt->pam_done = 1;
769 xfree(msg);
770 return (0);
772 error("PAM: %s for %s%.100s from %.100s", msg,
773 sshpam_authctxt->valid ? "" : "illegal user ",
774 sshpam_authctxt->user,
775 get_remote_name_or_ip(utmp_len, options.use_dns));
776 /* FALLTHROUGH */
777 default:
778 *num = 0;
779 **echo_on = 0;
780 xfree(msg);
781 ctxt->pam_done = -1;
782 return (-1);
785 return (-1);
788 /* XXX - see also comment in auth-chall.c:verify_response */
789 static int
790 sshpam_respond(void *ctx, u_int num, char **resp)
792 Buffer buffer;
793 struct pam_ctxt *ctxt = ctx;
795 debug2("PAM: %s entering, %u responses", __func__, num);
796 switch (ctxt->pam_done) {
797 case 1:
798 sshpam_authenticated = 1;
799 return (0);
800 case 0:
801 break;
802 default:
803 return (-1);
805 if (num != 1) {
806 error("PAM: expected one response, got %u", num);
807 return (-1);
809 buffer_init(&buffer);
810 if (sshpam_authctxt->valid &&
811 (sshpam_authctxt->pw->pw_uid != 0 ||
812 options.permit_root_login == PERMIT_YES))
813 buffer_put_cstring(&buffer, *resp);
814 else
815 buffer_put_cstring(&buffer, badpw);
816 if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer) == -1) {
817 buffer_free(&buffer);
818 return (-1);
820 buffer_free(&buffer);
821 return (1);
824 static void
825 sshpam_free_ctx(void *ctxtp)
827 struct pam_ctxt *ctxt = ctxtp;
829 debug3("PAM: %s entering", __func__);
830 sshpam_thread_cleanup();
831 xfree(ctxt);
833 * We don't call sshpam_cleanup() here because we may need the PAM
834 * handle at a later stage, e.g. when setting up a session. It's
835 * still on the cleanup list, so pam_end() *will* be called before
836 * the server process terminates.
840 KbdintDevice sshpam_device = {
841 "pam",
842 sshpam_init_ctx,
843 sshpam_query,
844 sshpam_respond,
845 sshpam_free_ctx
848 KbdintDevice mm_sshpam_device = {
849 "pam",
850 mm_sshpam_init_ctx,
851 mm_sshpam_query,
852 mm_sshpam_respond,
853 mm_sshpam_free_ctx
857 * This replaces auth-pam.c
859 void
860 start_pam(Authctxt *authctxt)
862 if (!options.use_pam)
863 fatal("PAM: initialisation requested when UsePAM=no");
865 if (sshpam_init(authctxt) == -1)
866 fatal("PAM: initialisation failed");
869 void
870 finish_pam(void)
872 sshpam_cleanup();
875 u_int
876 do_pam_account(void)
878 debug("%s: called", __func__);
879 if (sshpam_account_status != -1)
880 return (sshpam_account_status);
882 sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
883 debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
884 pam_strerror(sshpam_handle, sshpam_err));
886 if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
887 sshpam_account_status = 0;
888 return (sshpam_account_status);
891 if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
892 sshpam_password_change_required(1);
894 sshpam_account_status = 1;
895 return (sshpam_account_status);
898 void
899 do_pam_set_tty(const char *tty)
901 if (tty != NULL) {
902 debug("PAM: setting PAM_TTY to \"%s\"", tty);
903 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, tty);
904 if (sshpam_err != PAM_SUCCESS)
905 fatal("PAM: failed to set PAM_TTY: %s",
906 pam_strerror(sshpam_handle, sshpam_err));
910 void
911 do_pam_setcred(int init)
913 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
914 (const void *)&store_conv);
915 if (sshpam_err != PAM_SUCCESS)
916 fatal("PAM: failed to set PAM_CONV: %s",
917 pam_strerror(sshpam_handle, sshpam_err));
918 if (init) {
919 debug("PAM: establishing credentials");
920 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
921 } else {
922 debug("PAM: reinitializing credentials");
923 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
925 if (sshpam_err == PAM_SUCCESS) {
926 sshpam_cred_established = 1;
927 return;
929 if (sshpam_authenticated)
930 fatal("PAM: pam_setcred(): %s",
931 pam_strerror(sshpam_handle, sshpam_err));
932 else
933 debug("PAM: pam_setcred(): %s",
934 pam_strerror(sshpam_handle, sshpam_err));
937 static int
938 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
939 struct pam_response **resp, void *data)
941 char input[PAM_MAX_MSG_SIZE];
942 struct pam_response *reply;
943 int i;
945 debug3("PAM: %s called with %d messages", __func__, n);
947 *resp = NULL;
949 if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
950 return (PAM_CONV_ERR);
952 if ((reply = calloc(n, sizeof(*reply))) == NULL)
953 return (PAM_CONV_ERR);
955 for (i = 0; i < n; ++i) {
956 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
957 case PAM_PROMPT_ECHO_OFF:
958 reply[i].resp =
959 read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
960 RP_ALLOW_STDIN);
961 reply[i].resp_retcode = PAM_SUCCESS;
962 break;
963 case PAM_PROMPT_ECHO_ON:
964 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
965 fgets(input, sizeof input, stdin);
966 if ((reply[i].resp = strdup(input)) == NULL)
967 goto fail;
968 reply[i].resp_retcode = PAM_SUCCESS;
969 break;
970 case PAM_ERROR_MSG:
971 case PAM_TEXT_INFO:
972 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
973 reply[i].resp_retcode = PAM_SUCCESS;
974 break;
975 default:
976 goto fail;
979 *resp = reply;
980 return (PAM_SUCCESS);
982 fail:
983 for(i = 0; i < n; i++) {
984 if (reply[i].resp != NULL)
985 xfree(reply[i].resp);
987 xfree(reply);
988 return (PAM_CONV_ERR);
991 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
994 * XXX this should be done in the authentication phase, but ssh1 doesn't
995 * support that
997 void
998 do_pam_chauthtok(void)
1000 if (use_privsep)
1001 fatal("Password expired (unable to change with privsep)");
1002 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1003 (const void *)&tty_conv);
1004 if (sshpam_err != PAM_SUCCESS)
1005 fatal("PAM: failed to set PAM_CONV: %s",
1006 pam_strerror(sshpam_handle, sshpam_err));
1007 debug("PAM: changing password");
1008 sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1009 if (sshpam_err != PAM_SUCCESS)
1010 fatal("PAM: pam_chauthtok(): %s",
1011 pam_strerror(sshpam_handle, sshpam_err));
1014 void
1015 do_pam_session(void)
1017 debug3("PAM: opening session");
1018 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1019 (const void *)&store_conv);
1020 if (sshpam_err != PAM_SUCCESS)
1021 fatal("PAM: failed to set PAM_CONV: %s",
1022 pam_strerror(sshpam_handle, sshpam_err));
1023 sshpam_err = pam_open_session(sshpam_handle, 0);
1024 if (sshpam_err == PAM_SUCCESS)
1025 sshpam_session_open = 1;
1026 else {
1027 sshpam_session_open = 0;
1028 disable_forwarding();
1029 error("PAM: pam_open_session(): %s",
1030 pam_strerror(sshpam_handle, sshpam_err));
1036 is_pam_session_open(void)
1038 return sshpam_session_open;
1042 * Set a PAM environment string. We need to do this so that the session
1043 * modules can handle things like Kerberos/GSI credentials that appear
1044 * during the ssh authentication process.
1047 do_pam_putenv(char *name, char *value)
1049 int ret = 1;
1050 #ifdef HAVE_PAM_PUTENV
1051 char *compound;
1052 size_t len;
1054 len = strlen(name) + strlen(value) + 2;
1055 compound = xmalloc(len);
1057 snprintf(compound, len, "%s=%s", name, value);
1058 ret = pam_putenv(sshpam_handle, compound);
1059 xfree(compound);
1060 #endif
1062 return (ret);
1065 char **
1066 fetch_pam_child_environment(void)
1068 return sshpam_env;
1071 char **
1072 fetch_pam_environment(void)
1074 return (pam_getenvlist(sshpam_handle));
1077 void
1078 free_pam_environment(char **env)
1080 char **envp;
1082 if (env == NULL)
1083 return;
1085 for (envp = env; *envp; envp++)
1086 xfree(*envp);
1087 xfree(env);
1091 * "Blind" conversation function for password authentication. Assumes that
1092 * echo-off prompts are for the password and stores messages for later
1093 * display.
1095 static int
1096 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1097 struct pam_response **resp, void *data)
1099 struct pam_response *reply;
1100 int i;
1101 size_t len;
1103 debug3("PAM: %s called with %d messages", __func__, n);
1105 *resp = NULL;
1107 if (n <= 0 || n > PAM_MAX_NUM_MSG)
1108 return (PAM_CONV_ERR);
1110 if ((reply = malloc(n * sizeof(*reply))) == NULL)
1111 return (PAM_CONV_ERR);
1112 memset(reply, 0, n * sizeof(*reply));
1114 for (i = 0; i < n; ++i) {
1115 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1116 case PAM_PROMPT_ECHO_OFF:
1117 if (sshpam_password == NULL)
1118 goto fail;
1119 if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1120 goto fail;
1121 reply[i].resp_retcode = PAM_SUCCESS;
1122 break;
1123 case PAM_ERROR_MSG:
1124 case PAM_TEXT_INFO:
1125 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1126 if (len > 0) {
1127 buffer_append(&loginmsg,
1128 PAM_MSG_MEMBER(msg, i, msg), len);
1129 buffer_append(&loginmsg, "\n", 1);
1131 if ((reply[i].resp = strdup("")) == NULL)
1132 goto fail;
1133 reply[i].resp_retcode = PAM_SUCCESS;
1134 break;
1135 default:
1136 goto fail;
1139 *resp = reply;
1140 return (PAM_SUCCESS);
1142 fail:
1143 for(i = 0; i < n; i++) {
1144 if (reply[i].resp != NULL)
1145 xfree(reply[i].resp);
1147 xfree(reply);
1148 return (PAM_CONV_ERR);
1151 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1154 * Attempt password authentication via PAM
1157 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1159 int flags = (options.permit_empty_passwd == 0 ?
1160 PAM_DISALLOW_NULL_AUTHTOK : 0);
1162 if (!options.use_pam || sshpam_handle == NULL)
1163 fatal("PAM: %s called when PAM disabled or failed to "
1164 "initialise.", __func__);
1166 sshpam_password = password;
1167 sshpam_authctxt = authctxt;
1170 * If the user logging in is invalid, or is root but is not permitted
1171 * by PermitRootLogin, use an invalid password to prevent leaking
1172 * information via timing (eg if the PAM config has a delay on fail).
1174 if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1175 options.permit_root_login != PERMIT_YES))
1176 sshpam_password = badpw;
1178 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1179 (const void *)&passwd_conv);
1180 if (sshpam_err != PAM_SUCCESS)
1181 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1182 pam_strerror(sshpam_handle, sshpam_err));
1184 sshpam_err = pam_authenticate(sshpam_handle, flags);
1185 sshpam_password = NULL;
1186 if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1187 debug("PAM: password authentication accepted for %.100s",
1188 authctxt->user);
1189 return 1;
1190 } else {
1191 debug("PAM: password authentication failed for %.100s: %s",
1192 authctxt->valid ? authctxt->user : "an illegal user",
1193 pam_strerror(sshpam_handle, sshpam_err));
1194 return 0;
1197 #endif /* USE_PAM */