xref: /netbsd-src/crypto/external/bsd/openssh/dist/auth2.c (revision 7788a0781fe6ff2cce37368b4578a7ade0850cb1)
1 /*	$NetBSD: auth2.c,v 1.7 2013/03/29 16:19:44 christos Exp $	*/
2 /* $OpenBSD: auth2.c,v 1.126 2012/12/02 20:34:09 djm Exp $ */
3 /*
4  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "includes.h"
28 __RCSID("$NetBSD: auth2.c,v 1.7 2013/03/29 16:19:44 christos Exp $");
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/uio.h>
32 
33 #include <fcntl.h>
34 #include <pwd.h>
35 #include <stdarg.h>
36 #include <string.h>
37 #include <unistd.h>
38 
39 #include "atomicio.h"
40 #include "xmalloc.h"
41 #include "ssh2.h"
42 #include "packet.h"
43 #include "log.h"
44 #include "buffer.h"
45 #include "servconf.h"
46 #include "compat.h"
47 #include "key.h"
48 #include "hostfile.h"
49 #include "auth.h"
50 #include "dispatch.h"
51 #include "pathnames.h"
52 #include "buffer.h"
53 #include "canohost.h"
54 
55 #ifdef GSSAPI
56 #include "ssh-gss.h"
57 #endif
58 
59 #include "monitor_wrap.h"
60 
61 /* import */
62 extern ServerOptions options;
63 extern u_char *session_id2;
64 extern u_int session_id2_len;
65 extern Buffer loginmsg;
66 
67 /* methods */
68 
69 extern Authmethod method_none;
70 extern Authmethod method_pubkey;
71 extern Authmethod method_passwd;
72 extern Authmethod method_kbdint;
73 extern Authmethod method_hostbased;
74 #ifdef KRB5
75 extern Authmethod method_kerberos;
76 #endif
77 #ifdef GSSAPI
78 extern Authmethod method_gssapi;
79 #endif
80 #ifdef JPAKE
81 extern Authmethod method_jpake;
82 #endif
83 
84 static int log_flag = 0;
85 
86 Authmethod *authmethods[] = {
87 	&method_none,
88 	&method_pubkey,
89 #ifdef GSSAPI
90 	&method_gssapi,
91 #endif
92 #ifdef JPAKE
93 	&method_jpake,
94 #endif
95 	&method_passwd,
96 	&method_kbdint,
97 	&method_hostbased,
98 #ifdef KRB5
99 	&method_kerberos,
100 #endif
101 	NULL
102 };
103 
104 /* protocol */
105 
106 static void input_service_request(int, u_int32_t, void *);
107 static void input_userauth_request(int, u_int32_t, void *);
108 
109 /* helper */
110 static Authmethod *authmethod_lookup(Authctxt *, const char *);
111 static char *authmethods_get(Authctxt *authctxt);
112 static int method_allowed(Authctxt *, const char *);
113 static int list_starts_with(const char *, const char *);
114 
115 char *
116 auth2_read_banner(void)
117 {
118 	struct stat st;
119 	char *banner = NULL;
120 	size_t len, n;
121 	int fd;
122 
123 	if ((fd = open(options.banner, O_RDONLY)) == -1)
124 		return (NULL);
125 	if (fstat(fd, &st) == -1) {
126 		close(fd);
127 		return (NULL);
128 	}
129 	if (st.st_size <= 0 || st.st_size > 1*1024*1024) {
130 		close(fd);
131 		return (NULL);
132 	}
133 
134 	len = (size_t)st.st_size;		/* truncate */
135 	banner = xmalloc(len + 1);
136 	n = atomicio(read, fd, banner, len);
137 	close(fd);
138 
139 	if (n != len) {
140 		xfree(banner);
141 		return (NULL);
142 	}
143 	banner[n] = '\0';
144 
145 	return (banner);
146 }
147 
148 static void
149 userauth_send_banner(const char *msg)
150 {
151 	if (datafellows & SSH_BUG_BANNER)
152 		return;
153 
154 	packet_start(SSH2_MSG_USERAUTH_BANNER);
155 	packet_put_cstring(msg);
156 	packet_put_cstring("");		/* language, unused */
157 	packet_send();
158 	debug("%s: sent", __func__);
159 }
160 
161 static void
162 userauth_banner(void)
163 {
164 	char *banner = NULL;
165 
166 	if (options.banner == NULL ||
167 	    strcasecmp(options.banner, "none") == 0 ||
168 	    (datafellows & SSH_BUG_BANNER) != 0)
169 		return;
170 
171 	if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
172 		goto done;
173 
174 	userauth_send_banner(banner);
175 done:
176 	if (banner)
177 		xfree(banner);
178 }
179 
180 /*
181  * loop until authctxt->success == TRUE
182  */
183 void
184 do_authentication2(Authctxt *authctxt)
185 {
186 	dispatch_init(&dispatch_protocol_error);
187 	dispatch_set(SSH2_MSG_SERVICE_REQUEST, &input_service_request);
188 	dispatch_run(DISPATCH_BLOCK, &authctxt->success, authctxt);
189 }
190 
191 /*ARGSUSED*/
192 static void
193 input_service_request(int type, u_int32_t seq, void *ctxt)
194 {
195 	Authctxt *authctxt = ctxt;
196 	u_int len;
197 	int acceptit = 0;
198 	char *service = packet_get_cstring(&len);
199 	packet_check_eom();
200 
201 	if (authctxt == NULL)
202 		fatal("input_service_request: no authctxt");
203 
204 	if (strcmp(service, "ssh-userauth") == 0) {
205 		if (!authctxt->success) {
206 			acceptit = 1;
207 			/* now we can handle user-auth requests */
208 			dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &input_userauth_request);
209 		}
210 	}
211 	/* XXX all other service requests are denied */
212 
213 	if (acceptit) {
214 		packet_start(SSH2_MSG_SERVICE_ACCEPT);
215 		packet_put_cstring(service);
216 		packet_send();
217 		packet_write_wait();
218 	} else {
219 		debug("bad service request %s", service);
220 		packet_disconnect("bad service request %s", service);
221 	}
222 	xfree(service);
223 }
224 
225 /*ARGSUSED*/
226 static void
227 input_userauth_request(int type, u_int32_t seq, void *ctxt)
228 {
229 	Authctxt *authctxt = ctxt;
230 	Authmethod *m = NULL;
231 	char *user, *service, *method, *style = NULL;
232 	int authenticated = 0;
233 
234 	if (authctxt == NULL)
235 		fatal("input_userauth_request: no authctxt");
236 
237 	user = packet_get_cstring(NULL);
238 	service = packet_get_cstring(NULL);
239 	method = packet_get_cstring(NULL);
240 	debug("userauth-request for user %s service %s method %s", user, service, method);
241 	if (!log_flag) {
242 		logit("SSH: Server;Ltype: Authname;Remote: %s-%d;Name: %s",
243 		      get_remote_ipaddr(), get_remote_port(), user);
244 		log_flag = 1;
245 	}
246 	debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
247 
248 	if ((style = strchr(user, ':')) != NULL)
249 		*style++ = 0;
250 
251 	if (authctxt->attempt++ == 0) {
252 		/* setup auth context */
253 		authctxt->pw = PRIVSEP(getpwnamallow(user));
254 		authctxt->user = xstrdup(user);
255 		if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
256 			authctxt->valid = 1;
257 			debug2("input_userauth_request: setting up authctxt for %s", user);
258 		} else {
259 			logit("input_userauth_request: invalid user %s", user);
260 			authctxt->pw = fakepw();
261 		}
262 #ifdef USE_PAM
263 		if (options.use_pam)
264 			PRIVSEP(start_pam(authctxt));
265 #endif
266 		setproctitle("%s%s", authctxt->valid ? user : "unknown",
267 		    use_privsep ? " [net]" : "");
268 		authctxt->service = xstrdup(service);
269 		authctxt->style = style ? xstrdup(style) : NULL;
270 		if (use_privsep)
271 			mm_inform_authserv(service, style);
272 		userauth_banner();
273 		if (auth2_setup_methods_lists(authctxt) != 0)
274 			packet_disconnect("no authentication methods enabled");
275 	} else if (strcmp(user, authctxt->user) != 0 ||
276 	    strcmp(service, authctxt->service) != 0) {
277 		packet_disconnect("Change of username or service not allowed: "
278 		    "(%s,%s) -> (%s,%s)",
279 		    authctxt->user, authctxt->service, user, service);
280 	}
281 	/* reset state */
282 	auth2_challenge_stop(authctxt);
283 #ifdef JPAKE
284 	auth2_jpake_stop(authctxt);
285 #endif
286 
287 #ifdef GSSAPI
288 	/* XXX move to auth2_gssapi_stop() */
289 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
290 	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
291 #endif
292 
293 	authctxt->postponed = 0;
294 	authctxt->server_caused_failure = 0;
295 
296 	/* try to authenticate user */
297 	m = authmethod_lookup(authctxt, method);
298 	if (m != NULL && authctxt->failures < options.max_authtries) {
299 		debug2("input_userauth_request: try method %s", method);
300 		authenticated =	m->userauth(authctxt);
301 	}
302 	userauth_finish(authctxt, authenticated, method, NULL);
303 
304 	xfree(service);
305 	xfree(user);
306 	xfree(method);
307 }
308 
309 void
310 userauth_finish(Authctxt *authctxt, int authenticated, const char *method,
311     const char *submethod)
312 {
313 	char *methods;
314 	int partial = 0;
315 
316 	if (!authctxt->valid && authenticated)
317 		fatal("INTERNAL ERROR: authenticated invalid user %s",
318 		    authctxt->user);
319 	if (authenticated && authctxt->postponed)
320 		fatal("INTERNAL ERROR: authenticated and postponed");
321 
322 	/* Special handling for root */
323 	if (authenticated && authctxt->pw->pw_uid == 0 &&
324 	    !auth_root_allowed(method)) {
325 		authenticated = 0;
326 #ifdef SSH_AUDIT_EVENTS
327 		PRIVSEP(audit_event(SSH_LOGIN_ROOT_DENIED));
328 #endif
329 	}
330 
331 #ifdef USE_PAM
332 	if (options.use_pam && authenticated) {
333 		if (!PRIVSEP(do_pam_account())) {
334 			/* if PAM returned a message, send it to the user */
335 			if (buffer_len(&loginmsg) > 0) {
336 				buffer_append(&loginmsg, "\0", 1);
337 				userauth_send_banner(buffer_ptr(&loginmsg));
338 				packet_write_wait();
339 			}
340 			fatal("Access denied for user %s by PAM account "
341 			   "configuration", authctxt->user);
342 		}
343 	}
344 #endif
345 
346 	if (authenticated && options.num_auth_methods != 0) {
347 		if (!auth2_update_methods_lists(authctxt, method)) {
348 			authenticated = 0;
349 			partial = 1;
350 		}
351 	}
352 
353 	/* Log before sending the reply */
354 	auth_log(authctxt, authenticated, partial, method, submethod, " ssh2");
355 
356 	if (authctxt->postponed)
357 		return;
358 
359 	if (authenticated == 1) {
360 		/* turn off userauth */
361 		dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &dispatch_protocol_ignore);
362 		packet_start(SSH2_MSG_USERAUTH_SUCCESS);
363 		packet_send();
364 		packet_write_wait();
365 		/* now we can break out */
366 		authctxt->success = 1;
367 	} else {
368 		/* Allow initial try of "none" auth without failure penalty */
369 		if (!authctxt->server_caused_failure &&
370 		    (authctxt->attempt > 1 || strcmp(method, "none") != 0))
371 			authctxt->failures++;
372 		if (authctxt->failures >= options.max_authtries) {
373 			packet_disconnect(AUTH_FAIL_MSG, authctxt->user);
374 #ifdef SSH_AUDIT_EVENTS
375 			PRIVSEP(audit_event(SSH_LOGIN_EXCEED_MAXTRIES));
376 #endif
377 		}
378 		methods = authmethods_get(authctxt);
379 		debug3("%s: failure partial=%d next methods=\"%s\"", __func__,
380 		    partial, methods);
381 		packet_start(SSH2_MSG_USERAUTH_FAILURE);
382 		packet_put_cstring(methods);
383 		packet_put_char(partial);
384 		packet_send();
385 		packet_write_wait();
386 		xfree(methods);
387 	}
388 }
389 
390 /*
391  * Checks whether method is allowed by at least one AuthenticationMethods
392  * methods list. Returns 1 if allowed, or no methods lists configured.
393  * 0 otherwise.
394  */
395 static int
396 method_allowed(Authctxt *authctxt, const char *method)
397 {
398 	u_int i;
399 
400 	/*
401 	 * NB. authctxt->num_auth_methods might be zero as a result of
402 	 * auth2_setup_methods_lists(), so check the configuration.
403 	 */
404 	if (options.num_auth_methods == 0)
405 		return 1;
406 	for (i = 0; i < authctxt->num_auth_methods; i++) {
407 		if (list_starts_with(authctxt->auth_methods[i], method))
408 			return 1;
409 	}
410 	return 0;
411 }
412 
413 static char *
414 authmethods_get(Authctxt *authctxt)
415 {
416 	Buffer b;
417 	char *list;
418 	u_int i;
419 
420 	buffer_init(&b);
421 	for (i = 0; authmethods[i] != NULL; i++) {
422 		if (strcmp(authmethods[i]->name, "none") == 0)
423 			continue;
424 		if (authmethods[i]->enabled == NULL ||
425 		    *(authmethods[i]->enabled) == 0)
426 			continue;
427 		if (!method_allowed(authctxt, authmethods[i]->name))
428 			continue;
429 		if (buffer_len(&b) > 0)
430 			buffer_append(&b, ",", 1);
431 		buffer_append(&b, authmethods[i]->name,
432 		    strlen(authmethods[i]->name));
433 	}
434 	buffer_append(&b, "\0", 1);
435 	list = xstrdup(buffer_ptr(&b));
436 	buffer_free(&b);
437 	return list;
438 }
439 
440 static Authmethod *
441 authmethod_lookup(Authctxt *authctxt, const char *name)
442 {
443 	int i;
444 
445 	if (name != NULL)
446 		for (i = 0; authmethods[i] != NULL; i++)
447 			if (authmethods[i]->enabled != NULL &&
448 			    *(authmethods[i]->enabled) != 0 &&
449 			    strcmp(name, authmethods[i]->name) == 0 &&
450 			    method_allowed(authctxt, authmethods[i]->name))
451 				return authmethods[i];
452 	debug2("Unrecognized authentication method name: %s",
453 	    name ? name : "NULL");
454 	return NULL;
455 }
456 
457 /*
458  * Check a comma-separated list of methods for validity. Is need_enable is
459  * non-zero, then also require that the methods are enabled.
460  * Returns 0 on success or -1 if the methods list is invalid.
461  */
462 int
463 auth2_methods_valid(const char *_methods, int need_enable)
464 {
465 	char *methods, *omethods, *method;
466 	u_int i, found;
467 	int ret = -1;
468 
469 	if (*_methods == '\0') {
470 		error("empty authentication method list");
471 		return -1;
472 	}
473 	omethods = methods = xstrdup(_methods);
474 	while ((method = strsep(&methods, ",")) != NULL) {
475 		for (found = i = 0; !found && authmethods[i] != NULL; i++) {
476 			if (strcmp(method, authmethods[i]->name) != 0)
477 				continue;
478 			if (need_enable) {
479 				if (authmethods[i]->enabled == NULL ||
480 				    *(authmethods[i]->enabled) == 0) {
481 					error("Disabled method \"%s\" in "
482 					    "AuthenticationMethods list \"%s\"",
483 					    method, _methods);
484 					goto out;
485 				}
486 			}
487 			found = 1;
488 			break;
489 		}
490 		if (!found) {
491 			error("Unknown authentication method \"%s\" in list",
492 			    method);
493 			goto out;
494 		}
495 	}
496 	ret = 0;
497  out:
498 	free(omethods);
499 	return ret;
500 }
501 
502 /*
503  * Prune the AuthenticationMethods supplied in the configuration, removing
504  * any methods lists that include disabled methods. Note that this might
505  * leave authctxt->num_auth_methods == 0, even when multiple required auth
506  * has been requested. For this reason, all tests for whether multiple is
507  * enabled should consult options.num_auth_methods directly.
508  */
509 int
510 auth2_setup_methods_lists(Authctxt *authctxt)
511 {
512 	u_int i;
513 
514 	if (options.num_auth_methods == 0)
515 		return 0;
516 	debug3("%s: checking methods", __func__);
517 	authctxt->auth_methods = xcalloc(options.num_auth_methods,
518 	    sizeof(*authctxt->auth_methods));
519 	authctxt->num_auth_methods = 0;
520 	for (i = 0; i < options.num_auth_methods; i++) {
521 		if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
522 			logit("Authentication methods list \"%s\" contains "
523 			    "disabled method, skipping",
524 			    options.auth_methods[i]);
525 			continue;
526 		}
527 		debug("authentication methods list %d: %s",
528 		    authctxt->num_auth_methods, options.auth_methods[i]);
529 		authctxt->auth_methods[authctxt->num_auth_methods++] =
530 		    xstrdup(options.auth_methods[i]);
531 	}
532 	if (authctxt->num_auth_methods == 0) {
533 		error("No AuthenticationMethods left after eliminating "
534 		    "disabled methods");
535 		return -1;
536 	}
537 	return 0;
538 }
539 
540 static int
541 list_starts_with(const char *methods, const char *method)
542 {
543 	size_t l = strlen(method);
544 
545 	if (strncmp(methods, method, l) != 0)
546 		return 0;
547 	if (methods[l] != ',' && methods[l] != '\0')
548 		return 0;
549 	return 1;
550 }
551 
552 /*
553  * Remove method from the start of a comma-separated list of methods.
554  * Returns 0 if the list of methods did not start with that method or 1
555  * if it did.
556  */
557 static int
558 remove_method(char **methods, const char *method)
559 {
560 	char *omethods = *methods;
561 	size_t l = strlen(method);
562 
563 	if (!list_starts_with(omethods, method))
564 		return 0;
565 	*methods = xstrdup(omethods + l + (omethods[l] == ',' ? 1 : 0));
566 	free(omethods);
567 	return 1;
568 }
569 
570 /*
571  * Called after successful authentication. Will remove the successful method
572  * from the start of each list in which it occurs. If it was the last method
573  * in any list, then authentication is deemed successful.
574  * Returns 1 if the method completed any authentication list or 0 otherwise.
575  */
576 int
577 auth2_update_methods_lists(Authctxt *authctxt, const char *method)
578 {
579 	u_int i, found = 0;
580 
581 	debug3("%s: updating methods list after \"%s\"", __func__, method);
582 	for (i = 0; i < authctxt->num_auth_methods; i++) {
583 		if (!remove_method(&(authctxt->auth_methods[i]), method))
584 			continue;
585 		found = 1;
586 		if (*authctxt->auth_methods[i] == '\0') {
587 			debug2("authentication methods list %d complete", i);
588 			return 1;
589 		}
590 		debug3("authentication methods list %d remaining: \"%s\"",
591 		    i, authctxt->auth_methods[i]);
592 	}
593 	/* This should not happen, but would be bad if it did */
594 	if (!found)
595 		fatal("%s: method not in AuthenticationMethods", __func__);
596 	return 0;
597 }
598 
599 
600