auth2.c revision 192595
1/* $OpenBSD: auth2.c,v 1.120 2008/11/04 08:22:12 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__RCSID("$FreeBSD: head/crypto/openssh/auth2.c 192595 2009-05-22 18:46:28Z des $");
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 "xmalloc.h"
40#include "atomicio.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#include "monitor_wrap.h"
59
60/* import */
61extern ServerOptions options;
62extern u_char *session_id2;
63extern u_int session_id2_len;
64extern Buffer loginmsg;
65
66/* methods */
67
68extern Authmethod method_none;
69extern Authmethod method_pubkey;
70extern Authmethod method_passwd;
71extern Authmethod method_kbdint;
72extern Authmethod method_hostbased;
73#ifdef GSSAPI
74extern Authmethod method_gssapi;
75#endif
76#ifdef JPAKE
77extern Authmethod method_jpake;
78#endif
79
80Authmethod *authmethods[] = {
81	&method_none,
82	&method_pubkey,
83#ifdef GSSAPI
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(const char *);
102static char *authmethods_get(void);
103
104char *
105auth2_read_banner(void)
106{
107	struct stat st;
108	char *banner = NULL;
109	size_t len, n;
110	int fd;
111
112	if ((fd = open(options.banner, O_RDONLY)) == -1)
113		return (NULL);
114	if (fstat(fd, &st) == -1) {
115		close(fd);
116		return (NULL);
117	}
118	if (st.st_size > 1*1024*1024) {
119		close(fd);
120		return (NULL);
121	}
122
123	len = (size_t)st.st_size;		/* truncate */
124	banner = xmalloc(len + 1);
125	n = atomicio(read, fd, banner, len);
126	close(fd);
127
128	if (n != len) {
129		xfree(banner);
130		return (NULL);
131	}
132	banner[n] = '\0';
133
134	return (banner);
135}
136
137void
138userauth_send_banner(const char *msg)
139{
140	if (datafellows & SSH_BUG_BANNER)
141		return;
142
143	packet_start(SSH2_MSG_USERAUTH_BANNER);
144	packet_put_cstring(msg);
145	packet_put_cstring("");		/* language, unused */
146	packet_send();
147	debug("%s: sent", __func__);
148}
149
150static void
151userauth_banner(void)
152{
153	char *banner = NULL;
154
155	if (options.banner == NULL ||
156	    strcasecmp(options.banner, "none") == 0 ||
157	    (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	if (banner)
166		xfree(banner);
167}
168
169/*
170 * loop until authctxt->success == TRUE
171 */
172void
173do_authentication2(Authctxt *authctxt)
174{
175	dispatch_init(&dispatch_protocol_error);
176	dispatch_set(SSH2_MSG_SERVICE_REQUEST, &input_service_request);
177	dispatch_run(DISPATCH_BLOCK, &authctxt->success, authctxt);
178}
179
180/*ARGSUSED*/
181static void
182input_service_request(int type, u_int32_t seq, void *ctxt)
183{
184	Authctxt *authctxt = ctxt;
185	u_int len;
186	int acceptit = 0;
187	char *service = packet_get_string(&len);
188	packet_check_eom();
189
190	if (authctxt == NULL)
191		fatal("input_service_request: no authctxt");
192
193	if (strcmp(service, "ssh-userauth") == 0) {
194		if (!authctxt->success) {
195			acceptit = 1;
196			/* now we can handle user-auth requests */
197			dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &input_userauth_request);
198		}
199	}
200	/* XXX all other service requests are denied */
201
202	if (acceptit) {
203		packet_start(SSH2_MSG_SERVICE_ACCEPT);
204		packet_put_cstring(service);
205		packet_send();
206		packet_write_wait();
207	} else {
208		debug("bad service request %s", service);
209		packet_disconnect("bad service request %s", service);
210	}
211	xfree(service);
212}
213
214/*ARGSUSED*/
215static void
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_string(NULL);
234	service = packet_get_string(NULL);
235	method = packet_get_string(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	} else if (strcmp(user, authctxt->user) != 0 ||
268	    strcmp(service, authctxt->service) != 0) {
269		packet_disconnect("Change of username or service not allowed: "
270		    "(%s,%s) -> (%s,%s)",
271		    authctxt->user, authctxt->service, user, service);
272	}
273
274#ifdef HAVE_LOGIN_CAP
275        if (authctxt->pw != NULL) {
276                lc = login_getpwclass(authctxt->pw);
277                if (lc == NULL)
278                        lc = login_getclassbyname(NULL, authctxt->pw);
279                if (!auth_hostok(lc, from_host, from_ip)) {
280                        logit("Denied connection for %.200s from %.200s [%.200s].",
281                            authctxt->pw->pw_name, from_host, from_ip);
282                        packet_disconnect("Sorry, you are not allowed to connect.");
283                }
284                if (!auth_timeok(lc, time(NULL))) {
285                        logit("LOGIN %.200s REFUSED (TIME) FROM %.200s",
286                            authctxt->pw->pw_name, from_host);
287                        packet_disconnect("Logins not available right now.");
288                }
289                login_close(lc);
290                lc = NULL;
291        }
292#endif  /* HAVE_LOGIN_CAP */
293
294	/* reset state */
295	auth2_challenge_stop(authctxt);
296#ifdef JPAKE
297	auth2_jpake_stop(authctxt);
298#endif
299
300#ifdef GSSAPI
301	/* XXX move to auth2_gssapi_stop() */
302	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
303	dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
304#endif
305
306	authctxt->postponed = 0;
307
308	/* try to authenticate user */
309	m = authmethod_lookup(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);
315
316	xfree(service);
317	xfree(user);
318	xfree(method);
319}
320
321void
322userauth_finish(Authctxt *authctxt, int authenticated, char *method)
323{
324	char *methods;
325
326	if (!authctxt->valid && authenticated)
327		fatal("INTERNAL ERROR: authenticated invalid user %s",
328		    authctxt->user);
329
330	/* Special handling for root */
331	if (authenticated && authctxt->pw->pw_uid == 0 &&
332	    !auth_root_allowed(method)) {
333		authenticated = 0;
334#ifdef SSH_AUDIT_EVENTS
335		PRIVSEP(audit_event(SSH_LOGIN_ROOT_DENIED));
336#endif
337	}
338
339#ifdef USE_PAM
340	if (options.use_pam && authenticated) {
341		if (!PRIVSEP(do_pam_account())) {
342			/* if PAM returned a message, send it to the user */
343			if (buffer_len(&loginmsg) > 0) {
344				buffer_append(&loginmsg, "\0", 1);
345				userauth_send_banner(buffer_ptr(&loginmsg));
346				packet_write_wait();
347			}
348			fatal("Access denied for user %s by PAM account "
349			    "configuration", authctxt->user);
350		}
351	}
352#endif
353
354#ifdef _UNICOS
355	if (authenticated && cray_access_denied(authctxt->user)) {
356		authenticated = 0;
357		fatal("Access denied for user %s.",authctxt->user);
358	}
359#endif /* _UNICOS */
360
361	/* Log before sending the reply */
362	auth_log(authctxt, authenticated, method, " ssh2");
363
364	if (authctxt->postponed)
365		return;
366
367	/* XXX todo: check if multiple auth methods are needed */
368	if (authenticated == 1) {
369		/* turn off userauth */
370		dispatch_set(SSH2_MSG_USERAUTH_REQUEST, &dispatch_protocol_ignore);
371		packet_start(SSH2_MSG_USERAUTH_SUCCESS);
372		packet_send();
373		packet_write_wait();
374		/* now we can break out */
375		authctxt->success = 1;
376	} else {
377
378		/* Allow initial try of "none" auth without failure penalty */
379		if (authctxt->attempt > 1 || strcmp(method, "none") != 0)
380			authctxt->failures++;
381		if (authctxt->failures >= options.max_authtries) {
382#ifdef SSH_AUDIT_EVENTS
383			PRIVSEP(audit_event(SSH_LOGIN_EXCEED_MAXTRIES));
384#endif
385			packet_disconnect(AUTH_FAIL_MSG, authctxt->user);
386		}
387		methods = authmethods_get();
388		packet_start(SSH2_MSG_USERAUTH_FAILURE);
389		packet_put_cstring(methods);
390		packet_put_char(0);	/* XXX partial success, unused */
391		packet_send();
392		packet_write_wait();
393		xfree(methods);
394	}
395}
396
397static char *
398authmethods_get(void)
399{
400	Buffer b;
401	char *list;
402	int i;
403
404	buffer_init(&b);
405	for (i = 0; authmethods[i] != NULL; i++) {
406		if (strcmp(authmethods[i]->name, "none") == 0)
407			continue;
408		if (authmethods[i]->enabled != NULL &&
409		    *(authmethods[i]->enabled) != 0) {
410			if (buffer_len(&b) > 0)
411				buffer_append(&b, ",", 1);
412			buffer_append(&b, authmethods[i]->name,
413			    strlen(authmethods[i]->name));
414		}
415	}
416	buffer_append(&b, "\0", 1);
417	list = xstrdup(buffer_ptr(&b));
418	buffer_free(&b);
419	return list;
420}
421
422static Authmethod *
423authmethod_lookup(const char *name)
424{
425	int i;
426
427	if (name != NULL)
428		for (i = 0; authmethods[i] != NULL; i++)
429			if (authmethods[i]->enabled != NULL &&
430			    *(authmethods[i]->enabled) != 0 &&
431			    strcmp(name, authmethods[i]->name) == 0)
432				return authmethods[i];
433	debug2("Unrecognized authentication method name: %s",
434	    name ? name : "NULL");
435	return NULL;
436}
437
438