]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - auth-pam.c
Vendor import of OpenSSH 7.7p1.
[FreeBSD/FreeBSD.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 */
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         extern struct sshauthopt *auth_opts;
291         static int saved_port, saved_agent, saved_x11;
292
293         debug3("%s %d", __func__, reqd);
294         if (sshpam_authctxt == NULL)
295                 fatal("%s: PAM authctxt not initialized", __func__);
296         sshpam_authctxt->force_pwchange = reqd;
297         if (reqd) {
298                 saved_port = auth_opts->permit_port_forwarding_flag;
299                 saved_agent = auth_opts->permit_agent_forwarding_flag;
300                 saved_x11 = auth_opts->permit_x11_forwarding_flag;
301                 auth_opts->permit_port_forwarding_flag = 0;
302                 auth_opts->permit_agent_forwarding_flag = 0;
303                 auth_opts->permit_x11_forwarding_flag = 0;
304         } else {
305                 if (saved_port)
306                         auth_opts->permit_port_forwarding_flag = saved_port;
307                 if (saved_agent)
308                         auth_opts->permit_agent_forwarding_flag = saved_agent;
309                 if (saved_x11)
310                         auth_opts->permit_x11_forwarding_flag = saved_x11;
311         }
312 }
313
314 /* Import regular and PAM environment from subprocess */
315 static void
316 import_environments(Buffer *b)
317 {
318         char *env;
319         u_int i, num_env;
320         int err;
321
322         debug3("PAM: %s entering", __func__);
323
324 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
325         /* Import variables set by do_pam_account */
326         sshpam_account_status = buffer_get_int(b);
327         sshpam_password_change_required(buffer_get_int(b));
328
329         /* Import environment from subprocess */
330         num_env = buffer_get_int(b);
331         if (num_env > 1024)
332                 fatal("%s: received %u environment variables, expected <= 1024",
333                     __func__, num_env);
334         sshpam_env = xcalloc(num_env + 1, sizeof(*sshpam_env));
335         debug3("PAM: num env strings %d", num_env);
336         for(i = 0; i < num_env; i++)
337                 sshpam_env[i] = buffer_get_string(b, NULL);
338
339         sshpam_env[num_env] = NULL;
340
341         /* Import PAM environment from subprocess */
342         num_env = buffer_get_int(b);
343         debug("PAM: num PAM env strings %d", num_env);
344         for(i = 0; i < num_env; i++) {
345                 env = buffer_get_string(b, NULL);
346
347 #ifdef HAVE_PAM_PUTENV
348                 /* Errors are not fatal here */
349                 if ((err = pam_putenv(sshpam_handle, env)) != PAM_SUCCESS) {
350                         error("PAM: pam_putenv: %s",
351                             pam_strerror(sshpam_handle, sshpam_err));
352                 }
353 #endif
354         }
355 #endif
356 }
357
358 /*
359  * Conversation function for authentication thread.
360  */
361 static int
362 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
363     struct pam_response **resp, void *data)
364 {
365         Buffer buffer;
366         struct pam_ctxt *ctxt;
367         struct pam_response *reply;
368         int i;
369
370         debug3("PAM: %s entering, %d messages", __func__, n);
371         *resp = NULL;
372
373         if (data == NULL) {
374                 error("PAM: conversation function passed a null context");
375                 return (PAM_CONV_ERR);
376         }
377         ctxt = data;
378         if (n <= 0 || n > PAM_MAX_NUM_MSG)
379                 return (PAM_CONV_ERR);
380
381         if ((reply = calloc(n, sizeof(*reply))) == NULL)
382                 return (PAM_CONV_ERR);
383
384         buffer_init(&buffer);
385         for (i = 0; i < n; ++i) {
386                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
387                 case PAM_PROMPT_ECHO_OFF:
388                 case PAM_PROMPT_ECHO_ON:
389                         buffer_put_cstring(&buffer,
390                             PAM_MSG_MEMBER(msg, i, msg));
391                         if (ssh_msg_send(ctxt->pam_csock,
392                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
393                                 goto fail;
394                         if (ssh_msg_recv(ctxt->pam_csock, &buffer) == -1)
395                                 goto fail;
396                         if (buffer_get_char(&buffer) != PAM_AUTHTOK)
397                                 goto fail;
398                         reply[i].resp = buffer_get_string(&buffer, NULL);
399                         break;
400                 case PAM_ERROR_MSG:
401                 case PAM_TEXT_INFO:
402                         buffer_put_cstring(&buffer,
403                             PAM_MSG_MEMBER(msg, i, msg));
404                         if (ssh_msg_send(ctxt->pam_csock,
405                             PAM_MSG_MEMBER(msg, i, msg_style), &buffer) == -1)
406                                 goto fail;
407                         break;
408                 default:
409                         goto fail;
410                 }
411                 buffer_clear(&buffer);
412         }
413         buffer_free(&buffer);
414         *resp = reply;
415         return (PAM_SUCCESS);
416
417  fail:
418         for(i = 0; i < n; i++) {
419                 free(reply[i].resp);
420         }
421         free(reply);
422         buffer_free(&buffer);
423         return (PAM_CONV_ERR);
424 }
425
426 /*
427  * Authentication thread.
428  */
429 static void *
430 sshpam_thread(void *ctxtp)
431 {
432         struct pam_ctxt *ctxt = ctxtp;
433         Buffer buffer;
434         struct pam_conv sshpam_conv;
435         int flags = (options.permit_empty_passwd == 0 ?
436             PAM_DISALLOW_NULL_AUTHTOK : 0);
437 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
438         extern char **environ;
439         char **env_from_pam;
440         u_int i;
441         const char *pam_user;
442         const char **ptr_pam_user = &pam_user;
443         char *tz = getenv("TZ");
444
445         sshpam_err = pam_get_item(sshpam_handle, PAM_USER,
446             (sshpam_const void **)ptr_pam_user);
447         if (sshpam_err != PAM_SUCCESS)
448                 goto auth_fail;
449
450         environ[0] = NULL;
451         if (tz != NULL)
452                 if (setenv("TZ", tz, 1) == -1)
453                         error("PAM: could not set TZ environment: %s",
454                             strerror(errno));
455
456         if (sshpam_authctxt != NULL) {
457                 setproctitle("%s [pam]",
458                     sshpam_authctxt->valid ? pam_user : "unknown");
459         }
460 #endif
461
462         sshpam_conv.conv = sshpam_thread_conv;
463         sshpam_conv.appdata_ptr = ctxt;
464
465         if (sshpam_authctxt == NULL)
466                 fatal("%s: PAM authctxt not initialized", __func__);
467
468         buffer_init(&buffer);
469         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
470             (const void *)&sshpam_conv);
471         if (sshpam_err != PAM_SUCCESS)
472                 goto auth_fail;
473         sshpam_err = pam_authenticate(sshpam_handle, flags);
474         if (sshpam_err == PAM_MAXTRIES)
475                 sshpam_set_maxtries_reached(1);
476         if (sshpam_err != PAM_SUCCESS)
477                 goto auth_fail;
478
479         if (!do_pam_account()) {
480                 sshpam_err = PAM_ACCT_EXPIRED;
481                 goto auth_fail;
482         }
483         if (sshpam_authctxt->force_pwchange) {
484                 sshpam_err = pam_chauthtok(sshpam_handle,
485                     PAM_CHANGE_EXPIRED_AUTHTOK);
486                 if (sshpam_err != PAM_SUCCESS)
487                         goto auth_fail;
488                 sshpam_password_change_required(0);
489         }
490
491         buffer_put_cstring(&buffer, "OK");
492
493 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
494         /* Export variables set by do_pam_account */
495         buffer_put_int(&buffer, sshpam_account_status);
496         buffer_put_int(&buffer, sshpam_authctxt->force_pwchange);
497
498         /* Export any environment strings set in child */
499         for(i = 0; environ[i] != NULL; i++)
500                 ; /* Count */
501         buffer_put_int(&buffer, i);
502         for(i = 0; environ[i] != NULL; i++)
503                 buffer_put_cstring(&buffer, environ[i]);
504
505         /* Export any environment strings set by PAM in child */
506         env_from_pam = pam_getenvlist(sshpam_handle);
507         for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
508                 ; /* Count */
509         buffer_put_int(&buffer, i);
510         for(i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++)
511                 buffer_put_cstring(&buffer, env_from_pam[i]);
512 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
513
514         /* XXX - can't do much about an error here */
515         ssh_msg_send(ctxt->pam_csock, sshpam_err, &buffer);
516         buffer_free(&buffer);
517         pthread_exit(NULL);
518
519  auth_fail:
520         buffer_put_cstring(&buffer,
521             pam_strerror(sshpam_handle, sshpam_err));
522         /* XXX - can't do much about an error here */
523         if (sshpam_err == PAM_ACCT_EXPIRED)
524                 ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, &buffer);
525         else if (sshpam_maxtries_reached)
526                 ssh_msg_send(ctxt->pam_csock, PAM_MAXTRIES, &buffer);
527         else
528                 ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, &buffer);
529         buffer_free(&buffer);
530         pthread_exit(NULL);
531
532         return (NULL); /* Avoid warning for non-pthread case */
533 }
534
535 void
536 sshpam_thread_cleanup(void)
537 {
538         struct pam_ctxt *ctxt = cleanup_ctxt;
539
540         debug3("PAM: %s entering", __func__);
541         if (ctxt != NULL && ctxt->pam_thread != 0) {
542                 pthread_cancel(ctxt->pam_thread);
543                 pthread_join(ctxt->pam_thread, NULL);
544                 close(ctxt->pam_psock);
545                 close(ctxt->pam_csock);
546                 memset(ctxt, 0, sizeof(*ctxt));
547                 cleanup_ctxt = NULL;
548         }
549 }
550
551 static int
552 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
553     struct pam_response **resp, void *data)
554 {
555         debug3("PAM: %s entering, %d messages", __func__, n);
556         return (PAM_CONV_ERR);
557 }
558
559 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
560
561 static int
562 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
563     struct pam_response **resp, void *data)
564 {
565         struct pam_response *reply;
566         int i;
567         size_t len;
568
569         debug3("PAM: %s called with %d messages", __func__, n);
570         *resp = NULL;
571
572         if (n <= 0 || n > PAM_MAX_NUM_MSG)
573                 return (PAM_CONV_ERR);
574
575         if ((reply = calloc(n, sizeof(*reply))) == NULL)
576                 return (PAM_CONV_ERR);
577
578         for (i = 0; i < n; ++i) {
579                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
580                 case PAM_ERROR_MSG:
581                 case PAM_TEXT_INFO:
582                         len = strlen(PAM_MSG_MEMBER(msg, i, msg));
583                         buffer_append(&loginmsg, PAM_MSG_MEMBER(msg, i, msg), len);
584                         buffer_append(&loginmsg, "\n", 1 );
585                         reply[i].resp_retcode = PAM_SUCCESS;
586                         break;
587                 default:
588                         goto fail;
589                 }
590         }
591         *resp = reply;
592         return (PAM_SUCCESS);
593
594  fail:
595         for(i = 0; i < n; i++) {
596                 free(reply[i].resp);
597         }
598         free(reply);
599         return (PAM_CONV_ERR);
600 }
601
602 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
603
604 void
605 sshpam_cleanup(void)
606 {
607         if (sshpam_handle == NULL || (use_privsep && !mm_is_monitor()))
608                 return;
609         debug("PAM: cleanup");
610         pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
611         if (sshpam_session_open) {
612                 debug("PAM: closing session");
613                 pam_close_session(sshpam_handle, PAM_SILENT);
614                 sshpam_session_open = 0;
615         }
616         if (sshpam_cred_established) {
617                 debug("PAM: deleting credentials");
618                 pam_setcred(sshpam_handle, PAM_DELETE_CRED);
619                 sshpam_cred_established = 0;
620         }
621         sshpam_authenticated = 0;
622         pam_end(sshpam_handle, sshpam_err);
623         sshpam_handle = NULL;
624 }
625
626 static int
627 sshpam_init(Authctxt *authctxt)
628 {
629         const char *pam_rhost, *pam_user, *user = authctxt->user;
630         const char **ptr_pam_user = &pam_user;
631         struct ssh *ssh = active_state; /* XXX */
632
633         if (sshpam_handle != NULL) {
634                 /* We already have a PAM context; check if the user matches */
635                 sshpam_err = pam_get_item(sshpam_handle,
636                     PAM_USER, (sshpam_const void **)ptr_pam_user);
637                 if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
638                         return (0);
639                 pam_end(sshpam_handle, sshpam_err);
640                 sshpam_handle = NULL;
641         }
642         debug("PAM: initializing for \"%s\"", user);
643         sshpam_err =
644             pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
645         sshpam_authctxt = authctxt;
646
647         if (sshpam_err != PAM_SUCCESS) {
648                 pam_end(sshpam_handle, sshpam_err);
649                 sshpam_handle = NULL;
650                 return (-1);
651         }
652         pam_rhost = auth_get_canonical_hostname(ssh, options.use_dns);
653         debug("PAM: setting PAM_RHOST to \"%s\"", pam_rhost);
654         sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST, pam_rhost);
655         if (sshpam_err != PAM_SUCCESS) {
656                 pam_end(sshpam_handle, sshpam_err);
657                 sshpam_handle = NULL;
658                 return (-1);
659         }
660 #ifdef PAM_TTY_KLUDGE
661         /*
662          * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
663          * sshd doesn't set the tty until too late in the auth process and
664          * may not even set one (for tty-less connections)
665          */
666         debug("PAM: setting PAM_TTY to \"ssh\"");
667         sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
668         if (sshpam_err != PAM_SUCCESS) {
669                 pam_end(sshpam_handle, sshpam_err);
670                 sshpam_handle = NULL;
671                 return (-1);
672         }
673 #endif
674         return (0);
675 }
676
677 static void *
678 sshpam_init_ctx(Authctxt *authctxt)
679 {
680         struct pam_ctxt *ctxt;
681         int socks[2];
682
683         debug3("PAM: %s entering", __func__);
684         /*
685          * Refuse to start if we don't have PAM enabled or do_pam_account
686          * has previously failed.
687          */
688         if (!options.use_pam || sshpam_account_status == 0)
689                 return NULL;
690
691         /* Initialize PAM */
692         if (sshpam_init(authctxt) == -1) {
693                 error("PAM: initialization failed");
694                 return (NULL);
695         }
696
697         ctxt = xcalloc(1, sizeof *ctxt);
698
699         /* Start the authentication thread */
700         if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
701                 error("PAM: failed create sockets: %s", strerror(errno));
702                 free(ctxt);
703                 return (NULL);
704         }
705         ctxt->pam_psock = socks[0];
706         ctxt->pam_csock = socks[1];
707         if (pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt) == -1) {
708                 error("PAM: failed to start authentication thread: %s",
709                     strerror(errno));
710                 close(socks[0]);
711                 close(socks[1]);
712                 free(ctxt);
713                 return (NULL);
714         }
715         cleanup_ctxt = ctxt;
716         return (ctxt);
717 }
718
719 static int
720 sshpam_query(void *ctx, char **name, char **info,
721     u_int *num, char ***prompts, u_int **echo_on)
722 {
723         struct ssh *ssh = active_state; /* XXX */
724         Buffer buffer;
725         struct pam_ctxt *ctxt = ctx;
726         size_t plen;
727         u_char type;
728         char *msg;
729         size_t len, mlen;
730
731         debug3("PAM: %s entering", __func__);
732         buffer_init(&buffer);
733         *name = xstrdup("");
734         *info = xstrdup("");
735         *prompts = xmalloc(sizeof(char *));
736         **prompts = NULL;
737         plen = 0;
738         *echo_on = xmalloc(sizeof(u_int));
739         while (ssh_msg_recv(ctxt->pam_psock, &buffer) == 0) {
740                 type = buffer_get_char(&buffer);
741                 msg = buffer_get_string(&buffer, NULL);
742                 mlen = strlen(msg);
743                 switch (type) {
744                 case PAM_PROMPT_ECHO_ON:
745                 case PAM_PROMPT_ECHO_OFF:
746                         *num = 1;
747                         len = plen + mlen + 1;
748                         **prompts = xreallocarray(**prompts, 1, len);
749                         strlcpy(**prompts + plen, msg, len - plen);
750                         plen += mlen;
751                         **echo_on = (type == PAM_PROMPT_ECHO_ON);
752                         free(msg);
753                         return (0);
754                 case PAM_ERROR_MSG:
755                 case PAM_TEXT_INFO:
756                         /* accumulate messages */
757                         len = plen + mlen + 2;
758                         **prompts = xreallocarray(**prompts, 1, len);
759                         strlcpy(**prompts + plen, msg, len - plen);
760                         plen += mlen;
761                         strlcat(**prompts + plen, "\n", len - plen);
762                         plen++;
763                         free(msg);
764                         break;
765                 case PAM_ACCT_EXPIRED:
766                 case PAM_MAXTRIES:
767                         if (type == PAM_ACCT_EXPIRED)
768                                 sshpam_account_status = 0;
769                         if (type == PAM_MAXTRIES)
770                                 sshpam_set_maxtries_reached(1);
771                         /* FALLTHROUGH */
772                 case PAM_AUTH_ERR:
773                         debug3("PAM: %s", pam_strerror(sshpam_handle, type));
774                         if (**prompts != NULL && strlen(**prompts) != 0) {
775                                 *info = **prompts;
776                                 **prompts = NULL;
777                                 *num = 0;
778                                 **echo_on = 0;
779                                 ctxt->pam_done = -1;
780                                 free(msg);
781                                 return 0;
782                         }
783                         /* FALLTHROUGH */
784                 case PAM_SUCCESS:
785                         if (**prompts != NULL) {
786                                 /* drain any accumulated messages */
787                                 debug("PAM: %s", **prompts);
788                                 buffer_append(&loginmsg, **prompts,
789                                     strlen(**prompts));
790                                 free(**prompts);
791                                 **prompts = NULL;
792                         }
793                         if (type == PAM_SUCCESS) {
794                                 if (!sshpam_authctxt->valid ||
795                                     (sshpam_authctxt->pw->pw_uid == 0 &&
796                                     options.permit_root_login != PERMIT_YES))
797                                         fatal("Internal error: PAM auth "
798                                             "succeeded when it should have "
799                                             "failed");
800                                 import_environments(&buffer);
801                                 *num = 0;
802                                 **echo_on = 0;
803                                 ctxt->pam_done = 1;
804                                 free(msg);
805                                 return (0);
806                         }
807                         error("PAM: %s for %s%.100s from %.100s", msg,
808                             sshpam_authctxt->valid ? "" : "illegal user ",
809                             sshpam_authctxt->user,
810                             auth_get_canonical_hostname(ssh, options.use_dns));
811                         /* FALLTHROUGH */
812                 default:
813                         *num = 0;
814                         **echo_on = 0;
815                         free(msg);
816                         ctxt->pam_done = -1;
817                         return (-1);
818                 }
819         }
820         return (-1);
821 }
822
823 /*
824  * Returns a junk password of identical length to that the user supplied.
825  * Used to mitigate timing attacks against crypt(3)/PAM stacks that
826  * vary processing time in proportion to password length.
827  */
828 static char *
829 fake_password(const char *wire_password)
830 {
831         const char junk[] = "\b\n\r\177INCORRECT";
832         char *ret = NULL;
833         size_t i, l = wire_password != NULL ? strlen(wire_password) : 0;
834
835         if (l >= INT_MAX)
836                 fatal("%s: password length too long: %zu", __func__, l);
837
838         ret = malloc(l + 1);
839         if (ret == NULL)
840                 return NULL;
841         for (i = 0; i < l; i++)
842                 ret[i] = junk[i % (sizeof(junk) - 1)];
843         ret[i] = '\0';
844         return ret;
845 }
846
847 /* XXX - see also comment in auth-chall.c:verify_response */
848 static int
849 sshpam_respond(void *ctx, u_int num, char **resp)
850 {
851         Buffer buffer;
852         struct pam_ctxt *ctxt = ctx;
853         char *fake;
854
855         debug2("PAM: %s entering, %u responses", __func__, num);
856         switch (ctxt->pam_done) {
857         case 1:
858                 sshpam_authenticated = 1;
859                 return (0);
860         case 0:
861                 break;
862         default:
863                 return (-1);
864         }
865         if (num != 1) {
866                 error("PAM: expected one response, got %u", num);
867                 return (-1);
868         }
869         buffer_init(&buffer);
870         if (sshpam_authctxt->valid &&
871             (sshpam_authctxt->pw->pw_uid != 0 ||
872             options.permit_root_login == PERMIT_YES))
873                 buffer_put_cstring(&buffer, *resp);
874         else {
875                 fake = fake_password(*resp);
876                 buffer_put_cstring(&buffer, fake);
877                 free(fake);
878         }
879         if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, &buffer) == -1) {
880                 buffer_free(&buffer);
881                 return (-1);
882         }
883         buffer_free(&buffer);
884         return (1);
885 }
886
887 static void
888 sshpam_free_ctx(void *ctxtp)
889 {
890         struct pam_ctxt *ctxt = ctxtp;
891
892         debug3("PAM: %s entering", __func__);
893         sshpam_thread_cleanup();
894         free(ctxt);
895         /*
896          * We don't call sshpam_cleanup() here because we may need the PAM
897          * handle at a later stage, e.g. when setting up a session.  It's
898          * still on the cleanup list, so pam_end() *will* be called before
899          * the server process terminates.
900          */
901 }
902
903 KbdintDevice sshpam_device = {
904         "pam",
905         sshpam_init_ctx,
906         sshpam_query,
907         sshpam_respond,
908         sshpam_free_ctx
909 };
910
911 KbdintDevice mm_sshpam_device = {
912         "pam",
913         mm_sshpam_init_ctx,
914         mm_sshpam_query,
915         mm_sshpam_respond,
916         mm_sshpam_free_ctx
917 };
918
919 /*
920  * This replaces auth-pam.c
921  */
922 void
923 start_pam(Authctxt *authctxt)
924 {
925         if (!options.use_pam)
926                 fatal("PAM: initialisation requested when UsePAM=no");
927
928         if (sshpam_init(authctxt) == -1)
929                 fatal("PAM: initialisation failed");
930 }
931
932 void
933 finish_pam(void)
934 {
935         sshpam_cleanup();
936 }
937
938 static void
939 expose_authinfo(const char *caller)
940 {
941         char *auth_info;
942
943         /*
944          * Expose authentication information to PAM.
945          * The enviornment variable is versioned. Please increment the
946          * version suffix if the format of session_info changes.
947          */
948         if (sshpam_authctxt->session_info == NULL)
949                 auth_info = xstrdup("");
950         else if ((auth_info = sshbuf_dup_string(
951             sshpam_authctxt->session_info)) == NULL)
952                 fatal("%s: sshbuf_dup_string failed", __func__);
953
954         debug2("%s: auth information in SSH_AUTH_INFO_0", caller);
955         do_pam_putenv("SSH_AUTH_INFO_0", auth_info);
956         free(auth_info);
957 }
958
959 u_int
960 do_pam_account(void)
961 {
962         debug("%s: called", __func__);
963         if (sshpam_account_status != -1)
964                 return (sshpam_account_status);
965
966         expose_authinfo(__func__);
967
968         sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
969         debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
970             pam_strerror(sshpam_handle, sshpam_err));
971
972         if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
973                 sshpam_account_status = 0;
974                 return (sshpam_account_status);
975         }
976
977         if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
978                 sshpam_password_change_required(1);
979
980         sshpam_account_status = 1;
981         return (sshpam_account_status);
982 }
983
984 void
985 do_pam_setcred(int init)
986 {
987         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
988             (const void *)&store_conv);
989         if (sshpam_err != PAM_SUCCESS)
990                 fatal("PAM: failed to set PAM_CONV: %s",
991                     pam_strerror(sshpam_handle, sshpam_err));
992         if (init) {
993                 debug("PAM: establishing credentials");
994                 sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
995         } else {
996                 debug("PAM: reinitializing credentials");
997                 sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
998         }
999         if (sshpam_err == PAM_SUCCESS) {
1000                 sshpam_cred_established = 1;
1001                 return;
1002         }
1003         if (sshpam_authenticated)
1004                 fatal("PAM: pam_setcred(): %s",
1005                     pam_strerror(sshpam_handle, sshpam_err));
1006         else
1007                 debug("PAM: pam_setcred(): %s",
1008                     pam_strerror(sshpam_handle, sshpam_err));
1009 }
1010
1011 static int
1012 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
1013     struct pam_response **resp, void *data)
1014 {
1015         char input[PAM_MAX_MSG_SIZE];
1016         struct pam_response *reply;
1017         int i;
1018
1019         debug3("PAM: %s called with %d messages", __func__, n);
1020
1021         *resp = NULL;
1022
1023         if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
1024                 return (PAM_CONV_ERR);
1025
1026         if ((reply = calloc(n, sizeof(*reply))) == NULL)
1027                 return (PAM_CONV_ERR);
1028
1029         for (i = 0; i < n; ++i) {
1030                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1031                 case PAM_PROMPT_ECHO_OFF:
1032                         reply[i].resp =
1033                             read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
1034                             RP_ALLOW_STDIN);
1035                         reply[i].resp_retcode = PAM_SUCCESS;
1036                         break;
1037                 case PAM_PROMPT_ECHO_ON:
1038                         fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1039                         if (fgets(input, sizeof input, stdin) == NULL)
1040                                 input[0] = '\0';
1041                         if ((reply[i].resp = strdup(input)) == NULL)
1042                                 goto fail;
1043                         reply[i].resp_retcode = PAM_SUCCESS;
1044                         break;
1045                 case PAM_ERROR_MSG:
1046                 case PAM_TEXT_INFO:
1047                         fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1048                         reply[i].resp_retcode = PAM_SUCCESS;
1049                         break;
1050                 default:
1051                         goto fail;
1052                 }
1053         }
1054         *resp = reply;
1055         return (PAM_SUCCESS);
1056
1057  fail:
1058         for(i = 0; i < n; i++) {
1059                 free(reply[i].resp);
1060         }
1061         free(reply);
1062         return (PAM_CONV_ERR);
1063 }
1064
1065 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
1066
1067 /*
1068  * XXX this should be done in the authentication phase, but ssh1 doesn't
1069  * support that
1070  */
1071 void
1072 do_pam_chauthtok(void)
1073 {
1074         if (use_privsep)
1075                 fatal("Password expired (unable to change with privsep)");
1076         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1077             (const void *)&tty_conv);
1078         if (sshpam_err != PAM_SUCCESS)
1079                 fatal("PAM: failed to set PAM_CONV: %s",
1080                     pam_strerror(sshpam_handle, sshpam_err));
1081         debug("PAM: changing password");
1082         sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1083         if (sshpam_err != PAM_SUCCESS)
1084                 fatal("PAM: pam_chauthtok(): %s",
1085                     pam_strerror(sshpam_handle, sshpam_err));
1086 }
1087
1088 void
1089 do_pam_session(struct ssh *ssh)
1090 {
1091         debug3("PAM: opening session");
1092
1093         expose_authinfo(__func__);
1094
1095         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1096             (const void *)&store_conv);
1097         if (sshpam_err != PAM_SUCCESS)
1098                 fatal("PAM: failed to set PAM_CONV: %s",
1099                     pam_strerror(sshpam_handle, sshpam_err));
1100         sshpam_err = pam_open_session(sshpam_handle, 0);
1101         if (sshpam_err == PAM_SUCCESS)
1102                 sshpam_session_open = 1;
1103         else {
1104                 sshpam_session_open = 0;
1105                 auth_restrict_session(ssh);
1106                 error("PAM: pam_open_session(): %s",
1107                     pam_strerror(sshpam_handle, sshpam_err));
1108         }
1109
1110 }
1111
1112 int
1113 is_pam_session_open(void)
1114 {
1115         return sshpam_session_open;
1116 }
1117
1118 /*
1119  * Set a PAM environment string. We need to do this so that the session
1120  * modules can handle things like Kerberos/GSI credentials that appear
1121  * during the ssh authentication process.
1122  */
1123 int
1124 do_pam_putenv(char *name, char *value)
1125 {
1126         int ret = 1;
1127 #ifdef HAVE_PAM_PUTENV
1128         char *compound;
1129         size_t len;
1130
1131         len = strlen(name) + strlen(value) + 2;
1132         compound = xmalloc(len);
1133
1134         snprintf(compound, len, "%s=%s", name, value);
1135         ret = pam_putenv(sshpam_handle, compound);
1136         free(compound);
1137 #endif
1138
1139         return (ret);
1140 }
1141
1142 char **
1143 fetch_pam_child_environment(void)
1144 {
1145         return sshpam_env;
1146 }
1147
1148 char **
1149 fetch_pam_environment(void)
1150 {
1151         return (pam_getenvlist(sshpam_handle));
1152 }
1153
1154 void
1155 free_pam_environment(char **env)
1156 {
1157         char **envp;
1158
1159         if (env == NULL)
1160                 return;
1161
1162         for (envp = env; *envp; envp++)
1163                 free(*envp);
1164         free(env);
1165 }
1166
1167 /*
1168  * "Blind" conversation function for password authentication.  Assumes that
1169  * echo-off prompts are for the password and stores messages for later
1170  * display.
1171  */
1172 static int
1173 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1174     struct pam_response **resp, void *data)
1175 {
1176         struct pam_response *reply;
1177         int i;
1178         size_t len;
1179
1180         debug3("PAM: %s called with %d messages", __func__, n);
1181
1182         *resp = NULL;
1183
1184         if (n <= 0 || n > PAM_MAX_NUM_MSG)
1185                 return (PAM_CONV_ERR);
1186
1187         if ((reply = calloc(n, sizeof(*reply))) == NULL)
1188                 return (PAM_CONV_ERR);
1189
1190         for (i = 0; i < n; ++i) {
1191                 switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1192                 case PAM_PROMPT_ECHO_OFF:
1193                         if (sshpam_password == NULL)
1194                                 goto fail;
1195                         if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1196                                 goto fail;
1197                         reply[i].resp_retcode = PAM_SUCCESS;
1198                         break;
1199                 case PAM_ERROR_MSG:
1200                 case PAM_TEXT_INFO:
1201                         len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1202                         if (len > 0) {
1203                                 buffer_append(&loginmsg,
1204                                     PAM_MSG_MEMBER(msg, i, msg), len);
1205                                 buffer_append(&loginmsg, "\n", 1);
1206                         }
1207                         if ((reply[i].resp = strdup("")) == NULL)
1208                                 goto fail;
1209                         reply[i].resp_retcode = PAM_SUCCESS;
1210                         break;
1211                 default:
1212                         goto fail;
1213                 }
1214         }
1215         *resp = reply;
1216         return (PAM_SUCCESS);
1217
1218  fail:
1219         for(i = 0; i < n; i++) {
1220                 free(reply[i].resp);
1221         }
1222         free(reply);
1223         return (PAM_CONV_ERR);
1224 }
1225
1226 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1227
1228 /*
1229  * Attempt password authentication via PAM
1230  */
1231 int
1232 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1233 {
1234         int flags = (options.permit_empty_passwd == 0 ?
1235             PAM_DISALLOW_NULL_AUTHTOK : 0);
1236         char *fake = NULL;
1237
1238         if (!options.use_pam || sshpam_handle == NULL)
1239                 fatal("PAM: %s called when PAM disabled or failed to "
1240                     "initialise.", __func__);
1241
1242         sshpam_password = password;
1243         sshpam_authctxt = authctxt;
1244
1245         /*
1246          * If the user logging in is invalid, or is root but is not permitted
1247          * by PermitRootLogin, use an invalid password to prevent leaking
1248          * information via timing (eg if the PAM config has a delay on fail).
1249          */
1250         if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1251             options.permit_root_login != PERMIT_YES))
1252                 sshpam_password = fake = fake_password(password);
1253
1254         sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1255             (const void *)&passwd_conv);
1256         if (sshpam_err != PAM_SUCCESS)
1257                 fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1258                     pam_strerror(sshpam_handle, sshpam_err));
1259
1260         sshpam_err = pam_authenticate(sshpam_handle, flags);
1261         sshpam_password = NULL;
1262         free(fake);
1263         if (sshpam_err == PAM_MAXTRIES)
1264                 sshpam_set_maxtries_reached(1);
1265         if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1266                 debug("PAM: password authentication accepted for %.100s",
1267                     authctxt->user);
1268                 return 1;
1269         } else {
1270                 debug("PAM: password authentication failed for %.100s: %s",
1271                     authctxt->valid ? authctxt->user : "an illegal user",
1272                     pam_strerror(sshpam_handle, sshpam_err));
1273                 return 0;
1274         }
1275 }
1276
1277 int
1278 sshpam_get_maxtries_reached(void)
1279 {
1280         return sshpam_maxtries_reached;
1281 }
1282
1283 void
1284 sshpam_set_maxtries_reached(int reached)
1285 {
1286         if (reached == 0 || sshpam_maxtries_reached)
1287                 return;
1288         sshpam_maxtries_reached = 1;
1289         options.password_authentication = 0;
1290         options.kbd_interactive_authentication = 0;
1291         options.challenge_response_authentication = 0;
1292 }
1293 #endif /* USE_PAM */