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