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