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