kernel - CAM cleanup 3/N - Remove unnecessary mplocks
[dragonfly.git] / crypto / openssh / auth.c
blob24527dd7c3b9da4123d7246be4ef8b5b11e7ca05
1 /* $OpenBSD: auth.c,v 1.115 2016/06/15 00:40:40 dtucker Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
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.
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.
26 #include "includes.h"
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/socket.h>
32 #include <netinet/in.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #ifdef HAVE_PATHS_H
37 # include <paths.h>
38 #endif
39 #include <pwd.h>
40 #ifdef HAVE_LOGIN_H
41 #include <login.h>
42 #endif
43 #ifdef USE_SHADOW
44 #include <shadow.h>
45 #endif
46 #ifdef HAVE_LIBGEN_H
47 #include <libgen.h>
48 #endif
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <limits.h>
54 #include <netdb.h>
56 #include "xmalloc.h"
57 #include "match.h"
58 #include "groupaccess.h"
59 #include "log.h"
60 #include "buffer.h"
61 #include "misc.h"
62 #include "servconf.h"
63 #include "key.h"
64 #include "hostfile.h"
65 #include "auth.h"
66 #include "auth-options.h"
67 #include "canohost.h"
68 #include "uidswap.h"
69 #include "packet.h"
70 #include "loginrec.h"
71 #ifdef GSSAPI
72 #include "ssh-gss.h"
73 #endif
74 #include "authfile.h"
75 #include "monitor_wrap.h"
76 #include "authfile.h"
77 #include "ssherr.h"
78 #include "compat.h"
80 /* import */
81 extern ServerOptions options;
82 extern int use_privsep;
83 extern Buffer loginmsg;
84 extern struct passwd *privsep_pw;
86 /* Debugging messages */
87 Buffer auth_debug;
88 int auth_debug_init;
91 * Check if the user is allowed to log in via ssh. If user is listed
92 * in DenyUsers or one of user's groups is listed in DenyGroups, false
93 * will be returned. If AllowUsers isn't empty and user isn't listed
94 * there, or if AllowGroups isn't empty and one of user's groups isn't
95 * listed there, false will be returned.
96 * If the user's shell is not executable, false will be returned.
97 * Otherwise true is returned.
99 int
100 allowed_user(struct passwd * pw)
102 struct ssh *ssh = active_state; /* XXX */
103 struct stat st;
104 const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
105 u_int i;
106 #ifdef USE_SHADOW
107 struct spwd *spw = NULL;
108 #endif
110 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
111 if (!pw || !pw->pw_name)
112 return 0;
114 #ifdef USE_SHADOW
115 if (!options.use_pam)
116 spw = getspnam(pw->pw_name);
117 #ifdef HAS_SHADOW_EXPIRE
118 if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
119 return 0;
120 #endif /* HAS_SHADOW_EXPIRE */
121 #endif /* USE_SHADOW */
123 /* grab passwd field for locked account check */
124 passwd = pw->pw_passwd;
125 #ifdef USE_SHADOW
126 if (spw != NULL)
127 #ifdef USE_LIBIAF
128 passwd = get_iaf_password(pw);
129 #else
130 passwd = spw->sp_pwdp;
131 #endif /* USE_LIBIAF */
132 #endif
134 /* check for locked account */
135 if (!options.use_pam && passwd && *passwd) {
136 int locked = 0;
138 #ifdef LOCKED_PASSWD_STRING
139 if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
140 locked = 1;
141 #endif
142 #ifdef LOCKED_PASSWD_PREFIX
143 if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
144 strlen(LOCKED_PASSWD_PREFIX)) == 0)
145 locked = 1;
146 #endif
147 #ifdef LOCKED_PASSWD_SUBSTR
148 if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
149 locked = 1;
150 #endif
151 #ifdef USE_LIBIAF
152 free((void *) passwd);
153 #endif /* USE_LIBIAF */
154 if (locked) {
155 logit("User %.100s not allowed because account is locked",
156 pw->pw_name);
157 return 0;
162 * Deny if shell does not exist or is not executable unless we
163 * are chrooting.
165 if (options.chroot_directory == NULL ||
166 strcasecmp(options.chroot_directory, "none") == 0) {
167 char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
168 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
170 if (stat(shell, &st) != 0) {
171 logit("User %.100s not allowed because shell %.100s "
172 "does not exist", pw->pw_name, shell);
173 free(shell);
174 return 0;
176 if (S_ISREG(st.st_mode) == 0 ||
177 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
178 logit("User %.100s not allowed because shell %.100s "
179 "is not executable", pw->pw_name, shell);
180 free(shell);
181 return 0;
183 free(shell);
186 if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
187 options.num_deny_groups > 0 || options.num_allow_groups > 0) {
188 hostname = auth_get_canonical_hostname(ssh, options.use_dns);
189 ipaddr = ssh_remote_ipaddr(ssh);
192 /* Return false if user is listed in DenyUsers */
193 if (options.num_deny_users > 0) {
194 for (i = 0; i < options.num_deny_users; i++)
195 if (match_user(pw->pw_name, hostname, ipaddr,
196 options.deny_users[i])) {
197 logit("User %.100s from %.100s not allowed "
198 "because listed in DenyUsers",
199 pw->pw_name, hostname);
200 return 0;
203 /* Return false if AllowUsers isn't empty and user isn't listed there */
204 if (options.num_allow_users > 0) {
205 for (i = 0; i < options.num_allow_users; i++)
206 if (match_user(pw->pw_name, hostname, ipaddr,
207 options.allow_users[i]))
208 break;
209 /* i < options.num_allow_users iff we break for loop */
210 if (i >= options.num_allow_users) {
211 logit("User %.100s from %.100s not allowed because "
212 "not listed in AllowUsers", pw->pw_name, hostname);
213 return 0;
216 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
217 /* Get the user's group access list (primary and supplementary) */
218 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
219 logit("User %.100s from %.100s not allowed because "
220 "not in any group", pw->pw_name, hostname);
221 return 0;
224 /* Return false if one of user's groups is listed in DenyGroups */
225 if (options.num_deny_groups > 0)
226 if (ga_match(options.deny_groups,
227 options.num_deny_groups)) {
228 ga_free();
229 logit("User %.100s from %.100s not allowed "
230 "because a group is listed in DenyGroups",
231 pw->pw_name, hostname);
232 return 0;
235 * Return false if AllowGroups isn't empty and one of user's groups
236 * isn't listed there
238 if (options.num_allow_groups > 0)
239 if (!ga_match(options.allow_groups,
240 options.num_allow_groups)) {
241 ga_free();
242 logit("User %.100s from %.100s not allowed "
243 "because none of user's groups are listed "
244 "in AllowGroups", pw->pw_name, hostname);
245 return 0;
247 ga_free();
250 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
251 if (!sys_auth_allowed_user(pw, &loginmsg))
252 return 0;
253 #endif
255 /* We found no reason not to let this user try to log on... */
256 return 1;
259 void
260 auth_info(Authctxt *authctxt, const char *fmt, ...)
262 va_list ap;
263 int i;
265 free(authctxt->info);
266 authctxt->info = NULL;
268 va_start(ap, fmt);
269 i = vasprintf(&authctxt->info, fmt, ap);
270 va_end(ap);
272 if (i < 0 || authctxt->info == NULL)
273 fatal("vasprintf failed");
276 void
277 auth_log(Authctxt *authctxt, int authenticated, int partial,
278 const char *method, const char *submethod)
280 struct ssh *ssh = active_state; /* XXX */
281 void (*authlog) (const char *fmt,...) = verbose;
282 char *authmsg;
284 if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
285 return;
287 /* Raise logging level */
288 if (authenticated == 1 ||
289 !authctxt->valid ||
290 authctxt->failures >= options.max_authtries / 2 ||
291 strcmp(method, "password") == 0)
292 authlog = logit;
294 if (authctxt->postponed)
295 authmsg = "Postponed";
296 else if (partial)
297 authmsg = "Partial";
298 else
299 authmsg = authenticated ? "Accepted" : "Failed";
301 authlog("%s %s%s%s for %s%.100s from %.200s port %d %s%s%s",
302 authmsg,
303 method,
304 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
305 authctxt->valid ? "" : "invalid user ",
306 authctxt->user,
307 ssh_remote_ipaddr(ssh),
308 ssh_remote_port(ssh),
309 compat20 ? "ssh2" : "ssh1",
310 authctxt->info != NULL ? ": " : "",
311 authctxt->info != NULL ? authctxt->info : "");
312 free(authctxt->info);
313 authctxt->info = NULL;
315 #ifdef CUSTOM_FAILED_LOGIN
316 if (authenticated == 0 && !authctxt->postponed &&
317 (strcmp(method, "password") == 0 ||
318 strncmp(method, "keyboard-interactive", 20) == 0 ||
319 strcmp(method, "challenge-response") == 0))
320 record_failed_login(authctxt->user,
321 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
322 # ifdef WITH_AIXAUTHENTICATE
323 if (authenticated)
324 sys_auth_record_login(authctxt->user,
325 auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
326 &loginmsg);
327 # endif
328 #endif
329 #ifdef SSH_AUDIT_EVENTS
330 if (authenticated == 0 && !authctxt->postponed)
331 audit_event(audit_classify_auth(method));
332 #endif
336 void
337 auth_maxtries_exceeded(Authctxt *authctxt)
339 struct ssh *ssh = active_state; /* XXX */
341 error("maximum authentication attempts exceeded for "
342 "%s%.100s from %.200s port %d %s",
343 authctxt->valid ? "" : "invalid user ",
344 authctxt->user,
345 ssh_remote_ipaddr(ssh),
346 ssh_remote_port(ssh),
347 compat20 ? "ssh2" : "ssh1");
348 packet_disconnect("Too many authentication failures");
349 /* NOTREACHED */
353 * Check whether root logins are disallowed.
356 auth_root_allowed(const char *method)
358 struct ssh *ssh = active_state; /* XXX */
360 switch (options.permit_root_login) {
361 case PERMIT_YES:
362 return 1;
363 case PERMIT_NO_PASSWD:
364 if (strcmp(method, "publickey") == 0 ||
365 strcmp(method, "hostbased") == 0 ||
366 strcmp(method, "gssapi-with-mic") == 0)
367 return 1;
368 break;
369 case PERMIT_FORCED_ONLY:
370 if (forced_command) {
371 logit("Root login accepted for forced command.");
372 return 1;
374 break;
376 logit("ROOT LOGIN REFUSED FROM %.200s port %d",
377 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
378 return 0;
383 * Given a template and a passwd structure, build a filename
384 * by substituting % tokenised options. Currently, %% becomes '%',
385 * %h becomes the home directory and %u the username.
387 * This returns a buffer allocated by xmalloc.
389 char *
390 expand_authorized_keys(const char *filename, struct passwd *pw)
392 char *file, ret[PATH_MAX];
393 int i;
395 file = percent_expand(filename, "h", pw->pw_dir,
396 "u", pw->pw_name, (char *)NULL);
399 * Ensure that filename starts anchored. If not, be backward
400 * compatible and prepend the '%h/'
402 if (*file == '/')
403 return (file);
405 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
406 if (i < 0 || (size_t)i >= sizeof(ret))
407 fatal("expand_authorized_keys: path too long");
408 free(file);
409 return (xstrdup(ret));
412 char *
413 authorized_principals_file(struct passwd *pw)
415 if (options.authorized_principals_file == NULL)
416 return NULL;
417 return expand_authorized_keys(options.authorized_principals_file, pw);
420 /* return ok if key exists in sysfile or userfile */
421 HostStatus
422 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
423 const char *sysfile, const char *userfile)
425 char *user_hostfile;
426 struct stat st;
427 HostStatus host_status;
428 struct hostkeys *hostkeys;
429 const struct hostkey_entry *found;
431 hostkeys = init_hostkeys();
432 load_hostkeys(hostkeys, host, sysfile);
433 if (userfile != NULL) {
434 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
435 if (options.strict_modes &&
436 (stat(user_hostfile, &st) == 0) &&
437 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
438 (st.st_mode & 022) != 0)) {
439 logit("Authentication refused for %.100s: "
440 "bad owner or modes for %.200s",
441 pw->pw_name, user_hostfile);
442 auth_debug_add("Ignored %.200s: bad ownership or modes",
443 user_hostfile);
444 } else {
445 temporarily_use_uid(pw);
446 load_hostkeys(hostkeys, host, user_hostfile);
447 restore_uid();
449 free(user_hostfile);
451 host_status = check_key_in_hostkeys(hostkeys, key, &found);
452 if (host_status == HOST_REVOKED)
453 error("WARNING: revoked key for %s attempted authentication",
454 found->host);
455 else if (host_status == HOST_OK)
456 debug("%s: key for %s found at %s:%ld", __func__,
457 found->host, found->file, found->line);
458 else
459 debug("%s: key for host %s not found", __func__, host);
461 free_hostkeys(hostkeys);
463 return host_status;
467 * Check a given path for security. This is defined as all components
468 * of the path to the file must be owned by either the owner of
469 * of the file or root and no directories must be group or world writable.
471 * XXX Should any specific check be done for sym links ?
473 * Takes a file name, its stat information (preferably from fstat() to
474 * avoid races), the uid of the expected owner, their home directory and an
475 * error buffer plus max size as arguments.
477 * Returns 0 on success and -1 on failure
480 auth_secure_path(const char *name, struct stat *stp, const char *pw_dir,
481 uid_t uid, char *err, size_t errlen)
483 char buf[PATH_MAX], homedir[PATH_MAX];
484 char *cp;
485 int comparehome = 0;
486 struct stat st;
488 if (realpath(name, buf) == NULL) {
489 snprintf(err, errlen, "realpath %s failed: %s", name,
490 strerror(errno));
491 return -1;
493 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
494 comparehome = 1;
496 if (!S_ISREG(stp->st_mode)) {
497 snprintf(err, errlen, "%s is not a regular file", buf);
498 return -1;
500 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
501 (stp->st_mode & 022) != 0) {
502 snprintf(err, errlen, "bad ownership or modes for file %s",
503 buf);
504 return -1;
507 /* for each component of the canonical path, walking upwards */
508 for (;;) {
509 if ((cp = dirname(buf)) == NULL) {
510 snprintf(err, errlen, "dirname() failed");
511 return -1;
513 strlcpy(buf, cp, sizeof(buf));
515 if (stat(buf, &st) < 0 ||
516 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
517 (st.st_mode & 022) != 0) {
518 snprintf(err, errlen,
519 "bad ownership or modes for directory %s", buf);
520 return -1;
523 /* If are past the homedir then we can stop */
524 if (comparehome && strcmp(homedir, buf) == 0)
525 break;
528 * dirname should always complete with a "/" path,
529 * but we can be paranoid and check for "." too
531 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
532 break;
534 return 0;
538 * Version of secure_path() that accepts an open file descriptor to
539 * avoid races.
541 * Returns 0 on success and -1 on failure
543 static int
544 secure_filename(FILE *f, const char *file, struct passwd *pw,
545 char *err, size_t errlen)
547 struct stat st;
549 /* check the open file to avoid races */
550 if (fstat(fileno(f), &st) < 0) {
551 snprintf(err, errlen, "cannot stat file %s: %s",
552 file, strerror(errno));
553 return -1;
555 return auth_secure_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
558 static FILE *
559 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
560 int log_missing, char *file_type)
562 char line[1024];
563 struct stat st;
564 int fd;
565 FILE *f;
567 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
568 if (log_missing || errno != ENOENT)
569 debug("Could not open %s '%s': %s", file_type, file,
570 strerror(errno));
571 return NULL;
574 if (fstat(fd, &st) < 0) {
575 close(fd);
576 return NULL;
578 if (!S_ISREG(st.st_mode)) {
579 logit("User %s %s %s is not a regular file",
580 pw->pw_name, file_type, file);
581 close(fd);
582 return NULL;
584 unset_nonblock(fd);
585 if ((f = fdopen(fd, "r")) == NULL) {
586 close(fd);
587 return NULL;
589 if (strict_modes &&
590 secure_filename(f, file, pw, line, sizeof(line)) != 0) {
591 fclose(f);
592 logit("Authentication refused: %s", line);
593 auth_debug_add("Ignored %s: %s", file_type, line);
594 return NULL;
597 return f;
601 FILE *
602 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
604 return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
607 FILE *
608 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
610 return auth_openfile(file, pw, strict_modes, 0,
611 "authorized principals");
614 struct passwd *
615 getpwnamallow(const char *user)
617 struct ssh *ssh = active_state; /* XXX */
618 #ifdef HAVE_LOGIN_CAP
619 extern login_cap_t *lc;
620 #ifdef BSD_AUTH
621 auth_session_t *as;
622 #endif
623 #endif
624 struct passwd *pw;
625 struct connection_info *ci = get_connection_info(1, options.use_dns);
627 ci->user = user;
628 parse_server_match_config(&options, ci);
630 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
631 aix_setauthdb(user);
632 #endif
634 pw = getpwnam(user);
636 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
637 aix_restoreauthdb();
638 #endif
639 #ifdef HAVE_CYGWIN
641 * Windows usernames are case-insensitive. To avoid later problems
642 * when trying to match the username, the user is only allowed to
643 * login if the username is given in the same case as stored in the
644 * user database.
646 if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
647 logit("Login name %.100s does not match stored username %.100s",
648 user, pw->pw_name);
649 pw = NULL;
651 #endif
652 if (pw == NULL) {
653 logit("Invalid user %.100s from %.100s port %d",
654 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
655 #ifdef CUSTOM_FAILED_LOGIN
656 record_failed_login(user,
657 auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
658 #endif
659 #ifdef SSH_AUDIT_EVENTS
660 audit_event(SSH_INVALID_USER);
661 #endif /* SSH_AUDIT_EVENTS */
662 return (NULL);
664 if (!allowed_user(pw))
665 return (NULL);
666 #ifdef HAVE_LOGIN_CAP
667 if ((lc = login_getclass(pw->pw_class)) == NULL) {
668 debug("unable to get login class: %s", user);
669 return (NULL);
671 #ifdef BSD_AUTH
672 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
673 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
674 debug("Approval failure for %s", user);
675 pw = NULL;
677 if (as != NULL)
678 auth_close(as);
679 #endif
680 #endif
681 if (pw != NULL)
682 return (pwcopy(pw));
683 return (NULL);
686 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
688 auth_key_is_revoked(Key *key)
690 char *fp = NULL;
691 int r;
693 if (options.revoked_keys_file == NULL)
694 return 0;
695 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
696 SSH_FP_DEFAULT)) == NULL) {
697 r = SSH_ERR_ALLOC_FAIL;
698 error("%s: fingerprint key: %s", __func__, ssh_err(r));
699 goto out;
702 r = sshkey_check_revoked(key, options.revoked_keys_file);
703 switch (r) {
704 case 0:
705 break; /* not revoked */
706 case SSH_ERR_KEY_REVOKED:
707 error("Authentication key %s %s revoked by file %s",
708 sshkey_type(key), fp, options.revoked_keys_file);
709 goto out;
710 default:
711 error("Error checking authentication key %s %s in "
712 "revoked keys file %s: %s", sshkey_type(key), fp,
713 options.revoked_keys_file, ssh_err(r));
714 goto out;
717 /* Success */
718 r = 0;
720 out:
721 free(fp);
722 return r == 0 ? 0 : 1;
725 void
726 auth_debug_add(const char *fmt,...)
728 char buf[1024];
729 va_list args;
731 if (!auth_debug_init)
732 return;
734 va_start(args, fmt);
735 vsnprintf(buf, sizeof(buf), fmt, args);
736 va_end(args);
737 buffer_put_cstring(&auth_debug, buf);
740 void
741 auth_debug_send(void)
743 char *msg;
745 if (!auth_debug_init)
746 return;
747 while (buffer_len(&auth_debug)) {
748 msg = buffer_get_string(&auth_debug, NULL);
749 packet_send_debug("%s", msg);
750 free(msg);
754 void
755 auth_debug_reset(void)
757 if (auth_debug_init)
758 buffer_clear(&auth_debug);
759 else {
760 buffer_init(&auth_debug);
761 auth_debug_init = 1;
765 struct passwd *
766 fakepw(void)
768 static struct passwd fake;
770 memset(&fake, 0, sizeof(fake));
771 fake.pw_name = "NOUSER";
772 fake.pw_passwd =
773 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
774 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
775 fake.pw_gecos = "NOUSER";
776 #endif
777 fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
778 fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
779 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
780 fake.pw_class = "";
781 #endif
782 fake.pw_dir = "/nonexist";
783 fake.pw_shell = "/nonexist";
785 return (&fake);
789 * Returns the remote DNS hostname as a string. The returned string must not
790 * be freed. NB. this will usually trigger a DNS query the first time it is
791 * called.
792 * This function does additional checks on the hostname to mitigate some
793 * attacks on legacy rhosts-style authentication.
794 * XXX is RhostsRSAAuthentication vulnerable to these?
795 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
798 static char *
799 remote_hostname(struct ssh *ssh)
801 struct sockaddr_storage from;
802 socklen_t fromlen;
803 struct addrinfo hints, *ai, *aitop;
804 char name[NI_MAXHOST], ntop2[NI_MAXHOST];
805 const char *ntop = ssh_remote_ipaddr(ssh);
807 /* Get IP address of client. */
808 fromlen = sizeof(from);
809 memset(&from, 0, sizeof(from));
810 if (getpeername(ssh_packet_get_connection_in(ssh),
811 (struct sockaddr *)&from, &fromlen) < 0) {
812 debug("getpeername failed: %.100s", strerror(errno));
813 return strdup(ntop);
816 ipv64_normalise_mapped(&from, &fromlen);
817 if (from.ss_family == AF_INET6)
818 fromlen = sizeof(struct sockaddr_in6);
820 debug3("Trying to reverse map address %.100s.", ntop);
821 /* Map the IP address to a host name. */
822 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
823 NULL, 0, NI_NAMEREQD) != 0) {
824 /* Host name not found. Use ip address. */
825 return strdup(ntop);
829 * if reverse lookup result looks like a numeric hostname,
830 * someone is trying to trick us by PTR record like following:
831 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
833 memset(&hints, 0, sizeof(hints));
834 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
835 hints.ai_flags = AI_NUMERICHOST;
836 if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
837 logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
838 name, ntop);
839 freeaddrinfo(ai);
840 return strdup(ntop);
843 /* Names are stored in lowercase. */
844 lowercase(name);
847 * Map it back to an IP address and check that the given
848 * address actually is an address of this host. This is
849 * necessary because anyone with access to a name server can
850 * define arbitrary names for an IP address. Mapping from
851 * name to IP address can be trusted better (but can still be
852 * fooled if the intruder has access to the name server of
853 * the domain).
855 memset(&hints, 0, sizeof(hints));
856 hints.ai_family = from.ss_family;
857 hints.ai_socktype = SOCK_STREAM;
858 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
859 logit("reverse mapping checking getaddrinfo for %.700s "
860 "[%s] failed.", name, ntop);
861 return strdup(ntop);
863 /* Look for the address from the list of addresses. */
864 for (ai = aitop; ai; ai = ai->ai_next) {
865 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
866 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
867 (strcmp(ntop, ntop2) == 0))
868 break;
870 freeaddrinfo(aitop);
871 /* If we reached the end of the list, the address was not there. */
872 if (ai == NULL) {
873 /* Address not found for the host name. */
874 logit("Address %.100s maps to %.600s, but this does not "
875 "map back to the address.", ntop, name);
876 return strdup(ntop);
878 return strdup(name);
882 * Return the canonical name of the host in the other side of the current
883 * connection. The host name is cached, so it is efficient to call this
884 * several times.
887 const char *
888 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
890 static char *dnsname;
892 if (!use_dns)
893 return ssh_remote_ipaddr(ssh);
894 else if (dnsname != NULL)
895 return dnsname;
896 else {
897 dnsname = remote_hostname(ssh);
898 return dnsname;