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