1/* $OpenBSD: auth2.c,v 1.126 2012/12/02 20:34:09 djm 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
28#include <sys/types.h>
29#include <sys/stat.h>
30#include <sys/uio.h>
31
32#include <fcntl.h>
33#include <pwd.h>
34#include <stdarg.h>
35#include <string.h>
36#include <unistd.h>
37
38#include "atomicio.h"
39#include "xmalloc.h"
40#include "ssh2.h"
41#include "packet.h"
42#include "log.h"
43#include "buffer.h"
44#include "servconf.h"
45#include "compat.h"
46#include "key.h"
47#include "hostfile.h"
48#include "auth.h"
49#include "dispatch.h"
50#include "pathnames.h"
51#include "buffer.h"
52
53#ifdef GSSAPI
54#include "ssh-gss.h"
55#endif
56#include "monitor_wrap.h"
57
58/* import */
59extern ServerOptions options;
60extern u_char *session_id2;
61extern u_int session_id2_len;
62extern Buffer loginmsg;
63
64/* methods */
65
66extern Authmethod method_none;
67extern Authmethod method_pubkey;
68extern Authmethod method_passwd;
69extern Authmethod method_kbdint;
70extern Authmethod method_hostbased;
71#ifdef GSSAPI
72extern Authmethod method_gsskeyex;
73extern Authmethod method_gssapi;
74#endif
75#ifdef JPAKE
76extern Authmethod method_jpake;
77#endif
78
79Authmethod *authmethods[] = {
80	&method_none,
81	&method_pubkey,
82#ifdef GSSAPI
83	&method_gsskeyex,
84	&method_gssapi,
85#endif
86#ifdef JPAKE
87	&method_jpake,
88#endif
89	&method_passwd,
90	&method_kbdint,
91	&method_hostbased,
92	NULL
93};
94
95/* protocol */
96
97static void input_service_request(int, u_int32_t, void *);
98static void input_userauth_request(int, u_int32_t, void *);
99
100/* helper */
101static Authmethod *authmethod_lookup(Authctxt *, const char *);
102static char *authmethods_get(Authctxt *authctxt);
103static int method_allowed(Authctxt *, const char *);
104static int list_starts_with(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		xfree(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 ||
158	    strcasecmp(options.banner, "none") == 0 ||
159	    (datafellows & SSH_BUG_BANNER) != 0)
160		return;
161
162	if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
163		goto done;
164	userauth_send_banner(banner);
165
166done:
167	if (banner)
168		xfree(banner);
169}
170
171/*
172 * loop until authctxt->success == TRUE
173 */
174void
175do_authentication2(Authctxt *authctxt)
176{
177	dispatch_init(&dispatch_protocol_error);
178	dispatch_set(SSH2_MSG_SERVICE_REQUEST, &input_service_request);
179	dispatch_run(DISPATCH_BLOCK, &authctxt->success, authctxt);
180}
181
182/*ARGSUSED*/
183static void
184input_service_request(int type, u_int32_t seq, void *ctxt)
185{
186	Authctxt *authctxt = ctxt;
187	u_int len;
188	int acceptit = 0;
189	char *service = packet_get_cstring(&len);
190	packet_check_eom();
191
192	if (authctxt == NULL)
193		fatal("input_service_request: no authctxt");
194
195	if (strcmp(service, "ssh-userauth") == 0) {
196		if (!authctxt->success) {
197			acceptit = 1;
198			/* now we can handle user-auth requests */
199			dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &input_userauth_request);
200		}
201	}
202	/* XXX all other service requests are denied */
203
204	if (acceptit) {
205		packet_start(SSH2_MSG_SERVICE_ACCEPT);
206		packet_put_cstring(service);
207		packet_send();
208		packet_write_wait();
209	} else {
210		debug("bad service request %s", service);
211		packet_disconnect("bad service request %s", service);
212	}
213	xfree(service);
214}
215
216/*ARGSUSED*/
217static void
218input_userauth_request(int type, u_int32_t seq, void *ctxt)
219{
220	Authctxt *authctxt = ctxt;
221	Authmethod *m = NULL;
222	char *user, *service, *method, *style = NULL;
223	int authenticated = 0;
224
225	if (authctxt == NULL)
226		fatal("input_userauth_request: no authctxt");
227
228	user = packet_get_cstring(NULL);
229	service = packet_get_cstring(NULL);
230	method = packet_get_cstring(NULL);
231	debug("userauth-request for user %s service %s method %s", user, service, method);
232	debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
233
234	if ((style = strchr(user, ':')) != NULL)
235		*style++ = 0;
236
237	if (authctxt->attempt++ == 0) {
238		/* setup auth context */
239		authctxt->pw = PRIVSEP(getpwnamallow(user));
240		authctxt->user = xstrdup(user);
241		if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
242			authctxt->valid = 1;
243			debug2("input_userauth_request: setting up authctxt for %s", user);
244		} else {
245			logit("input_userauth_request: invalid user %s", user);
246			authctxt->pw = fakepw();
247#ifdef SSH_AUDIT_EVENTS
248			PRIVSEP(audit_event(SSH_INVALID_USER));
249#endif
250		}
251#ifdef USE_PAM
252		if (options.use_pam)
253			PRIVSEP(start_pam(authctxt));
254#endif
255		setproctitle("%s%s", authctxt->valid ? user : "unknown",
256		    use_privsep ? " [net]" : "");
257		authctxt->service = xstrdup(service);
258		authctxt->style = style ? xstrdup(style) : NULL;
259		if (use_privsep)
260			mm_inform_authserv(service, style);
261		userauth_banner();
262		if (auth2_setup_methods_lists(authctxt) != 0)
263			packet_disconnect("no authentication methods enabled");
264	} else if (strcmp(user, authctxt->user) != 0 ||
265	    strcmp(service, authctxt->service) != 0) {
266		packet_disconnect("Change of username or service not allowed: "
267		    "(%s,%s) -> (%s,%s)",
268		    authctxt->user, authctxt->service, user, service);
269	}
270	/* reset state */
271	auth2_challenge_stop(authctxt);
272#ifdef JPAKE
273	auth2_jpake_stop(authctxt);
274#endif
275
276#ifdef GSSAPI
277	/* XXX move to auth2_gssapi_stop() */
278	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
279	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
280#endif
281
282	authctxt->postponed = 0;
283	authctxt->server_caused_failure = 0;
284
285	/* try to authenticate user */
286	m = authmethod_lookup(authctxt, method);
287	if (m != NULL && authctxt->failures < options.max_authtries) {
288		debug2("input_userauth_request: try method %s", method);
289		authenticated =	m->userauth(authctxt);
290	}
291	userauth_finish(authctxt, authenticated, method, NULL);
292
293	xfree(service);
294	xfree(user);
295	xfree(method);
296}
297
298void
299userauth_finish(Authctxt *authctxt, int authenticated, const char *method,
300    const char *submethod)
301{
302	char *methods;
303	int partial = 0;
304
305	if (!authctxt->valid && authenticated)
306		fatal("INTERNAL ERROR: authenticated invalid user %s",
307		    authctxt->user);
308	if (authenticated && authctxt->postponed)
309		fatal("INTERNAL ERROR: authenticated and postponed");
310
311	/* Special handling for root */
312	if (authenticated && authctxt->pw->pw_uid == 0 &&
313	    !auth_root_allowed(method)) {
314		authenticated = 0;
315#ifdef SSH_AUDIT_EVENTS
316		PRIVSEP(audit_event(SSH_LOGIN_ROOT_DENIED));
317#endif
318	}
319
320	if (authenticated && options.num_auth_methods != 0) {
321		if (!auth2_update_methods_lists(authctxt, method)) {
322			authenticated = 0;
323			partial = 1;
324		}
325	}
326
327	/* Log before sending the reply */
328	auth_log(authctxt, authenticated, partial, method, submethod, " ssh2");
329
330	if (authctxt->postponed)
331		return;
332
333#ifdef USE_PAM
334	if (options.use_pam && authenticated) {
335		if (!PRIVSEP(do_pam_account())) {
336			/* if PAM returned a message, send it to the user */
337			if (buffer_len(&loginmsg) > 0) {
338				buffer_append(&loginmsg, "\0", 1);
339				userauth_send_banner(buffer_ptr(&loginmsg));
340				packet_write_wait();
341			}
342			fatal("Access denied for user %s by PAM account "
343			    "configuration", authctxt->user);
344		}
345	}
346#endif
347
348#ifdef _UNICOS
349	if (authenticated && cray_access_denied(authctxt->user)) {
350		authenticated = 0;
351		fatal("Access denied for user %s.", authctxt->user);
352	}
353#endif /* _UNICOS */
354
355	if (authenticated == 1) {
356		/* turn off userauth */
357		dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &dispatch_protocol_ignore);
358		packet_start(SSH2_MSG_USERAUTH_SUCCESS);
359		packet_send();
360		packet_write_wait();
361		/* now we can break out */
362		authctxt->success = 1;
363	} else {
364
365		/* Allow initial try of "none" auth without failure penalty */
366		if (!authctxt->server_caused_failure &&
367		    (authctxt->attempt > 1 || strcmp(method, "none") != 0))
368			authctxt->failures++;
369		if (authctxt->failures >= options.max_authtries) {
370#ifdef SSH_AUDIT_EVENTS
371			PRIVSEP(audit_event(SSH_LOGIN_EXCEED_MAXTRIES));
372#endif
373			packet_disconnect(AUTH_FAIL_MSG, authctxt->user);
374		}
375		methods = authmethods_get(authctxt);
376		debug3("%s: failure partial=%d next methods=\"%s\"", __func__,
377		    partial, methods);
378		packet_start(SSH2_MSG_USERAUTH_FAILURE);
379		packet_put_cstring(methods);
380		packet_put_char(partial);
381		packet_send();
382		packet_write_wait();
383		xfree(methods);
384	}
385}
386
387/*
388 * Checks whether method is allowed by at least one AuthenticationMethods
389 * methods list. Returns 1 if allowed, or no methods lists configured.
390 * 0 otherwise.
391 */
392static int
393method_allowed(Authctxt *authctxt, const char *method)
394{
395	u_int i;
396
397	/*
398	 * NB. authctxt->num_auth_methods might be zero as a result of
399	 * auth2_setup_methods_lists(), so check the configuration.
400	 */
401	if (options.num_auth_methods == 0)
402		return 1;
403	for (i = 0; i < authctxt->num_auth_methods; i++) {
404		if (list_starts_with(authctxt->auth_methods[i], method))
405			return 1;
406	}
407	return 0;
408}
409
410static char *
411authmethods_get(Authctxt *authctxt)
412{
413	Buffer b;
414	char *list;
415	u_int i;
416
417	buffer_init(&b);
418	for (i = 0; authmethods[i] != NULL; i++) {
419		if (strcmp(authmethods[i]->name, "none") == 0)
420			continue;
421		if (authmethods[i]->enabled == NULL ||
422		    *(authmethods[i]->enabled) == 0)
423			continue;
424		if (!method_allowed(authctxt, authmethods[i]->name))
425			continue;
426		if (buffer_len(&b) > 0)
427			buffer_append(&b, ",", 1);
428		buffer_append(&b, authmethods[i]->name,
429		    strlen(authmethods[i]->name));
430	}
431	buffer_append(&b, "\0", 1);
432	list = xstrdup(buffer_ptr(&b));
433	buffer_free(&b);
434	return list;
435}
436
437static Authmethod *
438authmethod_lookup(Authctxt *authctxt, const char *name)
439{
440	int i;
441
442	if (name != NULL)
443		for (i = 0; authmethods[i] != NULL; i++)
444			if (authmethods[i]->enabled != NULL &&
445			    *(authmethods[i]->enabled) != 0 &&
446			    strcmp(name, authmethods[i]->name) == 0 &&
447			    method_allowed(authctxt, authmethods[i]->name))
448				return authmethods[i];
449	debug2("Unrecognized authentication method name: %s",
450	    name ? name : "NULL");
451	return NULL;
452}
453
454/*
455 * Check a comma-separated list of methods for validity. Is need_enable is
456 * non-zero, then also require that the methods are enabled.
457 * Returns 0 on success or -1 if the methods list is invalid.
458 */
459int
460auth2_methods_valid(const char *_methods, int need_enable)
461{
462	char *methods, *omethods, *method;
463	u_int i, found;
464	int ret = -1;
465
466	if (*_methods == '\0') {
467		error("empty authentication method list");
468		return -1;
469	}
470	omethods = methods = xstrdup(_methods);
471	while ((method = strsep(&methods, ",")) != NULL) {
472		for (found = i = 0; !found && authmethods[i] != NULL; i++) {
473			if (strcmp(method, authmethods[i]->name) != 0)
474				continue;
475			if (need_enable) {
476				if (authmethods[i]->enabled == NULL ||
477				    *(authmethods[i]->enabled) == 0) {
478					error("Disabled method \"%s\" in "
479					    "AuthenticationMethods list \"%s\"",
480					    method, _methods);
481					goto out;
482				}
483			}
484			found = 1;
485			break;
486		}
487		if (!found) {
488			error("Unknown authentication method \"%s\" in list",
489			    method);
490			goto out;
491		}
492	}
493	ret = 0;
494 out:
495	free(omethods);
496	return ret;
497}
498
499/*
500 * Prune the AuthenticationMethods supplied in the configuration, removing
501 * any methods lists that include disabled methods. Note that this might
502 * leave authctxt->num_auth_methods == 0, even when multiple required auth
503 * has been requested. For this reason, all tests for whether multiple is
504 * enabled should consult options.num_auth_methods directly.
505 */
506int
507auth2_setup_methods_lists(Authctxt *authctxt)
508{
509	u_int i;
510
511	if (options.num_auth_methods == 0)
512		return 0;
513	debug3("%s: checking methods", __func__);
514	authctxt->auth_methods = xcalloc(options.num_auth_methods,
515	    sizeof(*authctxt->auth_methods));
516	authctxt->num_auth_methods = 0;
517	for (i = 0; i < options.num_auth_methods; i++) {
518		if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
519			logit("Authentication methods list \"%s\" contains "
520			    "disabled method, skipping",
521			    options.auth_methods[i]);
522			continue;
523		}
524		debug("authentication methods list %d: %s",
525		    authctxt->num_auth_methods, options.auth_methods[i]);
526		authctxt->auth_methods[authctxt->num_auth_methods++] =
527		    xstrdup(options.auth_methods[i]);
528	}
529	if (authctxt->num_auth_methods == 0) {
530		error("No AuthenticationMethods left after eliminating "
531		    "disabled methods");
532		return -1;
533	}
534	return 0;
535}
536
537static int
538list_starts_with(const char *methods, const char *method)
539{
540	size_t l = strlen(method);
541
542	if (strncmp(methods, method, l) != 0)
543		return 0;
544	if (methods[l] != ',' && methods[l] != '\0')
545		return 0;
546	return 1;
547}
548
549/*
550 * Remove method from the start of a comma-separated list of methods.
551 * Returns 0 if the list of methods did not start with that method or 1
552 * if it did.
553 */
554static int
555remove_method(char **methods, const char *method)
556{
557	char *omethods = *methods;
558	size_t l = strlen(method);
559
560	if (!list_starts_with(omethods, method))
561		return 0;
562	*methods = xstrdup(omethods + l + (omethods[l] == ',' ? 1 : 0));
563	free(omethods);
564	return 1;
565}
566
567/*
568 * Called after successful authentication. Will remove the successful method
569 * from the start of each list in which it occurs. If it was the last method
570 * in any list, then authentication is deemed successful.
571 * Returns 1 if the method completed any authentication list or 0 otherwise.
572 */
573int
574auth2_update_methods_lists(Authctxt *authctxt, const char *method)
575{
576	u_int i, found = 0;
577
578	debug3("%s: updating methods list after \"%s\"", __func__, method);
579	for (i = 0; i < authctxt->num_auth_methods; i++) {
580		if (!remove_method(&(authctxt->auth_methods[i]), method))
581			continue;
582		found = 1;
583		if (*authctxt->auth_methods[i] == '\0') {
584			debug2("authentication methods list %d complete", i);
585			return 1;
586		}
587		debug3("authentication methods list %d remaining: \"%s\"",
588		    i, authctxt->auth_methods[i]);
589	}
590	/* This should not happen, but would be bad if it did */
591	if (!found)
592		fatal("%s: method not in AuthenticationMethods", __func__);
593	return 0;
594}
595
596
597