Instead of duplicating the Kerberos tools, use a single version.
[dragonfly.git] / secure / usr.sbin / sshd / auth2-pam-freebsd.c
1 /*-
2  * Copyright (c) 2002 Networks Associates Technology, Inc.
3  * All rights reserved.
4  *
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.
9  *
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.
18  *
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.
30  *
31  * $FreeBSD: src/crypto/openssh/auth2-pam-freebsd.c,v 1.1.2.6 2003/04/07 09:56:46 des Exp $
32  * $DragonFly: src/secure/usr.sbin/sshd/Attic/auth2-pam-freebsd.c,v 1.3 2005/07/11 22:49:46 corecode Exp $
33  */
34
35 #include "includes.h"
36
37 #ifdef USE_PAM
38 #include <security/pam_appl.h>
39
40 #include "auth.h"
41 #include "auth-pam.h"
42 #include "buffer.h"
43 #include "bufaux.h"
44 #include "canohost.h"
45 #include "log.h"
46 #include "monitor_wrap.h"
47 #include "msg.h"
48 #include "packet.h"
49 #include "misc.h"
50 #include "servconf.h"
51 #include "ssh2.h"
52 #include "xmalloc.h"
53
54 #ifdef USE_POSIX_THREADS
55 #include <pthread.h>
56 #else
57 typedef pid_t pthread_t;
58 #endif
59
60 struct pam_ctxt {
61         pthread_t        pam_thread;
62         int              pam_psock;
63         int              pam_csock;
64         int              pam_done;
65 };
66
67 static void sshpam_free_ctx(void *);
68 static struct pam_ctxt *cleanup_ctxt;
69 static Authctxt *sshpam_authctxt = NULL;
70 static const char *sshpam_password = NULL;
71
72
73 #ifndef USE_POSIX_THREADS
74 /*
75  * Simulate threads with processes.
76  */
77
78 static int sshpam_thread_status = -1;
79 static mysig_t sshpam_oldsig;
80
81 static void 
82 sshpam_sigchld_handler(int sig)
83 {
84         if (cleanup_ctxt == NULL)
85                 return; /* handler called after PAM cleanup, shouldn't happen */
86         if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, 0) == -1)
87                 return; /* couldn't wait for process */
88         if (WIFSIGNALED(sshpam_thread_status) &&
89             WTERMSIG(sshpam_thread_status) == SIGTERM)
90                 return; /* terminated by pthread_cancel */
91         if (!WIFEXITED(sshpam_thread_status))
92                 fatal("PAM: authentication thread exited unexpectedly");
93         if (WEXITSTATUS(sshpam_thread_status) != 0)
94                 fatal("PAM: authentication thread exited uncleanly");
95 }
96
97
98 static void
99 pthread_exit(void *value __unused)
100 {
101         _exit(0);
102 }
103
104 static int
105 pthread_create(pthread_t *thread, const void *attr __unused,
106     void *(*thread_start)(void *), void *arg)
107 {
108         pid_t pid;
109
110         switch ((pid = fork())) {
111         case -1:
112                 error("fork(): %s", strerror(errno));
113                 return (-1);
114         case 0:
115                 thread_start(arg);
116                 _exit(1);
117         default:
118                 *thread = pid;
119                 sshpam_oldsig = signal(SIGCHLD, sshpam_sigchld_handler);
120                 return (0);
121         }
122 }
123
124 static int
125 pthread_cancel(pthread_t thread)
126 {
127         signal(SIGCHLD, sshpam_oldsig);
128         return (kill(thread, SIGTERM));
129 }
130
131 static int
132 pthread_join(pthread_t thread, void **value __unused)
133 {
134         int status;
135
136         if (sshpam_thread_status != -1)
137                 return (sshpam_thread_status);
138         signal(SIGCHLD, sshpam_oldsig);
139         waitpid(thread, &status, 0);
140         return (status);
141 }
142 #endif
143
144
145 extern ServerOptions options;
146 extern Buffer loginmsg;
147 extern int compat20;
148 extern u_int utmp_len;
149
150 static pam_handle_t *sshpam_handle;
151 static int sshpam_err;
152 static int sshpam_authenticated;
153 static int sshpam_new_authtok_reqd;
154 static int sshpam_session_open;
155 static int sshpam_cred_established;
156
157 /*
158  * Conversation function for authentication thread.
159  */
160 static int
161 sshpam_thread_conv(int n,
162          const struct pam_message **msg,
163          struct pam_response **resp,
164          void *data)
165 {
166         Buffer buffer;
167         struct pam_ctxt *ctxt;
168         int i;
169
170         ctxt = data;
171         if (n <= 0 || n > PAM_MAX_NUM_MSG)
172                 return (PAM_CONV_ERR);
173         *resp = xmalloc(n * sizeof **resp);
174         buffer_init(&buffer);
175         for (i = 0; i < n; ++i) {
176                 resp[i]->resp_retcode = 0;
177                 resp[i]->resp = NULL;
178                 switch (msg[i]->msg_style) {
179                 case PAM_PROMPT_ECHO_OFF:
180                         buffer_put_cstring(&buffer, msg[i]->msg);
181                         ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
182                         ssh_msg_recv(ctxt->pam_csock, &buffer);
183                         if (buffer_get_char(&buffer) != PAM_AUTHTOK)
184                                 goto fail;
185                         resp[i]->resp = buffer_get_string(&buffer, NULL);
186                         break;
187                 case PAM_PROMPT_ECHO_ON:
188                         buffer_put_cstring(&buffer, msg[i]->msg);
189                         ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
190                         ssh_msg_recv(ctxt->pam_csock, &buffer);
191                         if (buffer_get_char(&buffer) != PAM_AUTHTOK)
192                                 goto fail;
193                         resp[i]->resp = buffer_get_string(&buffer, NULL);
194                         break;
195                 case PAM_ERROR_MSG:
196                         buffer_put_cstring(&buffer, msg[i]->msg);
197                         ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
198                         break;
199                 case PAM_TEXT_INFO:
200                         buffer_put_cstring(&buffer, msg[i]->msg);
201                         ssh_msg_send(ctxt->pam_csock, msg[i]->msg_style, &buffer);
202                         break;
203                 default:
204                         goto fail;
205                 }
206                 buffer_clear(&buffer);
207         }
208         buffer_free(&buffer);
209         return (PAM_SUCCESS);
210  fail:
211         while (i)
212                 xfree(resp[--i]);
213         xfree(*resp);
214         *resp = NULL;
215         buffer_free(&buffer);
216         return (PAM_CONV_ERR);
217 }
218
219 /*
220  * Authentication thread.
221  */
222 static void *
223 sshpam_thread(void *ctxtp)
224 {
225         struct pam_ctxt *ctxt = ctxtp;
226         Buffer buffer;
227         struct pam_conv pam_conv = { sshpam_thread_conv, ctxt };
228
229 #ifndef USE_POSIX_THREADS
230         {
231                 const char *pam_user;
232
233                 pam_get_item(sshpam_handle, PAM_USER, (const void **)&pam_user);
234                 setproctitle("%s [pam]", pam_user);
235         }
236 #endif
237         buffer_init(&buffer);
238         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV, (const void *)&pam_conv);
239         if (sshpam_err != PAM_SUCCESS)
240                 goto auth_fail;
241         sshpam_err = pam_authenticate(sshpam_handle, 0);
242         if (sshpam_err != PAM_SUCCESS)
243                 goto auth_fail;
244         sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
245         if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD)
246                 goto auth_fail;
247         buffer_put_cstring(&buffer, "OK");
248         ssh_msg_send(ctxt->pam_csock, sshpam_err, &buffer);
249         buffer_free(&buffer);
250         pthread_exit(NULL);
251  auth_fail:
252         buffer_put_cstring(&buffer,
253             pam_strerror(sshpam_handle, sshpam_err));
254         ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
255         buffer_free(&buffer);
256         pthread_exit(NULL);
257 }
258
259 void
260 sshpam_thread_cleanup(void)
261 {
262         struct pam_ctxt *ctxt = cleanup_ctxt;
263
264         if (ctxt != NULL && ctxt->pam_thread != 0) {
265                 pthread_cancel(ctxt->pam_thread);
266                 pthread_join(ctxt->pam_thread, NULL);
267                 close(ctxt->pam_psock);
268                 close(ctxt->pam_csock);
269                 memset(ctxt, 0, sizeof(*ctxt));
270                 cleanup_ctxt = NULL;
271         }
272 }
273
274 static int
275 sshpam_null_conv(int n,
276          const struct pam_message **msg,
277          struct pam_response **resp,
278          void *data)
279 {
280
281         return (PAM_CONV_ERR);
282 }
283
284 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
285
286 void
287 sshpam_cleanup(void)
288 {
289         debug("PAM: cleanup");
290         pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
291         if (sshpam_cred_established) {
292                 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
293                 sshpam_cred_established = 0;
294         }
295         if (sshpam_session_open) {
296                 pam_close_session(sshpam_handle, PAM_SILENT);
297                 sshpam_session_open = 0;
298         }
299         sshpam_authenticated = sshpam_new_authtok_reqd = 0;
300         pam_end(sshpam_handle, sshpam_err);
301         sshpam_handle = NULL;
302 }
303
304 static int
305 sshpam_init(Authctxt *authctxt)
306 {
307         extern u_int utmp_len;
308         const char *pam_rhost, *pam_user, *user = authctxt->user;
309
310         if (sshpam_handle != NULL) {
311                 /* We already have a PAM context; check if the user matches */
312                 sshpam_err = pam_get_item(sshpam_handle,
313                     PAM_USER, (const void **)&pam_user);
314                 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
315                         return (0);
316                 pam_end(sshpam_handle, sshpam_err);
317                 sshpam_handle = NULL;
318         }
319         debug("PAM: initializing for \"%s\"", user);
320         sshpam_err = pam_start("sshd", user, &null_conv, &sshpam_handle);
321         if (sshpam_err != PAM_SUCCESS)
322                 return (-1);
323         pam_rhost = get_remote_name_or_ip(utmp_len, options.use_dns);
324         debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
325         sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
326         if (sshpam_err != PAM_SUCCESS) {
327                 pam_end(sshpam_handle, sshpam_err);
328                 sshpam_handle = NULL;
329                 return (-1);
330         }
331         return (0);
332 }
333
334 static void *
335 sshpam_init_ctx(Authctxt *authctxt)
336 {
337         struct pam_ctxt *ctxt;
338         int socks[2];
339
340         /* Initialize PAM */
341         if (sshpam_init(authctxt) == -1) {
342                 error("PAM: initialization failed");
343                 return (NULL);
344         }
345
346         ctxt = xmalloc(sizeof *ctxt);
347         ctxt->pam_done = 0;
348
349         /* Start the authentication thread */
350         if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
351                 error("PAM: failed create sockets: %s", strerror(errno));
352                 xfree(ctxt);
353                 return (NULL);
354         }
355         ctxt->pam_psock = socks[0];
356         ctxt->pam_csock = socks[1];
357         if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
358                 error("PAM: failed to start authentication thread: %s",
359                     strerror(errno));
360                 close(socks[0]);
361                 close(socks[1]);
362                 xfree(ctxt);
363                 return (NULL);
364         }
365         cleanup_ctxt = ctxt;
366         return (ctxt);
367 }
368
369 static int
370 sshpam_query(void *ctx, char **name, char **info,
371     u_int *num, char ***prompts, u_int **echo_on)
372 {
373         Buffer buffer;
374         struct pam_ctxt *ctxt = ctx;
375         size_t plen;
376         u_char type;
377         char *msg;
378
379         buffer_init(&buffer);
380         *name = xstrdup("");
381         *info = xstrdup("");
382         *prompts = xmalloc(sizeof(char *));
383         **prompts = NULL;
384         plen = 0;
385         *echo_on = xmalloc(sizeof(u_int));
386         while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
387                 type = buffer_get_char(&buffer);
388                 msg = buffer_get_string(&buffer, NULL);
389                 switch (type) {
390                 case PAM_PROMPT_ECHO_ON:
391                 case PAM_PROMPT_ECHO_OFF:
392                         *num = 1;
393                         **prompts = xrealloc(**prompts, plen + strlen(msg) + 1);
394                         plen += sprintf(**prompts + plen, "%s", msg);
395                         **echo_on = (type == PAM_PROMPT_ECHO_ON);
396                         xfree(msg);
397                         return (0);
398                 case PAM_ERROR_MSG:
399                 case PAM_TEXT_INFO:
400                         /* accumulate messages */
401                         **prompts = xrealloc(**prompts, plen + strlen(msg) + 1);
402                         plen += sprintf(**prompts + plen, "%s", msg);
403                         xfree(msg);
404                         break;
405                 case PAM_NEW_AUTHTOK_REQD:
406                         sshpam_new_authtok_reqd = 1;
407                         /* FALLTHROUGH */
408                 case PAM_SUCCESS:
409                 case PAM_AUTH_ERR:
410                         if (**prompts != NULL) {
411                                 /* drain any accumulated messages */
412 #if 0 /* not compatible with privsep */
413                                 packet_start(SSH2_MSG_USERAUTH_BANNER);
414                                 packet_put_cstring(**prompts);
415                                 packet_put_cstring("");
416                                 packet_send();
417                                 packet_write_wait();
418 #endif
419                                 xfree(**prompts);
420                                 **prompts = NULL;
421                         }
422                         if (type == PAM_SUCCESS) {
423                                 *num = 0;
424                                 **echo_on = 0;
425                                 ctxt->pam_done = 1;
426                                 xfree(msg);
427                                 return (0);
428                         }
429                         error("PAM: %s", msg);
430                 default:
431                         *num = 0;
432                         **echo_on = 0;
433                         xfree(msg);
434                         ctxt->pam_done = -1;
435                         return (-1);
436                 }
437         }
438         return (-1);
439 }
440
441 static int
442 sshpam_respond(void *ctx, u_int num, char **resp)
443 {
444         Buffer buffer;
445         struct pam_ctxt *ctxt = ctx;
446         char *msg;
447
448         debug2("PAM: %s", __func__);
449         switch (ctxt->pam_done) {
450         case 1:
451                 sshpam_authenticated = 1;
452                 return (0);
453         case 0:
454                 break;
455         default:
456                 return (-1);
457         }
458         if (num != 1) {
459                 error("PAM: expected one response, got %u", num);
460                 return (-1);
461         }
462         buffer_init(&buffer);
463         buffer_put_cstring(&buffer, *resp);
464         ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer);
465         buffer_free(&buffer);
466         return (1);
467 }
468
469 static void
470 sshpam_free_ctx(void *ctxtp)
471 {
472         struct pam_ctxt *ctxt = ctxtp;
473
474         sshpam_thread_cleanup();
475         xfree(ctxt);
476         /*
477          * We don't call pam_cleanup() here because we may need the PAM
478          * handle at a later stage, e.g. when setting up a session.  It's
479          * still on the cleanup list, so pam_end() *will* be called before
480          * the server process terminates.
481          */
482 }
483
484 KbdintDevice sshpam_device = {
485         "pam",
486         sshpam_init_ctx,
487         sshpam_query,
488         sshpam_respond,
489         sshpam_free_ctx
490 };
491
492 KbdintDevice mm_sshpam_device = {
493         "pam",
494         mm_sshpam_init_ctx,
495         mm_sshpam_query,
496         mm_sshpam_respond,
497         mm_sshpam_free_ctx
498 };
499
500 /*
501  * This replaces auth-pam.c
502  */
503 void
504 start_pam(Authctxt *authctxt)
505 {
506         if (!options.use_pam)
507                 fatal("PAM: initialisation requested when UsePAM=no");
508
509         if (sshpam_init(authctxt) == -1)
510                 fatal("PAM: initialisation failed");
511 }
512
513 void
514 finish_pam(void)
515 {
516         sshpam_cleanup();
517 }
518
519 u_int
520 do_pam_account(void)
521 {
522         /* XXX */
523         return (1);
524 }
525
526 void
527 do_pam_set_tty(const char *tty)
528 {
529         if (tty != NULL) {
530                 debug("PAM: setting PAM_TTY to \"%s\"", tty);
531                 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, tty);
532                 if (sshpam_err != PAM_SUCCESS)
533                         fatal("PAM: failed to set PAM_TTY: %s",
534                             pam_strerror(sshpam_handle, sshpam_err));
535         }
536 }
537
538 void
539 do_pam_session(void)
540 {
541         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
542         if (sshpam_err != PAM_SUCCESS)
543                 fatal("PAM: failed to set PAM_CONV: %s",
544                     pam_strerror(sshpam_handle, sshpam_err));
545         sshpam_err = pam_open_session(sshpam_handle, 0);
546         if (sshpam_err != PAM_SUCCESS)
547                 fatal("PAM: pam_open_session(): %s",
548                     pam_strerror(sshpam_handle, sshpam_err));
549         sshpam_session_open = 1;
550 }
551
552 int
553 is_pam_session_open(void)
554 {
555         return sshpam_session_open;
556 }
557
558 void
559 do_pam_setcred(int init)
560 {
561         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
562         if (sshpam_err != PAM_SUCCESS)
563                 fatal("PAM: failed to set PAM_CONV: %s",
564                     pam_strerror(sshpam_handle, sshpam_err));
565         if (init) {
566                 debug("PAM: establishing credentials");
567                 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
568         } else {
569                 debug("PAM: reinitializing credentials");
570                 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
571         }
572         if (sshpam_err == PAM_SUCCESS) {
573                 sshpam_cred_established = 1;
574                 return;
575         }
576         if (sshpam_authenticated)
577                 fatal("PAM: pam_setcred(): %s",
578                     pam_strerror(sshpam_handle, sshpam_err));
579         else
580                 debug("PAM: pam_setcred(): %s",
581                     pam_strerror(sshpam_handle, sshpam_err));
582 }
583
584 int
585 is_pam_password_change_required(void)
586 {
587         return (sshpam_new_authtok_reqd);
588 }
589
590 static int
591 sshpam_chauthtok_conv(int n,
592          const struct pam_message **msg,
593          struct pam_response **resp,
594          void *data)
595 {
596         char input[PAM_MAX_MSG_SIZE];
597         int i;
598
599         if (n <= 0 || n > PAM_MAX_NUM_MSG)
600                 return (PAM_CONV_ERR);
601         *resp = xmalloc(n * sizeof **resp);
602         for (i = 0; i < n; ++i) {
603                 switch (msg[i]->msg_style) {
604                 case PAM_PROMPT_ECHO_OFF:
605                         resp[i]->resp =
606                             read_passphrase(msg[i]->msg, RP_ALLOW_STDIN);
607                         resp[i]->resp_retcode = PAM_SUCCESS;
608                         break;
609                 case PAM_PROMPT_ECHO_ON:
610                         fputs(msg[i]->msg, stderr);
611                         fgets(input, sizeof input, stdin);
612                         resp[i]->resp = xstrdup(input);
613                         resp[i]->resp_retcode = PAM_SUCCESS;
614                         break;
615                 case PAM_ERROR_MSG:
616                 case PAM_TEXT_INFO:
617                         fputs(msg[i]->msg, stderr);
618                         resp[i]->resp_retcode = PAM_SUCCESS;
619                         break;
620                 default:
621                         goto fail;
622                 }
623         }
624         return (PAM_SUCCESS);
625  fail:
626         while (i)
627                 xfree(resp[--i]);
628         xfree(*resp);
629         *resp = NULL;
630         return (PAM_CONV_ERR);
631 }
632
633 /*
634  * XXX this should be done in the authentication phase, but ssh1 doesn't
635  * support that
636  */
637 void
638 do_pam_chauthtok(void)
639 {
640         struct pam_conv pam_conv = { sshpam_chauthtok_conv, NULL };
641
642         if (use_privsep)
643                 fatal("PAM: chauthtok not supprted with privsep");
644         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV, (const void *)&pam_conv);
645         if (sshpam_err != PAM_SUCCESS)
646                 fatal("PAM: failed to set PAM_CONV: %s",
647                     pam_strerror(sshpam_handle, sshpam_err));
648         debug("PAM: changing password");
649         sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
650         if (sshpam_err != PAM_SUCCESS)
651                 fatal("PAM: pam_chauthtok(): %s",
652                     pam_strerror(sshpam_handle, sshpam_err));
653 }
654
655 void
656 print_pam_messages(void)
657 {
658         /* XXX */
659 }
660
661 char **
662 fetch_pam_child_environment(void)
663 {
664         /* XXX */
665         return (NULL);
666 }
667
668 char **
669 fetch_pam_environment(void)
670 {
671 #ifdef HAVE_PAM_GETENVLIST
672         debug("PAM: retrieving environment");
673         return (pam_getenvlist(sshpam_handle));
674 #else
675         return (NULL);
676 #endif
677 }
678
679 void
680 free_pam_environment(char **env)
681 {
682         char **envp;
683
684         if (env == NULL)
685                 return;
686
687         for (envp = env; *envp; envp++)
688                 xfree(*envp);
689         xfree(env);
690 }
691
692 /*
693  * "Blind" conversation function for password authentication.  Assumes that
694  * echo-off prompts are for the password and stores messages for later
695  * display.
696  */
697 static int
698 sshpam_passwd_conv(int n, const struct pam_message **msg,
699     struct pam_response **resp, void *data)
700 {
701         struct pam_response *reply;
702         int i;
703         size_t len;
704
705         debug3("PAM: %s called with %d messages", __func__, n);
706
707         *resp = NULL;
708
709         if (n <= 0 || n > PAM_MAX_NUM_MSG)
710                 return (PAM_CONV_ERR);
711
712         if ((reply = malloc(n * sizeof(*reply))) == NULL)
713                 return (PAM_CONV_ERR);
714         memset(reply, 0, n * sizeof(*reply));
715
716         for (i = 0; i < n; ++i) {
717                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
718                 case PAM_PROMPT_ECHO_OFF:
719                         if (sshpam_password == NULL)
720                                 goto fail;
721                         if ((reply[i].resp = strdup(sshpam_password)) == NULL)
722                                 goto fail;
723                         reply[i].resp_retcode = PAM_SUCCESS;
724                         break;
725                 case PAM_ERROR_MSG:
726                 case PAM_TEXT_INFO:
727                         len = strlen(PAM_MSG_MEMBER(msg, i, msg));
728                         if (len > 0) {
729                                 buffer_append(&loginmsg,
730                                     PAM_MSG_MEMBER(msg, i, msg), len);
731                                 buffer_append(&loginmsg, "\n", 1);
732                         }
733                         if ((reply[i].resp = strdup("")) == NULL)
734                                 goto fail;
735                         reply[i].resp_retcode = PAM_SUCCESS;
736                         break;
737                 default:
738                         goto fail;
739                 }
740         }
741         *resp = reply;
742         return (PAM_SUCCESS);
743
744  fail:
745         for(i = 0; i < n; i++) {
746                 if (reply[i].resp != NULL)
747                         xfree(reply[i].resp);
748         }
749         xfree(reply);
750         return (PAM_CONV_ERR);
751 }
752
753 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
754
755 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
756 {
757         int flags = (options.permit_empty_passwd == 0 ?
758             PAM_DISALLOW_NULL_AUTHTOK : 0);
759         static char badpw[] = "\b\n\r\177INCORRECT";
760
761         if (!options.use_pam || sshpam_handle == NULL)
762                 fatal("PAM: %s called when PAM disabled or failed to "
763                     "initialise.", __func__);
764
765         sshpam_password = password;
766         sshpam_authctxt = authctxt;
767
768         /*
769          * If the user logging in is invalid, or is root but is not permitted
770          * by PermitRootLogin, use an invalid password to prevent leaking
771          * information via timing (eg if the PAM config has a delay on fail).
772          */
773         if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
774              options.permit_root_login != PERMIT_YES))
775                 sshpam_password = badpw;
776
777         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
778             (const void *)&passwd_conv);
779         if (sshpam_err != PAM_SUCCESS)
780                 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
781                     pam_strerror(sshpam_handle, sshpam_err));
782
783         sshpam_err = pam_authenticate(sshpam_handle, flags);
784         sshpam_password = NULL;
785         if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
786                 debug("PAM: password authentication accepted for %.100s",
787                     authctxt->user);
788                return 1;
789         } else {
790                 debug("PAM: password authentication failed for %.100s: %s",
791                     authctxt->valid ? authctxt->user : "an illegal user",
792                     pam_strerror(sshpam_handle, sshpam_err));
793                 return 0;
794         }
795 }
796
797 #endif /* USE_PAM */