sdhci - Implement ADMA2 transfer support. Keep SDMA support for now.
[dragonfly.git] / crypto / openssh / auth-pam.c
blobda7aa31e4b9339571b302e8686ab9f67068a2978
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 */
50 #include "includes.h"
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <sys/wait.h>
56 #include <errno.h>
57 #include <signal.h>
58 #include <stdarg.h>
59 #include <string.h>
60 #include <unistd.h>
62 #ifdef USE_PAM
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>
67 #endif
69 /* OpenGroup RFC86.0 and XSSO specify no "const" on arguments */
70 #ifdef PAM_SUN_CODEBASE
71 # define sshpam_const /* Solaris, HP-UX, SunOS */
72 #else
73 # define sshpam_const const /* LinuxPAM, OpenPAM, AIX */
74 #endif
76 /* Ambiguity in spec: is it an array of pointers or a pointer to an array? */
77 #ifdef PAM_SUN_CODEBASE
78 # define PAM_MSG_MEMBER(msg, n, member) ((*(msg))[(n)].member)
79 #else
80 # define PAM_MSG_MEMBER(msg, n, member) ((msg)[(n)]->member)
81 #endif
83 #include "xmalloc.h"
84 #include "buffer.h"
85 #include "key.h"
86 #include "hostfile.h"
87 #include "auth.h"
88 #include "auth-pam.h"
89 #include "canohost.h"
90 #include "log.h"
91 #include "msg.h"
92 #include "packet.h"
93 #include "misc.h"
94 #include "servconf.h"
95 #include "ssh2.h"
96 #include "auth-options.h"
97 #ifdef GSSAPI
98 #include "ssh-gss.h"
99 #endif
100 #include "monitor_wrap.h"
102 extern ServerOptions options;
103 extern Buffer loginmsg;
104 extern int compat20;
105 extern u_int utmp_len;
107 /* so we don't silently change behaviour */
108 #ifdef USE_POSIX_THREADS
109 # error "USE_POSIX_THREADS replaced by UNSUPPORTED_POSIX_THREADS_HACK"
110 #endif
113 * Formerly known as USE_POSIX_THREADS, using this is completely unsupported
114 * and generally a bad idea. Use at own risk and do not expect support if
115 * this breaks.
117 #ifdef UNSUPPORTED_POSIX_THREADS_HACK
118 #include <pthread.h>
120 * Avoid namespace clash when *not* using pthreads for systems *with*
121 * pthreads, which unconditionally define pthread_t via sys/types.h
122 * (e.g. Linux)
124 typedef pthread_t sp_pthread_t;
125 #else
126 typedef pid_t sp_pthread_t;
127 #endif
129 struct pam_ctxt {
130 sp_pthread_t pam_thread;
131 int pam_psock;
132 int pam_csock;
133 int pam_done;
136 static void sshpam_free_ctx(void *);
137 static struct pam_ctxt *cleanup_ctxt;
139 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
141 * Simulate threads with processes.
144 static int sshpam_thread_status = -1;
145 static mysig_t sshpam_oldsig;
147 static void
148 sshpam_sigchld_handler(int sig)
150 signal(SIGCHLD, SIG_DFL);
151 if (cleanup_ctxt == NULL)
152 return; /* handler called after PAM cleanup, shouldn't happen */
153 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, WNOHANG)
154 <= 0) {
155 /* PAM thread has not exitted, privsep slave must have */
156 kill(cleanup_ctxt->pam_thread, SIGTERM);
157 while (waitpid(cleanup_ctxt->pam_thread,
158 &sshpam_thread_status, 0) == -1) {
159 if (errno == EINTR)
160 continue;
161 return;
164 if (WIFSIGNALED(sshpam_thread_status) &&
165 WTERMSIG(sshpam_thread_status) == SIGTERM)
166 return; /* terminated by pthread_cancel */
167 if (!WIFEXITED(sshpam_thread_status))
168 sigdie("PAM: authentication thread exited unexpectedly");
169 if (WEXITSTATUS(sshpam_thread_status) != 0)
170 sigdie("PAM: authentication thread exited uncleanly");
173 /* ARGSUSED */
174 static void
175 pthread_exit(void *value)
177 _exit(0);
180 /* ARGSUSED */
181 static int
182 pthread_create(sp_pthread_t *thread, const void *attr,
183 void *(*thread_start)(void *), void *arg)
185 pid_t pid;
186 struct pam_ctxt *ctx = arg;
188 sshpam_thread_status = -1;
189 switch ((pid = fork())) {
190 case -1:
191 error("fork(): %s", strerror(errno));
192 return (-1);
193 case 0:
194 close(ctx->pam_psock);
195 ctx->pam_psock = -1;
196 thread_start(arg);
197 _exit(1);
198 default:
199 *thread = pid;
200 close(ctx->pam_csock);
201 ctx->pam_csock = -1;
202 sshpam_oldsig = signal(SIGCHLD, sshpam_sigchld_handler);
203 return (0);
207 static int
208 pthread_cancel(sp_pthread_t thread)
210 signal(SIGCHLD, sshpam_oldsig);
211 return (kill(thread, SIGTERM));
214 /* ARGSUSED */
215 static int
216 pthread_join(sp_pthread_t thread, void **value)
218 int status;
220 if (sshpam_thread_status != -1)
221 return (sshpam_thread_status);
222 signal(SIGCHLD, sshpam_oldsig);
223 while (waitpid(thread, &status, 0) == -1) {
224 if (errno == EINTR)
225 continue;
226 fatal("%s: waitpid: %s", __func__, strerror(errno));
228 return (status);
230 #endif
233 static pam_handle_t *sshpam_handle = NULL;
234 static int sshpam_err = 0;
235 static int sshpam_authenticated = 0;
236 static int sshpam_session_open = 0;
237 static int sshpam_cred_established = 0;
238 static int sshpam_account_status = -1;
239 static int sshpam_maxtries_reached = 0;
240 static char **sshpam_env = NULL;
241 static Authctxt *sshpam_authctxt = NULL;
242 static const char *sshpam_password = NULL;
244 /* Some PAM implementations don't implement this */
245 #ifndef HAVE_PAM_GETENVLIST
246 static char **
247 pam_getenvlist(pam_handle_t *pamh)
250 * XXX - If necessary, we can still support envrionment passing
251 * for platforms without pam_getenvlist by searching for known
252 * env vars (e.g. KRB5CCNAME) from the PAM environment.
254 return NULL;
256 #endif
259 * Some platforms, notably Solaris, do not enforce password complexity
260 * rules during pam_chauthtok() if the real uid of the calling process
261 * is 0, on the assumption that it's being called by "passwd" run by root.
262 * This wraps pam_chauthtok and sets/restore the real uid so PAM will do
263 * the right thing.
265 #ifdef SSHPAM_CHAUTHTOK_NEEDS_RUID
266 static int
267 sshpam_chauthtok_ruid(pam_handle_t *pamh, int flags)
269 int result;
271 if (sshpam_authctxt == NULL)
272 fatal("PAM: sshpam_authctxt not initialized");
273 if (setreuid(sshpam_authctxt->pw->pw_uid, -1) == -1)
274 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
275 result = pam_chauthtok(pamh, flags);
276 if (setreuid(0, -1) == -1)
277 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
278 return result;
280 # define pam_chauthtok(a,b) (sshpam_chauthtok_ruid((a), (b)))
281 #endif
283 static void
284 sshpam_password_change_required(int reqd)
286 debug3("%s %d", __func__, reqd);
287 if (sshpam_authctxt == NULL)
288 fatal("%s: PAM authctxt not initialized", __func__);
289 sshpam_authctxt->force_pwchange = reqd;
290 if (reqd) {
291 no_port_forwarding_flag |= 2;
292 no_agent_forwarding_flag |= 2;
293 no_x11_forwarding_flag |= 2;
294 } else {
295 no_port_forwarding_flag &= ~2;
296 no_agent_forwarding_flag &= ~2;
297 no_x11_forwarding_flag &= ~2;
301 /* Import regular and PAM environment from subprocess */
302 static void
303 import_environments(Buffer *b)
305 char *env;
306 u_int i, num_env;
307 int err;
309 debug3("PAM: %s entering", __func__);
311 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
312 /* Import variables set by do_pam_account */
313 sshpam_account_status = buffer_get_int(b);
314 sshpam_password_change_required(buffer_get_int(b));
316 /* Import environment from subprocess */
317 num_env = buffer_get_int(b);
318 if (num_env > 1024)
319 fatal("%s: received %u environment variables, expected <= 1024",
320 __func__, num_env);
321 sshpam_env = xcalloc(num_env + 1, sizeof(*sshpam_env));
322 debug3("PAM: num env strings %d", num_env);
323 for(i = 0; i < num_env; i++)
324 sshpam_env[i] = buffer_get_string(b, NULL);
326 sshpam_env[num_env] = NULL;
328 /* Import PAM environment from subprocess */
329 num_env = buffer_get_int(b);
330 debug("PAM: num PAM env strings %d", num_env);
331 for(i = 0; i < num_env; i++) {
332 env = buffer_get_string(b, NULL);
334 #ifdef HAVE_PAM_PUTENV
335 /* Errors are not fatal here */
336 if ((err = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
337 error("PAM: pam_putenv: %s",
338 pam_strerror(sshpam_handle, sshpam_err));
340 #endif
342 #endif
346 * Conversation function for authentication thread.
348 static int
349 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
350 struct pam_response **resp, void *data)
352 Buffer buffer;
353 struct pam_ctxt *ctxt;
354 struct pam_response *reply;
355 int i;
357 debug3("PAM: %s entering, %d messages", __func__, n);
358 *resp = NULL;
360 if (data == NULL) {
361 error("PAM: conversation function passed a null context");
362 return (PAM_CONV_ERR);
364 ctxt = data;
365 if (n <= 0 || n > PAM_MAX_NUM_MSG)
366 return (PAM_CONV_ERR);
368 if ((reply = calloc(n, sizeof(*reply))) == NULL)
369 return (PAM_CONV_ERR);
371 buffer_init(&buffer);
372 for (i = 0; i < n; ++i) {
373 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
374 case PAM_PROMPT_ECHO_OFF:
375 case PAM_PROMPT_ECHO_ON:
376 buffer_put_cstring(&buffer,
377 PAM_MSG_MEMBER(msg, i, msg));
378 if (ssh_msg_send(ctxt->pam_csock,
379 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
380 goto fail;
381 if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
382 goto fail;
383 if (buffer_get_char(&buffer) != PAM_AUTHTOK)
384 goto fail;
385 reply[i].resp = buffer_get_string(&buffer, NULL);
386 break;
387 case PAM_ERROR_MSG:
388 case PAM_TEXT_INFO:
389 buffer_put_cstring(&buffer,
390 PAM_MSG_MEMBER(msg, i, msg));
391 if (ssh_msg_send(ctxt->pam_csock,
392 PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
393 goto fail;
394 break;
395 default:
396 goto fail;
398 buffer_clear(&buffer);
400 buffer_free(&buffer);
401 *resp = reply;
402 return (PAM_SUCCESS);
404 fail:
405 for(i = 0; i < n; i++) {
406 free(reply[i].resp);
408 free(reply);
409 buffer_free(&buffer);
410 return (PAM_CONV_ERR);
414 * Authentication thread.
416 static void *
417 sshpam_thread(void *ctxtp)
419 struct pam_ctxt *ctxt = ctxtp;
420 Buffer buffer;
421 struct pam_conv sshpam_conv;
422 int flags = (options.permit_empty_passwd == 0 ?
423 PAM_DISALLOW_NULL_AUTHTOK : 0);
424 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
425 extern char **environ;
426 char **env_from_pam;
427 u_int i;
428 const char *pam_user;
429 const char **ptr_pam_user = &pam_user;
430 char *tz = getenv("TZ");
432 sshpam_err = pam_get_item(sshpam_handle, PAM_USER,
433 (sshpam_const void **)ptr_pam_user);
434 if (sshpam_err != PAM_SUCCESS)
435 goto auth_fail;
437 environ[0] = NULL;
438 if (tz != NULL)
439 if (setenv("TZ", tz, 1) == -1)
440 error("PAM: could not set TZ environment: %s",
441 strerror(errno));
443 if (sshpam_authctxt != NULL) {
444 setproctitle("%s [pam]",
445 sshpam_authctxt->valid ? pam_user : "unknown");
447 #endif
449 sshpam_conv.conv = sshpam_thread_conv;
450 sshpam_conv.appdata_ptr = ctxt;
452 if (sshpam_authctxt == NULL)
453 fatal("%s: PAM authctxt not initialized", __func__);
455 buffer_init(&buffer);
456 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
457 (const void *)&sshpam_conv);
458 if (sshpam_err != PAM_SUCCESS)
459 goto auth_fail;
460 sshpam_err = pam_authenticate(sshpam_handle, flags);
461 if (sshpam_err == PAM_MAXTRIES)
462 sshpam_set_maxtries_reached(1);
463 if (sshpam_err != PAM_SUCCESS)
464 goto auth_fail;
466 if (compat20) {
467 if (!do_pam_account()) {
468 sshpam_err = PAM_ACCT_EXPIRED;
469 goto auth_fail;
471 if (sshpam_authctxt->force_pwchange) {
472 sshpam_err = pam_chauthtok(sshpam_handle,
473 PAM_CHANGE_EXPIRED_AUTHTOK);
474 if (sshpam_err != PAM_SUCCESS)
475 goto auth_fail;
476 sshpam_password_change_required(0);
480 buffer_put_cstring(&buffer, "OK");
482 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
483 /* Export variables set by do_pam_account */
484 buffer_put_int(&buffer, sshpam_account_status);
485 buffer_put_int(&buffer, sshpam_authctxt->force_pwchange);
487 /* Export any environment strings set in child */
488 for(i = 0; environ[i] != NULL; i++)
489 ; /* Count */
490 buffer_put_int(&buffer, i);
491 for(i = 0; environ[i] != NULL; i++)
492 buffer_put_cstring(&buffer, environ[i]);
494 /* Export any environment strings set by PAM in child */
495 env_from_pam = pam_getenvlist(sshpam_handle);
496 for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
497 ; /* Count */
498 buffer_put_int(&buffer, i);
499 for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
500 buffer_put_cstring(&buffer, env_from_pam[i]);
501 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
503 /* XXX - can't do much about an error here */
504 ssh_msg_send(ctxt->pam_csock, sshpam_err, &buffer);
505 buffer_free(&buffer);
506 pthread_exit(NULL);
508 auth_fail:
509 buffer_put_cstring(&buffer,
510 pam_strerror(sshpam_handle, sshpam_err));
511 /* XXX - can't do much about an error here */
512 if (sshpam_err == PAM_ACCT_EXPIRED)
513 ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, &buffer);
514 else if (sshpam_maxtries_reached)
515 ssh_msg_send(ctxt->pam_csock, PAM_MAXTRIES, &buffer);
516 else
517 ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
518 buffer_free(&buffer);
519 pthread_exit(NULL);
521 return (NULL); /* Avoid warning for non-pthread case */
524 void
525 sshpam_thread_cleanup(void)
527 struct pam_ctxt *ctxt = cleanup_ctxt;
529 debug3("PAM: %s entering", __func__);
530 if (ctxt != NULL && ctxt->pam_thread != 0) {
531 pthread_cancel(ctxt->pam_thread);
532 pthread_join(ctxt->pam_thread, NULL);
533 close(ctxt->pam_psock);
534 close(ctxt->pam_csock);
535 memset(ctxt, 0, sizeof(*ctxt));
536 cleanup_ctxt = NULL;
540 static int
541 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
542 struct pam_response **resp, void *data)
544 debug3("PAM: %s entering, %d messages", __func__, n);
545 return (PAM_CONV_ERR);
548 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
550 static int
551 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
552 struct pam_response **resp, void *data)
554 struct pam_response *reply;
555 int i;
556 size_t len;
558 debug3("PAM: %s called with %d messages", __func__, n);
559 *resp = NULL;
561 if (n <= 0 || n > PAM_MAX_NUM_MSG)
562 return (PAM_CONV_ERR);
564 if ((reply = calloc(n, sizeof(*reply))) == NULL)
565 return (PAM_CONV_ERR);
567 for (i = 0; i < n; ++i) {
568 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
569 case PAM_ERROR_MSG:
570 case PAM_TEXT_INFO:
571 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
572 buffer_append(&loginmsg, PAM_MSG_MEMBER(msg, i, msg), len);
573 buffer_append(&loginmsg, "\n", 1 );
574 reply[i].resp_retcode = PAM_SUCCESS;
575 break;
576 default:
577 goto fail;
580 *resp = reply;
581 return (PAM_SUCCESS);
583 fail:
584 for(i = 0; i < n; i++) {
585 free(reply[i].resp);
587 free(reply);
588 return (PAM_CONV_ERR);
591 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
593 void
594 sshpam_cleanup(void)
596 if (sshpam_handle == NULL || (use_privsep && !mm_is_monitor()))
597 return;
598 debug("PAM: cleanup");
599 pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
600 if (sshpam_session_open) {
601 debug("PAM: closing session");
602 pam_close_session(sshpam_handle, PAM_SILENT);
603 sshpam_session_open = 0;
605 if (sshpam_cred_established) {
606 debug("PAM: deleting credentials");
607 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
608 sshpam_cred_established = 0;
610 sshpam_authenticated = 0;
611 pam_end(sshpam_handle, sshpam_err);
612 sshpam_handle = NULL;
615 static int
616 sshpam_init(Authctxt *authctxt)
618 extern char *__progname;
619 const char *pam_rhost, *pam_user, *user = authctxt->user;
620 const char **ptr_pam_user = &pam_user;
621 struct ssh *ssh = active_state; /* XXX */
623 if (sshpam_handle != NULL) {
624 /* We already have a PAM context; check if the user matches */
625 sshpam_err = pam_get_item(sshpam_handle,
626 PAM_USER, (sshpam_const void **)ptr_pam_user);
627 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
628 return (0);
629 pam_end(sshpam_handle, sshpam_err);
630 sshpam_handle = NULL;
632 debug("PAM: initializing for \"%s\"", user);
633 sshpam_err =
634 pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
635 sshpam_authctxt = authctxt;
637 if (sshpam_err != PAM_SUCCESS) {
638 pam_end(sshpam_handle, sshpam_err);
639 sshpam_handle = NULL;
640 return (-1);
642 pam_rhost = auth_get_canonical_hostname(ssh, options.use_dns);
643 debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
644 sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
645 if (sshpam_err != PAM_SUCCESS) {
646 pam_end(sshpam_handle, sshpam_err);
647 sshpam_handle = NULL;
648 return (-1);
650 #ifdef PAM_TTY_KLUDGE
652 * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
653 * sshd doesn't set the tty until too late in the auth process and
654 * may not even set one (for tty-less connections)
656 debug("PAM: setting PAM_TTY to \"ssh\"");
657 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
658 if (sshpam_err != PAM_SUCCESS) {
659 pam_end(sshpam_handle, sshpam_err);
660 sshpam_handle = NULL;
661 return (-1);
663 #endif
664 return (0);
667 static void *
668 sshpam_init_ctx(Authctxt *authctxt)
670 struct pam_ctxt *ctxt;
671 int socks[2];
673 debug3("PAM: %s entering", __func__);
675 * Refuse to start if we don't have PAM enabled or do_pam_account
676 * has previously failed.
678 if (!options.use_pam || sshpam_account_status == 0)
679 return NULL;
681 /* Initialize PAM */
682 if (sshpam_init(authctxt) == -1) {
683 error("PAM: initialization failed");
684 return (NULL);
687 ctxt = xcalloc(1, sizeof *ctxt);
689 /* Start the authentication thread */
690 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
691 error("PAM: failed create sockets: %s", strerror(errno));
692 free(ctxt);
693 return (NULL);
695 ctxt->pam_psock = socks[0];
696 ctxt->pam_csock = socks[1];
697 if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
698 error("PAM: failed to start authentication thread: %s",
699 strerror(errno));
700 close(socks[0]);
701 close(socks[1]);
702 free(ctxt);
703 return (NULL);
705 cleanup_ctxt = ctxt;
706 return (ctxt);
709 static int
710 sshpam_query(void *ctx, char **name, char **info,
711 u_int *num, char ***prompts, u_int **echo_on)
713 struct ssh *ssh = active_state; /* XXX */
714 Buffer buffer;
715 struct pam_ctxt *ctxt = ctx;
716 size_t plen;
717 u_char type;
718 char *msg;
719 size_t len, mlen;
721 debug3("PAM: %s entering", __func__);
722 buffer_init(&buffer);
723 *name = xstrdup("");
724 *info = xstrdup("");
725 *prompts = xmalloc(sizeof(char *));
726 **prompts = NULL;
727 plen = 0;
728 *echo_on = xmalloc(sizeof(u_int));
729 while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
730 type = buffer_get_char(&buffer);
731 msg = buffer_get_string(&buffer, NULL);
732 mlen = strlen(msg);
733 switch (type) {
734 case PAM_PROMPT_ECHO_ON:
735 case PAM_PROMPT_ECHO_OFF:
736 *num = 1;
737 len = plen + mlen + 1;
738 **prompts = xreallocarray(**prompts, 1, len);
739 strlcpy(**prompts + plen, msg, len - plen);
740 plen += mlen;
741 **echo_on = (type == PAM_PROMPT_ECHO_ON);
742 free(msg);
743 return (0);
744 case PAM_ERROR_MSG:
745 case PAM_TEXT_INFO:
746 /* accumulate messages */
747 len = plen + mlen + 2;
748 **prompts = xreallocarray(**prompts, 1, len);
749 strlcpy(**prompts + plen, msg, len - plen);
750 plen += mlen;
751 strlcat(**prompts + plen, "\n", len - plen);
752 plen++;
753 free(msg);
754 break;
755 case PAM_ACCT_EXPIRED:
756 case PAM_MAXTRIES:
757 if (type == PAM_ACCT_EXPIRED)
758 sshpam_account_status = 0;
759 if (type == PAM_MAXTRIES)
760 sshpam_set_maxtries_reached(1);
761 /* FALLTHROUGH */
762 case PAM_AUTH_ERR:
763 debug3("PAM: %s", pam_strerror(sshpam_handle, type));
764 if (**prompts != NULL && strlen(**prompts) != 0) {
765 *info = **prompts;
766 **prompts = NULL;
767 *num = 0;
768 **echo_on = 0;
769 ctxt->pam_done = -1;
770 free(msg);
771 return 0;
773 /* FALLTHROUGH */
774 case PAM_SUCCESS:
775 if (**prompts != NULL) {
776 /* drain any accumulated messages */
777 debug("PAM: %s", **prompts);
778 buffer_append(&loginmsg, **prompts,
779 strlen(**prompts));
780 free(**prompts);
781 **prompts = NULL;
783 if (type == PAM_SUCCESS) {
784 if (!sshpam_authctxt->valid ||
785 (sshpam_authctxt->pw->pw_uid == 0 &&
786 options.permit_root_login != PERMIT_YES))
787 fatal("Internal error: PAM auth "
788 "succeeded when it should have "
789 "failed");
790 import_environments(&buffer);
791 *num = 0;
792 **echo_on = 0;
793 ctxt->pam_done = 1;
794 free(msg);
795 return (0);
797 error("PAM: %s for %s%.100s from %.100s", msg,
798 sshpam_authctxt->valid ? "" : "illegal user ",
799 sshpam_authctxt->user,
800 auth_get_canonical_hostname(ssh, options.use_dns));
801 /* FALLTHROUGH */
802 default:
803 *num = 0;
804 **echo_on = 0;
805 free(msg);
806 ctxt->pam_done = -1;
807 return (-1);
810 return (-1);
814 * Returns a junk password of identical length to that the user supplied.
815 * Used to mitigate timing attacks against crypt(3)/PAM stacks that
816 * vary processing time in proportion to password length.
818 static char *
819 fake_password(const char *wire_password)
821 const char junk[] = "\b\n\r\177INCORRECT";
822 char *ret = NULL;
823 size_t i, l = wire_password != NULL ? strlen(wire_password) : 0;
825 if (l >= INT_MAX)
826 fatal("%s: password length too long: %zu", __func__, l);
828 ret = malloc(l + 1);
829 for (i = 0; i < l; i++)
830 ret[i] = junk[i % (sizeof(junk) - 1)];
831 ret[i] = '\0';
832 return ret;
835 /* XXX - see also comment in auth-chall.c:verify_response */
836 static int
837 sshpam_respond(void *ctx, u_int num, char **resp)
839 Buffer buffer;
840 struct pam_ctxt *ctxt = ctx;
841 char *fake;
843 debug2("PAM: %s entering, %u responses", __func__, num);
844 switch (ctxt->pam_done) {
845 case 1:
846 sshpam_authenticated = 1;
847 return (0);
848 case 0:
849 break;
850 default:
851 return (-1);
853 if (num != 1) {
854 error("PAM: expected one response, got %u", num);
855 return (-1);
857 buffer_init(&buffer);
858 if (sshpam_authctxt->valid &&
859 (sshpam_authctxt->pw->pw_uid != 0 ||
860 options.permit_root_login == PERMIT_YES))
861 buffer_put_cstring(&buffer, *resp);
862 else {
863 fake = fake_password(*resp);
864 buffer_put_cstring(&buffer, fake);
865 free(fake);
867 if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer) == -1) {
868 buffer_free(&buffer);
869 return (-1);
871 buffer_free(&buffer);
872 return (1);
875 static void
876 sshpam_free_ctx(void *ctxtp)
878 struct pam_ctxt *ctxt = ctxtp;
880 debug3("PAM: %s entering", __func__);
881 sshpam_thread_cleanup();
882 free(ctxt);
884 * We don't call sshpam_cleanup() here because we may need the PAM
885 * handle at a later stage, e.g. when setting up a session. It's
886 * still on the cleanup list, so pam_end() *will* be called before
887 * the server process terminates.
891 KbdintDevice sshpam_device = {
892 "pam",
893 sshpam_init_ctx,
894 sshpam_query,
895 sshpam_respond,
896 sshpam_free_ctx
899 KbdintDevice mm_sshpam_device = {
900 "pam",
901 mm_sshpam_init_ctx,
902 mm_sshpam_query,
903 mm_sshpam_respond,
904 mm_sshpam_free_ctx
908 * This replaces auth-pam.c
910 void
911 start_pam(Authctxt *authctxt)
913 if (!options.use_pam)
914 fatal("PAM: initialisation requested when UsePAM=no");
916 if (sshpam_init(authctxt) == -1)
917 fatal("PAM: initialisation failed");
920 void
921 finish_pam(void)
923 sshpam_cleanup();
926 u_int
927 do_pam_account(void)
929 debug("%s: called", __func__);
930 if (sshpam_account_status != -1)
931 return (sshpam_account_status);
933 sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
934 debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
935 pam_strerror(sshpam_handle, sshpam_err));
937 if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
938 sshpam_account_status = 0;
939 return (sshpam_account_status);
942 if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
943 sshpam_password_change_required(1);
945 sshpam_account_status = 1;
946 return (sshpam_account_status);
949 void
950 do_pam_set_tty(const char *tty)
952 if (tty != NULL) {
953 debug("PAM: setting PAM_TTY to \"%s\"", tty);
954 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, tty);
955 if (sshpam_err != PAM_SUCCESS)
956 fatal("PAM: failed to set PAM_TTY: %s",
957 pam_strerror(sshpam_handle, sshpam_err));
961 void
962 do_pam_setcred(int init)
964 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
965 (const void *)&store_conv);
966 if (sshpam_err != PAM_SUCCESS)
967 fatal("PAM: failed to set PAM_CONV: %s",
968 pam_strerror(sshpam_handle, sshpam_err));
969 if (init) {
970 debug("PAM: establishing credentials");
971 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
972 } else {
973 debug("PAM: reinitializing credentials");
974 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
976 if (sshpam_err == PAM_SUCCESS) {
977 sshpam_cred_established = 1;
978 return;
980 if (sshpam_authenticated)
981 fatal("PAM: pam_setcred(): %s",
982 pam_strerror(sshpam_handle, sshpam_err));
983 else
984 debug("PAM: pam_setcred(): %s",
985 pam_strerror(sshpam_handle, sshpam_err));
988 static int
989 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
990 struct pam_response **resp, void *data)
992 char input[PAM_MAX_MSG_SIZE];
993 struct pam_response *reply;
994 int i;
996 debug3("PAM: %s called with %d messages", __func__, n);
998 *resp = NULL;
1000 if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
1001 return (PAM_CONV_ERR);
1003 if ((reply = calloc(n, sizeof(*reply))) == NULL)
1004 return (PAM_CONV_ERR);
1006 for (i = 0; i < n; ++i) {
1007 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1008 case PAM_PROMPT_ECHO_OFF:
1009 reply[i].resp =
1010 read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
1011 RP_ALLOW_STDIN);
1012 reply[i].resp_retcode = PAM_SUCCESS;
1013 break;
1014 case PAM_PROMPT_ECHO_ON:
1015 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1016 if (fgets(input, sizeof input, stdin) == NULL)
1017 input[0] = '\0';
1018 if ((reply[i].resp = strdup(input)) == NULL)
1019 goto fail;
1020 reply[i].resp_retcode = PAM_SUCCESS;
1021 break;
1022 case PAM_ERROR_MSG:
1023 case PAM_TEXT_INFO:
1024 fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1025 reply[i].resp_retcode = PAM_SUCCESS;
1026 break;
1027 default:
1028 goto fail;
1031 *resp = reply;
1032 return (PAM_SUCCESS);
1034 fail:
1035 for(i = 0; i < n; i++) {
1036 free(reply[i].resp);
1038 free(reply);
1039 return (PAM_CONV_ERR);
1042 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
1045 * XXX this should be done in the authentication phase, but ssh1 doesn't
1046 * support that
1048 void
1049 do_pam_chauthtok(void)
1051 if (use_privsep)
1052 fatal("Password expired (unable to change with privsep)");
1053 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1054 (const void *)&tty_conv);
1055 if (sshpam_err != PAM_SUCCESS)
1056 fatal("PAM: failed to set PAM_CONV: %s",
1057 pam_strerror(sshpam_handle, sshpam_err));
1058 debug("PAM: changing password");
1059 sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1060 if (sshpam_err != PAM_SUCCESS)
1061 fatal("PAM: pam_chauthtok(): %s",
1062 pam_strerror(sshpam_handle, sshpam_err));
1065 void
1066 do_pam_session(void)
1068 debug3("PAM: opening session");
1069 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1070 (const void *)&store_conv);
1071 if (sshpam_err != PAM_SUCCESS)
1072 fatal("PAM: failed to set PAM_CONV: %s",
1073 pam_strerror(sshpam_handle, sshpam_err));
1074 sshpam_err = pam_open_session(sshpam_handle, 0);
1075 if (sshpam_err == PAM_SUCCESS)
1076 sshpam_session_open = 1;
1077 else {
1078 sshpam_session_open = 0;
1079 disable_forwarding();
1080 error("PAM: pam_open_session(): %s",
1081 pam_strerror(sshpam_handle, sshpam_err));
1087 is_pam_session_open(void)
1089 return sshpam_session_open;
1093 * Set a PAM environment string. We need to do this so that the session
1094 * modules can handle things like Kerberos/GSI credentials that appear
1095 * during the ssh authentication process.
1098 do_pam_putenv(char *name, char *value)
1100 int ret = 1;
1101 #ifdef HAVE_PAM_PUTENV
1102 char *compound;
1103 size_t len;
1105 len = strlen(name) + strlen(value) + 2;
1106 compound = xmalloc(len);
1108 snprintf(compound, len, "%s=%s", name, value);
1109 ret = pam_putenv(sshpam_handle, compound);
1110 free(compound);
1111 #endif
1113 return (ret);
1116 char **
1117 fetch_pam_child_environment(void)
1119 return sshpam_env;
1122 char **
1123 fetch_pam_environment(void)
1125 return (pam_getenvlist(sshpam_handle));
1128 void
1129 free_pam_environment(char **env)
1131 char **envp;
1133 if (env == NULL)
1134 return;
1136 for (envp = env; *envp; envp++)
1137 free(*envp);
1138 free(env);
1142 * "Blind" conversation function for password authentication. Assumes that
1143 * echo-off prompts are for the password and stores messages for later
1144 * display.
1146 static int
1147 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1148 struct pam_response **resp, void *data)
1150 struct pam_response *reply;
1151 int i;
1152 size_t len;
1154 debug3("PAM: %s called with %d messages", __func__, n);
1156 *resp = NULL;
1158 if (n <= 0 || n > PAM_MAX_NUM_MSG)
1159 return (PAM_CONV_ERR);
1161 if ((reply = calloc(n, sizeof(*reply))) == NULL)
1162 return (PAM_CONV_ERR);
1164 for (i = 0; i < n; ++i) {
1165 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1166 case PAM_PROMPT_ECHO_OFF:
1167 if (sshpam_password == NULL)
1168 goto fail;
1169 if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1170 goto fail;
1171 reply[i].resp_retcode = PAM_SUCCESS;
1172 break;
1173 case PAM_ERROR_MSG:
1174 case PAM_TEXT_INFO:
1175 len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1176 if (len > 0) {
1177 buffer_append(&loginmsg,
1178 PAM_MSG_MEMBER(msg, i, msg), len);
1179 buffer_append(&loginmsg, "\n", 1);
1181 if ((reply[i].resp = strdup("")) == NULL)
1182 goto fail;
1183 reply[i].resp_retcode = PAM_SUCCESS;
1184 break;
1185 default:
1186 goto fail;
1189 *resp = reply;
1190 return (PAM_SUCCESS);
1192 fail:
1193 for(i = 0; i < n; i++) {
1194 free(reply[i].resp);
1196 free(reply);
1197 return (PAM_CONV_ERR);
1200 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1203 * Attempt password authentication via PAM
1206 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1208 int flags = (options.permit_empty_passwd == 0 ?
1209 PAM_DISALLOW_NULL_AUTHTOK : 0);
1210 char *fake = NULL;
1212 if (!options.use_pam || sshpam_handle == NULL)
1213 fatal("PAM: %s called when PAM disabled or failed to "
1214 "initialise.", __func__);
1216 sshpam_password = password;
1217 sshpam_authctxt = authctxt;
1220 * If the user logging in is invalid, or is root but is not permitted
1221 * by PermitRootLogin, use an invalid password to prevent leaking
1222 * information via timing (eg if the PAM config has a delay on fail).
1224 if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1225 options.permit_root_login != PERMIT_YES))
1226 sshpam_password = fake = fake_password(password);
1228 sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1229 (const void *)&passwd_conv);
1230 if (sshpam_err != PAM_SUCCESS)
1231 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1232 pam_strerror(sshpam_handle, sshpam_err));
1234 sshpam_err = pam_authenticate(sshpam_handle, flags);
1235 sshpam_password = NULL;
1236 free(fake);
1237 if (sshpam_err == PAM_MAXTRIES)
1238 sshpam_set_maxtries_reached(1);
1239 if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1240 debug("PAM: password authentication accepted for %.100s",
1241 authctxt->user);
1242 return 1;
1243 } else {
1244 debug("PAM: password authentication failed for %.100s: %s",
1245 authctxt->valid ? authctxt->user : "an illegal user",
1246 pam_strerror(sshpam_handle, sshpam_err));
1247 return 0;
1252 sshpam_get_maxtries_reached(void)
1254 return sshpam_maxtries_reached;
1257 void
1258 sshpam_set_maxtries_reached(int reached)
1260 if (reached == 0 || sshpam_maxtries_reached)
1261 return;
1262 sshpam_maxtries_reached = 1;
1263 options.password_authentication = 0;
1264 options.kbd_interactive_authentication = 0;
1265 options.challenge_response_authentication = 0;
1267 #endif /* USE_PAM */