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