xref: /titanic_41/usr/src/cmd/ssh/sshd/auth-pam.c (revision bdfc6d18da790deeec2e0eb09c625902defe2498)
1 /*
2  * Copyright (c) 2000 Damien Miller.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24 /*
25  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
26  * Use is subject to license terms.
27  */
28 
29 #include "includes.h"
30 
31 #ifdef USE_PAM
32 #include "xmalloc.h"
33 #include "log.h"
34 #include "auth.h"
35 #include "auth-options.h"
36 #include "auth-pam.h"
37 #include "servconf.h"
38 #include "canohost.h"
39 #include "compat.h"
40 #include "misc.h"
41 #include "sshlogin.h"
42 #include "monitor_wrap.h"
43 
44 #include <security/pam_appl.h>
45 
46 extern char *__progname;
47 
48 extern int use_privsep;
49 
50 extern u_int utmp_len;
51 extern ServerOptions options;
52 
53 extern Authmethod method_kbdint;
54 
55 RCSID("$Id: auth-pam.c,v 1.54 2002/07/28 20:24:08 stevesk Exp $");
56 
57 #pragma ident	"%Z%%M%	%I%	%E% SMI"
58 
59 #define NEW_AUTHTOK_MSG \
60 	"Warning: Your password has expired, please change it now."
61 #define NEW_AUTHTOK_MSG_PRIVSEP \
62 	"Your password has expired, the session cannot proceed."
63 
64 /* PAM conversation for non-interactive userauth methods */
65 static int do_pam_conversation(int num_msg, const struct pam_message **msg,
66 	struct pam_response **resp, void *appdata_ptr);
67 
68 static void do_pam_cleanup_proc(void *context);
69 
70 static char *get_method_name(Authctxt *authctxt);
71 
72 /* PAM conversation for non-interactive userauth methods */
73 static struct pam_conv conv = {
74 	(int (*)())do_pam_conversation,
75 	NULL
76 };
77 static char *__pam_msg = NULL;
78 
79 static
80 char *
81 get_method_name(Authctxt *authctxt)
82 {
83 	if (!authctxt)
84 		return "(unknown)";
85 
86 	if (!compat20)
87 		return (authctxt->v1_auth_name) ? authctxt->v1_auth_name :
88 						  "(sshv1-unknown)";
89 
90 	if (!authctxt->method || !authctxt->method->name)
91 			return "(sshv2-unknown)";
92 
93 	return authctxt->method->name;
94 }
95 
96 const
97 char *
98 derive_pam_svc_name(Authmethod *method)
99 {
100 	if (compat20 && method) {
101 		char *method_name = method->name;
102 
103 		if (!method_name)
104 			fatal("Userauth method unknown while starting PAM");
105 
106 		/* For SSHv2 we use "sshd-<userauth name> */
107 		if (strcmp(method_name, "none") == 0) {
108 			return "sshd-none";
109 		}
110 		if (strcmp(method_name, "password") == 0) {
111 			return "sshd-password";
112 		}
113 		if (strcmp(method_name, "keyboard-interactive") == 0) {
114 			/* "keyboard-interactive" is too long, shorten it */
115 			return "sshd-kbdint";
116 		}
117 		if (strcmp(method_name, "publickey") == 0) {
118 			/* "publickey" is too long, shorten it */
119 			return "sshd-pubkey";
120 		}
121 		if (strcmp(method_name, "hostbased") == 0) {
122 			/* "hostbased" can't really be shortened... */
123 			return "sshd-hostbased";
124 		}
125 		if (strncmp(method_name, "gss", 3) == 0) {
126 			/* "hostbased" can't really be shortened... */
127 			return "sshd-gssapi";
128 		}
129 	}
130 
131 	return "sshd-v1"; /* SSHv1 doesn't get to be so cool */
132 }
133 
134 void
135 new_start_pam(Authctxt *authctxt, struct pam_conv *conv)
136 {
137 	int		retval;
138 	pam_handle_t	*pamh;
139 	const char	*rhost, *svc;
140 	char		*user = NULL;
141 	pam_stuff	*pam;
142 
143 	if (authctxt == NULL)
144 		fatal("Internal error during userauth");
145 
146 	if (compat20 && authctxt->method == NULL)
147 		fatal("Userauth method unknown while starting PAM");
148 
149 	/* PAM service selected here */
150 	svc = derive_pam_svc_name(authctxt->method);
151 	debug2("Starting PAM service %s for method %s", svc,
152 		get_method_name(authctxt));
153 
154 	if (authctxt->user != NULL)
155 		user = authctxt->user;
156 
157 	/* Cleanup previous PAM state */
158 	if (authctxt->pam != NULL) {
159 		fatal_remove_cleanup(&do_pam_cleanup_proc, authctxt->pam);
160 		do_pam_cleanup_proc(authctxt->pam);
161 	}
162 
163 	pam = xmalloc(sizeof(pam_stuff));
164 	(void) memset(pam, 0, sizeof(pam_stuff));
165 
166 	/*
167 	 * pam->last_pam_retval has to be and is considered
168 	 * along with pam->state.
169 	 *
170 	 * pam->state = 0; -> no PAM auth, account, etc, work
171 	 * done yet.  (Set by memset() above.)
172 	 *
173 	 * pam->last_pam_retval = PAM_SUCCESS; -> meaningless at
174 	 * this point.
175 	 *
176 	 * See finish_userauth_do_pam() below.
177 	 */
178 	pam->authctxt = authctxt;
179 	pam->last_pam_retval = PAM_SUCCESS;
180 
181 	authctxt->pam = pam;
182 
183 	/* Free any previously stored text/error PAM prompts */
184 	if (__pam_msg) {
185 		xfree(__pam_msg);
186 		__pam_msg = NULL;
187 	}
188 
189 	if ((retval = pam_start(svc, user, conv, &pamh)) != PAM_SUCCESS) {
190 		fatal("PAM initialization failed during %s userauth",
191 			get_method_name(authctxt));
192 	}
193 
194 	fatal_add_cleanup((void (*)(void *)) &do_pam_cleanup_proc,
195 			  (void *) authctxt->pam);
196 
197 	rhost = get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping);
198 	if ((retval = pam_set_item(pamh, PAM_RHOST, rhost)) != PAM_SUCCESS) {
199 		(void) pam_end(pamh, retval);
200 		fatal("Could not set PAM_RHOST item during %s userauth",
201 			get_method_name(authctxt));
202 	}
203 
204 	if ((retval = pam_set_item(pamh, PAM_TTY, "sshd")) != PAM_SUCCESS) {
205 		(void) pam_end(pamh, retval);
206 		fatal("Could not set PAM_TTY item during %s userauth",
207 			get_method_name(authctxt));
208 	}
209 
210 	authctxt->pam->h = pamh;
211 }
212 
213 /*
214  * To be called from userauth methods, directly (as in keyboard-interactive) or
215  * indirectly (from auth_pam_password() or from do_pam_non_initial_userauth().
216  *
217  * The caller is responsible for calling new_start_pam() first.
218  *
219  * PAM state is not cleaned up here on error.  This is left to subsequent calls
220  * to new_start_pam() or to the cleanup function upon authentication error.
221  */
222 int
223 finish_userauth_do_pam(Authctxt *authctxt)
224 {
225 	int retval;
226 	char *user, *method;
227 
228 	/* Various checks; fail gracefully */
229 	if (authctxt == NULL || authctxt->pam == NULL)
230 		return PAM_SYSTEM_ERR;	/* shouldn't happen */
231 
232 	if (compat20) {
233 		if (authctxt->method == NULL || authctxt->method->name == NULL)
234 			return PAM_SYSTEM_ERR;	/* shouldn't happen */
235 		method = authctxt->method->name;
236 	} else if ((method = authctxt->v1_auth_name) == NULL)
237 		return PAM_SYSTEM_ERR;	/* shouldn't happen */
238 
239 	if (AUTHPAM_DONE(authctxt))
240 		return PAM_SYSTEM_ERR;	/* shouldn't happen */
241 
242 	if (!(authctxt->pam->state & PAM_S_DONE_ACCT_MGMT)) {
243 		retval = pam_acct_mgmt(authctxt->pam->h, 0);
244 		authctxt->pam->last_pam_retval = retval;
245 		if (retval == PAM_NEW_AUTHTOK_REQD) {
246 			userauth_force_kbdint();
247 			return retval;
248 		}
249 		if (retval != PAM_SUCCESS)
250 			return retval;
251 		authctxt->pam->state |= PAM_S_DONE_ACCT_MGMT;
252 	}
253 
254 	/*
255 	 * Handle PAM_USER change, if any.
256 	 *
257 	 * We do this before pam_open_session() because we need the PAM_USER's
258 	 * UID for:
259 	 *
260 	 * a) PermitRootLogin checking
261 	 * b) to get at the lastlog entry before pam_open_session() updates it.
262 	 */
263 	retval = pam_get_item(authctxt->pam->h, PAM_USER, (void **) &user);
264 	if (retval != PAM_SUCCESS) {
265 		fatal("PAM failure: pam_get_item(PAM_USER) "
266 		      "returned %d: %.200s", retval,
267 		      PAM_STRERROR(authctxt->pam->h, retval));
268 	}
269 
270 	if (user == NULL || *user == '\0') {
271 		debug("PAM set NULL PAM_USER");
272 		return PAM_PERM_DENIED;
273 	}
274 
275 	if (strcmp(user, authctxt->user) != 0) {
276 		log("PAM changed the SSH username");
277 		pwfree(&authctxt->pw);
278 		authctxt->pw = PRIVSEP(getpwnamallow(user));
279 		authctxt->valid = (authctxt->pw != NULL);
280 		xfree(authctxt->user);
281 		authctxt->user = xstrdup(user);
282 	}
283 
284 	if (!authctxt->valid) {
285 		debug2("PAM set PAM_USER to unknown user");
286 		/*
287 		 * Return success, userauth_finish() will catch
288 		 * this and send back a failure message.
289 		 */
290 		return PAM_SUCCESS;
291 	}
292 
293 	/* Check PermitRootLogin semantics */
294 	if (authctxt->pw->pw_uid == 0 && !auth_root_allowed(method))
295 		return PAM_PERM_DENIED;
296 
297 	if (!(authctxt->pam->state & PAM_S_DONE_SETCRED)) {
298 		retval = pam_setcred(authctxt->pam->h,
299 				     PAM_ESTABLISH_CRED);
300 		authctxt->pam->last_pam_retval = retval;
301 		if (retval != PAM_SUCCESS)
302 			return retval;
303 		authctxt->pam->state |= PAM_S_DONE_SETCRED;
304 
305 #ifdef GSSAPI
306 		/*
307 		 * Store GSS-API delegated creds after pam_setcred(), which may
308 		 * have set the current credential store.
309 		 */
310 		ssh_gssapi_storecreds(NULL, authctxt);
311 #endif /* GSSAPI */
312 	}
313 
314 	/*
315 	 * On Solaris pam_unix_session.so updates the lastlog, but does
316 	 * not converse a PAM_TEXT_INFO message about it.  So we need to
317 	 * fetch the lastlog entry here and save it for use later.
318 	 */
319 	authctxt->last_login_time =
320 		get_last_login_time(authctxt->pw->pw_uid,
321 			authctxt->pw->pw_name,
322 			authctxt->last_login_host,
323 			sizeof(authctxt->last_login_host));
324 
325 	if (!(authctxt->pam->state & PAM_S_DONE_OPEN_SESSION)) {
326 		retval = pam_open_session(authctxt->pam->h, 0);
327 		authctxt->pam->last_pam_retval = retval;
328 		if (retval != PAM_SUCCESS)
329 			return retval;
330 		authctxt->pam->state |= PAM_S_DONE_OPEN_SESSION;
331 	}
332 
333 	/*
334 	 * All PAM work done successfully.
335 	 *
336 	 * PAM handle stays around so we can call pam_close_session() on
337 	 * it later.
338 	 */
339 	return PAM_SUCCESS;
340 }
341 
342 /*
343  * PAM conversation function for non-interactive userauth methods that
344  * really cannot do any prompting.  Password userauth and CHANGEREQ can
345  * always set the PAM_AUTHTOK and PAM_OLDAUTHTOK items to avoid
346  * conversation (and if they do and nonetheless some module tries to
347  * converse, then password userauth / CHANGEREQ MUST fail).
348  *
349  * Except, PAM_TEXT_INFO and PAM_ERROR_MSG prompts can be squirelled
350  * away and shown to the user later.
351  *
352  * Keyboard-interactive userauth has its own much more interesting
353  * conversation function.
354  *
355  */
356 static int
357 do_pam_conversation(int num_msg, const struct pam_message **msg,
358 	struct pam_response **resp, void *appdata_ptr)
359 {
360 	struct pam_response *reply;
361 	int count;
362 
363 	/* PAM will free this later */
364 	reply = xmalloc(num_msg * sizeof(*reply));
365 
366 	(void) memset(reply, 0, num_msg * sizeof(*reply));
367 
368 	for (count = 0; count < num_msg; count++) {
369 		/*
370 		 * We can't use stdio yet, queue messages for
371 		 * printing later
372 		 */
373 		switch(PAM_MSG_MEMBER(msg, count, msg_style)) {
374 		case PAM_PROMPT_ECHO_ON:
375 			xfree(reply);
376 			return PAM_CONV_ERR;
377 		case PAM_PROMPT_ECHO_OFF:
378 			xfree(reply);
379 			return PAM_CONV_ERR;
380 			break;
381 		case PAM_ERROR_MSG:
382 		case PAM_TEXT_INFO:
383 			if (PAM_MSG_MEMBER(msg, count, msg) != NULL) {
384 				message_cat(&__pam_msg,
385 				    PAM_MSG_MEMBER(msg, count, msg));
386 			}
387 			reply[count].resp = xstrdup("");
388 			reply[count].resp_retcode = PAM_SUCCESS;
389 			break;
390 		default:
391 			xfree(reply);
392 			return PAM_CONV_ERR;
393 		}
394 	}
395 
396 	*resp = reply;
397 
398 	return PAM_SUCCESS;
399 }
400 
401 /* Called at exit to cleanly shutdown PAM */
402 static void
403 do_pam_cleanup_proc(void *context)
404 {
405 	int pam_retval;
406 	pam_stuff *pam = (pam_stuff *) context;
407 
408 	if (pam == NULL)
409 		return;
410 
411 	if (pam->authctxt != NULL && pam->authctxt->pam == pam) {
412 		pam->authctxt->pam_retval = pam->last_pam_retval;
413 		pam->authctxt->pam = NULL;
414 		pam->authctxt = NULL;
415 	}
416 
417 	if (pam->h == NULL)
418 		return;
419 
420 	/*
421 	 * We're in fatal_cleanup() or not in userauth or without a
422 	 * channel -- can't converse now, too bad.
423 	 */
424 	pam_retval = pam_set_item(pam->h, PAM_CONV, NULL);
425 	if (pam_retval != PAM_SUCCESS) {
426 		log("Cannot remove PAM conv, close session or delete creds[%d]: %.200s",
427 			pam_retval, PAM_STRERROR(pam->h, pam_retval));
428 		goto cleanup;
429 	}
430 
431 	if (pam->state & PAM_S_DONE_OPEN_SESSION) {
432 		pam_retval = pam_close_session(pam->h, 0);
433 		if (pam_retval != PAM_SUCCESS)
434 			log("Cannot close PAM session[%d]: %.200s",
435 			    pam_retval, PAM_STRERROR(pam->h, pam_retval));
436 	}
437 
438 	if (pam->state & PAM_S_DONE_SETCRED) {
439 		pam_retval = pam_setcred(pam->h, PAM_DELETE_CRED);
440 		if (pam_retval != PAM_SUCCESS)
441 			debug("Cannot delete credentials[%d]: %.200s",
442 			    pam_retval, PAM_STRERROR(pam->h, pam_retval));
443 	}
444 
445 cleanup:
446 
447 	/* Use the previous PAM result, if not PAM_SUCCESS for pam_end() */
448 	if (pam->last_pam_retval != PAM_SUCCESS)
449 		pam_retval = pam_end(pam->h, pam->last_pam_retval);
450 	else if (pam_retval != PAM_SUCCESS)
451 		pam_retval = pam_end(pam->h, pam_retval);
452 	else
453 		pam_retval = pam_end(pam->h, PAM_ABORT);
454 
455 	if (pam_retval != PAM_SUCCESS)
456 		log("Cannot release PAM authentication[%d]: %.200s",
457 		    pam_retval, PAM_STRERROR(pam->h, pam_retval));
458 
459 	xfree(pam);
460 }
461 
462 /* Attempt password authentation using PAM */
463 int
464 auth_pam_password(Authctxt *authctxt, const char *password)
465 {
466 	int retval;
467 
468 	/* Ensure we have a fresh PAM handle / state */
469 	new_start_pam(authctxt, &conv);
470 
471 	retval = pam_set_item(authctxt->pam->h, PAM_AUTHTOK, password);
472 	if (retval != PAM_SUCCESS)
473 		return 1;
474 
475 	retval = pam_authenticate(authctxt->pam->h,
476 			options.permit_empty_passwd ?  0 :
477 			PAM_DISALLOW_NULL_AUTHTOK);
478 
479 	if (retval != PAM_SUCCESS)
480 		return 0;
481 
482 	if ((retval = finish_userauth_do_pam(authctxt)) != PAM_SUCCESS)
483 		return 0;
484 
485 	if (authctxt->method)
486 		authctxt->method->authenticated = 1;	/* SSHv2 */
487 
488 	return 1;
489 }
490 
491 int
492 do_pam_non_initial_userauth(Authctxt *authctxt)
493 {
494 	new_start_pam(authctxt, NULL);
495 	return (finish_userauth_do_pam(authctxt) == PAM_SUCCESS);
496 }
497 
498 /* Cleanly shutdown PAM */
499 void finish_pam(Authctxt *authctxt)
500 {
501 	fatal_remove_cleanup(&do_pam_cleanup_proc, authctxt->pam);
502 	do_pam_cleanup_proc(authctxt->pam);
503 }
504 
505 static
506 char **
507 find_env(char **env, char *var)
508 {
509 	char **p;
510 	int len;
511 
512 	if (strchr(var, '=') == NULL)
513 		len = strlen(var);
514 	else
515 		len = (strchr(var, '=') - var) + 1;
516 
517 	for ( p = env ; p != NULL && *p != NULL ; p++ ) {
518 		if (strncmp(*p, var, len) == 0)
519 			return (p);
520 	}
521 
522 	return (NULL);
523 }
524 
525 /* Return list of PAM environment strings */
526 char **
527 fetch_pam_environment(Authctxt *authctxt)
528 {
529 #ifdef HAVE_PAM_GETENVLIST
530 	char	**penv;
531 
532 	if (authctxt == NULL || authctxt->pam == NULL ||
533 	    authctxt->pam->h == NULL)
534 		return (NULL);
535 
536 	penv = pam_getenvlist(authctxt->pam->h);
537 
538 	return (penv);
539 #else /* HAVE_PAM_GETENVLIST */
540 	return(NULL);
541 #endif /* HAVE_PAM_GETENVLIST */
542 }
543 
544 void free_pam_environment(char **env)
545 {
546 	int i;
547 
548 	if (env != NULL) {
549 		for (i = 0; env[i] != NULL; i++)
550 			xfree(env[i]);
551 	}
552 
553 	xfree(env);
554 }
555 
556 /* Print any messages that have been generated during authentication */
557 /* or account checking to stderr */
558 void print_pam_messages(void)
559 {
560 	if (__pam_msg != NULL)
561 		(void) fputs(__pam_msg, stderr);
562 }
563 
564 /* Append a message to buffer */
565 void message_cat(char **p, const char *a)
566 {
567 	char *cp;
568 	size_t new_len;
569 
570 	new_len = strlen(a);
571 
572 	if (*p) {
573 		size_t len = strlen(*p);
574 
575 		*p = xrealloc(*p, new_len + len + 2);
576 		cp = *p + len;
577 	} else
578 		*p = cp = xmalloc(new_len + 2);
579 
580 	(void) memcpy(cp, a, new_len);
581 	cp[new_len] = '\n';
582 	cp[new_len + 1] = '\0';
583 }
584 
585 #endif /* USE_PAM */
586