12061Sjkh/* $OpenBSD: auth.c,v 1.115 2016/06/15 00:40:40 dtucker Exp $ */
250479Speter/*
32061Sjkh * Copyright (c) 2000 Markus Friedl.  All rights reserved.
438666Sjb *
532427Sjb * Redistribution and use in source and binary forms, with or without
6111131Sru * modification, are permitted provided that the following conditions
7111131Sru * are met:
838666Sjb * 1. Redistributions of source code must retain the above copyright
938666Sjb *    notice, this list of conditions and the following disclaimer.
1038666Sjb * 2. Redistributions in binary form must reproduce the above copyright
1138666Sjb *    notice, this list of conditions and the following disclaimer in the
1264049Salex *    documentation and/or other materials provided with the distribution.
1364049Salex *
14116679Ssimokawa * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1566071Smarkm * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16116679Ssimokawa * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1773504Sobrien * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1838666Sjb * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
1938666Sjb * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2038666Sjb * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2132427Sjb * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2238666Sjb * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23108451Sschweikh * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2438666Sjb */
2538666Sjb
2638666Sjb#include "includes.h"
2738666Sjb__RCSID("$FreeBSD: stable/10/crypto/openssh/auth.c 323124 2017-09-01 22:52:18Z des $");
2817308Speter
2991606Skeramida#include <sys/types.h>
3019175Sbde#include <sys/stat.h>
3196205Sjwd#include <sys/socket.h>
3296205Sjwd
3338042Sbde#include <netinet/in.h>
3496205Sjwd
3596205Sjwd#include <errno.h>
3638042Sbde#include <fcntl.h>
3796205Sjwd#ifdef HAVE_PATHS_H
3896205Sjwd# include <paths.h>
3917308Speter#endif
4096205Sjwd#include <pwd.h>
4196205Sjwd#ifdef HAVE_LOGIN_H
4217308Speter#include <login.h>
4396205Sjwd#endif
4496205Sjwd#ifdef USE_SHADOW
4596205Sjwd#include <shadow.h>
4696205Sjwd#endif
4796205Sjwd#ifdef HAVE_LIBGEN_H
4896205Sjwd#include <libgen.h>
4996205Sjwd#endif
5096205Sjwd#include <stdarg.h>
5196205Sjwd#include <stdio.h>
5296205Sjwd#include <string.h>
5396205Sjwd#include <unistd.h>
5496205Sjwd#include <limits.h>
5598775Sdillon#include <netdb.h>
5698723Sdillon
5798723Sdillon#include "xmalloc.h"
5898723Sdillon#include "match.h"
5998723Sdillon#include "groupaccess.h"
6038666Sjb#include "log.h"
6138666Sjb#include "buffer.h"
6217308Speter#include "misc.h"
6395509Sru#include "servconf.h"
6495793Sru#include "key.h"
65116679Ssimokawa#include "hostfile.h"
66116679Ssimokawa#include "auth.h"
67116679Ssimokawa#include "auth-options.h"
68117806Sru#include "canohost.h"
692061Sjkh#include "uidswap.h"
7097769Sru#include "packet.h"
7197252Sru#include "loginrec.h"
7297252Sru#ifdef GSSAPI
7395730Sru#include "ssh-gss.h"
7495793Sru#endif
75111617Sru#include "authfile.h"
7695730Sru#include "monitor_wrap.h"
77116679Ssimokawa#include "authfile.h"
7895730Sru#include "ssherr.h"
79116679Ssimokawa#include "compat.h"
8095730Sru
81110035Sru/* import */
82107516Sruextern ServerOptions options;
83110035Sruextern int use_privsep;
84117234Sruextern Buffer loginmsg;
85110035Sruextern struct passwd *privsep_pw;
86117229Sru
87117234Sru/* Debugging messages */
8854324SmarcelBuffer auth_debug;
8917308Speterint auth_debug_init;
9038666Sjb
9117308Speter/*
9297252Sru * Check if the user is allowed to log in via ssh. If user is listed
9338666Sjb * in DenyUsers or one of user's groups is listed in DenyGroups, false
94110035Sru * will be returned. If AllowUsers isn't empty and user isn't listed
952302Spaul * there, or if AllowGroups isn't empty and one of user's groups isn't
9639206Sjkh * listed there, false will be returned.
9739206Sjkh * If the user's shell is not executable, false will be returned.
9839206Sjkh * Otherwise true is returned.
9973349Sru */
10017308Speterint
10154324Smarcelallowed_user(struct passwd * pw)
10254324Smarcel{
10354324Smarcel	struct ssh *ssh = active_state; /* XXX */
10454324Smarcel	struct stat st;
10554324Smarcel	const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
10654324Smarcel	u_int i;
10754324Smarcel#ifdef USE_SHADOW
108103436Speter	struct spwd *spw = NULL;
10954324Smarcel#endif
11054324Smarcel
11154324Smarcel	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
11254324Smarcel	if (!pw || !pw->pw_name)
11354324Smarcel		return 0;
11454324Smarcel
115110035Sru#ifdef USE_SHADOW
11654324Smarcel	if (!options.use_pam)
117110035Sru		spw = getspnam(pw->pw_name);
118110035Sru#ifdef HAS_SHADOW_EXPIRE
11954324Smarcel	if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
12054324Smarcel		return 0;
12154324Smarcel#endif /* HAS_SHADOW_EXPIRE */
12254324Smarcel#endif /* USE_SHADOW */
12354324Smarcel
124110035Sru	/* grab passwd field for locked account check */
12554324Smarcel	passwd = pw->pw_passwd;
12654324Smarcel#ifdef USE_SHADOW
12754324Smarcel	if (spw != NULL)
128103436Speter#ifdef USE_LIBIAF
12954324Smarcel		passwd = get_iaf_password(pw);
13054324Smarcel#else
13154324Smarcel		passwd = spw->sp_pwdp;
13295730Sru#endif /* USE_LIBIAF */
13395730Sru#endif
13495730Sru
13595730Sru	/* check for locked account */
13695730Sru	if (!options.use_pam && passwd && *passwd) {
13795730Sru		int locked = 0;
13895730Sru
13938666Sjb#ifdef LOCKED_PASSWD_STRING
140107374Sru		if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
14117308Speter			 locked = 1;
14255678Smarcel#endif
143110035Sru#ifdef LOCKED_PASSWD_PREFIX
144117793Sru		if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
145110035Sru		    strlen(LOCKED_PASSWD_PREFIX)) == 0)
146110035Sru			 locked = 1;
147110035Sru#endif
1482061Sjkh#ifdef LOCKED_PASSWD_SUBSTR
14917308Speter		if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
150107516Sru			locked = 1;
151107374Sru#endif
15255678Smarcel#ifdef USE_LIBIAF
153107516Sru		free((void *) passwd);
154107516Sru#endif /* USE_LIBIAF */
155107516Sru		if (locked) {
156107516Sru			logit("User %.100s not allowed because account is locked",
157107516Sru			    pw->pw_name);
158107516Sru			return 0;
159107516Sru		}
160107516Sru	}
16155678Smarcel
16255678Smarcel	/*
16355678Smarcel	 * Deny if shell does not exist or is not executable unless we
164116696Sru	 * are chrooting.
16555678Smarcel	 */
16655678Smarcel	if (options.chroot_directory == NULL ||
167107516Sru	    strcasecmp(options.chroot_directory, "none") == 0) {
168107516Sru		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
169107516Sru		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
170107516Sru
17155678Smarcel		if (stat(shell, &st) != 0) {
17255678Smarcel			logit("User %.100s not allowed because shell %.100s "
173111131Sru			    "does not exist", pw->pw_name, shell);
174111131Sru			free(shell);
175111131Sru			return 0;
176111131Sru		}
177111131Sru		if (S_ISREG(st.st_mode) == 0 ||
178111131Sru		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
179111131Sru			logit("User %.100s not allowed because shell %.100s "
180103985Sphk			    "is not executable", pw->pw_name, shell);
181103985Sphk			free(shell);
182103985Sphk			return 0;
183103985Sphk		}
184111089Sphk		free(shell);
185111131Sru	}
186111131Sru
187111131Sru	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
188111131Sru	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
189111131Sru		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
190111131Sru		ipaddr = ssh_remote_ipaddr(ssh);
191111131Sru	}
192111131Sru
193111131Sru	/* Return false if user is listed in DenyUsers */
194111133Sru	if (options.num_deny_users > 0) {
195103985Sphk		for (i = 0; i < options.num_deny_users; i++)
196111131Sru			if (match_user(pw->pw_name, hostname, ipaddr,
197111131Sru			    options.deny_users[i])) {
198103985Sphk				logit("User %.100s from %.100s not allowed "
199111131Sru				    "because listed in DenyUsers",
200103985Sphk				    pw->pw_name, hostname);
201107884Simp				return 0;
202103985Sphk			}
203103985Sphk	}
204111131Sru	/* Return false if AllowUsers isn't empty and user isn't listed there */
205111131Sru	if (options.num_allow_users > 0) {
206103985Sphk		for (i = 0; i < options.num_allow_users; i++)
207103985Sphk			if (match_user(pw->pw_name, hostname, ipaddr,
208111131Sru			    options.allow_users[i]))
209111131Sru				break;
210111131Sru		/* i < options.num_allow_users iff we break for loop */
211111131Sru		if (i >= options.num_allow_users) {
212111131Sru			logit("User %.100s from %.100s not allowed because "
213103985Sphk			    "not listed in AllowUsers", pw->pw_name, hostname);
214			return 0;
215		}
216	}
217	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
218		/* Get the user's group access list (primary and supplementary) */
219		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
220			logit("User %.100s from %.100s not allowed because "
221			    "not in any group", pw->pw_name, hostname);
222			return 0;
223		}
224
225		/* Return false if one of user's groups is listed in DenyGroups */
226		if (options.num_deny_groups > 0)
227			if (ga_match(options.deny_groups,
228			    options.num_deny_groups)) {
229				ga_free();
230				logit("User %.100s from %.100s not allowed "
231				    "because a group is listed in DenyGroups",
232				    pw->pw_name, hostname);
233				return 0;
234			}
235		/*
236		 * Return false if AllowGroups isn't empty and one of user's groups
237		 * isn't listed there
238		 */
239		if (options.num_allow_groups > 0)
240			if (!ga_match(options.allow_groups,
241			    options.num_allow_groups)) {
242				ga_free();
243				logit("User %.100s from %.100s not allowed "
244				    "because none of user's groups are listed "
245				    "in AllowGroups", pw->pw_name, hostname);
246				return 0;
247			}
248		ga_free();
249	}
250
251#ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
252	if (!sys_auth_allowed_user(pw, &loginmsg))
253		return 0;
254#endif
255
256	/* We found no reason not to let this user try to log on... */
257	return 1;
258}
259
260void
261auth_info(Authctxt *authctxt, const char *fmt, ...)
262{
263	va_list ap;
264        int i;
265
266	free(authctxt->info);
267	authctxt->info = NULL;
268
269	va_start(ap, fmt);
270	i = vasprintf(&authctxt->info, fmt, ap);
271	va_end(ap);
272
273	if (i < 0 || authctxt->info == NULL)
274		fatal("vasprintf failed");
275}
276
277void
278auth_log(Authctxt *authctxt, int authenticated, int partial,
279    const char *method, const char *submethod)
280{
281	struct ssh *ssh = active_state; /* XXX */
282	void (*authlog) (const char *fmt,...) = verbose;
283	char *authmsg;
284
285	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
286		return;
287
288	/* Raise logging level */
289	if (authenticated == 1 ||
290	    !authctxt->valid ||
291	    authctxt->failures >= options.max_authtries / 2 ||
292	    strcmp(method, "password") == 0)
293		authlog = logit;
294
295	if (authctxt->postponed)
296		authmsg = "Postponed";
297	else if (partial)
298		authmsg = "Partial";
299	else
300		authmsg = authenticated ? "Accepted" : "Failed";
301
302	authlog("%s %s%s%s for %s%.100s from %.200s port %d %s%s%s",
303	    authmsg,
304	    method,
305	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
306	    authctxt->valid ? "" : "invalid user ",
307	    authctxt->user,
308	    ssh_remote_ipaddr(ssh),
309	    ssh_remote_port(ssh),
310	    compat20 ? "ssh2" : "ssh1",
311	    authctxt->info != NULL ? ": " : "",
312	    authctxt->info != NULL ? authctxt->info : "");
313	free(authctxt->info);
314	authctxt->info = NULL;
315
316#ifdef CUSTOM_FAILED_LOGIN
317	if (authenticated == 0 && !authctxt->postponed &&
318	    (strcmp(method, "password") == 0 ||
319	    strncmp(method, "keyboard-interactive", 20) == 0 ||
320	    strcmp(method, "challenge-response") == 0))
321		record_failed_login(authctxt->user,
322		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
323# ifdef WITH_AIXAUTHENTICATE
324	if (authenticated)
325		sys_auth_record_login(authctxt->user,
326		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
327		    &loginmsg);
328# endif
329#endif
330#ifdef SSH_AUDIT_EVENTS
331	if (authenticated == 0 && !authctxt->postponed)
332		audit_event(audit_classify_auth(method));
333#endif
334}
335
336
337void
338auth_maxtries_exceeded(Authctxt *authctxt)
339{
340	struct ssh *ssh = active_state; /* XXX */
341
342	error("maximum authentication attempts exceeded for "
343	    "%s%.100s from %.200s port %d %s",
344	    authctxt->valid ? "" : "invalid user ",
345	    authctxt->user,
346	    ssh_remote_ipaddr(ssh),
347	    ssh_remote_port(ssh),
348	    compat20 ? "ssh2" : "ssh1");
349	packet_disconnect("Too many authentication failures");
350	/* NOTREACHED */
351}
352
353/*
354 * Check whether root logins are disallowed.
355 */
356int
357auth_root_allowed(const char *method)
358{
359	struct ssh *ssh = active_state; /* XXX */
360
361	switch (options.permit_root_login) {
362	case PERMIT_YES:
363		return 1;
364	case PERMIT_NO_PASSWD:
365		if (strcmp(method, "publickey") == 0 ||
366		    strcmp(method, "hostbased") == 0 ||
367		    strcmp(method, "gssapi-with-mic") == 0)
368			return 1;
369		break;
370	case PERMIT_FORCED_ONLY:
371		if (forced_command) {
372			logit("Root login accepted for forced command.");
373			return 1;
374		}
375		break;
376	}
377	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
378	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
379	return 0;
380}
381
382
383/*
384 * Given a template and a passwd structure, build a filename
385 * by substituting % tokenised options. Currently, %% becomes '%',
386 * %h becomes the home directory and %u the username.
387 *
388 * This returns a buffer allocated by xmalloc.
389 */
390char *
391expand_authorized_keys(const char *filename, struct passwd *pw)
392{
393	char *file, ret[PATH_MAX];
394	int i;
395
396	file = percent_expand(filename, "h", pw->pw_dir,
397	    "u", pw->pw_name, (char *)NULL);
398
399	/*
400	 * Ensure that filename starts anchored. If not, be backward
401	 * compatible and prepend the '%h/'
402	 */
403	if (*file == '/')
404		return (file);
405
406	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
407	if (i < 0 || (size_t)i >= sizeof(ret))
408		fatal("expand_authorized_keys: path too long");
409	free(file);
410	return (xstrdup(ret));
411}
412
413char *
414authorized_principals_file(struct passwd *pw)
415{
416	if (options.authorized_principals_file == NULL)
417		return NULL;
418	return expand_authorized_keys(options.authorized_principals_file, pw);
419}
420
421/* return ok if key exists in sysfile or userfile */
422HostStatus
423check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
424    const char *sysfile, const char *userfile)
425{
426	char *user_hostfile;
427	struct stat st;
428	HostStatus host_status;
429	struct hostkeys *hostkeys;
430	const struct hostkey_entry *found;
431
432	hostkeys = init_hostkeys();
433	load_hostkeys(hostkeys, host, sysfile);
434	if (userfile != NULL) {
435		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
436		if (options.strict_modes &&
437		    (stat(user_hostfile, &st) == 0) &&
438		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
439		    (st.st_mode & 022) != 0)) {
440			logit("Authentication refused for %.100s: "
441			    "bad owner or modes for %.200s",
442			    pw->pw_name, user_hostfile);
443			auth_debug_add("Ignored %.200s: bad ownership or modes",
444			    user_hostfile);
445		} else {
446			temporarily_use_uid(pw);
447			load_hostkeys(hostkeys, host, user_hostfile);
448			restore_uid();
449		}
450		free(user_hostfile);
451	}
452	host_status = check_key_in_hostkeys(hostkeys, key, &found);
453	if (host_status == HOST_REVOKED)
454		error("WARNING: revoked key for %s attempted authentication",
455		    found->host);
456	else if (host_status == HOST_OK)
457		debug("%s: key for %s found at %s:%ld", __func__,
458		    found->host, found->file, found->line);
459	else
460		debug("%s: key for host %s not found", __func__, host);
461
462	free_hostkeys(hostkeys);
463
464	return host_status;
465}
466
467/*
468 * Check a given path for security. This is defined as all components
469 * of the path to the file must be owned by either the owner of
470 * of the file or root and no directories must be group or world writable.
471 *
472 * XXX Should any specific check be done for sym links ?
473 *
474 * Takes a file name, its stat information (preferably from fstat() to
475 * avoid races), the uid of the expected owner, their home directory and an
476 * error buffer plus max size as arguments.
477 *
478 * Returns 0 on success and -1 on failure
479 */
480int
481auth_secure_path(const char *name, struct stat *stp, const char *pw_dir,
482    uid_t uid, char *err, size_t errlen)
483{
484	char buf[PATH_MAX], homedir[PATH_MAX];
485	char *cp;
486	int comparehome = 0;
487	struct stat st;
488
489	if (realpath(name, buf) == NULL) {
490		snprintf(err, errlen, "realpath %s failed: %s", name,
491		    strerror(errno));
492		return -1;
493	}
494	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
495		comparehome = 1;
496
497	if (!S_ISREG(stp->st_mode)) {
498		snprintf(err, errlen, "%s is not a regular file", buf);
499		return -1;
500	}
501	if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
502	    (stp->st_mode & 022) != 0) {
503		snprintf(err, errlen, "bad ownership or modes for file %s",
504		    buf);
505		return -1;
506	}
507
508	/* for each component of the canonical path, walking upwards */
509	for (;;) {
510		if ((cp = dirname(buf)) == NULL) {
511			snprintf(err, errlen, "dirname() failed");
512			return -1;
513		}
514		strlcpy(buf, cp, sizeof(buf));
515
516		if (stat(buf, &st) < 0 ||
517		    (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
518		    (st.st_mode & 022) != 0) {
519			snprintf(err, errlen,
520			    "bad ownership or modes for directory %s", buf);
521			return -1;
522		}
523
524		/* If are past the homedir then we can stop */
525		if (comparehome && strcmp(homedir, buf) == 0)
526			break;
527
528		/*
529		 * dirname should always complete with a "/" path,
530		 * but we can be paranoid and check for "." too
531		 */
532		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
533			break;
534	}
535	return 0;
536}
537
538/*
539 * Version of secure_path() that accepts an open file descriptor to
540 * avoid races.
541 *
542 * Returns 0 on success and -1 on failure
543 */
544static int
545secure_filename(FILE *f, const char *file, struct passwd *pw,
546    char *err, size_t errlen)
547{
548	struct stat st;
549
550	/* check the open file to avoid races */
551	if (fstat(fileno(f), &st) < 0) {
552		snprintf(err, errlen, "cannot stat file %s: %s",
553		    file, strerror(errno));
554		return -1;
555	}
556	return auth_secure_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
557}
558
559static FILE *
560auth_openfile(const char *file, struct passwd *pw, int strict_modes,
561    int log_missing, char *file_type)
562{
563	char line[1024];
564	struct stat st;
565	int fd;
566	FILE *f;
567
568	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
569		if (log_missing || errno != ENOENT)
570			debug("Could not open %s '%s': %s", file_type, file,
571			   strerror(errno));
572		return NULL;
573	}
574
575	if (fstat(fd, &st) < 0) {
576		close(fd);
577		return NULL;
578	}
579	if (!S_ISREG(st.st_mode)) {
580		logit("User %s %s %s is not a regular file",
581		    pw->pw_name, file_type, file);
582		close(fd);
583		return NULL;
584	}
585	unset_nonblock(fd);
586	if ((f = fdopen(fd, "r")) == NULL) {
587		close(fd);
588		return NULL;
589	}
590	if (strict_modes &&
591	    secure_filename(f, file, pw, line, sizeof(line)) != 0) {
592		fclose(f);
593		logit("Authentication refused: %s", line);
594		auth_debug_add("Ignored %s: %s", file_type, line);
595		return NULL;
596	}
597
598	return f;
599}
600
601
602FILE *
603auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
604{
605	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
606}
607
608FILE *
609auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
610{
611	return auth_openfile(file, pw, strict_modes, 0,
612	    "authorized principals");
613}
614
615struct passwd *
616getpwnamallow(const char *user)
617{
618	struct ssh *ssh = active_state; /* XXX */
619#ifdef HAVE_LOGIN_CAP
620	extern login_cap_t *lc;
621#ifdef BSD_AUTH
622	auth_session_t *as;
623#endif
624#endif
625	struct passwd *pw;
626	struct connection_info *ci = get_connection_info(1, options.use_dns);
627
628	ci->user = user;
629	parse_server_match_config(&options, ci);
630
631#if defined(_AIX) && defined(HAVE_SETAUTHDB)
632	aix_setauthdb(user);
633#endif
634
635	pw = getpwnam(user);
636
637#if defined(_AIX) && defined(HAVE_SETAUTHDB)
638	aix_restoreauthdb();
639#endif
640#ifdef HAVE_CYGWIN
641	/*
642	 * Windows usernames are case-insensitive.  To avoid later problems
643	 * when trying to match the username, the user is only allowed to
644	 * login if the username is given in the same case as stored in the
645	 * user database.
646	 */
647	if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
648		logit("Login name %.100s does not match stored username %.100s",
649		    user, pw->pw_name);
650		pw = NULL;
651	}
652#endif
653	if (pw == NULL) {
654		logit("Invalid user %.100s from %.100s port %d",
655		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
656#ifdef CUSTOM_FAILED_LOGIN
657		record_failed_login(user,
658		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
659#endif
660#ifdef SSH_AUDIT_EVENTS
661		audit_event(SSH_INVALID_USER);
662#endif /* SSH_AUDIT_EVENTS */
663		return (NULL);
664	}
665	if (!allowed_user(pw))
666		return (NULL);
667#ifdef HAVE_LOGIN_CAP
668	if ((lc = login_getpwclass(pw)) == NULL) {
669		debug("unable to get login class: %s", user);
670		return (NULL);
671	}
672#ifdef BSD_AUTH
673	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
674	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
675		debug("Approval failure for %s", user);
676		pw = NULL;
677	}
678	if (as != NULL)
679		auth_close(as);
680#endif
681#endif
682	if (pw != NULL)
683		return (pwcopy(pw));
684	return (NULL);
685}
686
687/* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
688int
689auth_key_is_revoked(Key *key)
690{
691	char *fp = NULL;
692	int r;
693
694	if (options.revoked_keys_file == NULL)
695		return 0;
696	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
697	    SSH_FP_DEFAULT)) == NULL) {
698		r = SSH_ERR_ALLOC_FAIL;
699		error("%s: fingerprint key: %s", __func__, ssh_err(r));
700		goto out;
701	}
702
703	r = sshkey_check_revoked(key, options.revoked_keys_file);
704	switch (r) {
705	case 0:
706		break; /* not revoked */
707	case SSH_ERR_KEY_REVOKED:
708		error("Authentication key %s %s revoked by file %s",
709		    sshkey_type(key), fp, options.revoked_keys_file);
710		goto out;
711	default:
712		error("Error checking authentication key %s %s in "
713		    "revoked keys file %s: %s", sshkey_type(key), fp,
714		    options.revoked_keys_file, ssh_err(r));
715		goto out;
716	}
717
718	/* Success */
719	r = 0;
720
721 out:
722	free(fp);
723	return r == 0 ? 0 : 1;
724}
725
726void
727auth_debug_add(const char *fmt,...)
728{
729	char buf[1024];
730	va_list args;
731
732	if (!auth_debug_init)
733		return;
734
735	va_start(args, fmt);
736	vsnprintf(buf, sizeof(buf), fmt, args);
737	va_end(args);
738	buffer_put_cstring(&auth_debug, buf);
739}
740
741void
742auth_debug_send(void)
743{
744	char *msg;
745
746	if (!auth_debug_init)
747		return;
748	while (buffer_len(&auth_debug)) {
749		msg = buffer_get_string(&auth_debug, NULL);
750		packet_send_debug("%s", msg);
751		free(msg);
752	}
753}
754
755void
756auth_debug_reset(void)
757{
758	if (auth_debug_init)
759		buffer_clear(&auth_debug);
760	else {
761		buffer_init(&auth_debug);
762		auth_debug_init = 1;
763	}
764}
765
766struct passwd *
767fakepw(void)
768{
769	static struct passwd fake;
770
771	memset(&fake, 0, sizeof(fake));
772	fake.pw_name = "NOUSER";
773	fake.pw_passwd =
774	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
775#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
776	fake.pw_gecos = "NOUSER";
777#endif
778	fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
779	fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
780#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
781	fake.pw_class = "";
782#endif
783	fake.pw_dir = "/nonexist";
784	fake.pw_shell = "/nonexist";
785
786	return (&fake);
787}
788
789/*
790 * Returns the remote DNS hostname as a string. The returned string must not
791 * be freed. NB. this will usually trigger a DNS query the first time it is
792 * called.
793 * This function does additional checks on the hostname to mitigate some
794 * attacks on legacy rhosts-style authentication.
795 * XXX is RhostsRSAAuthentication vulnerable to these?
796 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
797 */
798
799static char *
800remote_hostname(struct ssh *ssh)
801{
802	struct sockaddr_storage from;
803	socklen_t fromlen;
804	struct addrinfo hints, *ai, *aitop;
805	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
806	const char *ntop = ssh_remote_ipaddr(ssh);
807
808	/* Get IP address of client. */
809	fromlen = sizeof(from);
810	memset(&from, 0, sizeof(from));
811	if (getpeername(ssh_packet_get_connection_in(ssh),
812	    (struct sockaddr *)&from, &fromlen) < 0) {
813		debug("getpeername failed: %.100s", strerror(errno));
814		return strdup(ntop);
815	}
816
817	ipv64_normalise_mapped(&from, &fromlen);
818	if (from.ss_family == AF_INET6)
819		fromlen = sizeof(struct sockaddr_in6);
820
821	debug3("Trying to reverse map address %.100s.", ntop);
822	/* Map the IP address to a host name. */
823	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
824	    NULL, 0, NI_NAMEREQD) != 0) {
825		/* Host name not found.  Use ip address. */
826		return strdup(ntop);
827	}
828
829	/*
830	 * if reverse lookup result looks like a numeric hostname,
831	 * someone is trying to trick us by PTR record like following:
832	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
833	 */
834	memset(&hints, 0, sizeof(hints));
835	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
836	hints.ai_flags = AI_NUMERICHOST;
837	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
838		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
839		    name, ntop);
840		freeaddrinfo(ai);
841		return strdup(ntop);
842	}
843
844	/* Names are stored in lowercase. */
845	lowercase(name);
846
847	/*
848	 * Map it back to an IP address and check that the given
849	 * address actually is an address of this host.  This is
850	 * necessary because anyone with access to a name server can
851	 * define arbitrary names for an IP address. Mapping from
852	 * name to IP address can be trusted better (but can still be
853	 * fooled if the intruder has access to the name server of
854	 * the domain).
855	 */
856	memset(&hints, 0, sizeof(hints));
857	hints.ai_family = from.ss_family;
858	hints.ai_socktype = SOCK_STREAM;
859	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
860		logit("reverse mapping checking getaddrinfo for %.700s "
861		    "[%s] failed.", name, ntop);
862		return strdup(ntop);
863	}
864	/* Look for the address from the list of addresses. */
865	for (ai = aitop; ai; ai = ai->ai_next) {
866		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
867		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
868		    (strcmp(ntop, ntop2) == 0))
869				break;
870	}
871	freeaddrinfo(aitop);
872	/* If we reached the end of the list, the address was not there. */
873	if (ai == NULL) {
874		/* Address not found for the host name. */
875		logit("Address %.100s maps to %.600s, but this does not "
876		    "map back to the address.", ntop, name);
877		return strdup(ntop);
878	}
879	return strdup(name);
880}
881
882/*
883 * Return the canonical name of the host in the other side of the current
884 * connection.  The host name is cached, so it is efficient to call this
885 * several times.
886 */
887
888const char *
889auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
890{
891	static char *dnsname;
892
893	if (!use_dns)
894		return ssh_remote_ipaddr(ssh);
895	else if (dnsname != NULL)
896		return dnsname;
897	else {
898		dnsname = remote_hostname(ssh);
899		return dnsname;
900	}
901}
902