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>
64 #if defined(HAVE_SECURITY_PAM_APPL_H)
65 #include <security/pam_appl.h>
66 #elif defined (HAVE_PAM_PAM_APPL_H)
67 #include <pam/pam_appl.h>
70 #if !defined(SSHD_PAM_SERVICE)
71 extern char *__progname;
72 # define SSHD_PAM_SERVICE __progname
75 /* OpenGroup RFC86.0 and XSSO specify no "const" on arguments */
76 #ifdef PAM_SUN_CODEBASE
77 # define sshpam_const /* Solaris, HP-UX, SunOS */
79 # define sshpam_const const /* LinuxPAM, OpenPAM, AIX */
82 /* Ambiguity in spec: is it an array of pointers or a pointer to an array? */
83 #ifdef PAM_SUN_CODEBASE
84 # define PAM_MSG_MEMBER(msg, n, member) ((*(msg))[(n)].member)
86 # define PAM_MSG_MEMBER(msg, n, member) ((msg)[(n)]->member)
100 #include "servconf.h"
102 #include "auth-options.h"
107 #include "monitor_wrap.h"
108 #include "blacklist_client.h"
110 extern ServerOptions options;
111 extern struct sshbuf *loginmsg;
112 extern u_int utmp_len;
114 /* so we don't silently change behaviour */
115 #ifdef USE_POSIX_THREADS
116 # error "USE_POSIX_THREADS replaced by UNSUPPORTED_POSIX_THREADS_HACK"
120 * Formerly known as USE_POSIX_THREADS, using this is completely unsupported
121 * and generally a bad idea. Use at own risk and do not expect support if
124 #ifdef UNSUPPORTED_POSIX_THREADS_HACK
127 * Avoid namespace clash when *not* using pthreads for systems *with*
128 * pthreads, which unconditionally define pthread_t via sys/types.h
131 typedef pthread_t sp_pthread_t;
133 typedef pid_t sp_pthread_t;
134 #define pthread_exit fake_pthread_exit
135 #define pthread_create fake_pthread_create
136 #define pthread_cancel fake_pthread_cancel
137 #define pthread_join fake_pthread_join
141 sp_pthread_t pam_thread;
147 static void sshpam_free_ctx(void *);
148 static struct pam_ctxt *cleanup_ctxt;
150 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
152 * Simulate threads with processes.
155 static int sshpam_thread_status = -1;
156 static sshsig_t sshpam_oldsig;
159 sshpam_sigchld_handler(int sig)
161 ssh_signal(SIGCHLD, SIG_DFL);
162 if (cleanup_ctxt == NULL)
163 return; /* handler called after PAM cleanup, shouldn't happen */
164 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, WNOHANG)
166 /* PAM thread has not exitted, privsep slave must have */
167 kill(cleanup_ctxt->pam_thread, SIGTERM);
168 while (waitpid(cleanup_ctxt->pam_thread,
169 &sshpam_thread_status, 0) == -1) {
175 if (WIFSIGNALED(sshpam_thread_status) &&
176 WTERMSIG(sshpam_thread_status) == SIGTERM)
177 return; /* terminated by pthread_cancel */
178 if (!WIFEXITED(sshpam_thread_status))
179 sigdie("PAM: authentication thread exited unexpectedly");
180 if (WEXITSTATUS(sshpam_thread_status) != 0)
181 sigdie("PAM: authentication thread exited uncleanly");
186 pthread_exit(void *value)
193 pthread_create(sp_pthread_t *thread, const void *attr,
194 void *(*thread_start)(void *), void *arg)
197 struct pam_ctxt *ctx = arg;
199 sshpam_thread_status = -1;
200 switch ((pid = fork())) {
202 error("fork(): %s", strerror(errno));
205 close(ctx->pam_psock);
211 close(ctx->pam_csock);
213 sshpam_oldsig = ssh_signal(SIGCHLD, sshpam_sigchld_handler);
219 pthread_cancel(sp_pthread_t thread)
221 ssh_signal(SIGCHLD, sshpam_oldsig);
222 return (kill(thread, SIGTERM));
227 pthread_join(sp_pthread_t thread, void **value)
231 if (sshpam_thread_status != -1)
232 return (sshpam_thread_status);
233 ssh_signal(SIGCHLD, sshpam_oldsig);
234 while (waitpid(thread, &status, 0) == -1) {
237 fatal("%s: waitpid: %s", __func__, strerror(errno));
244 static pam_handle_t *sshpam_handle = NULL;
245 static int sshpam_err = 0;
246 static int sshpam_authenticated = 0;
247 static int sshpam_session_open = 0;
248 static int sshpam_cred_established = 0;
249 static int sshpam_account_status = -1;
250 static int sshpam_maxtries_reached = 0;
251 static char **sshpam_env = NULL;
252 static Authctxt *sshpam_authctxt = NULL;
253 static const char *sshpam_password = NULL;
254 static char *sshpam_rhost = NULL;
255 static char *sshpam_laddr = NULL;
257 /* Some PAM implementations don't implement this */
258 #ifndef HAVE_PAM_GETENVLIST
260 pam_getenvlist(pam_handle_t *pamh)
263 * XXX - If necessary, we can still support environment passing
264 * for platforms without pam_getenvlist by searching for known
265 * env vars (e.g. KRB5CCNAME) from the PAM environment.
271 #ifndef HAVE_PAM_PUTENV
273 pam_putenv(pam_handle_t *pamh, const char *name_value)
277 #endif /* HAVE_PAM_PUTENV */
280 * Some platforms, notably Solaris, do not enforce password complexity
281 * rules during pam_chauthtok() if the real uid of the calling process
282 * is 0, on the assumption that it's being called by "passwd" run by root.
283 * This wraps pam_chauthtok and sets/restore the real uid so PAM will do
286 #ifdef SSHPAM_CHAUTHTOK_NEEDS_RUID
288 sshpam_chauthtok_ruid(pam_handle_t *pamh, int flags)
292 if (sshpam_authctxt == NULL)
293 fatal("PAM: sshpam_authctxt not initialized");
294 if (setreuid(sshpam_authctxt->pw->pw_uid, -1) == -1)
295 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
296 result = pam_chauthtok(pamh, flags);
297 if (setreuid(0, -1) == -1)
298 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
301 # define pam_chauthtok(a,b) (sshpam_chauthtok_ruid((a), (b)))
305 sshpam_password_change_required(int reqd)
307 extern struct sshauthopt *auth_opts;
308 static int saved_port, saved_agent, saved_x11;
310 debug3("%s %d", __func__, reqd);
311 if (sshpam_authctxt == NULL)
312 fatal("%s: PAM authctxt not initialized", __func__);
313 sshpam_authctxt->force_pwchange = reqd;
315 saved_port = auth_opts->permit_port_forwarding_flag;
316 saved_agent = auth_opts->permit_agent_forwarding_flag;
317 saved_x11 = auth_opts->permit_x11_forwarding_flag;
318 auth_opts->permit_port_forwarding_flag = 0;
319 auth_opts->permit_agent_forwarding_flag = 0;
320 auth_opts->permit_x11_forwarding_flag = 0;
323 auth_opts->permit_port_forwarding_flag = saved_port;
325 auth_opts->permit_agent_forwarding_flag = saved_agent;
327 auth_opts->permit_x11_forwarding_flag = saved_x11;
331 /* Import regular and PAM environment from subprocess */
333 import_environments(struct sshbuf *b)
339 debug3("PAM: %s entering", __func__);
341 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
342 /* Import variables set by do_pam_account */
343 if ((r = sshbuf_get_u32(b, &n)) != 0)
344 fatal("%s: buffer error: %s", __func__, ssh_err(r));
346 fatal("%s: invalid PAM account status %u", __func__, n);
347 sshpam_account_status = (int)n;
348 if ((r = sshbuf_get_u32(b, &n)) != 0)
349 fatal("%s: buffer error: %s", __func__, ssh_err(r));
350 sshpam_password_change_required(n != 0);
352 /* Import environment from subprocess */
353 if ((r = sshbuf_get_u32(b, &num_env)) != 0)
354 fatal("%s: buffer error: %s", __func__, ssh_err(r));
355 if (num_env > 1024) {
356 fatal_f("received %u environment variables, expected <= 1024",
359 sshpam_env = xcalloc(num_env + 1, sizeof(*sshpam_env));
360 debug3("PAM: num env strings %u", num_env);
361 for(i = 0; i < num_env; i++) {
362 if ((r = sshbuf_get_cstring(b, &(sshpam_env[i]), NULL)) != 0)
363 fatal("%s: buffer error: %s", __func__, ssh_err(r));
365 sshpam_env[num_env] = NULL;
367 /* Import PAM environment from subprocess */
368 if ((r = sshbuf_get_u32(b, &num_env)) != 0)
369 fatal("%s: buffer error: %s", __func__, ssh_err(r));
370 if (num_env > 1024) {
371 fatal_f("received %u PAM env variables, expected <= 1024",
374 debug("PAM: num PAM env strings %u", num_env);
375 for (i = 0; i < num_env; i++) {
376 if ((r = sshbuf_get_cstring(b, &env, NULL)) != 0)
377 fatal("%s: buffer error: %s", __func__, ssh_err(r));
378 /* Errors are not fatal here */
379 if ((r = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
380 error("PAM: pam_putenv: %s",
381 pam_strerror(sshpam_handle, r));
384 * XXX this possibly leaks env because it is not documented
385 * what pam_putenv() does with it. Does it copy it? Does it
386 * take ownweship? We don't know, so it's safest just to leak.
393 * Conversation function for authentication thread.
396 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
397 struct pam_response **resp, void *data)
399 struct sshbuf *buffer;
400 struct pam_ctxt *ctxt;
401 struct pam_response *reply;
405 debug3("PAM: %s entering, %d messages", __func__, n);
409 error("PAM: conversation function passed a null context");
410 return (PAM_CONV_ERR);
413 if (n <= 0 || n > PAM_MAX_NUM_MSG)
414 return (PAM_CONV_ERR);
416 if ((reply = calloc(n, sizeof(*reply))) == NULL)
418 if ((buffer = sshbuf_new()) == NULL) {
423 for (i = 0; i < n; ++i) {
424 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
425 case PAM_PROMPT_ECHO_OFF:
426 case PAM_PROMPT_ECHO_ON:
427 if ((r = sshbuf_put_cstring(buffer,
428 PAM_MSG_MEMBER(msg, i, msg))) != 0)
429 fatal("%s: buffer error: %s",
430 __func__, ssh_err(r));
431 if (ssh_msg_send(ctxt->pam_csock,
432 PAM_MSG_MEMBER(msg, i, msg_style), buffer) == -1)
435 if (ssh_msg_recv(ctxt->pam_csock, buffer) == -1)
437 if ((r = sshbuf_get_u8(buffer, &status)) != 0)
438 fatal("%s: buffer error: %s",
439 __func__, ssh_err(r));
440 if (status != PAM_AUTHTOK)
442 if ((r = sshbuf_get_cstring(buffer,
443 &reply[i].resp, NULL)) != 0)
444 fatal("%s: buffer error: %s",
445 __func__, ssh_err(r));
449 if ((r = sshbuf_put_cstring(buffer,
450 PAM_MSG_MEMBER(msg, i, msg))) != 0)
451 fatal("%s: buffer error: %s",
452 __func__, ssh_err(r));
453 if (ssh_msg_send(ctxt->pam_csock,
454 PAM_MSG_MEMBER(msg, i, msg_style), buffer) == -1)
460 sshbuf_reset(buffer);
464 return (PAM_SUCCESS);
467 for(i = 0; i < n; i++) {
472 return (PAM_CONV_ERR);
476 * Authentication thread.
479 sshpam_thread(void *ctxtp)
481 struct pam_ctxt *ctxt = ctxtp;
482 struct sshbuf *buffer = NULL;
483 struct pam_conv sshpam_conv;
484 int r, flags = (options.permit_empty_passwd == 0 ?
485 PAM_DISALLOW_NULL_AUTHTOK : 0);
486 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
487 extern char **environ;
490 const char *pam_user;
491 const char **ptr_pam_user = &pam_user;
492 char *tz = getenv("TZ");
494 sshpam_err = pam_get_item(sshpam_handle, PAM_USER,
495 (sshpam_const void **)ptr_pam_user);
496 if (sshpam_err != PAM_SUCCESS)
501 if (setenv("TZ", tz, 1) == -1)
502 error("PAM: could not set TZ environment: %s",
505 if (sshpam_authctxt != NULL) {
506 setproctitle("%s [pam]",
507 sshpam_authctxt->valid ? pam_user : "unknown");
511 sshpam_conv.conv = sshpam_thread_conv;
512 sshpam_conv.appdata_ptr = ctxt;
514 if (sshpam_authctxt == NULL)
515 fatal("%s: PAM authctxt not initialized", __func__);
517 if ((buffer = sshbuf_new()) == NULL)
518 fatal("%s: sshbuf_new failed", __func__);
520 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
521 (const void *)&sshpam_conv);
522 if (sshpam_err != PAM_SUCCESS)
524 sshpam_err = pam_authenticate(sshpam_handle, flags);
525 if (sshpam_err == PAM_MAXTRIES)
526 sshpam_set_maxtries_reached(1);
527 if (sshpam_err != PAM_SUCCESS)
530 if (!do_pam_account()) {
531 sshpam_err = PAM_ACCT_EXPIRED;
534 if (sshpam_authctxt->force_pwchange) {
535 sshpam_err = pam_chauthtok(sshpam_handle,
536 PAM_CHANGE_EXPIRED_AUTHTOK);
537 if (sshpam_err != PAM_SUCCESS)
539 sshpam_password_change_required(0);
542 if ((r = sshbuf_put_cstring(buffer, "OK")) != 0)
543 fatal("%s: buffer error: %s", __func__, ssh_err(r));
545 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
546 /* Export variables set by do_pam_account */
547 if ((r = sshbuf_put_u32(buffer, sshpam_account_status)) != 0 ||
548 (r = sshbuf_put_u32(buffer, sshpam_authctxt->force_pwchange)) != 0)
549 fatal("%s: buffer error: %s", __func__, ssh_err(r));
551 /* Export any environment strings set in child */
552 for (i = 0; environ[i] != NULL; i++) {
555 fatal("%s: too many environment strings", __func__);
557 if ((r = sshbuf_put_u32(buffer, i)) != 0)
558 fatal("%s: buffer error: %s", __func__, ssh_err(r));
559 for (i = 0; environ[i] != NULL; i++) {
560 if ((r = sshbuf_put_cstring(buffer, environ[i])) != 0)
561 fatal("%s: buffer error: %s", __func__, ssh_err(r));
563 /* Export any environment strings set by PAM in child */
564 env_from_pam = pam_getenvlist(sshpam_handle);
565 for (i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++) {
568 fatal("%s: too many PAM environment strings", __func__);
570 if ((r = sshbuf_put_u32(buffer, i)) != 0)
571 fatal("%s: buffer error: %s", __func__, ssh_err(r));
572 for (i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++) {
573 if ((r = sshbuf_put_cstring(buffer, env_from_pam[i])) != 0)
574 fatal("%s: buffer error: %s", __func__, ssh_err(r));
576 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
578 /* XXX - can't do much about an error here */
579 ssh_msg_send(ctxt->pam_csock, sshpam_err, buffer);
584 if ((r = sshbuf_put_cstring(buffer,
585 pam_strerror(sshpam_handle, sshpam_err))) != 0)
586 fatal("%s: buffer error: %s", __func__, ssh_err(r));
587 /* XXX - can't do much about an error here */
588 if (sshpam_err == PAM_ACCT_EXPIRED)
589 ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, buffer);
590 else if (sshpam_maxtries_reached)
591 ssh_msg_send(ctxt->pam_csock, PAM_MAXTRIES, buffer);
593 ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, buffer);
597 return (NULL); /* Avoid warning for non-pthread case */
601 sshpam_thread_cleanup(void)
603 struct pam_ctxt *ctxt = cleanup_ctxt;
605 debug3("PAM: %s entering", __func__);
606 if (ctxt != NULL && ctxt->pam_thread != 0) {
607 pthread_cancel(ctxt->pam_thread);
608 pthread_join(ctxt->pam_thread, NULL);
609 close(ctxt->pam_psock);
610 close(ctxt->pam_csock);
611 memset(ctxt, 0, sizeof(*ctxt));
617 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
618 struct pam_response **resp, void *data)
620 debug3("PAM: %s entering, %d messages", __func__, n);
621 return (PAM_CONV_ERR);
624 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
627 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
628 struct pam_response **resp, void *data)
630 struct pam_response *reply;
633 debug3("PAM: %s called with %d messages", __func__, n);
636 if (n <= 0 || n > PAM_MAX_NUM_MSG)
637 return (PAM_CONV_ERR);
639 if ((reply = calloc(n, sizeof(*reply))) == NULL)
640 return (PAM_CONV_ERR);
642 for (i = 0; i < n; ++i) {
643 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
646 if ((r = sshbuf_putf(loginmsg, "%s\n",
647 PAM_MSG_MEMBER(msg, i, msg))) != 0)
648 fatal("%s: buffer error: %s",
649 __func__, ssh_err(r));
650 reply[i].resp_retcode = PAM_SUCCESS;
657 return (PAM_SUCCESS);
660 for(i = 0; i < n; i++) {
664 return (PAM_CONV_ERR);
667 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
672 if (sshpam_handle == NULL || (use_privsep && !mm_is_monitor()))
674 debug("PAM: cleanup");
675 pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
676 if (sshpam_session_open) {
677 debug("PAM: closing session");
678 pam_close_session(sshpam_handle, PAM_SILENT);
679 sshpam_session_open = 0;
681 if (sshpam_cred_established) {
682 debug("PAM: deleting credentials");
683 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
684 sshpam_cred_established = 0;
686 sshpam_authenticated = 0;
687 pam_end(sshpam_handle, sshpam_err);
688 sshpam_handle = NULL;
692 sshpam_init(struct ssh *ssh, Authctxt *authctxt)
694 const char *pam_user, *user = authctxt->user;
695 const char **ptr_pam_user = &pam_user;
698 #if defined(PAM_SUN_CODEBASE) && defined(PAM_MAX_RESP_SIZE)
699 /* Protect buggy PAM implementations from excessively long usernames */
700 if (strlen(user) >= PAM_MAX_RESP_SIZE)
701 fatal("Username too long from %s port %d",
702 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
704 if (sshpam_handle == NULL) {
706 fatal("%s: called initially with no "
707 "packet context", __func__);
709 } if (sshpam_handle != NULL) {
710 /* We already have a PAM context; check if the user matches */
711 sshpam_err = pam_get_item(sshpam_handle,
712 PAM_USER, (sshpam_const void **)ptr_pam_user);
713 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
715 pam_end(sshpam_handle, sshpam_err);
716 sshpam_handle = NULL;
718 debug("PAM: initializing for \"%s\"", user);
720 pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
721 sshpam_authctxt = authctxt;
723 if (sshpam_err != PAM_SUCCESS) {
724 pam_end(sshpam_handle, sshpam_err);
725 sshpam_handle = NULL;
729 if (ssh != NULL && sshpam_rhost == NULL) {
731 * We need to cache these as we don't have packet context
732 * during the kbdint flow.
734 sshpam_rhost = xstrdup(auth_get_canonical_hostname(ssh,
736 sshpam_laddr = get_local_ipaddr(
737 ssh_packet_get_connection_in(ssh));
739 if (sshpam_rhost != NULL) {
740 debug("PAM: setting PAM_RHOST to \"%s\"", sshpam_rhost);
741 sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST,
743 if (sshpam_err != PAM_SUCCESS) {
744 pam_end(sshpam_handle, sshpam_err);
745 sshpam_handle = NULL;
749 if (ssh != NULL && sshpam_laddr != NULL) {
752 /* Put SSH_CONNECTION in the PAM environment too */
753 xasprintf(&conninfo, "SSH_CONNECTION=%.50s %d %.50s %d",
754 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
755 sshpam_laddr, ssh_local_port(ssh));
756 if ((r = pam_putenv(sshpam_handle, conninfo)) != PAM_SUCCESS)
757 logit("pam_putenv: %s", pam_strerror(sshpam_handle, r));
761 #ifdef PAM_TTY_KLUDGE
763 * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
764 * sshd doesn't set the tty until too late in the auth process and
765 * may not even set one (for tty-less connections)
767 debug("PAM: setting PAM_TTY to \"ssh\"");
768 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
769 if (sshpam_err != PAM_SUCCESS) {
770 pam_end(sshpam_handle, sshpam_err);
771 sshpam_handle = NULL;
779 expose_authinfo(const char *caller)
784 * Expose authentication information to PAM.
785 * The environment variable is versioned. Please increment the
786 * version suffix if the format of session_info changes.
788 if (sshpam_authctxt->session_info == NULL)
789 auth_info = xstrdup("");
790 else if ((auth_info = sshbuf_dup_string(
791 sshpam_authctxt->session_info)) == NULL)
792 fatal("%s: sshbuf_dup_string failed", __func__);
794 debug2("%s: auth information in SSH_AUTH_INFO_0", caller);
795 do_pam_putenv("SSH_AUTH_INFO_0", auth_info);
800 sshpam_init_ctx(Authctxt *authctxt)
802 struct pam_ctxt *ctxt;
803 int result, socks[2];
805 debug3("PAM: %s entering", __func__);
807 * Refuse to start if we don't have PAM enabled or do_pam_account
808 * has previously failed.
810 if (!options.use_pam || sshpam_account_status == 0)
814 if (sshpam_init(NULL, authctxt) == -1) {
815 error("PAM: initialization failed");
819 expose_authinfo(__func__);
820 ctxt = xcalloc(1, sizeof *ctxt);
822 /* Start the authentication thread */
823 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
824 error("PAM: failed create sockets: %s", strerror(errno));
828 ctxt->pam_psock = socks[0];
829 ctxt->pam_csock = socks[1];
830 result = pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt);
832 error("PAM: failed to start authentication thread: %s",
844 sshpam_query(void *ctx, char **name, char **info,
845 u_int *num, char ***prompts, u_int **echo_on)
847 struct sshbuf *buffer;
848 struct pam_ctxt *ctxt = ctx;
852 size_t len, mlen, nmesg = 0;
855 debug3("PAM: %s entering", __func__);
856 if ((buffer = sshbuf_new()) == NULL)
857 fatal("%s: sshbuf_new failed", __func__);
860 *prompts = xmalloc(sizeof(char *));
863 *echo_on = xmalloc(sizeof(u_int));
864 while (ssh_msg_recv(ctxt->pam_psock, buffer) == 0) {
865 if (++nmesg > PAM_MAX_NUM_MSG)
866 fatal_f("too many query messages");
867 if ((r = sshbuf_get_u8(buffer, &type)) != 0 ||
868 (r = sshbuf_get_cstring(buffer, &msg, &mlen)) != 0)
869 fatal("%s: buffer error: %s", __func__, ssh_err(r));
871 case PAM_PROMPT_ECHO_ON:
872 case PAM_PROMPT_ECHO_OFF:
874 len = plen + mlen + 1;
875 **prompts = xreallocarray(**prompts, 1, len);
876 strlcpy(**prompts + plen, msg, len - plen);
878 **echo_on = (type == PAM_PROMPT_ECHO_ON);
884 /* accumulate messages */
885 len = plen + mlen + 2;
886 **prompts = xreallocarray(**prompts, 1, len);
887 strlcpy(**prompts + plen, msg, len - plen);
889 strlcat(**prompts + plen, "\n", len - plen);
893 case PAM_ACCT_EXPIRED:
895 if (type == PAM_ACCT_EXPIRED)
896 sshpam_account_status = 0;
897 if (type == PAM_MAXTRIES)
898 sshpam_set_maxtries_reached(1);
901 debug3("PAM: %s", pam_strerror(sshpam_handle, type));
902 if (**prompts != NULL && strlen(**prompts) != 0) {
915 if (**prompts != NULL) {
916 /* drain any accumulated messages */
917 debug("PAM: %s", **prompts);
918 if ((r = sshbuf_put(loginmsg, **prompts,
919 strlen(**prompts))) != 0)
920 fatal("%s: buffer error: %s",
921 __func__, ssh_err(r));
925 if (type == PAM_SUCCESS) {
926 if (!sshpam_authctxt->valid ||
927 (sshpam_authctxt->pw->pw_uid == 0 &&
928 options.permit_root_login != PERMIT_YES))
929 fatal("Internal error: PAM auth "
930 "succeeded when it should have "
932 import_environments(buffer);
940 BLACKLIST_NOTIFY(NULL, BLACKLIST_BAD_USER,
941 sshpam_authctxt->user);
942 error("PAM: %s for %s%.100s from %.100s", msg,
943 sshpam_authctxt->valid ? "" : "illegal user ",
944 sshpam_authctxt->user, sshpam_rhost);
960 * Returns a junk password of identical length to that the user supplied.
961 * Used to mitigate timing attacks against crypt(3)/PAM stacks that
962 * vary processing time in proportion to password length.
965 fake_password(const char *wire_password)
967 const char junk[] = "\b\n\r\177INCORRECT";
969 size_t i, l = wire_password != NULL ? strlen(wire_password) : 0;
972 fatal("%s: password length too long: %zu", __func__, l);
977 for (i = 0; i < l; i++)
978 ret[i] = junk[i % (sizeof(junk) - 1)];
983 /* XXX - see also comment in auth-chall.c:verify_response */
985 sshpam_respond(void *ctx, u_int num, char **resp)
987 struct sshbuf *buffer;
988 struct pam_ctxt *ctxt = ctx;
992 debug2("PAM: %s entering, %u responses", __func__, num);
993 switch (ctxt->pam_done) {
995 sshpam_authenticated = 1;
1003 error("PAM: expected one response, got %u", num);
1006 if ((buffer = sshbuf_new()) == NULL)
1007 fatal("%s: sshbuf_new failed", __func__);
1008 if (sshpam_authctxt->valid &&
1009 (sshpam_authctxt->pw->pw_uid != 0 ||
1010 options.permit_root_login == PERMIT_YES)) {
1011 if ((r = sshbuf_put_cstring(buffer, *resp)) != 0)
1012 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1014 fake = fake_password(*resp);
1015 if ((r = sshbuf_put_cstring(buffer, fake)) != 0)
1016 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1019 if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, buffer) == -1) {
1020 sshbuf_free(buffer);
1023 sshbuf_free(buffer);
1028 sshpam_free_ctx(void *ctxtp)
1030 struct pam_ctxt *ctxt = ctxtp;
1032 debug3("PAM: %s entering", __func__);
1033 sshpam_thread_cleanup();
1036 * We don't call sshpam_cleanup() here because we may need the PAM
1037 * handle at a later stage, e.g. when setting up a session. It's
1038 * still on the cleanup list, so pam_end() *will* be called before
1039 * the server process terminates.
1043 KbdintDevice sshpam_device = {
1051 KbdintDevice mm_sshpam_device = {
1060 * This replaces auth-pam.c
1063 start_pam(struct ssh *ssh)
1065 Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1067 if (!options.use_pam)
1068 fatal("PAM: initialisation requested when UsePAM=no");
1070 if (sshpam_init(ssh, authctxt) == -1)
1071 fatal("PAM: initialisation failed");
1082 do_pam_account(void)
1084 debug("%s: called", __func__);
1085 if (sshpam_account_status != -1)
1086 return (sshpam_account_status);
1088 expose_authinfo(__func__);
1090 sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
1091 debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
1092 pam_strerror(sshpam_handle, sshpam_err));
1094 if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
1095 sshpam_account_status = 0;
1096 return (sshpam_account_status);
1099 if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
1100 sshpam_password_change_required(1);
1102 sshpam_account_status = 1;
1103 return (sshpam_account_status);
1107 do_pam_setcred(int init)
1109 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1110 (const void *)&store_conv);
1111 if (sshpam_err != PAM_SUCCESS)
1112 fatal("PAM: failed to set PAM_CONV: %s",
1113 pam_strerror(sshpam_handle, sshpam_err));
1115 debug("PAM: establishing credentials");
1116 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
1118 debug("PAM: reinitializing credentials");
1119 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
1121 if (sshpam_err == PAM_SUCCESS) {
1122 sshpam_cred_established = 1;
1125 if (sshpam_authenticated)
1126 fatal("PAM: pam_setcred(): %s",
1127 pam_strerror(sshpam_handle, sshpam_err));
1129 debug("PAM: pam_setcred(): %s",
1130 pam_strerror(sshpam_handle, sshpam_err));
1134 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
1135 struct pam_response **resp, void *data)
1137 char input[PAM_MAX_MSG_SIZE];
1138 struct pam_response *reply;
1141 debug3("PAM: %s called with %d messages", __func__, n);
1145 if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
1146 return (PAM_CONV_ERR);
1148 if ((reply = calloc(n, sizeof(*reply))) == NULL)
1149 return (PAM_CONV_ERR);
1151 for (i = 0; i < n; ++i) {
1152 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1153 case PAM_PROMPT_ECHO_OFF:
1155 read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
1157 reply[i].resp_retcode = PAM_SUCCESS;
1159 case PAM_PROMPT_ECHO_ON:
1160 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1161 if (fgets(input, sizeof input, stdin) == NULL)
1163 if ((reply[i].resp = strdup(input)) == NULL)
1165 reply[i].resp_retcode = PAM_SUCCESS;
1169 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1170 reply[i].resp_retcode = PAM_SUCCESS;
1177 return (PAM_SUCCESS);
1180 for(i = 0; i < n; i++) {
1181 free(reply[i].resp);
1184 return (PAM_CONV_ERR);
1187 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
1190 * XXX this should be done in the authentication phase, but ssh1 doesn't
1194 do_pam_chauthtok(void)
1197 fatal("Password expired (unable to change with privsep)");
1198 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1199 (const void *)&tty_conv);
1200 if (sshpam_err != PAM_SUCCESS)
1201 fatal("PAM: failed to set PAM_CONV: %s",
1202 pam_strerror(sshpam_handle, sshpam_err));
1203 debug("PAM: changing password");
1204 sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1205 if (sshpam_err != PAM_SUCCESS)
1206 fatal("PAM: pam_chauthtok(): %s",
1207 pam_strerror(sshpam_handle, sshpam_err));
1211 do_pam_session(struct ssh *ssh)
1213 debug3("PAM: opening session");
1215 expose_authinfo(__func__);
1217 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1218 (const void *)&store_conv);
1219 if (sshpam_err != PAM_SUCCESS)
1220 fatal("PAM: failed to set PAM_CONV: %s",
1221 pam_strerror(sshpam_handle, sshpam_err));
1222 sshpam_err = pam_open_session(sshpam_handle, 0);
1223 if (sshpam_err == PAM_SUCCESS)
1224 sshpam_session_open = 1;
1226 sshpam_session_open = 0;
1227 auth_restrict_session(ssh);
1228 error("PAM: pam_open_session(): %s",
1229 pam_strerror(sshpam_handle, sshpam_err));
1235 is_pam_session_open(void)
1237 return sshpam_session_open;
1241 * Set a PAM environment string. We need to do this so that the session
1242 * modules can handle things like Kerberos/GSI credentials that appear
1243 * during the ssh authentication process.
1246 do_pam_putenv(char *name, char *value)
1252 len = strlen(name) + strlen(value) + 2;
1253 compound = xmalloc(len);
1255 snprintf(compound, len, "%s=%s", name, value);
1256 ret = pam_putenv(sshpam_handle, compound);
1263 fetch_pam_child_environment(void)
1269 fetch_pam_environment(void)
1271 return (pam_getenvlist(sshpam_handle));
1275 free_pam_environment(char **env)
1282 for (envp = env; *envp; envp++)
1288 * "Blind" conversation function for password authentication. Assumes that
1289 * echo-off prompts are for the password and stores messages for later
1293 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1294 struct pam_response **resp, void *data)
1296 struct pam_response *reply;
1300 debug3("PAM: %s called with %d messages", __func__, n);
1304 if (n <= 0 || n > PAM_MAX_NUM_MSG)
1305 return (PAM_CONV_ERR);
1307 if ((reply = calloc(n, sizeof(*reply))) == NULL)
1308 return (PAM_CONV_ERR);
1310 for (i = 0; i < n; ++i) {
1311 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1312 case PAM_PROMPT_ECHO_OFF:
1313 if (sshpam_password == NULL)
1315 if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1317 reply[i].resp_retcode = PAM_SUCCESS;
1321 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1323 if ((r = sshbuf_putf(loginmsg, "%s\n",
1324 PAM_MSG_MEMBER(msg, i, msg))) != 0)
1325 fatal("%s: buffer error: %s",
1326 __func__, ssh_err(r));
1328 if ((reply[i].resp = strdup("")) == NULL)
1330 reply[i].resp_retcode = PAM_SUCCESS;
1337 return (PAM_SUCCESS);
1340 for(i = 0; i < n; i++) {
1341 free(reply[i].resp);
1344 return (PAM_CONV_ERR);
1347 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1350 * Attempt password authentication via PAM
1353 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1355 int flags = (options.permit_empty_passwd == 0 ?
1356 PAM_DISALLOW_NULL_AUTHTOK : 0);
1359 if (!options.use_pam || sshpam_handle == NULL)
1360 fatal("PAM: %s called when PAM disabled or failed to "
1361 "initialise.", __func__);
1363 sshpam_password = password;
1364 sshpam_authctxt = authctxt;
1367 * If the user logging in is invalid, or is root but is not permitted
1368 * by PermitRootLogin, use an invalid password to prevent leaking
1369 * information via timing (eg if the PAM config has a delay on fail).
1371 if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1372 options.permit_root_login != PERMIT_YES))
1373 sshpam_password = fake = fake_password(password);
1375 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1376 (const void *)&passwd_conv);
1377 if (sshpam_err != PAM_SUCCESS)
1378 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1379 pam_strerror(sshpam_handle, sshpam_err));
1381 sshpam_err = pam_authenticate(sshpam_handle, flags);
1382 sshpam_password = NULL;
1384 if (sshpam_err == PAM_MAXTRIES)
1385 sshpam_set_maxtries_reached(1);
1386 if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1387 debug("PAM: password authentication accepted for %.100s",
1391 debug("PAM: password authentication failed for %.100s: %s",
1392 authctxt->valid ? authctxt->user : "an illegal user",
1393 pam_strerror(sshpam_handle, sshpam_err));
1399 sshpam_get_maxtries_reached(void)
1401 return sshpam_maxtries_reached;
1405 sshpam_set_maxtries_reached(int reached)
1407 if (reached == 0 || sshpam_maxtries_reached)
1409 sshpam_maxtries_reached = 1;
1410 options.password_authentication = 0;
1411 options.kbd_interactive_authentication = 0;
1413 #endif /* USE_PAM */