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