2 * Copyright (c) 2002 Networks Associates Technology, Inc.
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
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
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 */
52 #include <sys/types.h>
63 #if defined(HAVE_SECURITY_PAM_APPL_H)
64 #include <security/pam_appl.h>
65 #elif defined (HAVE_PAM_PAM_APPL_H)
66 #include <pam/pam_appl.h>
69 #if !defined(SSHD_PAM_SERVICE)
70 extern char *__progname;
71 # define SSHD_PAM_SERVICE __progname
74 /* OpenGroup RFC86.0 and XSSO specify no "const" on arguments */
75 #ifdef PAM_SUN_CODEBASE
76 # define sshpam_const /* Solaris, HP-UX, SunOS */
78 # define sshpam_const const /* LinuxPAM, OpenPAM, AIX */
81 /* Ambiguity in spec: is it an array of pointers or a pointer to an array? */
82 #ifdef PAM_SUN_CODEBASE
83 # define PAM_MSG_MEMBER(msg, n, member) ((*(msg))[(n)].member)
85 # define PAM_MSG_MEMBER(msg, n, member) ((msg)[(n)]->member)
101 #include "auth-options.h"
105 #include "monitor_wrap.h"
107 extern ServerOptions options;
108 extern struct sshbuf *loginmsg;
109 extern u_int utmp_len;
111 /* so we don't silently change behaviour */
112 #ifdef USE_POSIX_THREADS
113 # error "USE_POSIX_THREADS replaced by UNSUPPORTED_POSIX_THREADS_HACK"
117 * Formerly known as USE_POSIX_THREADS, using this is completely unsupported
118 * and generally a bad idea. Use at own risk and do not expect support if
121 #ifdef UNSUPPORTED_POSIX_THREADS_HACK
124 * Avoid namespace clash when *not* using pthreads for systems *with*
125 * pthreads, which unconditionally define pthread_t via sys/types.h
128 typedef pthread_t sp_pthread_t;
130 typedef pid_t sp_pthread_t;
131 #define pthread_exit fake_pthread_exit
132 #define pthread_create fake_pthread_create
133 #define pthread_cancel fake_pthread_cancel
134 #define pthread_join fake_pthread_join
138 sp_pthread_t pam_thread;
144 static void sshpam_free_ctx(void *);
145 static struct pam_ctxt *cleanup_ctxt;
147 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
149 * Simulate threads with processes.
152 static int sshpam_thread_status = -1;
153 static mysig_t sshpam_oldsig;
156 sshpam_sigchld_handler(int sig)
158 signal(SIGCHLD, SIG_DFL);
159 if (cleanup_ctxt == NULL)
160 return; /* handler called after PAM cleanup, shouldn't happen */
161 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, WNOHANG)
163 /* PAM thread has not exitted, privsep slave must have */
164 kill(cleanup_ctxt->pam_thread, SIGTERM);
165 while (waitpid(cleanup_ctxt->pam_thread,
166 &sshpam_thread_status, 0) == -1) {
172 if (WIFSIGNALED(sshpam_thread_status) &&
173 WTERMSIG(sshpam_thread_status) == SIGTERM)
174 return; /* terminated by pthread_cancel */
175 if (!WIFEXITED(sshpam_thread_status))
176 sigdie("PAM: authentication thread exited unexpectedly");
177 if (WEXITSTATUS(sshpam_thread_status) != 0)
178 sigdie("PAM: authentication thread exited uncleanly");
183 pthread_exit(void *value)
190 pthread_create(sp_pthread_t *thread, const void *attr,
191 void *(*thread_start)(void *), void *arg)
194 struct pam_ctxt *ctx = arg;
196 sshpam_thread_status = -1;
197 switch ((pid = fork())) {
199 error("fork(): %s", strerror(errno));
202 close(ctx->pam_psock);
208 close(ctx->pam_csock);
210 sshpam_oldsig = signal(SIGCHLD, sshpam_sigchld_handler);
216 pthread_cancel(sp_pthread_t thread)
218 signal(SIGCHLD, sshpam_oldsig);
219 return (kill(thread, SIGTERM));
224 pthread_join(sp_pthread_t thread, void **value)
228 if (sshpam_thread_status != -1)
229 return (sshpam_thread_status);
230 signal(SIGCHLD, sshpam_oldsig);
231 while (waitpid(thread, &status, 0) == -1) {
234 fatal("%s: waitpid: %s", __func__, strerror(errno));
241 static pam_handle_t *sshpam_handle = NULL;
242 static int sshpam_err = 0;
243 static int sshpam_authenticated = 0;
244 static int sshpam_session_open = 0;
245 static int sshpam_cred_established = 0;
246 static int sshpam_account_status = -1;
247 static int sshpam_maxtries_reached = 0;
248 static char **sshpam_env = NULL;
249 static Authctxt *sshpam_authctxt = NULL;
250 static const char *sshpam_password = NULL;
251 static char *sshpam_rhost = NULL;
252 static char *sshpam_laddr = NULL;
253 static char *sshpam_conninfo = NULL;
255 /* Some PAM implementations don't implement this */
256 #ifndef HAVE_PAM_GETENVLIST
258 pam_getenvlist(pam_handle_t *pamh)
261 * XXX - If necessary, we can still support envrionment passing
262 * for platforms without pam_getenvlist by searching for known
263 * env vars (e.g. KRB5CCNAME) from the PAM environment.
270 * Some platforms, notably Solaris, do not enforce password complexity
271 * rules during pam_chauthtok() if the real uid of the calling process
272 * is 0, on the assumption that it's being called by "passwd" run by root.
273 * This wraps pam_chauthtok and sets/restore the real uid so PAM will do
276 #ifdef SSHPAM_CHAUTHTOK_NEEDS_RUID
278 sshpam_chauthtok_ruid(pam_handle_t *pamh, int flags)
282 if (sshpam_authctxt == NULL)
283 fatal("PAM: sshpam_authctxt not initialized");
284 if (setreuid(sshpam_authctxt->pw->pw_uid, -1) == -1)
285 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
286 result = pam_chauthtok(pamh, flags);
287 if (setreuid(0, -1) == -1)
288 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
291 # define pam_chauthtok(a,b) (sshpam_chauthtok_ruid((a), (b)))
295 sshpam_password_change_required(int reqd)
297 extern struct sshauthopt *auth_opts;
298 static int saved_port, saved_agent, saved_x11;
300 debug3("%s %d", __func__, reqd);
301 if (sshpam_authctxt == NULL)
302 fatal("%s: PAM authctxt not initialized", __func__);
303 sshpam_authctxt->force_pwchange = reqd;
305 saved_port = auth_opts->permit_port_forwarding_flag;
306 saved_agent = auth_opts->permit_agent_forwarding_flag;
307 saved_x11 = auth_opts->permit_x11_forwarding_flag;
308 auth_opts->permit_port_forwarding_flag = 0;
309 auth_opts->permit_agent_forwarding_flag = 0;
310 auth_opts->permit_x11_forwarding_flag = 0;
313 auth_opts->permit_port_forwarding_flag = saved_port;
315 auth_opts->permit_agent_forwarding_flag = saved_agent;
317 auth_opts->permit_x11_forwarding_flag = saved_x11;
321 /* Import regular and PAM environment from subprocess */
323 import_environments(struct sshbuf *b)
329 debug3("PAM: %s entering", __func__);
331 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
332 /* Import variables set by do_pam_account */
333 if ((r = sshbuf_get_u32(b, &n)) != 0)
334 fatal("%s: buffer error: %s", __func__, ssh_err(r));
336 fatal("%s: invalid PAM account status %u", __func__, n);
337 sshpam_account_status = (int)n;
338 if ((r = sshbuf_get_u32(b, &n)) != 0)
339 fatal("%s: buffer error: %s", __func__, ssh_err(r));
340 sshpam_password_change_required(n != 0);
342 /* Import environment from subprocess */
343 if ((r = sshbuf_get_u32(b, &num_env)) != 0)
344 fatal("%s: buffer error: %s", __func__, ssh_err(r));
346 fatal("%s: received %u environment variables, expected <= 1024",
348 sshpam_env = xcalloc(num_env + 1, sizeof(*sshpam_env));
349 debug3("PAM: num env strings %d", num_env);
350 for(i = 0; i < num_env; i++) {
351 if ((r = sshbuf_get_cstring(b, &(sshpam_env[i]), NULL)) != 0)
352 fatal("%s: buffer error: %s", __func__, ssh_err(r));
354 sshpam_env[num_env] = NULL;
356 /* Import PAM environment from subprocess */
357 if ((r = sshbuf_get_u32(b, &num_env)) != 0)
358 fatal("%s: buffer error: %s", __func__, ssh_err(r));
359 debug("PAM: num PAM env strings %d", num_env);
360 for (i = 0; i < num_env; i++) {
361 if ((r = sshbuf_get_cstring(b, &env, NULL)) != 0)
362 fatal("%s: buffer error: %s", __func__, ssh_err(r));
363 #ifdef HAVE_PAM_PUTENV
364 /* Errors are not fatal here */
365 if ((r = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
366 error("PAM: pam_putenv: %s",
367 pam_strerror(sshpam_handle, r));
376 * Conversation function for authentication thread.
379 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
380 struct pam_response **resp, void *data)
382 struct sshbuf *buffer;
383 struct pam_ctxt *ctxt;
384 struct pam_response *reply;
388 debug3("PAM: %s entering, %d messages", __func__, n);
392 error("PAM: conversation function passed a null context");
393 return (PAM_CONV_ERR);
396 if (n <= 0 || n > PAM_MAX_NUM_MSG)
397 return (PAM_CONV_ERR);
399 if ((reply = calloc(n, sizeof(*reply))) == NULL)
401 if ((buffer = sshbuf_new()) == NULL) {
406 for (i = 0; i < n; ++i) {
407 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
408 case PAM_PROMPT_ECHO_OFF:
409 case PAM_PROMPT_ECHO_ON:
410 if ((r = sshbuf_put_cstring(buffer,
411 PAM_MSG_MEMBER(msg, i, msg))) != 0)
412 fatal("%s: buffer error: %s",
413 __func__, ssh_err(r));
414 if (ssh_msg_send(ctxt->pam_csock,
415 PAM_MSG_MEMBER(msg, i, msg_style), buffer) == -1)
418 if (ssh_msg_recv(ctxt->pam_csock, buffer) == -1)
420 if ((r = sshbuf_get_u8(buffer, &status)) != 0)
421 fatal("%s: buffer error: %s",
422 __func__, ssh_err(r));
423 if (status != PAM_AUTHTOK)
425 if ((r = sshbuf_get_cstring(buffer,
426 &reply[i].resp, NULL)) != 0)
427 fatal("%s: buffer error: %s",
428 __func__, ssh_err(r));
432 if ((r = sshbuf_put_cstring(buffer,
433 PAM_MSG_MEMBER(msg, i, msg))) != 0)
434 fatal("%s: buffer error: %s",
435 __func__, ssh_err(r));
436 if (ssh_msg_send(ctxt->pam_csock,
437 PAM_MSG_MEMBER(msg, i, msg_style), buffer) == -1)
443 sshbuf_reset(buffer);
447 return (PAM_SUCCESS);
450 for(i = 0; i < n; i++) {
455 return (PAM_CONV_ERR);
459 * Authentication thread.
462 sshpam_thread(void *ctxtp)
464 struct pam_ctxt *ctxt = ctxtp;
465 struct sshbuf *buffer = NULL;
466 struct pam_conv sshpam_conv;
467 int r, flags = (options.permit_empty_passwd == 0 ?
468 PAM_DISALLOW_NULL_AUTHTOK : 0);
469 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
470 extern char **environ;
473 const char *pam_user;
474 const char **ptr_pam_user = &pam_user;
475 char *tz = getenv("TZ");
477 sshpam_err = pam_get_item(sshpam_handle, PAM_USER,
478 (sshpam_const void **)ptr_pam_user);
479 if (sshpam_err != PAM_SUCCESS)
484 if (setenv("TZ", tz, 1) == -1)
485 error("PAM: could not set TZ environment: %s",
488 if (sshpam_authctxt != NULL) {
489 setproctitle("%s [pam]",
490 sshpam_authctxt->valid ? pam_user : "unknown");
494 sshpam_conv.conv = sshpam_thread_conv;
495 sshpam_conv.appdata_ptr = ctxt;
497 if (sshpam_authctxt == NULL)
498 fatal("%s: PAM authctxt not initialized", __func__);
500 if ((buffer = sshbuf_new()) == NULL)
501 fatal("%s: sshbuf_new failed", __func__);
503 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
504 (const void *)&sshpam_conv);
505 if (sshpam_err != PAM_SUCCESS)
507 sshpam_err = pam_authenticate(sshpam_handle, flags);
508 if (sshpam_err == PAM_MAXTRIES)
509 sshpam_set_maxtries_reached(1);
510 if (sshpam_err != PAM_SUCCESS)
513 if (!do_pam_account()) {
514 sshpam_err = PAM_ACCT_EXPIRED;
517 if (sshpam_authctxt->force_pwchange) {
518 sshpam_err = pam_chauthtok(sshpam_handle,
519 PAM_CHANGE_EXPIRED_AUTHTOK);
520 if (sshpam_err != PAM_SUCCESS)
522 sshpam_password_change_required(0);
525 if ((r = sshbuf_put_cstring(buffer, "OK")) != 0)
526 fatal("%s: buffer error: %s", __func__, ssh_err(r));
528 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
529 /* Export variables set by do_pam_account */
530 if ((r = sshbuf_put_u32(buffer, sshpam_account_status)) != 0 ||
531 (r = sshbuf_put_u32(buffer, sshpam_authctxt->force_pwchange)) != 0)
532 fatal("%s: buffer error: %s", __func__, ssh_err(r));
534 /* Export any environment strings set in child */
535 for (i = 0; environ[i] != NULL; i++) {
538 fatal("%s: too many enviornment strings", __func__);
540 if ((r = sshbuf_put_u32(buffer, i)) != 0)
541 fatal("%s: buffer error: %s", __func__, ssh_err(r));
542 for (i = 0; environ[i] != NULL; i++) {
543 if ((r = sshbuf_put_cstring(buffer, environ[i])) != 0)
544 fatal("%s: buffer error: %s", __func__, ssh_err(r));
546 /* Export any environment strings set by PAM in child */
547 env_from_pam = pam_getenvlist(sshpam_handle);
548 for (i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++) {
551 fatal("%s: too many PAM enviornment strings", __func__);
553 if ((r = sshbuf_put_u32(buffer, i)) != 0)
554 fatal("%s: buffer error: %s", __func__, ssh_err(r));
555 for (i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++) {
556 if ((r = sshbuf_put_cstring(buffer, env_from_pam[i])) != 0)
557 fatal("%s: buffer error: %s", __func__, ssh_err(r));
559 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
561 /* XXX - can't do much about an error here */
562 ssh_msg_send(ctxt->pam_csock, sshpam_err, buffer);
567 if ((r = sshbuf_put_cstring(buffer,
568 pam_strerror(sshpam_handle, sshpam_err))) != 0)
569 fatal("%s: buffer error: %s", __func__, ssh_err(r));
570 /* XXX - can't do much about an error here */
571 if (sshpam_err == PAM_ACCT_EXPIRED)
572 ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, buffer);
573 else if (sshpam_maxtries_reached)
574 ssh_msg_send(ctxt->pam_csock, PAM_MAXTRIES, buffer);
576 ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, buffer);
580 return (NULL); /* Avoid warning for non-pthread case */
584 sshpam_thread_cleanup(void)
586 struct pam_ctxt *ctxt = cleanup_ctxt;
588 debug3("PAM: %s entering", __func__);
589 if (ctxt != NULL && ctxt->pam_thread != 0) {
590 pthread_cancel(ctxt->pam_thread);
591 pthread_join(ctxt->pam_thread, NULL);
592 close(ctxt->pam_psock);
593 close(ctxt->pam_csock);
594 memset(ctxt, 0, sizeof(*ctxt));
600 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
601 struct pam_response **resp, void *data)
603 debug3("PAM: %s entering, %d messages", __func__, n);
604 return (PAM_CONV_ERR);
607 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
610 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
611 struct pam_response **resp, void *data)
613 struct pam_response *reply;
616 debug3("PAM: %s called with %d messages", __func__, n);
619 if (n <= 0 || n > PAM_MAX_NUM_MSG)
620 return (PAM_CONV_ERR);
622 if ((reply = calloc(n, sizeof(*reply))) == NULL)
623 return (PAM_CONV_ERR);
625 for (i = 0; i < n; ++i) {
626 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
629 if ((r = sshbuf_putf(loginmsg, "%s\n",
630 PAM_MSG_MEMBER(msg, i, msg))) != 0)
631 fatal("%s: buffer error: %s",
632 __func__, ssh_err(r));
633 reply[i].resp_retcode = PAM_SUCCESS;
640 return (PAM_SUCCESS);
643 for(i = 0; i < n; i++) {
647 return (PAM_CONV_ERR);
650 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
655 if (sshpam_handle == NULL || (use_privsep && !mm_is_monitor()))
657 debug("PAM: cleanup");
658 pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
659 if (sshpam_session_open) {
660 debug("PAM: closing session");
661 pam_close_session(sshpam_handle, PAM_SILENT);
662 sshpam_session_open = 0;
664 if (sshpam_cred_established) {
665 debug("PAM: deleting credentials");
666 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
667 sshpam_cred_established = 0;
669 sshpam_authenticated = 0;
670 pam_end(sshpam_handle, sshpam_err);
671 sshpam_handle = NULL;
675 sshpam_init(struct ssh *ssh, Authctxt *authctxt)
677 const char *pam_user, *user = authctxt->user;
678 const char **ptr_pam_user = &pam_user;
680 if (sshpam_handle == NULL) {
682 fatal("%s: called initially with no "
683 "packet context", __func__);
685 } if (sshpam_handle != NULL) {
686 /* We already have a PAM context; check if the user matches */
687 sshpam_err = pam_get_item(sshpam_handle,
688 PAM_USER, (sshpam_const void **)ptr_pam_user);
689 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
691 pam_end(sshpam_handle, sshpam_err);
692 sshpam_handle = NULL;
694 debug("PAM: initializing for \"%s\"", user);
696 pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
697 sshpam_authctxt = authctxt;
699 if (sshpam_err != PAM_SUCCESS) {
700 pam_end(sshpam_handle, sshpam_err);
701 sshpam_handle = NULL;
705 if (ssh != NULL && sshpam_rhost == NULL) {
707 * We need to cache these as we don't have packet context
708 * during the kbdint flow.
710 sshpam_rhost = xstrdup(auth_get_canonical_hostname(ssh,
712 sshpam_laddr = get_local_ipaddr(
713 ssh_packet_get_connection_in(ssh));
714 xasprintf(&sshpam_conninfo, "SSH_CONNECTION=%.50s %d %.50s %d",
715 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
716 sshpam_laddr, ssh_local_port(ssh));
718 if (sshpam_rhost != NULL) {
719 debug("PAM: setting PAM_RHOST to \"%s\"", sshpam_rhost);
720 sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST,
722 if (sshpam_err != PAM_SUCCESS) {
723 pam_end(sshpam_handle, sshpam_err);
724 sshpam_handle = NULL;
727 /* Put SSH_CONNECTION in the PAM environment too */
728 pam_putenv(sshpam_handle, sshpam_conninfo);
731 #ifdef PAM_TTY_KLUDGE
733 * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
734 * sshd doesn't set the tty until too late in the auth process and
735 * may not even set one (for tty-less connections)
737 debug("PAM: setting PAM_TTY to \"ssh\"");
738 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
739 if (sshpam_err != PAM_SUCCESS) {
740 pam_end(sshpam_handle, sshpam_err);
741 sshpam_handle = NULL;
749 expose_authinfo(const char *caller)
754 * Expose authentication information to PAM.
755 * The environment variable is versioned. Please increment the
756 * version suffix if the format of session_info changes.
758 if (sshpam_authctxt->session_info == NULL)
759 auth_info = xstrdup("");
760 else if ((auth_info = sshbuf_dup_string(
761 sshpam_authctxt->session_info)) == NULL)
762 fatal("%s: sshbuf_dup_string failed", __func__);
764 debug2("%s: auth information in SSH_AUTH_INFO_0", caller);
765 do_pam_putenv("SSH_AUTH_INFO_0", auth_info);
770 sshpam_init_ctx(Authctxt *authctxt)
772 struct pam_ctxt *ctxt;
775 debug3("PAM: %s entering", __func__);
777 * Refuse to start if we don't have PAM enabled or do_pam_account
778 * has previously failed.
780 if (!options.use_pam || sshpam_account_status == 0)
784 if (sshpam_init(NULL, authctxt) == -1) {
785 error("PAM: initialization failed");
789 expose_authinfo(__func__);
790 ctxt = xcalloc(1, sizeof *ctxt);
792 /* Start the authentication thread */
793 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
794 error("PAM: failed create sockets: %s", strerror(errno));
798 ctxt->pam_psock = socks[0];
799 ctxt->pam_csock = socks[1];
800 if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
801 error("PAM: failed to start authentication thread: %s",
813 sshpam_query(void *ctx, char **name, char **info,
814 u_int *num, char ***prompts, u_int **echo_on)
816 struct sshbuf *buffer;
817 struct pam_ctxt *ctxt = ctx;
824 debug3("PAM: %s entering", __func__);
825 if ((buffer = sshbuf_new()) == NULL)
826 fatal("%s: sshbuf_new failed", __func__);
829 *prompts = xmalloc(sizeof(char *));
832 *echo_on = xmalloc(sizeof(u_int));
833 while (ssh_msg_recv(ctxt->pam_psock, buffer) == 0) {
834 if ((r = sshbuf_get_u8(buffer, &type)) != 0 ||
835 (r = sshbuf_get_cstring(buffer, &msg, &mlen)) != 0)
836 fatal("%s: buffer error: %s", __func__, ssh_err(r));
838 case PAM_PROMPT_ECHO_ON:
839 case PAM_PROMPT_ECHO_OFF:
841 len = plen + mlen + 1;
842 **prompts = xreallocarray(**prompts, 1, len);
843 strlcpy(**prompts + plen, msg, len - plen);
845 **echo_on = (type == PAM_PROMPT_ECHO_ON);
850 /* accumulate messages */
851 len = plen + mlen + 2;
852 **prompts = xreallocarray(**prompts, 1, len);
853 strlcpy(**prompts + plen, msg, len - plen);
855 strlcat(**prompts + plen, "\n", len - plen);
859 case PAM_ACCT_EXPIRED:
861 if (type == PAM_ACCT_EXPIRED)
862 sshpam_account_status = 0;
863 if (type == PAM_MAXTRIES)
864 sshpam_set_maxtries_reached(1);
867 debug3("PAM: %s", pam_strerror(sshpam_handle, type));
868 if (**prompts != NULL && strlen(**prompts) != 0) {
879 if (**prompts != NULL) {
880 /* drain any accumulated messages */
881 debug("PAM: %s", **prompts);
882 if ((r = sshbuf_put(loginmsg, **prompts,
883 strlen(**prompts))) != 0)
884 fatal("%s: buffer error: %s",
885 __func__, ssh_err(r));
889 if (type == PAM_SUCCESS) {
890 if (!sshpam_authctxt->valid ||
891 (sshpam_authctxt->pw->pw_uid == 0 &&
892 options.permit_root_login != PERMIT_YES))
893 fatal("Internal error: PAM auth "
894 "succeeded when it should have "
896 import_environments(buffer);
903 error("PAM: %s for %s%.100s from %.100s", msg,
904 sshpam_authctxt->valid ? "" : "illegal user ",
905 sshpam_authctxt->user, sshpam_rhost);
919 * Returns a junk password of identical length to that the user supplied.
920 * Used to mitigate timing attacks against crypt(3)/PAM stacks that
921 * vary processing time in proportion to password length.
924 fake_password(const char *wire_password)
926 const char junk[] = "\b\n\r\177INCORRECT";
928 size_t i, l = wire_password != NULL ? strlen(wire_password) : 0;
931 fatal("%s: password length too long: %zu", __func__, l);
936 for (i = 0; i < l; i++)
937 ret[i] = junk[i % (sizeof(junk) - 1)];
942 /* XXX - see also comment in auth-chall.c:verify_response */
944 sshpam_respond(void *ctx, u_int num, char **resp)
946 struct sshbuf *buffer;
947 struct pam_ctxt *ctxt = ctx;
951 debug2("PAM: %s entering, %u responses", __func__, num);
952 switch (ctxt->pam_done) {
954 sshpam_authenticated = 1;
962 error("PAM: expected one response, got %u", num);
965 if ((buffer = sshbuf_new()) == NULL)
966 fatal("%s: sshbuf_new failed", __func__);
967 if (sshpam_authctxt->valid &&
968 (sshpam_authctxt->pw->pw_uid != 0 ||
969 options.permit_root_login == PERMIT_YES)) {
970 if ((r = sshbuf_put_cstring(buffer, *resp)) != 0)
971 fatal("%s: buffer error: %s", __func__, ssh_err(r));
973 fake = fake_password(*resp);
974 if ((r = sshbuf_put_cstring(buffer, fake)) != 0)
975 fatal("%s: buffer error: %s", __func__, ssh_err(r));
978 if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, buffer) == -1) {
987 sshpam_free_ctx(void *ctxtp)
989 struct pam_ctxt *ctxt = ctxtp;
991 debug3("PAM: %s entering", __func__);
992 sshpam_thread_cleanup();
995 * We don't call sshpam_cleanup() here because we may need the PAM
996 * handle at a later stage, e.g. when setting up a session. It's
997 * still on the cleanup list, so pam_end() *will* be called before
998 * the server process terminates.
1002 KbdintDevice sshpam_device = {
1010 KbdintDevice mm_sshpam_device = {
1019 * This replaces auth-pam.c
1022 start_pam(struct ssh *ssh)
1024 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1026 if (!options.use_pam)
1027 fatal("PAM: initialisation requested when UsePAM=no");
1029 if (sshpam_init(ssh, authctxt) == -1)
1030 fatal("PAM: initialisation failed");
1041 do_pam_account(void)
1043 debug("%s: called", __func__);
1044 if (sshpam_account_status != -1)
1045 return (sshpam_account_status);
1047 expose_authinfo(__func__);
1049 sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
1050 debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
1051 pam_strerror(sshpam_handle, sshpam_err));
1053 if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
1054 sshpam_account_status = 0;
1055 return (sshpam_account_status);
1058 if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
1059 sshpam_password_change_required(1);
1061 sshpam_account_status = 1;
1062 return (sshpam_account_status);
1066 do_pam_setcred(int init)
1068 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1069 (const void *)&store_conv);
1070 if (sshpam_err != PAM_SUCCESS)
1071 fatal("PAM: failed to set PAM_CONV: %s",
1072 pam_strerror(sshpam_handle, sshpam_err));
1074 debug("PAM: establishing credentials");
1075 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
1077 debug("PAM: reinitializing credentials");
1078 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
1080 if (sshpam_err == PAM_SUCCESS) {
1081 sshpam_cred_established = 1;
1084 if (sshpam_authenticated)
1085 fatal("PAM: pam_setcred(): %s",
1086 pam_strerror(sshpam_handle, sshpam_err));
1088 debug("PAM: pam_setcred(): %s",
1089 pam_strerror(sshpam_handle, sshpam_err));
1093 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
1094 struct pam_response **resp, void *data)
1096 char input[PAM_MAX_MSG_SIZE];
1097 struct pam_response *reply;
1100 debug3("PAM: %s called with %d messages", __func__, n);
1104 if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
1105 return (PAM_CONV_ERR);
1107 if ((reply = calloc(n, sizeof(*reply))) == NULL)
1108 return (PAM_CONV_ERR);
1110 for (i = 0; i < n; ++i) {
1111 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1112 case PAM_PROMPT_ECHO_OFF:
1114 read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
1116 reply[i].resp_retcode = PAM_SUCCESS;
1118 case PAM_PROMPT_ECHO_ON:
1119 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1120 if (fgets(input, sizeof input, stdin) == NULL)
1122 if ((reply[i].resp = strdup(input)) == NULL)
1124 reply[i].resp_retcode = PAM_SUCCESS;
1128 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1129 reply[i].resp_retcode = PAM_SUCCESS;
1136 return (PAM_SUCCESS);
1139 for(i = 0; i < n; i++) {
1140 free(reply[i].resp);
1143 return (PAM_CONV_ERR);
1146 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
1149 * XXX this should be done in the authentication phase, but ssh1 doesn't
1153 do_pam_chauthtok(void)
1156 fatal("Password expired (unable to change with privsep)");
1157 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1158 (const void *)&tty_conv);
1159 if (sshpam_err != PAM_SUCCESS)
1160 fatal("PAM: failed to set PAM_CONV: %s",
1161 pam_strerror(sshpam_handle, sshpam_err));
1162 debug("PAM: changing password");
1163 sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1164 if (sshpam_err != PAM_SUCCESS)
1165 fatal("PAM: pam_chauthtok(): %s",
1166 pam_strerror(sshpam_handle, sshpam_err));
1170 do_pam_session(struct ssh *ssh)
1172 debug3("PAM: opening session");
1174 expose_authinfo(__func__);
1176 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1177 (const void *)&store_conv);
1178 if (sshpam_err != PAM_SUCCESS)
1179 fatal("PAM: failed to set PAM_CONV: %s",
1180 pam_strerror(sshpam_handle, sshpam_err));
1181 sshpam_err = pam_open_session(sshpam_handle, 0);
1182 if (sshpam_err == PAM_SUCCESS)
1183 sshpam_session_open = 1;
1185 sshpam_session_open = 0;
1186 auth_restrict_session(ssh);
1187 error("PAM: pam_open_session(): %s",
1188 pam_strerror(sshpam_handle, sshpam_err));
1194 is_pam_session_open(void)
1196 return sshpam_session_open;
1200 * Set a PAM environment string. We need to do this so that the session
1201 * modules can handle things like Kerberos/GSI credentials that appear
1202 * during the ssh authentication process.
1205 do_pam_putenv(char *name, char *value)
1208 #ifdef HAVE_PAM_PUTENV
1212 len = strlen(name) + strlen(value) + 2;
1213 compound = xmalloc(len);
1215 snprintf(compound, len, "%s=%s", name, value);
1216 ret = pam_putenv(sshpam_handle, compound);
1224 fetch_pam_child_environment(void)
1230 fetch_pam_environment(void)
1232 return (pam_getenvlist(sshpam_handle));
1236 free_pam_environment(char **env)
1243 for (envp = env; *envp; envp++)
1249 * "Blind" conversation function for password authentication. Assumes that
1250 * echo-off prompts are for the password and stores messages for later
1254 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1255 struct pam_response **resp, void *data)
1257 struct pam_response *reply;
1261 debug3("PAM: %s called with %d messages", __func__, n);
1265 if (n <= 0 || n > PAM_MAX_NUM_MSG)
1266 return (PAM_CONV_ERR);
1268 if ((reply = calloc(n, sizeof(*reply))) == NULL)
1269 return (PAM_CONV_ERR);
1271 for (i = 0; i < n; ++i) {
1272 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1273 case PAM_PROMPT_ECHO_OFF:
1274 if (sshpam_password == NULL)
1276 if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1278 reply[i].resp_retcode = PAM_SUCCESS;
1282 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1284 if ((r = sshbuf_putf(loginmsg, "%s\n",
1285 PAM_MSG_MEMBER(msg, i, msg))) != 0)
1286 fatal("%s: buffer error: %s",
1287 __func__, ssh_err(r));
1289 if ((reply[i].resp = strdup("")) == NULL)
1291 reply[i].resp_retcode = PAM_SUCCESS;
1298 return (PAM_SUCCESS);
1301 for(i = 0; i < n; i++) {
1302 free(reply[i].resp);
1305 return (PAM_CONV_ERR);
1308 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1311 * Attempt password authentication via PAM
1314 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1316 int flags = (options.permit_empty_passwd == 0 ?
1317 PAM_DISALLOW_NULL_AUTHTOK : 0);
1320 if (!options.use_pam || sshpam_handle == NULL)
1321 fatal("PAM: %s called when PAM disabled or failed to "
1322 "initialise.", __func__);
1324 sshpam_password = password;
1325 sshpam_authctxt = authctxt;
1328 * If the user logging in is invalid, or is root but is not permitted
1329 * by PermitRootLogin, use an invalid password to prevent leaking
1330 * information via timing (eg if the PAM config has a delay on fail).
1332 if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1333 options.permit_root_login != PERMIT_YES))
1334 sshpam_password = fake = fake_password(password);
1336 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1337 (const void *)&passwd_conv);
1338 if (sshpam_err != PAM_SUCCESS)
1339 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1340 pam_strerror(sshpam_handle, sshpam_err));
1342 sshpam_err = pam_authenticate(sshpam_handle, flags);
1343 sshpam_password = NULL;
1345 if (sshpam_err == PAM_MAXTRIES)
1346 sshpam_set_maxtries_reached(1);
1347 if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1348 debug("PAM: password authentication accepted for %.100s",
1352 debug("PAM: password authentication failed for %.100s: %s",
1353 authctxt->valid ? authctxt->user : "an illegal user",
1354 pam_strerror(sshpam_handle, sshpam_err));
1360 sshpam_get_maxtries_reached(void)
1362 return sshpam_maxtries_reached;
1366 sshpam_set_maxtries_reached(int reached)
1368 if (reached == 0 || sshpam_maxtries_reached)
1370 sshpam_maxtries_reached = 1;
1371 options.password_authentication = 0;
1372 options.kbd_interactive_authentication = 0;
1373 options.challenge_response_authentication = 0;
1375 #endif /* USE_PAM */