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