xref: /openssh-portable/auth-pam.c (revision 57ed647e)
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 		/*
379 		 * XXX this possibly leaks env because it is not documented
380 		 * what pam_putenv() does with it. Does it copy it? Does it
381 		 * take ownweship? We don't know, so it's safest just to leak.
382 		 */
383 	}
384 #endif
385 }
386 
387 /*
388  * Conversation function for authentication thread.
389  */
390 static int
sshpam_thread_conv(int n,sshpam_const struct pam_message ** msg,struct pam_response ** resp,void * data)391 sshpam_thread_conv(int n, sshpam_const struct pam_message **msg,
392     struct pam_response **resp, void *data)
393 {
394 	struct sshbuf *buffer;
395 	struct pam_ctxt *ctxt;
396 	struct pam_response *reply;
397 	int r, i;
398 	u_char status;
399 
400 	debug3("PAM: %s entering, %d messages", __func__, n);
401 	*resp = NULL;
402 
403 	if (data == NULL) {
404 		error("PAM: conversation function passed a null context");
405 		return (PAM_CONV_ERR);
406 	}
407 	ctxt = data;
408 	if (n <= 0 || n > PAM_MAX_NUM_MSG)
409 		return (PAM_CONV_ERR);
410 
411 	if ((reply = calloc(n, sizeof(*reply))) == NULL)
412 		return PAM_CONV_ERR;
413 	if ((buffer = sshbuf_new()) == NULL) {
414 		free(reply);
415 		return PAM_CONV_ERR;
416 	}
417 
418 	for (i = 0; i < n; ++i) {
419 		switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
420 		case PAM_PROMPT_ECHO_OFF:
421 		case PAM_PROMPT_ECHO_ON:
422 			if ((r = sshbuf_put_cstring(buffer,
423 			    PAM_MSG_MEMBER(msg, i, msg))) != 0)
424 				fatal("%s: buffer error: %s",
425 				    __func__, ssh_err(r));
426 			if (ssh_msg_send(ctxt->pam_csock,
427 			    PAM_MSG_MEMBER(msg, i, msg_style), buffer) == -1)
428 				goto fail;
429 
430 			if (ssh_msg_recv(ctxt->pam_csock, buffer) == -1)
431 				goto fail;
432 			if ((r = sshbuf_get_u8(buffer, &status)) != 0)
433 				fatal("%s: buffer error: %s",
434 				    __func__, ssh_err(r));
435 			if (status != PAM_AUTHTOK)
436 				goto fail;
437 			if ((r = sshbuf_get_cstring(buffer,
438 			    &reply[i].resp, NULL)) != 0)
439 				fatal("%s: buffer error: %s",
440 				    __func__, ssh_err(r));
441 			break;
442 		case PAM_ERROR_MSG:
443 		case PAM_TEXT_INFO:
444 			if ((r = sshbuf_put_cstring(buffer,
445 			    PAM_MSG_MEMBER(msg, i, msg))) != 0)
446 				fatal("%s: buffer error: %s",
447 				    __func__, ssh_err(r));
448 			if (ssh_msg_send(ctxt->pam_csock,
449 			    PAM_MSG_MEMBER(msg, i, msg_style), buffer) == -1)
450 				goto fail;
451 			break;
452 		default:
453 			goto fail;
454 		}
455 		sshbuf_reset(buffer);
456 	}
457 	sshbuf_free(buffer);
458 	*resp = reply;
459 	return (PAM_SUCCESS);
460 
461  fail:
462 	for(i = 0; i < n; i++) {
463 		free(reply[i].resp);
464 	}
465 	free(reply);
466 	sshbuf_free(buffer);
467 	return (PAM_CONV_ERR);
468 }
469 
470 /*
471  * Authentication thread.
472  */
473 static void *
sshpam_thread(void * ctxtp)474 sshpam_thread(void *ctxtp)
475 {
476 	struct pam_ctxt *ctxt = ctxtp;
477 	struct sshbuf *buffer = NULL;
478 	struct pam_conv sshpam_conv;
479 	int r, flags = (options.permit_empty_passwd == 0 ?
480 	    PAM_DISALLOW_NULL_AUTHTOK : 0);
481 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
482 	extern char **environ;
483 	char **env_from_pam;
484 	u_int i;
485 	const char *pam_user;
486 	const char **ptr_pam_user = &pam_user;
487 	char *tz = getenv("TZ");
488 
489 	sshpam_err = pam_get_item(sshpam_handle, PAM_USER,
490 	    (sshpam_const void **)ptr_pam_user);
491 	if (sshpam_err != PAM_SUCCESS)
492 		goto auth_fail;
493 
494 	environ[0] = NULL;
495 	if (tz != NULL)
496 		if (setenv("TZ", tz, 1) == -1)
497 			error("PAM: could not set TZ environment: %s",
498 			    strerror(errno));
499 
500 	if (sshpam_authctxt != NULL) {
501 		setproctitle("%s [pam]",
502 		    sshpam_authctxt->valid ? pam_user : "unknown");
503 	}
504 #endif
505 
506 	sshpam_conv.conv = sshpam_thread_conv;
507 	sshpam_conv.appdata_ptr = ctxt;
508 
509 	if (sshpam_authctxt == NULL)
510 		fatal("%s: PAM authctxt not initialized", __func__);
511 
512 	if ((buffer = sshbuf_new()) == NULL)
513 		fatal("%s: sshbuf_new failed", __func__);
514 
515 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
516 	    (const void *)&sshpam_conv);
517 	if (sshpam_err != PAM_SUCCESS)
518 		goto auth_fail;
519 	sshpam_err = pam_authenticate(sshpam_handle, flags);
520 	if (sshpam_err == PAM_MAXTRIES)
521 		sshpam_set_maxtries_reached(1);
522 	if (sshpam_err != PAM_SUCCESS)
523 		goto auth_fail;
524 
525 	if (!do_pam_account()) {
526 		sshpam_err = PAM_ACCT_EXPIRED;
527 		goto auth_fail;
528 	}
529 	if (sshpam_authctxt->force_pwchange) {
530 		sshpam_err = pam_chauthtok(sshpam_handle,
531 		    PAM_CHANGE_EXPIRED_AUTHTOK);
532 		if (sshpam_err != PAM_SUCCESS)
533 			goto auth_fail;
534 		sshpam_password_change_required(0);
535 	}
536 
537 	if ((r = sshbuf_put_cstring(buffer, "OK")) != 0)
538 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
539 
540 #ifndef UNSUPPORTED_POSIX_THREADS_HACK
541 	/* Export variables set by do_pam_account */
542 	if ((r = sshbuf_put_u32(buffer, sshpam_account_status)) != 0 ||
543 	    (r = sshbuf_put_u32(buffer, sshpam_authctxt->force_pwchange)) != 0)
544 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
545 
546 	/* Export any environment strings set in child */
547 	for (i = 0; environ[i] != NULL; i++) {
548 		/* Count */
549 		if (i > INT_MAX)
550 			fatal("%s: too many environment strings", __func__);
551 	}
552 	if ((r = sshbuf_put_u32(buffer, i)) != 0)
553 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
554 	for (i = 0; environ[i] != NULL; i++) {
555 		if ((r = sshbuf_put_cstring(buffer, environ[i])) != 0)
556 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
557 	}
558 	/* Export any environment strings set by PAM in child */
559 	env_from_pam = pam_getenvlist(sshpam_handle);
560 	for (i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++) {
561 		/* Count */
562 		if (i > INT_MAX)
563 			fatal("%s: too many PAM environment strings", __func__);
564 	}
565 	if ((r = sshbuf_put_u32(buffer, i)) != 0)
566 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
567 	for (i = 0; env_from_pam != NULL && env_from_pam[i] != NULL; i++) {
568 		if ((r = sshbuf_put_cstring(buffer, env_from_pam[i])) != 0)
569 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
570 	}
571 #endif /* UNSUPPORTED_POSIX_THREADS_HACK */
572 
573 	/* XXX - can't do much about an error here */
574 	ssh_msg_send(ctxt->pam_csock, sshpam_err, buffer);
575 	sshbuf_free(buffer);
576 	pthread_exit(NULL);
577 
578  auth_fail:
579 	if ((r = sshbuf_put_cstring(buffer,
580 	    pam_strerror(sshpam_handle, sshpam_err))) != 0)
581 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
582 	/* XXX - can't do much about an error here */
583 	if (sshpam_err == PAM_ACCT_EXPIRED)
584 		ssh_msg_send(ctxt->pam_csock, PAM_ACCT_EXPIRED, buffer);
585 	else if (sshpam_maxtries_reached)
586 		ssh_msg_send(ctxt->pam_csock, PAM_MAXTRIES, buffer);
587 	else
588 		ssh_msg_send(ctxt->pam_csock, PAM_AUTH_ERR, buffer);
589 	sshbuf_free(buffer);
590 	pthread_exit(NULL);
591 
592 	return (NULL); /* Avoid warning for non-pthread case */
593 }
594 
595 void
sshpam_thread_cleanup(void)596 sshpam_thread_cleanup(void)
597 {
598 	struct pam_ctxt *ctxt = cleanup_ctxt;
599 
600 	debug3("PAM: %s entering", __func__);
601 	if (ctxt != NULL && ctxt->pam_thread != 0) {
602 		pthread_cancel(ctxt->pam_thread);
603 		pthread_join(ctxt->pam_thread, NULL);
604 		close(ctxt->pam_psock);
605 		close(ctxt->pam_csock);
606 		memset(ctxt, 0, sizeof(*ctxt));
607 		cleanup_ctxt = NULL;
608 	}
609 }
610 
611 static int
sshpam_null_conv(int n,sshpam_const struct pam_message ** msg,struct pam_response ** resp,void * data)612 sshpam_null_conv(int n, sshpam_const struct pam_message **msg,
613     struct pam_response **resp, void *data)
614 {
615 	debug3("PAM: %s entering, %d messages", __func__, n);
616 	return (PAM_CONV_ERR);
617 }
618 
619 static struct pam_conv null_conv = { sshpam_null_conv, NULL };
620 
621 static int
sshpam_store_conv(int n,sshpam_const struct pam_message ** msg,struct pam_response ** resp,void * data)622 sshpam_store_conv(int n, sshpam_const struct pam_message **msg,
623     struct pam_response **resp, void *data)
624 {
625 	struct pam_response *reply;
626 	int r, i;
627 
628 	debug3("PAM: %s called with %d messages", __func__, n);
629 	*resp = NULL;
630 
631 	if (n <= 0 || n > PAM_MAX_NUM_MSG)
632 		return (PAM_CONV_ERR);
633 
634 	if ((reply = calloc(n, sizeof(*reply))) == NULL)
635 		return (PAM_CONV_ERR);
636 
637 	for (i = 0; i < n; ++i) {
638 		switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
639 		case PAM_ERROR_MSG:
640 		case PAM_TEXT_INFO:
641 			if ((r = sshbuf_putf(loginmsg, "%s\n",
642 			    PAM_MSG_MEMBER(msg, i, msg))) != 0)
643 				fatal("%s: buffer error: %s",
644 				    __func__, ssh_err(r));
645 			reply[i].resp_retcode = PAM_SUCCESS;
646 			break;
647 		default:
648 			goto fail;
649 		}
650 	}
651 	*resp = reply;
652 	return (PAM_SUCCESS);
653 
654  fail:
655 	for(i = 0; i < n; i++) {
656 		free(reply[i].resp);
657 	}
658 	free(reply);
659 	return (PAM_CONV_ERR);
660 }
661 
662 static struct pam_conv store_conv = { sshpam_store_conv, NULL };
663 
664 void
sshpam_cleanup(void)665 sshpam_cleanup(void)
666 {
667 	if (sshpam_handle == NULL || (use_privsep && !mm_is_monitor()))
668 		return;
669 	debug("PAM: cleanup");
670 	pam_set_item(sshpam_handle, PAM_CONV, (const void *)&null_conv);
671 	if (sshpam_session_open) {
672 		debug("PAM: closing session");
673 		pam_close_session(sshpam_handle, PAM_SILENT);
674 		sshpam_session_open = 0;
675 	}
676 	if (sshpam_cred_established) {
677 		debug("PAM: deleting credentials");
678 		pam_setcred(sshpam_handle, PAM_DELETE_CRED);
679 		sshpam_cred_established = 0;
680 	}
681 	sshpam_authenticated = 0;
682 	pam_end(sshpam_handle, sshpam_err);
683 	sshpam_handle = NULL;
684 }
685 
686 static int
sshpam_init(struct ssh * ssh,Authctxt * authctxt)687 sshpam_init(struct ssh *ssh, Authctxt *authctxt)
688 {
689 	const char *pam_user, *user = authctxt->user;
690 	const char **ptr_pam_user = &pam_user;
691 
692 #if defined(PAM_SUN_CODEBASE) && defined(PAM_MAX_RESP_SIZE)
693 	/* Protect buggy PAM implementations from excessively long usernames */
694 	if (strlen(user) >= PAM_MAX_RESP_SIZE)
695 		fatal("Username too long from %s port %d",
696 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
697 #endif
698 	if (sshpam_handle == NULL) {
699 		if (ssh == NULL) {
700 			fatal("%s: called initially with no "
701 			    "packet context", __func__);
702 		}
703 	} if (sshpam_handle != NULL) {
704 		/* We already have a PAM context; check if the user matches */
705 		sshpam_err = pam_get_item(sshpam_handle,
706 		    PAM_USER, (sshpam_const void **)ptr_pam_user);
707 		if (sshpam_err == PAM_SUCCESS && strcmp(user, pam_user) == 0)
708 			return (0);
709 		pam_end(sshpam_handle, sshpam_err);
710 		sshpam_handle = NULL;
711 	}
712 	debug("PAM: initializing for \"%s\"", user);
713 	sshpam_err =
714 	    pam_start(SSHD_PAM_SERVICE, user, &store_conv, &sshpam_handle);
715 	sshpam_authctxt = authctxt;
716 
717 	if (sshpam_err != PAM_SUCCESS) {
718 		pam_end(sshpam_handle, sshpam_err);
719 		sshpam_handle = NULL;
720 		return (-1);
721 	}
722 
723 	if (ssh != NULL && sshpam_rhost == NULL) {
724 		/*
725 		 * We need to cache these as we don't have packet context
726 		 * during the kbdint flow.
727 		 */
728 		sshpam_rhost = xstrdup(auth_get_canonical_hostname(ssh,
729 		    options.use_dns));
730 		sshpam_laddr = get_local_ipaddr(
731 		    ssh_packet_get_connection_in(ssh));
732 		xasprintf(&sshpam_conninfo, "SSH_CONNECTION=%.50s %d %.50s %d",
733 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
734 		    sshpam_laddr, ssh_local_port(ssh));
735 	}
736 	if (sshpam_rhost != NULL) {
737 		debug("PAM: setting PAM_RHOST to \"%s\"", sshpam_rhost);
738 		sshpam_err = pam_set_item(sshpam_handle, PAM_RHOST,
739 		    sshpam_rhost);
740 		if (sshpam_err != PAM_SUCCESS) {
741 			pam_end(sshpam_handle, sshpam_err);
742 			sshpam_handle = NULL;
743 			return (-1);
744 		}
745 		/* Put SSH_CONNECTION in the PAM environment too */
746 		pam_putenv(sshpam_handle, sshpam_conninfo);
747 	}
748 
749 #ifdef PAM_TTY_KLUDGE
750 	/*
751 	 * Some silly PAM modules (e.g. pam_time) require a TTY to operate.
752 	 * sshd doesn't set the tty until too late in the auth process and
753 	 * may not even set one (for tty-less connections)
754 	 */
755 	debug("PAM: setting PAM_TTY to \"ssh\"");
756 	sshpam_err = pam_set_item(sshpam_handle, PAM_TTY, "ssh");
757 	if (sshpam_err != PAM_SUCCESS) {
758 		pam_end(sshpam_handle, sshpam_err);
759 		sshpam_handle = NULL;
760 		return (-1);
761 	}
762 #endif
763 	return (0);
764 }
765 
766 static void
expose_authinfo(const char * caller)767 expose_authinfo(const char *caller)
768 {
769 	char *auth_info;
770 
771 	/*
772 	 * Expose authentication information to PAM.
773 	 * The environment variable is versioned. Please increment the
774 	 * version suffix if the format of session_info changes.
775 	 */
776 	if (sshpam_authctxt->session_info == NULL)
777 		auth_info = xstrdup("");
778 	else if ((auth_info = sshbuf_dup_string(
779 	    sshpam_authctxt->session_info)) == NULL)
780 		fatal("%s: sshbuf_dup_string failed", __func__);
781 
782 	debug2("%s: auth information in SSH_AUTH_INFO_0", caller);
783 	do_pam_putenv("SSH_AUTH_INFO_0", auth_info);
784 	free(auth_info);
785 }
786 
787 static void *
sshpam_init_ctx(Authctxt * authctxt)788 sshpam_init_ctx(Authctxt *authctxt)
789 {
790 	struct pam_ctxt *ctxt;
791 	int result, socks[2];
792 
793 	debug3("PAM: %s entering", __func__);
794 	/*
795 	 * Refuse to start if we don't have PAM enabled or do_pam_account
796 	 * has previously failed.
797 	 */
798 	if (!options.use_pam || sshpam_account_status == 0)
799 		return NULL;
800 
801 	/* Initialize PAM */
802 	if (sshpam_init(NULL, authctxt) == -1) {
803 		error("PAM: initialization failed");
804 		return (NULL);
805 	}
806 
807 	expose_authinfo(__func__);
808 	ctxt = xcalloc(1, sizeof *ctxt);
809 
810 	/* Start the authentication thread */
811 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, socks) == -1) {
812 		error("PAM: failed create sockets: %s", strerror(errno));
813 		free(ctxt);
814 		return (NULL);
815 	}
816 	ctxt->pam_psock = socks[0];
817 	ctxt->pam_csock = socks[1];
818 	result = pthread_create(&ctxt->pam_thread, NULL, sshpam_thread, ctxt);
819 	if (result != 0) {
820 		error("PAM: failed to start authentication thread: %s",
821 		    strerror(result));
822 		close(socks[0]);
823 		close(socks[1]);
824 		free(ctxt);
825 		return (NULL);
826 	}
827 	cleanup_ctxt = ctxt;
828 	return (ctxt);
829 }
830 
831 static int
sshpam_query(void * ctx,char ** name,char ** info,u_int * num,char *** prompts,u_int ** echo_on)832 sshpam_query(void *ctx, char **name, char **info,
833     u_int *num, char ***prompts, u_int **echo_on)
834 {
835 	struct sshbuf *buffer;
836 	struct pam_ctxt *ctxt = ctx;
837 	size_t plen;
838 	u_char type;
839 	char *msg;
840 	size_t len, mlen;
841 	int r;
842 
843 	debug3("PAM: %s entering", __func__);
844 	if ((buffer = sshbuf_new()) == NULL)
845 		fatal("%s: sshbuf_new failed", __func__);
846 	*name = xstrdup("");
847 	*info = xstrdup("");
848 	*prompts = xmalloc(sizeof(char *));
849 	**prompts = NULL;
850 	plen = 0;
851 	*echo_on = xmalloc(sizeof(u_int));
852 	while (ssh_msg_recv(ctxt->pam_psock, buffer) == 0) {
853 		if ((r = sshbuf_get_u8(buffer, &type)) != 0 ||
854 		    (r = sshbuf_get_cstring(buffer, &msg, &mlen)) != 0)
855 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
856 		switch (type) {
857 		case PAM_PROMPT_ECHO_ON:
858 		case PAM_PROMPT_ECHO_OFF:
859 			*num = 1;
860 			len = plen + mlen + 1;
861 			**prompts = xreallocarray(**prompts, 1, len);
862 			strlcpy(**prompts + plen, msg, len - plen);
863 			plen += mlen;
864 			**echo_on = (type == PAM_PROMPT_ECHO_ON);
865 			free(msg);
866 			sshbuf_free(buffer);
867 			return (0);
868 		case PAM_ERROR_MSG:
869 		case PAM_TEXT_INFO:
870 			/* accumulate messages */
871 			len = plen + mlen + 2;
872 			**prompts = xreallocarray(**prompts, 1, len);
873 			strlcpy(**prompts + plen, msg, len - plen);
874 			plen += mlen;
875 			strlcat(**prompts + plen, "\n", len - plen);
876 			plen++;
877 			free(msg);
878 			break;
879 		case PAM_ACCT_EXPIRED:
880 		case PAM_MAXTRIES:
881 			if (type == PAM_ACCT_EXPIRED)
882 				sshpam_account_status = 0;
883 			if (type == PAM_MAXTRIES)
884 				sshpam_set_maxtries_reached(1);
885 			/* FALLTHROUGH */
886 		case PAM_AUTH_ERR:
887 			debug3("PAM: %s", pam_strerror(sshpam_handle, type));
888 			if (**prompts != NULL && strlen(**prompts) != 0) {
889 				*info = **prompts;
890 				**prompts = NULL;
891 				*num = 0;
892 				**echo_on = 0;
893 				ctxt->pam_done = -1;
894 				free(msg);
895 				sshbuf_free(buffer);
896 				return 0;
897 			}
898 			/* FALLTHROUGH */
899 		case PAM_SUCCESS:
900 			if (**prompts != NULL) {
901 				/* drain any accumulated messages */
902 				debug("PAM: %s", **prompts);
903 				if ((r = sshbuf_put(loginmsg, **prompts,
904 				    strlen(**prompts))) != 0)
905 					fatal("%s: buffer error: %s",
906 					    __func__, ssh_err(r));
907 				free(**prompts);
908 				**prompts = NULL;
909 			}
910 			if (type == PAM_SUCCESS) {
911 				if (!sshpam_authctxt->valid ||
912 				    (sshpam_authctxt->pw->pw_uid == 0 &&
913 				    options.permit_root_login != PERMIT_YES))
914 					fatal("Internal error: PAM auth "
915 					    "succeeded when it should have "
916 					    "failed");
917 				import_environments(buffer);
918 				*num = 0;
919 				**echo_on = 0;
920 				ctxt->pam_done = 1;
921 				free(msg);
922 				sshbuf_free(buffer);
923 				return (0);
924 			}
925 			error("PAM: %s for %s%.100s from %.100s", msg,
926 			    sshpam_authctxt->valid ? "" : "illegal user ",
927 			    sshpam_authctxt->user, sshpam_rhost);
928 			/* FALLTHROUGH */
929 		default:
930 			*num = 0;
931 			**echo_on = 0;
932 			free(msg);
933 			ctxt->pam_done = -1;
934 			sshbuf_free(buffer);
935 			return (-1);
936 		}
937 	}
938 	sshbuf_free(buffer);
939 	return (-1);
940 }
941 
942 /*
943  * Returns a junk password of identical length to that the user supplied.
944  * Used to mitigate timing attacks against crypt(3)/PAM stacks that
945  * vary processing time in proportion to password length.
946  */
947 static char *
fake_password(const char * wire_password)948 fake_password(const char *wire_password)
949 {
950 	const char junk[] = "\b\n\r\177INCORRECT";
951 	char *ret = NULL;
952 	size_t i, l = wire_password != NULL ? strlen(wire_password) : 0;
953 
954 	if (l >= INT_MAX)
955 		fatal("%s: password length too long: %zu", __func__, l);
956 
957 	ret = malloc(l + 1);
958 	if (ret == NULL)
959 		return NULL;
960 	for (i = 0; i < l; i++)
961 		ret[i] = junk[i % (sizeof(junk) - 1)];
962 	ret[i] = '\0';
963 	return ret;
964 }
965 
966 /* XXX - see also comment in auth-chall.c:verify_response */
967 static int
sshpam_respond(void * ctx,u_int num,char ** resp)968 sshpam_respond(void *ctx, u_int num, char **resp)
969 {
970 	struct sshbuf *buffer;
971 	struct pam_ctxt *ctxt = ctx;
972 	char *fake;
973 	int r;
974 
975 	debug2("PAM: %s entering, %u responses", __func__, num);
976 	switch (ctxt->pam_done) {
977 	case 1:
978 		sshpam_authenticated = 1;
979 		return (0);
980 	case 0:
981 		break;
982 	default:
983 		return (-1);
984 	}
985 	if (num != 1) {
986 		error("PAM: expected one response, got %u", num);
987 		return (-1);
988 	}
989 	if ((buffer = sshbuf_new()) == NULL)
990 		fatal("%s: sshbuf_new failed", __func__);
991 	if (sshpam_authctxt->valid &&
992 	    (sshpam_authctxt->pw->pw_uid != 0 ||
993 	    options.permit_root_login == PERMIT_YES)) {
994 		if ((r = sshbuf_put_cstring(buffer, *resp)) != 0)
995 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
996 	} else {
997 		fake = fake_password(*resp);
998 		if ((r = sshbuf_put_cstring(buffer, fake)) != 0)
999 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1000 		free(fake);
1001 	}
1002 	if (ssh_msg_send(ctxt->pam_psock, PAM_AUTHTOK, buffer) == -1) {
1003 		sshbuf_free(buffer);
1004 		return (-1);
1005 	}
1006 	sshbuf_free(buffer);
1007 	return (1);
1008 }
1009 
1010 static void
sshpam_free_ctx(void * ctxtp)1011 sshpam_free_ctx(void *ctxtp)
1012 {
1013 	struct pam_ctxt *ctxt = ctxtp;
1014 
1015 	debug3("PAM: %s entering", __func__);
1016 	sshpam_thread_cleanup();
1017 	free(ctxt);
1018 	/*
1019 	 * We don't call sshpam_cleanup() here because we may need the PAM
1020 	 * handle at a later stage, e.g. when setting up a session.  It's
1021 	 * still on the cleanup list, so pam_end() *will* be called before
1022 	 * the server process terminates.
1023 	 */
1024 }
1025 
1026 KbdintDevice sshpam_device = {
1027 	"pam",
1028 	sshpam_init_ctx,
1029 	sshpam_query,
1030 	sshpam_respond,
1031 	sshpam_free_ctx
1032 };
1033 
1034 KbdintDevice mm_sshpam_device = {
1035 	"pam",
1036 	mm_sshpam_init_ctx,
1037 	mm_sshpam_query,
1038 	mm_sshpam_respond,
1039 	mm_sshpam_free_ctx
1040 };
1041 
1042 /*
1043  * This replaces auth-pam.c
1044  */
1045 void
start_pam(struct ssh * ssh)1046 start_pam(struct ssh *ssh)
1047 {
1048 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1049 
1050 	if (!options.use_pam)
1051 		fatal("PAM: initialisation requested when UsePAM=no");
1052 
1053 	if (sshpam_init(ssh, authctxt) == -1)
1054 		fatal("PAM: initialisation failed");
1055 }
1056 
1057 void
finish_pam(void)1058 finish_pam(void)
1059 {
1060 	sshpam_cleanup();
1061 }
1062 
1063 
1064 u_int
do_pam_account(void)1065 do_pam_account(void)
1066 {
1067 	debug("%s: called", __func__);
1068 	if (sshpam_account_status != -1)
1069 		return (sshpam_account_status);
1070 
1071 	expose_authinfo(__func__);
1072 
1073 	sshpam_err = pam_acct_mgmt(sshpam_handle, 0);
1074 	debug3("PAM: %s pam_acct_mgmt = %d (%s)", __func__, sshpam_err,
1075 	    pam_strerror(sshpam_handle, sshpam_err));
1076 
1077 	if (sshpam_err != PAM_SUCCESS && sshpam_err != PAM_NEW_AUTHTOK_REQD) {
1078 		sshpam_account_status = 0;
1079 		return (sshpam_account_status);
1080 	}
1081 
1082 	if (sshpam_err == PAM_NEW_AUTHTOK_REQD)
1083 		sshpam_password_change_required(1);
1084 
1085 	sshpam_account_status = 1;
1086 	return (sshpam_account_status);
1087 }
1088 
1089 void
do_pam_setcred(int init)1090 do_pam_setcred(int init)
1091 {
1092 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1093 	    (const void *)&store_conv);
1094 	if (sshpam_err != PAM_SUCCESS)
1095 		fatal("PAM: failed to set PAM_CONV: %s",
1096 		    pam_strerror(sshpam_handle, sshpam_err));
1097 	if (init) {
1098 		debug("PAM: establishing credentials");
1099 		sshpam_err = pam_setcred(sshpam_handle, PAM_ESTABLISH_CRED);
1100 	} else {
1101 		debug("PAM: reinitializing credentials");
1102 		sshpam_err = pam_setcred(sshpam_handle, PAM_REINITIALIZE_CRED);
1103 	}
1104 	if (sshpam_err == PAM_SUCCESS) {
1105 		sshpam_cred_established = 1;
1106 		return;
1107 	}
1108 	if (sshpam_authenticated)
1109 		fatal("PAM: pam_setcred(): %s",
1110 		    pam_strerror(sshpam_handle, sshpam_err));
1111 	else
1112 		debug("PAM: pam_setcred(): %s",
1113 		    pam_strerror(sshpam_handle, sshpam_err));
1114 }
1115 
1116 static int
sshpam_tty_conv(int n,sshpam_const struct pam_message ** msg,struct pam_response ** resp,void * data)1117 sshpam_tty_conv(int n, sshpam_const struct pam_message **msg,
1118     struct pam_response **resp, void *data)
1119 {
1120 	char input[PAM_MAX_MSG_SIZE];
1121 	struct pam_response *reply;
1122 	int i;
1123 
1124 	debug3("PAM: %s called with %d messages", __func__, n);
1125 
1126 	*resp = NULL;
1127 
1128 	if (n <= 0 || n > PAM_MAX_NUM_MSG || !isatty(STDIN_FILENO))
1129 		return (PAM_CONV_ERR);
1130 
1131 	if ((reply = calloc(n, sizeof(*reply))) == NULL)
1132 		return (PAM_CONV_ERR);
1133 
1134 	for (i = 0; i < n; ++i) {
1135 		switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1136 		case PAM_PROMPT_ECHO_OFF:
1137 			reply[i].resp =
1138 			    read_passphrase(PAM_MSG_MEMBER(msg, i, msg),
1139 			    RP_ALLOW_STDIN);
1140 			reply[i].resp_retcode = PAM_SUCCESS;
1141 			break;
1142 		case PAM_PROMPT_ECHO_ON:
1143 			fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1144 			if (fgets(input, sizeof input, stdin) == NULL)
1145 				input[0] = '\0';
1146 			if ((reply[i].resp = strdup(input)) == NULL)
1147 				goto fail;
1148 			reply[i].resp_retcode = PAM_SUCCESS;
1149 			break;
1150 		case PAM_ERROR_MSG:
1151 		case PAM_TEXT_INFO:
1152 			fprintf(stderr, "%s\n", PAM_MSG_MEMBER(msg, i, msg));
1153 			reply[i].resp_retcode = PAM_SUCCESS;
1154 			break;
1155 		default:
1156 			goto fail;
1157 		}
1158 	}
1159 	*resp = reply;
1160 	return (PAM_SUCCESS);
1161 
1162  fail:
1163 	for(i = 0; i < n; i++) {
1164 		free(reply[i].resp);
1165 	}
1166 	free(reply);
1167 	return (PAM_CONV_ERR);
1168 }
1169 
1170 static struct pam_conv tty_conv = { sshpam_tty_conv, NULL };
1171 
1172 /*
1173  * XXX this should be done in the authentication phase, but ssh1 doesn't
1174  * support that
1175  */
1176 void
do_pam_chauthtok(void)1177 do_pam_chauthtok(void)
1178 {
1179 	if (use_privsep)
1180 		fatal("Password expired (unable to change with privsep)");
1181 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1182 	    (const void *)&tty_conv);
1183 	if (sshpam_err != PAM_SUCCESS)
1184 		fatal("PAM: failed to set PAM_CONV: %s",
1185 		    pam_strerror(sshpam_handle, sshpam_err));
1186 	debug("PAM: changing password");
1187 	sshpam_err = pam_chauthtok(sshpam_handle, PAM_CHANGE_EXPIRED_AUTHTOK);
1188 	if (sshpam_err != PAM_SUCCESS)
1189 		fatal("PAM: pam_chauthtok(): %s",
1190 		    pam_strerror(sshpam_handle, sshpam_err));
1191 }
1192 
1193 void
do_pam_session(struct ssh * ssh)1194 do_pam_session(struct ssh *ssh)
1195 {
1196 	debug3("PAM: opening session");
1197 
1198 	expose_authinfo(__func__);
1199 
1200 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1201 	    (const void *)&store_conv);
1202 	if (sshpam_err != PAM_SUCCESS)
1203 		fatal("PAM: failed to set PAM_CONV: %s",
1204 		    pam_strerror(sshpam_handle, sshpam_err));
1205 	sshpam_err = pam_open_session(sshpam_handle, 0);
1206 	if (sshpam_err == PAM_SUCCESS)
1207 		sshpam_session_open = 1;
1208 	else {
1209 		sshpam_session_open = 0;
1210 		auth_restrict_session(ssh);
1211 		error("PAM: pam_open_session(): %s",
1212 		    pam_strerror(sshpam_handle, sshpam_err));
1213 	}
1214 
1215 }
1216 
1217 int
is_pam_session_open(void)1218 is_pam_session_open(void)
1219 {
1220 	return sshpam_session_open;
1221 }
1222 
1223 /*
1224  * Set a PAM environment string. We need to do this so that the session
1225  * modules can handle things like Kerberos/GSI credentials that appear
1226  * during the ssh authentication process.
1227  */
1228 int
do_pam_putenv(char * name,char * value)1229 do_pam_putenv(char *name, char *value)
1230 {
1231 	int ret = 1;
1232 	char *compound;
1233 	size_t len;
1234 
1235 	len = strlen(name) + strlen(value) + 2;
1236 	compound = xmalloc(len);
1237 
1238 	snprintf(compound, len, "%s=%s", name, value);
1239 	ret = pam_putenv(sshpam_handle, compound);
1240 	free(compound);
1241 
1242 	return (ret);
1243 }
1244 
1245 char **
fetch_pam_child_environment(void)1246 fetch_pam_child_environment(void)
1247 {
1248 	return sshpam_env;
1249 }
1250 
1251 char **
fetch_pam_environment(void)1252 fetch_pam_environment(void)
1253 {
1254 	return (pam_getenvlist(sshpam_handle));
1255 }
1256 
1257 void
free_pam_environment(char ** env)1258 free_pam_environment(char **env)
1259 {
1260 	char **envp;
1261 
1262 	if (env == NULL)
1263 		return;
1264 
1265 	for (envp = env; *envp; envp++)
1266 		free(*envp);
1267 	free(env);
1268 }
1269 
1270 /*
1271  * "Blind" conversation function for password authentication.  Assumes that
1272  * echo-off prompts are for the password and stores messages for later
1273  * display.
1274  */
1275 static int
sshpam_passwd_conv(int n,sshpam_const struct pam_message ** msg,struct pam_response ** resp,void * data)1276 sshpam_passwd_conv(int n, sshpam_const struct pam_message **msg,
1277     struct pam_response **resp, void *data)
1278 {
1279 	struct pam_response *reply;
1280 	int r, i;
1281 	size_t len;
1282 
1283 	debug3("PAM: %s called with %d messages", __func__, n);
1284 
1285 	*resp = NULL;
1286 
1287 	if (n <= 0 || n > PAM_MAX_NUM_MSG)
1288 		return (PAM_CONV_ERR);
1289 
1290 	if ((reply = calloc(n, sizeof(*reply))) == NULL)
1291 		return (PAM_CONV_ERR);
1292 
1293 	for (i = 0; i < n; ++i) {
1294 		switch (PAM_MSG_MEMBER(msg, i, msg_style)) {
1295 		case PAM_PROMPT_ECHO_OFF:
1296 			if (sshpam_password == NULL)
1297 				goto fail;
1298 			if ((reply[i].resp = strdup(sshpam_password)) == NULL)
1299 				goto fail;
1300 			reply[i].resp_retcode = PAM_SUCCESS;
1301 			break;
1302 		case PAM_ERROR_MSG:
1303 		case PAM_TEXT_INFO:
1304 			len = strlen(PAM_MSG_MEMBER(msg, i, msg));
1305 			if (len > 0) {
1306 				if ((r = sshbuf_putf(loginmsg, "%s\n",
1307 				    PAM_MSG_MEMBER(msg, i, msg))) != 0)
1308 					fatal("%s: buffer error: %s",
1309 					    __func__, ssh_err(r));
1310 			}
1311 			if ((reply[i].resp = strdup("")) == NULL)
1312 				goto fail;
1313 			reply[i].resp_retcode = PAM_SUCCESS;
1314 			break;
1315 		default:
1316 			goto fail;
1317 		}
1318 	}
1319 	*resp = reply;
1320 	return (PAM_SUCCESS);
1321 
1322  fail:
1323 	for(i = 0; i < n; i++) {
1324 		free(reply[i].resp);
1325 	}
1326 	free(reply);
1327 	return (PAM_CONV_ERR);
1328 }
1329 
1330 static struct pam_conv passwd_conv = { sshpam_passwd_conv, NULL };
1331 
1332 /*
1333  * Attempt password authentication via PAM
1334  */
1335 int
sshpam_auth_passwd(Authctxt * authctxt,const char * password)1336 sshpam_auth_passwd(Authctxt *authctxt, const char *password)
1337 {
1338 	int flags = (options.permit_empty_passwd == 0 ?
1339 	    PAM_DISALLOW_NULL_AUTHTOK : 0);
1340 	char *fake = NULL;
1341 
1342 	if (!options.use_pam || sshpam_handle == NULL)
1343 		fatal("PAM: %s called when PAM disabled or failed to "
1344 		    "initialise.", __func__);
1345 
1346 	sshpam_password = password;
1347 	sshpam_authctxt = authctxt;
1348 
1349 	/*
1350 	 * If the user logging in is invalid, or is root but is not permitted
1351 	 * by PermitRootLogin, use an invalid password to prevent leaking
1352 	 * information via timing (eg if the PAM config has a delay on fail).
1353 	 */
1354 	if (!authctxt->valid || (authctxt->pw->pw_uid == 0 &&
1355 	    options.permit_root_login != PERMIT_YES))
1356 		sshpam_password = fake = fake_password(password);
1357 
1358 	sshpam_err = pam_set_item(sshpam_handle, PAM_CONV,
1359 	    (const void *)&passwd_conv);
1360 	if (sshpam_err != PAM_SUCCESS)
1361 		fatal("PAM: %s: failed to set PAM_CONV: %s", __func__,
1362 		    pam_strerror(sshpam_handle, sshpam_err));
1363 
1364 	sshpam_err = pam_authenticate(sshpam_handle, flags);
1365 	sshpam_password = NULL;
1366 	free(fake);
1367 	if (sshpam_err == PAM_MAXTRIES)
1368 		sshpam_set_maxtries_reached(1);
1369 	if (sshpam_err == PAM_SUCCESS && authctxt->valid) {
1370 		debug("PAM: password authentication accepted for %.100s",
1371 		    authctxt->user);
1372 		return 1;
1373 	} else {
1374 		debug("PAM: password authentication failed for %.100s: %s",
1375 		    authctxt->valid ? authctxt->user : "an illegal user",
1376 		    pam_strerror(sshpam_handle, sshpam_err));
1377 		return 0;
1378 	}
1379 }
1380 
1381 int
sshpam_get_maxtries_reached(void)1382 sshpam_get_maxtries_reached(void)
1383 {
1384 	return sshpam_maxtries_reached;
1385 }
1386 
1387 void
sshpam_set_maxtries_reached(int reached)1388 sshpam_set_maxtries_reached(int reached)
1389 {
1390 	if (reached == 0 || sshpam_maxtries_reached)
1391 		return;
1392 	sshpam_maxtries_reached = 1;
1393 	options.password_authentication = 0;
1394 	options.kbd_interactive_authentication = 0;
1395 	options.challenge_response_authentication = 0;
1396 }
1397 #endif /* USE_PAM */
1398