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