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