openssh-5.9p1-xauthlocalhostname.diff
[platform/upstream/openssh.git] / auth-pam.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 /*
32  * Copyright (c) 2003,2004 Damien Miller <djm@mindrot.org>
33  * Copyright (c) 2003,2004 Darren Tucker <dtucker@zip.com.au>
34  *
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.
38  *
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.
46  */
47
48 /* Based on $FreeBSD: src/crypto/openssh/auth2-pam-freebsd.c,v 1.11 2003/03/31 13:48:18 des Exp $ */
49 #include "includes.h"
50
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <sys/wait.h>
54
55 #include <errno.h>
56 #include <signal.h>
57 #include <stdarg.h>
58 #include <string.h>
59 #include <unistd.h>
60
61 #ifdef USE_PAM
62 #if defined(HAVE_SECURITY_PAM_APPL_H)
63 #include <security/pam_appl.h>
64 #elif defined (HAVE_PAM_PAM_APPL_H)
65 #include <pam/pam_appl.h>
66 #endif
67
68 /* OpenGroup RFC86.0 and XSSO specify no "const" on arguments */
69 #ifdef PAM_SUN_CODEBASE
70 # define sshpam_const           /* Solaris, HP-UX, AIX */
71 #else
72 # define sshpam_const   const   /* LinuxPAM, OpenPAM */
73 #endif
74
75 /* Ambiguity in spec: is it an array of pointers or a pointer to an array? */
76 #ifdef PAM_SUN_CODEBASE
77 # define PAM_MSG_MEMBER(msg, n, member) ((*(msg))[(n)].member)
78 #else
79 # define PAM_MSG_MEMBER(msg, n, member) ((msg)[(n)]->member)
80 #endif
81
82 #include "xmalloc.h"
83 #include "buffer.h"
84 #include "key.h"
85 #include "hostfile.h"
86 #include "auth.h"
87 #include "auth-pam.h"
88 #include "canohost.h"
89 #include "log.h"
90 #include "msg.h"
91 #include "packet.h"
92 #include "misc.h"
93 #include "servconf.h"
94 #include "ssh2.h"
95 #include "auth-options.h"
96 #ifdef GSSAPI
97 #include "ssh-gss.h"
98 #endif
99 #include "monitor_wrap.h"
100
101 extern ServerOptions options;
102 extern Buffer loginmsg;
103 extern int compat20;
104 extern u_int utmp_len;
105
106 /* so we don't silently change behaviour */
107 #ifdef USE_POSIX_THREADS
108 # error "USE_POSIX_THREADS replaced by UNSUPPORTED_POSIX_THREADS_HACK"
109 #endif
110
111 /*
112  * Formerly known as USE_POSIX_THREADS, using this is completely unsupported
113  * and generally a bad idea.  Use at own risk and do not expect support if
114  * this breaks.
115  */
116 #ifdef UNSUPPORTED_POSIX_THREADS_HACK
117 #include <pthread.h>
118 /*
119  * Avoid namespace clash when *not* using pthreads for systems *with*
120  * pthreads, which unconditionally define pthread_t via sys/types.h
121  * (e.g. Linux)
122  */
123 typedef pthread_t sp_pthread_t;
124 #else
125 typedef pid_t sp_pthread_t;
126 #endif
127
128 struct pam_ctxt {
129         sp_pthread_t     pam_thread;
130         int              pam_psock;
131         int              pam_csock;
132         int              pam_done;
133 };
134
135 static void sshpam_free_ctx(void *);
136 static struct pam_ctxt *cleanup_ctxt;
137
138 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
139 /*
140  * Simulate threads with processes.
141  */
142
143 static int sshpam_thread_status = -1;
144 static mysig_t sshpam_oldsig;
145
146 static void
147 sshpam_sigchld_handler(int sig)
148 {
149         signal(SIGCHLD, SIG_DFL);
150         if (cleanup_ctxt == NULL)
151                 return; /* handler called after PAM cleanup, shouldn't happen */
152         if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, WNOHANG)
153             <= 0) {
154                 /* PAM thread has not exitted, privsep slave must have */
155                 kill(cleanup_ctxt->pam_thread, SIGTERM);
156                 if (waitpid(cleanup_ctxt->pam_thread, &sshpam_thread_status, 0)
157                     <= 0)
158                         return; /* could not wait */
159         }
160         if (WIFSIGNALED(sshpam_thread_status) &&
161             WTERMSIG(sshpam_thread_status) == SIGTERM)
162                 return; /* terminated by pthread_cancel */
163         if (!WIFEXITED(sshpam_thread_status))
164                 sigdie("PAM: authentication thread exited unexpectedly");
165         if (WEXITSTATUS(sshpam_thread_status) != 0)
166                 sigdie("PAM: authentication thread exited uncleanly");
167 }
168
169 /* ARGSUSED */
170 static void
171 pthread_exit(void *value)
172 {
173         _exit(0);
174 }
175
176 /* ARGSUSED */
177 static int
178 pthread_create(sp_pthread_t *thread, const void *attr,
179     void *(*thread_start)(void *), void *arg)
180 {
181         pid_t pid;
182         struct pam_ctxt *ctx = arg;
183
184         sshpam_thread_status = -1;
185         switch ((pid = fork())) {
186         case -1:
187                 error("fork(): %s", strerror(errno));
188                 return (-1);
189         case 0:
190                 close(ctx->pam_psock);
191                 ctx->pam_psock = -1;
192                 thread_start(arg);
193                 _exit(1);
194         default:
195                 *thread = pid;
196                 close(ctx->pam_csock);
197                 ctx->pam_csock = -1;
198                 sshpam_oldsig = signal(SIGCHLD, sshpam_sigchld_handler);
199                 return (0);
200         }
201 }
202
203 static int
204 pthread_cancel(sp_pthread_t thread)
205 {
206         signal(SIGCHLD, sshpam_oldsig);
207         return (kill(thread, SIGTERM));
208 }
209
210 /* ARGSUSED */
211 static int
212 pthread_join(sp_pthread_t thread, void **value)
213 {
214         int status;
215
216         if (sshpam_thread_status != -1)
217                 return (sshpam_thread_status);
218         signal(SIGCHLD, sshpam_oldsig);
219         waitpid(thread, &status, 0);
220         return (status);
221 }
222 #endif
223
224
225 static pam_handle_t *sshpam_handle = NULL;
226 static int sshpam_err = 0;
227 static int sshpam_authenticated = 0;
228 static int sshpam_session_open = 0;
229 static int sshpam_cred_established = 0;
230 static int sshpam_account_status = -1;
231 static char **sshpam_env = NULL;
232 static Authctxt *sshpam_authctxt = NULL;
233 static const char *sshpam_password = NULL;
234 static char badpw[] = "\b\n\r\177INCORRECT";
235
236 /* Some PAM implementations don't implement this */
237 #ifndef HAVE_PAM_GETENVLIST
238 static char **
239 pam_getenvlist(pam_handle_t *pamh)
240 {
241         /*
242          * XXX - If necessary, we can still support envrionment passing
243          * for platforms without pam_getenvlist by searching for known
244          * env vars (e.g. KRB5CCNAME) from the PAM environment.
245          */
246          return NULL;
247 }
248 #endif
249
250 /*
251  * Some platforms, notably Solaris, do not enforce password complexity
252  * rules during pam_chauthtok() if the real uid of the calling process
253  * is 0, on the assumption that it's being called by "passwd" run by root.
254  * This wraps pam_chauthtok and sets/restore the real uid so PAM will do
255  * the right thing.
256  */
257 #ifdef SSHPAM_CHAUTHTOK_NEEDS_RUID
258 static int
259 sshpam_chauthtok_ruid(pam_handle_t *pamh, int flags)
260 {
261         int result;
262
263         if (sshpam_authctxt == NULL)
264                 fatal("PAM: sshpam_authctxt not initialized");
265         if (setreuid(sshpam_authctxt->pw->pw_uid, -1) == -1)
266                 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
267         result = pam_chauthtok(pamh, flags);
268         if (setreuid(0, -1) == -1)
269                 fatal("%s: setreuid failed: %s", __func__, strerror(errno));
270         return result;
271 }
272 # define pam_chauthtok(a,b)     (sshpam_chauthtok_ruid((a), (b)))
273 #endif
274
275 void
276 sshpam_password_change_required(int reqd)
277 {
278         debug3("%s %d", __func__, reqd);
279         if (sshpam_authctxt == NULL)
280                 fatal("%s: PAM authctxt not initialized", __func__);
281         sshpam_authctxt->force_pwchange = reqd;
282         if (reqd) {
283                 no_port_forwarding_flag |= 2;
284                 no_agent_forwarding_flag |= 2;
285                 no_x11_forwarding_flag |= 2;
286         } else {
287                 no_port_forwarding_flag &= ~2;
288                 no_agent_forwarding_flag &= ~2;
289                 no_x11_forwarding_flag &= ~2;
290         }
291 }
292
293 /* Import regular and PAM environment from subprocess */
294 static void
295 import_environments(Buffer *b)
296 {
297         char *env;
298         u_int i, num_env;
299         int err;
300
301         debug3("PAM: %s entering", __func__);
302
303 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
304         /* Import variables set by do_pam_account */
305         sshpam_account_status = buffer_get_int(b);
306         sshpam_password_change_required(buffer_get_int(b));
307
308         /* Import environment from subprocess */
309         num_env = buffer_get_int(b);
310         if (num_env > 1024)
311                 fatal("%s: received %u environment variables, expected <= 1024",
312                     __func__, num_env);
313         sshpam_env = xcalloc(num_env + 1, sizeof(*sshpam_env));
314         debug3("PAM: num env strings %d", num_env);
315         for(i = 0; i < num_env; i++)
316                 sshpam_env[i] = buffer_get_string(b, NULL);
317
318         sshpam_env[num_env] = NULL;
319
320         /* Import PAM environment from subprocess */
321         num_env = buffer_get_int(b);
322         debug("PAM: num PAM env strings %d", num_env);
323         for(i = 0; i < num_env; i++) {
324                 env = buffer_get_string(b, NULL);
325
326 #ifdef HAVE_PAM_PUTENV
327                 /* Errors are not fatal here */
328                 if ((err = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
329                         error("PAM: pam_putenv: %s",
330                             pam_strerror(sshpam_handle, sshpam_err));
331                 }
332 #endif
333         }
334 #endif
335 }
336
337 /*
338  * Conversation function for authentication thread.
339  */
340 static int
341 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
342     struct pam_response **resp, void *data)
343 {
344         Buffer buffer;
345         struct pam_ctxt *ctxt;
346         struct pam_response *reply;
347         int i;
348
349         debug3("PAM: %s entering, %d messages", __func__, n);
350         *resp = NULL;
351
352         if (data == NULL) {
353                 error("PAM: conversation function passed a null context");
354                 return (PAM_CONV_ERR);
355         }
356         ctxt = data;
357         if (n <= 0 || n > PAM_MAX_NUM_MSG)
358                 return (PAM_CONV_ERR);
359
360         if ((reply = calloc(n, sizeof(*reply))) == NULL)
361                 return (PAM_CONV_ERR);
362
363         buffer_init(&buffer);
364         for (i = 0; i < n; ++i) {
365                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
366                 case PAM_PROMPT_ECHO_OFF:
367                         buffer_put_cstring(&buffer,
368                             PAM_MSG_MEMBER(msg, i, msg));
369                         if (ssh_msg_send(ctxt->pam_csock,
370                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
371                                 goto fail;
372                         if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
373                                 goto fail;
374                         if (buffer_get_char(&buffer) != PAM_AUTHTOK)
375                                 goto fail;
376                         reply[i].resp = buffer_get_string(&buffer, NULL);
377                         break;
378                 case PAM_PROMPT_ECHO_ON:
379                         buffer_put_cstring(&buffer,
380                             PAM_MSG_MEMBER(msg, i, msg));
381                         if (ssh_msg_send(ctxt->pam_csock,
382                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
383                                 goto fail;
384                         if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
385                                 goto fail;
386                         if (buffer_get_char(&buffer) != PAM_AUTHTOK)
387                                 goto fail;
388                         reply[i].resp = buffer_get_string(&buffer, NULL);
389                         break;
390                 case PAM_ERROR_MSG:
391                         buffer_put_cstring(&buffer,
392                             PAM_MSG_MEMBER(msg, i, msg));
393                         if (ssh_msg_send(ctxt->pam_csock,
394                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
395                                 goto fail;
396                         break;
397                 case PAM_TEXT_INFO:
398                         buffer_put_cstring(&buffer,
399                             PAM_MSG_MEMBER(msg, i, msg));
400                         if (ssh_msg_send(ctxt->pam_csock,
401                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
402                                 goto fail;
403                         break;
404                 default:
405                         goto fail;
406                 }
407                 buffer_clear(&buffer);
408         }
409         buffer_free(&buffer);
410         *resp = reply;
411         return (PAM_SUCCESS);
412
413  fail:
414         for(i = 0; i < n; i++) {
415                 free(reply[i].resp);
416         }
417         free(reply);
418         buffer_free(&buffer);
419         return (PAM_CONV_ERR);
420 }
421
422 /*
423  * Authentication thread.
424  */
425 static void *
426 sshpam_thread(void *ctxtp)
427 {
428         struct pam_ctxt *ctxt = ctxtp;
429         Buffer buffer;
430         struct pam_conv sshpam_conv;
431         int flags = (options.permit_empty_passwd == 0 ?
432             PAM_DISALLOW_NULL_AUTHTOK : 0);
433 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
434         extern char **environ;
435         char **env_from_pam;
436         u_int i;
437         const char *pam_user;
438         const char **ptr_pam_user = &pam_user;
439         char *tz = getenv("TZ");
440
441         sshpam_err = pam_get_item(sshpam_handle, PAM_USER,
442             (sshpam_const void **)ptr_pam_user);
443         if (sshpam_err != PAM_SUCCESS)
444                 goto auth_fail;
445
446         environ[0] = NULL;
447         if (tz != NULL)
448                 if (setenv("TZ", tz, 1) == -1)
449                         error("PAM: could not set TZ environment: %s",
450                             strerror(errno));
451
452         if (sshpam_authctxt != NULL) {
453                 setproctitle("%s [pam]",
454                     sshpam_authctxt->valid ? pam_user : "unknown");
455         }
456 #endif
457
458         sshpam_conv.conv = sshpam_thread_conv;
459         sshpam_conv.appdata_ptr = ctxt;
460
461         if (sshpam_authctxt == NULL)
462                 fatal("%s: PAM authctxt not initialized", __func__);
463
464         buffer_init(&buffer);
465         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
466             (const void *)&sshpam_conv);
467         if (sshpam_err != PAM_SUCCESS)
468                 goto auth_fail;
469         sshpam_err = pam_authenticate(sshpam_handle, flags);
470         if (sshpam_err != PAM_SUCCESS)
471                 goto auth_fail;
472
473         if (compat20) {
474                 if (!do_pam_account()) {
475                         sshpam_err = PAM_ACCT_EXPIRED;
476                         goto auth_fail;
477                 }
478                 if (sshpam_authctxt->force_pwchange) {
479                         sshpam_err = pam_chauthtok(sshpam_handle,
480                             PAM_CHANGE_EXPIRED_AUTHTOK);
481                         if (sshpam_err != PAM_SUCCESS)
482                                 goto auth_fail;
483                         sshpam_password_change_required(0);
484                 }
485         }
486
487         buffer_put_cstring(&buffer, "OK");
488
489 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
490         /* Export variables set by do_pam_account */
491         buffer_put_int(&buffer, sshpam_account_status);
492         buffer_put_int(&buffer, sshpam_authctxt->force_pwchange);
493
494         /* Export any environment strings set in child */
495         for(i = 0; environ[i] != NULL; i++)
496                 ; /* Count */
497         buffer_put_int(&buffer, i);
498         for(i = 0; environ[i] != NULL; i++)
499                 buffer_put_cstring(&buffer, environ[i]);
500
501         /* Export any environment strings set by PAM in child */
502         env_from_pam = pam_getenvlist(sshpam_handle);
503         for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
504                 ; /* Count */
505         buffer_put_int(&buffer, i);
506         for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
507                 buffer_put_cstring(&buffer, env_from_pam[i]);
508 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
509
510         /* XXX - can't do much about an error here */
511         ssh_msg_send(ctxt->pam_csock, sshpam_err, &buffer);
512         buffer_free(&buffer);
513         pthread_exit(NULL);
514
515  auth_fail:
516         buffer_put_cstring(&buffer,
517             pam_strerror(sshpam_handle, sshpam_err));
518         /* XXX - can't do much about an error here */
519         if (sshpam_err == PAM_ACCT_EXPIRED)
520                 ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, &buffer);
521         else
522                 ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
523         buffer_free(&buffer);
524         pthread_exit(NULL);
525
526         return (NULL); /* Avoid warning for non-pthread case */
527 }
528
529 void
530 sshpam_thread_cleanup(void)
531 {
532         struct pam_ctxt *ctxt = cleanup_ctxt;
533
534         debug3("PAM: %s entering", __func__);
535         if (ctxt != NULL && ctxt->pam_thread != 0) {
536                 pthread_cancel(ctxt->pam_thread);
537                 pthread_join(ctxt->pam_thread, NULL);
538                 close(ctxt->pam_psock);
539                 close(ctxt->pam_csock);
540                 memset(ctxt, 0, sizeof(*ctxt));
541                 cleanup_ctxt = NULL;
542         }
543 }
544
545 static int
546 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
547     struct pam_response **resp, void *data)
548 {
549         debug3("PAM: %s entering, %d messages", __func__, n);
550         return (PAM_CONV_ERR);
551 }
552
553 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
554
555 static int
556 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
557     struct pam_response **resp, void *data)
558 {
559         struct pam_response *reply;
560         int i;
561         size_t len;
562
563         debug3("PAM: %s called with %d messages", __func__, n);
564         *resp = NULL;
565
566         if (n <= 0 || n > PAM_MAX_NUM_MSG)
567                 return (PAM_CONV_ERR);
568
569         if ((reply = calloc(n, sizeof(*reply))) == NULL)
570                 return (PAM_CONV_ERR);
571
572         for (i = 0; i < n; ++i) {
573                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
574                 case PAM_ERROR_MSG:
575                 case PAM_TEXT_INFO:
576                         len = strlen(PAM_MSG_MEMBER(msg, i, msg));
577                         buffer_append(&loginmsg, PAM_MSG_MEMBER(msg, i, msg), len);
578                         buffer_append(&loginmsg, "\n", 1 );
579                         reply[i].resp_retcode = PAM_SUCCESS;
580                         break;
581                 default:
582                         goto fail;
583                 }
584         }
585         *resp = reply;
586         return (PAM_SUCCESS);
587
588  fail:
589         for(i = 0; i < n; i++) {
590                 free(reply[i].resp);
591         }
592         free(reply);
593         return (PAM_CONV_ERR);
594 }
595
596 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
597
598 void
599 sshpam_cleanup(void)
600 {
601         if (sshpam_handle == NULL || (use_privsep && !mm_is_monitor()))
602                 return;
603         debug("PAM: cleanup");
604         pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
605         if (sshpam_session_open) {
606                 debug("PAM: closing session");
607                 pam_close_session(sshpam_handle, PAM_SILENT);
608                 sshpam_session_open = 0;
609         }
610         if (sshpam_cred_established) {
611                 debug("PAM: deleting credentials");
612                 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
613                 sshpam_cred_established = 0;
614         }
615         sshpam_authenticated = 0;
616         pam_end(sshpam_handle, sshpam_err);
617         sshpam_handle = NULL;
618 }
619
620 static int
621 sshpam_init(Authctxt *authctxt)
622 {
623         extern char *__progname;
624         const char *pam_rhost, *pam_user, *user = authctxt->user;
625         const char **ptr_pam_user = &pam_user;
626
627         if (sshpam_handle != NULL) {
628                 /* We already have a PAM context; check if the user matches */
629                 sshpam_err = pam_get_item(sshpam_handle,
630                     PAM_USER, (sshpam_const void **)ptr_pam_user);
631                 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
632                         return (0);
633                 pam_end(sshpam_handle, sshpam_err);
634                 sshpam_handle = NULL;
635         }
636         debug("PAM: initializing for \"%s\"", user);
637         sshpam_err =
638             pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
639         sshpam_authctxt = authctxt;
640
641         if (sshpam_err != PAM_SUCCESS) {
642                 pam_end(sshpam_handle, sshpam_err);
643                 sshpam_handle = NULL;
644                 return (-1);
645         }
646         pam_rhost = get_remote_name_or_ip(utmp_len, options.use_dns);
647         debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
648         sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
649         if (sshpam_err != PAM_SUCCESS) {
650                 pam_end(sshpam_handle, sshpam_err);
651                 sshpam_handle = NULL;
652                 return (-1);
653         }
654 #ifdef PAM_TTY_KLUDGE
655         /*
656          * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
657          * sshd doesn't set the tty until too late in the auth process and
658          * may not even set one (for tty-less connections)
659          */
660         debug("PAM: setting PAM_TTY to \"ssh\"");
661         sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
662         if (sshpam_err != PAM_SUCCESS) {
663                 pam_end(sshpam_handle, sshpam_err);
664                 sshpam_handle = NULL;
665                 return (-1);
666         }
667 #endif
668         return (0);
669 }
670
671 static void *
672 sshpam_init_ctx(Authctxt *authctxt)
673 {
674         struct pam_ctxt *ctxt;
675         int socks[2];
676
677         debug3("PAM: %s entering", __func__);
678         /*
679          * Refuse to start if we don't have PAM enabled or do_pam_account
680          * has previously failed.
681          */
682         if (!options.use_pam || sshpam_account_status == 0)
683                 return NULL;
684
685         /* Initialize PAM */
686         if (sshpam_init(authctxt) == -1) {
687                 error("PAM: initialization failed");
688                 return (NULL);
689         }
690
691         ctxt = xcalloc(1, sizeof *ctxt);
692
693         /* Start the authentication thread */
694         if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
695                 error("PAM: failed create sockets: %s", strerror(errno));
696                 free(ctxt);
697                 return (NULL);
698         }
699         ctxt->pam_psock = socks[0];
700         ctxt->pam_csock = socks[1];
701         if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
702                 error("PAM: failed to start authentication thread: %s",
703                     strerror(errno));
704                 close(socks[0]);
705                 close(socks[1]);
706                 free(ctxt);
707                 return (NULL);
708         }
709         cleanup_ctxt = ctxt;
710         return (ctxt);
711 }
712
713 static int
714 sshpam_query(void *ctx, char **name, char **info,
715     u_int *num, char ***prompts, u_int **echo_on)
716 {
717         Buffer buffer;
718         struct pam_ctxt *ctxt = ctx;
719         size_t plen;
720         u_char type;
721         char *msg;
722         size_t len, mlen;
723
724         debug3("PAM: %s entering", __func__);
725         buffer_init(&buffer);
726         *name = xstrdup("");
727         *info = xstrdup("");
728         *prompts = xmalloc(sizeof(char *));
729         **prompts = NULL;
730         plen = 0;
731         *echo_on = xmalloc(sizeof(u_int));
732         while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
733                 type = buffer_get_char(&buffer);
734                 msg = buffer_get_string(&buffer, NULL);
735                 mlen = strlen(msg);
736                 switch (type) {
737                 case PAM_PROMPT_ECHO_ON:
738                 case PAM_PROMPT_ECHO_OFF:
739                         *num = 1;
740                         len = plen + mlen + 1;
741                         **prompts = xrealloc(**prompts, 1, len);
742                         strlcpy(**prompts + plen, msg, len - plen);
743                         plen += mlen;
744                         **echo_on = (type == PAM_PROMPT_ECHO_ON);
745                         free(msg);
746                         return (0);
747                 case PAM_ERROR_MSG:
748                 case PAM_TEXT_INFO:
749                         /* accumulate messages */
750                         len = plen + mlen + 2;
751                         **prompts = xrealloc(**prompts, 1, len);
752                         strlcpy(**prompts + plen, msg, len - plen);
753                         plen += mlen;
754                         strlcat(**prompts + plen, "\n", len - plen);
755                         plen++;
756                         free(msg);
757                         break;
758                 case PAM_ACCT_EXPIRED:
759                         sshpam_account_status = 0;
760                         /* FALLTHROUGH */
761                 case PAM_AUTH_ERR:
762                         debug3("PAM: %s", pam_strerror(sshpam_handle, type));
763                         if (**prompts != NULL && strlen(**prompts) != 0) {
764                                 *info = **prompts;
765                                 **prompts = NULL;
766                                 *num = 0;
767                                 **echo_on = 0;
768                                 ctxt->pam_done = -1;
769                                 free(msg);
770                                 return 0;
771                         }
772                         /* FALLTHROUGH */
773                 case PAM_SUCCESS:
774                         if (**prompts != NULL) {
775                                 /* drain any accumulated messages */
776                                 debug("PAM: %s", **prompts);
777                                 buffer_append(&loginmsg, **prompts,
778                                     strlen(**prompts));
779                                 free(**prompts);
780                                 **prompts = NULL;
781                         }
782                         if (type == PAM_SUCCESS) {
783                                 if (!sshpam_authctxt->valid ||
784                                     (sshpam_authctxt->pw->pw_uid == 0 &&
785                                     options.permit_root_login != PERMIT_YES))
786                                         fatal("Internal error: PAM auth "
787                                             "succeeded when it should have "
788                                             "failed");
789 #ifndef USE_POSIX_THREADS
790                 import_environments(&buffer);
791 #endif
792                                 *num = 0;
793                                 **echo_on = 0;
794                                 ctxt->pam_done = 1;
795                                 free(msg);
796                                 return (0);
797                         }
798                         error("PAM: %s for %s%.100s from %.100s", msg,
799                             sshpam_authctxt->valid ? "" : "illegal user ",
800                             sshpam_authctxt->user,
801                             get_remote_name_or_ip(utmp_len, options.use_dns));
802                         /* FALLTHROUGH */
803                 default:
804                         *num = 0;
805                         **echo_on = 0;
806                         free(msg);
807                         ctxt->pam_done = -1;
808                         return (-1);
809                 }
810         }
811         return (-1);
812 }
813
814 /* XXX - see also comment in auth-chall.c:verify_response */
815 static int
816 sshpam_respond(void *ctx, u_int num, char **resp)
817 {
818         Buffer buffer;
819         struct pam_ctxt *ctxt = ctx;
820
821         debug2("PAM: %s entering, %u responses", __func__, num);
822         switch (ctxt->pam_done) {
823         case 1:
824                 sshpam_authenticated = 1;
825                 return (0);
826         case 0:
827                 break;
828         default:
829                 return (-1);
830         }
831         if (num != 1) {
832                 error("PAM: expected one response, got %u", num);
833                 return (-1);
834         }
835         buffer_init(&buffer);
836         if (sshpam_authctxt->valid &&
837             (sshpam_authctxt->pw->pw_uid != 0 ||
838             options.permit_root_login == PERMIT_YES))
839                 buffer_put_cstring(&buffer, *resp);
840         else
841                 buffer_put_cstring(&buffer, badpw);
842         if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer) == -1) {
843                 buffer_free(&buffer);
844                 return (-1);
845         }
846         buffer_free(&buffer);
847         return (1);
848 }
849
850 static void
851 sshpam_free_ctx(void *ctxtp)
852 {
853         struct pam_ctxt *ctxt = ctxtp;
854
855         debug3("PAM: %s entering", __func__);
856         sshpam_thread_cleanup();
857         free(ctxt);
858         /*
859          * We don't call sshpam_cleanup() here because we may need the PAM
860          * handle at a later stage, e.g. when setting up a session.  It's
861          * still on the cleanup list, so pam_end() *will* be called before
862          * the server process terminates.
863          */
864 }
865
866 KbdintDevice sshpam_device = {
867         "pam",
868         sshpam_init_ctx,
869         sshpam_query,
870         sshpam_respond,
871         sshpam_free_ctx
872 };
873
874 KbdintDevice mm_sshpam_device = {
875         "pam",
876         mm_sshpam_init_ctx,
877         mm_sshpam_query,
878         mm_sshpam_respond,
879         mm_sshpam_free_ctx
880 };
881
882 /*
883  * This replaces auth-pam.c
884  */
885 void
886 start_pam(Authctxt *authctxt)
887 {
888         if (!options.use_pam)
889                 fatal("PAM: initialisation requested when UsePAM=no");
890
891         if (sshpam_init(authctxt) == -1)
892                 fatal("PAM: initialisation failed");
893 }
894
895 void
896 finish_pam(void)
897 {
898         sshpam_cleanup();
899 }
900
901 u_int
902 do_pam_account(void)
903 {
904         debug("%s: called", __func__);
905         if (sshpam_account_status != -1)
906                 return (sshpam_account_status);
907
908         sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
909         debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
910             pam_strerror(sshpam_handle, sshpam_err));
911
912         if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
913                 sshpam_account_status = 0;
914                 return (sshpam_account_status);
915         }
916
917         if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
918                 sshpam_password_change_required(1);
919
920         sshpam_account_status = 1;
921         return (sshpam_account_status);
922 }
923
924 void
925 do_pam_set_tty(const char *tty)
926 {
927         if (tty != NULL) {
928                 debug("PAM: setting PAM_TTY to \"%s\"", tty);
929                 sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, tty);
930                 if (sshpam_err != PAM_SUCCESS)
931                         fatal("PAM: failed to set PAM_TTY: %s",
932                             pam_strerror(sshpam_handle, sshpam_err));
933         }
934 }
935
936 void
937 do_pam_setcred(int init)
938 {
939         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
940             (const void *)&store_conv);
941         if (sshpam_err != PAM_SUCCESS)
942                 fatal("PAM: failed to set PAM_CONV: %s",
943                     pam_strerror(sshpam_handle, sshpam_err));
944         if (init) {
945                 debug("PAM: establishing credentials");
946                 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
947         } else {
948                 debug("PAM: reinitializing credentials");
949                 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
950         }
951         if (sshpam_err == PAM_SUCCESS) {
952                 sshpam_cred_established = 1;
953                 return;
954         }
955         if (sshpam_authenticated)
956                 fatal("PAM: pam_setcred(): %s",
957                     pam_strerror(sshpam_handle, sshpam_err));
958         else
959                 debug("PAM: pam_setcred(): %s",
960                     pam_strerror(sshpam_handle, sshpam_err));
961 }
962
963 static int
964 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
965     struct pam_response **resp, void *data)
966 {
967         char input[PAM_MAX_MSG_SIZE];
968         struct pam_response *reply;
969         int i;
970
971         debug3("PAM: %s called with %d messages", __func__, n);
972
973         *resp = NULL;
974
975         if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
976                 return (PAM_CONV_ERR);
977
978         if ((reply = calloc(n, sizeof(*reply))) == NULL)
979                 return (PAM_CONV_ERR);
980
981         for (i = 0; i < n; ++i) {
982                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
983                 case PAM_PROMPT_ECHO_OFF:
984                         reply[i].resp =
985                             read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
986                             RP_ALLOW_STDIN);
987                         reply[i].resp_retcode = PAM_SUCCESS;
988                         break;
989                 case PAM_PROMPT_ECHO_ON:
990                         fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
991                         if (fgets(input, sizeof input, stdin) == NULL)
992                                 input[0] = '\0';
993                         if ((reply[i].resp = strdup(input)) == NULL)
994                                 goto fail;
995                         reply[i].resp_retcode = PAM_SUCCESS;
996                         break;
997                 case PAM_ERROR_MSG:
998                 case PAM_TEXT_INFO:
999                         fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1000                         reply[i].resp_retcode = PAM_SUCCESS;
1001                         break;
1002                 default:
1003                         goto fail;
1004                 }
1005         }
1006         *resp = reply;
1007         return (PAM_SUCCESS);
1008
1009  fail:
1010         for(i = 0; i < n; i++) {
1011                 free(reply[i].resp);
1012         }
1013         free(reply);
1014         return (PAM_CONV_ERR);
1015 }
1016
1017 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
1018
1019 /*
1020  * XXX this should be done in the authentication phase, but ssh1 doesn't
1021  * support that
1022  */
1023 void
1024 do_pam_chauthtok(void)
1025 {
1026         if (use_privsep)
1027                 fatal("Password expired (unable to change with privsep)");
1028         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1029             (const void *)&tty_conv);
1030         if (sshpam_err != PAM_SUCCESS)
1031                 fatal("PAM: failed to set PAM_CONV: %s",
1032                     pam_strerror(sshpam_handle, sshpam_err));
1033         debug("PAM: changing password");
1034         sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1035         if (sshpam_err != PAM_SUCCESS)
1036                 fatal("PAM: pam_chauthtok(): %s",
1037                     pam_strerror(sshpam_handle, sshpam_err));
1038 }
1039
1040 void
1041 do_pam_session(void)
1042 {
1043         debug3("PAM: opening session");
1044         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1045             (const void *)&store_conv);
1046         if (sshpam_err != PAM_SUCCESS)
1047                 fatal("PAM: failed to set PAM_CONV: %s",
1048                     pam_strerror(sshpam_handle, sshpam_err));
1049         sshpam_err = pam_open_session(sshpam_handle, 0);
1050         if (sshpam_err == PAM_SUCCESS)
1051                 sshpam_session_open = 1;
1052         else {
1053                 sshpam_session_open = 0;
1054                 disable_forwarding();
1055                 error("PAM: pam_open_session(): %s",
1056                     pam_strerror(sshpam_handle, sshpam_err));
1057         }
1058
1059 }
1060
1061 int
1062 is_pam_session_open(void)
1063 {
1064         return sshpam_session_open;
1065 }
1066
1067 /*
1068  * Set a PAM environment string. We need to do this so that the session
1069  * modules can handle things like Kerberos/GSI credentials that appear
1070  * during the ssh authentication process.
1071  */
1072 int
1073 do_pam_putenv(char *name, char *value)
1074 {
1075         int ret = 1;
1076 #ifdef HAVE_PAM_PUTENV
1077         char *compound;
1078         size_t len;
1079
1080         len = strlen(name) + strlen(value) + 2;
1081         compound = xmalloc(len);
1082
1083         snprintf(compound, len, "%s=%s", name, value);
1084         ret = pam_putenv(sshpam_handle, compound);
1085         free(compound);
1086 #endif
1087
1088         return (ret);
1089 }
1090
1091 char **
1092 fetch_pam_child_environment(void)
1093 {
1094         return sshpam_env;
1095 }
1096
1097 char **
1098 fetch_pam_environment(void)
1099 {
1100         return (pam_getenvlist(sshpam_handle));
1101 }
1102
1103 void
1104 free_pam_environment(char **env)
1105 {
1106         char **envp;
1107
1108         if (env == NULL)
1109                 return;
1110
1111         for (envp = env; *envp; envp++)
1112                 free(*envp);
1113         free(env);
1114 }
1115
1116 /*
1117  * "Blind" conversation function for password authentication.  Assumes that
1118  * echo-off prompts are for the password and stores messages for later
1119  * display.
1120  */
1121 static int
1122 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1123     struct pam_response **resp, void *data)
1124 {
1125         struct pam_response *reply;
1126         int i;
1127         size_t len;
1128
1129         debug3("PAM: %s called with %d messages", __func__, n);
1130
1131         *resp = NULL;
1132
1133         if (n <= 0 || n > PAM_MAX_NUM_MSG)
1134                 return (PAM_CONV_ERR);
1135
1136         if ((reply = calloc(n, sizeof(*reply))) == NULL)
1137                 return (PAM_CONV_ERR);
1138
1139         for (i = 0; i < n; ++i) {
1140                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1141                 case PAM_PROMPT_ECHO_OFF:
1142                         if (sshpam_password == NULL)
1143                                 goto fail;
1144                         if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1145                                 goto fail;
1146                         reply[i].resp_retcode = PAM_SUCCESS;
1147                         break;
1148                 case PAM_ERROR_MSG:
1149                 case PAM_TEXT_INFO:
1150                         len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1151                         if (len > 0) {
1152                                 buffer_append(&loginmsg,
1153                                     PAM_MSG_MEMBER(msg, i, msg), len);
1154                                 buffer_append(&loginmsg, "\n", 1);
1155                         }
1156                         if ((reply[i].resp = strdup("")) == NULL)
1157                                 goto fail;
1158                         reply[i].resp_retcode = PAM_SUCCESS;
1159                         break;
1160                 default:
1161                         goto fail;
1162                 }
1163         }
1164         *resp = reply;
1165         return (PAM_SUCCESS);
1166
1167  fail:
1168         for(i = 0; i < n; i++) {
1169                 free(reply[i].resp);
1170         }
1171         free(reply);
1172         return (PAM_CONV_ERR);
1173 }
1174
1175 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1176
1177 /*
1178  * Attempt password authentication via PAM
1179  */
1180 int
1181 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1182 {
1183         int flags = (options.permit_empty_passwd == 0 ?
1184             PAM_DISALLOW_NULL_AUTHTOK : 0);
1185
1186         if (!options.use_pam || sshpam_handle == NULL)
1187                 fatal("PAM: %s called when PAM disabled or failed to "
1188                     "initialise.", __func__);
1189
1190         sshpam_password = password;
1191         sshpam_authctxt = authctxt;
1192
1193         /*
1194          * If the user logging in is invalid, or is root but is not permitted
1195          * by PermitRootLogin, use an invalid password to prevent leaking
1196          * information via timing (eg if the PAM config has a delay on fail).
1197          */
1198         if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1199             options.permit_root_login != PERMIT_YES))
1200                 sshpam_password = badpw;
1201
1202         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1203             (const void *)&passwd_conv);
1204         if (sshpam_err != PAM_SUCCESS)
1205                 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1206                     pam_strerror(sshpam_handle, sshpam_err));
1207
1208         sshpam_err = pam_authenticate(sshpam_handle, flags);
1209         sshpam_password = NULL;
1210         if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1211                 debug("PAM: password authentication accepted for %.100s",
1212                     authctxt->user);
1213                 return 1;
1214         } else {
1215                 debug("PAM: password authentication failed for %.100s: %s",
1216                     authctxt->valid ? authctxt->user : "an illegal user",
1217                     pam_strerror(sshpam_handle, sshpam_err));
1218                 return 0;
1219         }
1220 }
1221 #endif /* USE_PAM */