1 /* $OpenBSD: auth.c,v 1.122 2017/06/24 06:34:38 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 <sys/types.h> 27 #include <sys/stat.h> 28 #include <sys/socket.h> 29 30 #include <errno.h> 31 #include <fcntl.h> 32 #include <libgen.h> 33 #include <login_cap.h> 34 #include <paths.h> 35 #include <pwd.h> 36 #include <stdarg.h> 37 #include <stdio.h> 38 #include <string.h> 39 #include <unistd.h> 40 #include <limits.h> 41 #include <netdb.h> 42 43 #include "xmalloc.h" 44 #include "match.h" 45 #include "groupaccess.h" 46 #include "log.h" 47 #include "buffer.h" 48 #include "misc.h" 49 #include "servconf.h" 50 #include "key.h" 51 #include "hostfile.h" 52 #include "auth.h" 53 #include "auth-options.h" 54 #include "canohost.h" 55 #include "uidswap.h" 56 #include "packet.h" 57 #ifdef GSSAPI 58 #include "ssh-gss.h" 59 #endif 60 #include "authfile.h" 61 #include "monitor_wrap.h" 62 #include "authfile.h" 63 #include "ssherr.h" 64 #include "compat.h" 65 66 /* import */ 67 extern ServerOptions options; 68 extern int use_privsep; 69 70 /* Debugging messages */ 71 Buffer auth_debug; 72 int auth_debug_init; 73 74 /* 75 * Check if the user is allowed to log in via ssh. If user is listed 76 * in DenyUsers or one of user's groups is listed in DenyGroups, false 77 * will be returned. If AllowUsers isn't empty and user isn't listed 78 * there, or if AllowGroups isn't empty and one of user's groups isn't 79 * listed there, false will be returned. 80 * If the user's shell is not executable, false will be returned. 81 * Otherwise true is returned. 82 */ 83 int 84 allowed_user(struct passwd * pw) 85 { 86 struct ssh *ssh = active_state; /* XXX */ 87 struct stat st; 88 const char *hostname = NULL, *ipaddr = NULL; 89 int r; 90 u_int i; 91 92 /* Shouldn't be called if pw is NULL, but better safe than sorry... */ 93 if (!pw || !pw->pw_name) 94 return 0; 95 96 /* 97 * Deny if shell does not exist or is not executable unless we 98 * are chrooting. 99 */ 100 if (options.chroot_directory == NULL || 101 strcasecmp(options.chroot_directory, "none") == 0) { 102 char *shell = xstrdup((pw->pw_shell[0] == '\0') ? 103 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */ 104 105 if (stat(shell, &st) != 0) { 106 logit("User %.100s not allowed because shell %.100s " 107 "does not exist", pw->pw_name, shell); 108 free(shell); 109 return 0; 110 } 111 if (S_ISREG(st.st_mode) == 0 || 112 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) { 113 logit("User %.100s not allowed because shell %.100s " 114 "is not executable", pw->pw_name, shell); 115 free(shell); 116 return 0; 117 } 118 free(shell); 119 } 120 121 if (options.num_deny_users > 0 || options.num_allow_users > 0 || 122 options.num_deny_groups > 0 || options.num_allow_groups > 0) { 123 hostname = auth_get_canonical_hostname(ssh, options.use_dns); 124 ipaddr = ssh_remote_ipaddr(ssh); 125 } 126 127 /* Return false if user is listed in DenyUsers */ 128 if (options.num_deny_users > 0) { 129 for (i = 0; i < options.num_deny_users; i++) { 130 r = match_user(pw->pw_name, hostname, ipaddr, 131 options.deny_users[i]); 132 if (r < 0) { 133 fatal("Invalid DenyUsers pattern \"%.100s\"", 134 options.deny_users[i]); 135 } else if (r != 0) { 136 logit("User %.100s from %.100s not allowed " 137 "because listed in DenyUsers", 138 pw->pw_name, hostname); 139 return 0; 140 } 141 } 142 } 143 /* Return false if AllowUsers isn't empty and user isn't listed there */ 144 if (options.num_allow_users > 0) { 145 for (i = 0; i < options.num_allow_users; i++) { 146 r = match_user(pw->pw_name, hostname, ipaddr, 147 options.allow_users[i]); 148 if (r < 0) { 149 fatal("Invalid AllowUsers pattern \"%.100s\"", 150 options.allow_users[i]); 151 } else if (r == 1) 152 break; 153 } 154 /* i < options.num_allow_users iff we break for loop */ 155 if (i >= options.num_allow_users) { 156 logit("User %.100s from %.100s not allowed because " 157 "not listed in AllowUsers", pw->pw_name, hostname); 158 return 0; 159 } 160 } 161 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) { 162 /* Get the user's group access list (primary and supplementary) */ 163 if (ga_init(pw->pw_name, pw->pw_gid) == 0) { 164 logit("User %.100s from %.100s not allowed because " 165 "not in any group", pw->pw_name, hostname); 166 return 0; 167 } 168 169 /* Return false if one of user's groups is listed in DenyGroups */ 170 if (options.num_deny_groups > 0) 171 if (ga_match(options.deny_groups, 172 options.num_deny_groups)) { 173 ga_free(); 174 logit("User %.100s from %.100s not allowed " 175 "because a group is listed in DenyGroups", 176 pw->pw_name, hostname); 177 return 0; 178 } 179 /* 180 * Return false if AllowGroups isn't empty and one of user's groups 181 * isn't listed there 182 */ 183 if (options.num_allow_groups > 0) 184 if (!ga_match(options.allow_groups, 185 options.num_allow_groups)) { 186 ga_free(); 187 logit("User %.100s from %.100s not allowed " 188 "because none of user's groups are listed " 189 "in AllowGroups", pw->pw_name, hostname); 190 return 0; 191 } 192 ga_free(); 193 } 194 /* We found no reason not to let this user try to log on... */ 195 return 1; 196 } 197 198 /* 199 * Formats any key left in authctxt->auth_method_key for inclusion in 200 * auth_log()'s message. Also includes authxtct->auth_method_info if present. 201 */ 202 static char * 203 format_method_key(Authctxt *authctxt) 204 { 205 const struct sshkey *key = authctxt->auth_method_key; 206 const char *methinfo = authctxt->auth_method_info; 207 char *fp, *ret = NULL; 208 209 if (key == NULL) 210 return NULL; 211 212 if (key_is_cert(key)) { 213 fp = sshkey_fingerprint(key->cert->signature_key, 214 options.fingerprint_hash, SSH_FP_DEFAULT); 215 xasprintf(&ret, "%s ID %s (serial %llu) CA %s %s%s%s", 216 sshkey_type(key), key->cert->key_id, 217 (unsigned long long)key->cert->serial, 218 sshkey_type(key->cert->signature_key), 219 fp == NULL ? "(null)" : fp, 220 methinfo == NULL ? "" : ", ", 221 methinfo == NULL ? "" : methinfo); 222 free(fp); 223 } else { 224 fp = sshkey_fingerprint(key, options.fingerprint_hash, 225 SSH_FP_DEFAULT); 226 xasprintf(&ret, "%s %s%s%s", sshkey_type(key), 227 fp == NULL ? "(null)" : fp, 228 methinfo == NULL ? "" : ", ", 229 methinfo == NULL ? "" : methinfo); 230 free(fp); 231 } 232 return ret; 233 } 234 235 void 236 auth_log(Authctxt *authctxt, int authenticated, int partial, 237 const char *method, const char *submethod) 238 { 239 struct ssh *ssh = active_state; /* XXX */ 240 void (*authlog) (const char *fmt,...) = verbose; 241 const char *authmsg; 242 char *extra = NULL; 243 244 if (use_privsep && !mm_is_monitor() && !authctxt->postponed) 245 return; 246 247 /* Raise logging level */ 248 if (authenticated == 1 || 249 !authctxt->valid || 250 authctxt->failures >= options.max_authtries / 2 || 251 strcmp(method, "password") == 0) 252 authlog = logit; 253 254 if (authctxt->postponed) 255 authmsg = "Postponed"; 256 else if (partial) 257 authmsg = "Partial"; 258 else 259 authmsg = authenticated ? "Accepted" : "Failed"; 260 261 if ((extra = format_method_key(authctxt)) == NULL) { 262 if (authctxt->auth_method_info != NULL) 263 extra = xstrdup(authctxt->auth_method_info); 264 } 265 266 authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s", 267 authmsg, 268 method, 269 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod, 270 authctxt->valid ? "" : "invalid user ", 271 authctxt->user, 272 ssh_remote_ipaddr(ssh), 273 ssh_remote_port(ssh), 274 extra != NULL ? ": " : "", 275 extra != NULL ? extra : ""); 276 277 free(extra); 278 } 279 280 void 281 auth_maxtries_exceeded(Authctxt *authctxt) 282 { 283 struct ssh *ssh = active_state; /* XXX */ 284 285 error("maximum authentication attempts exceeded for " 286 "%s%.100s from %.200s port %d ssh2", 287 authctxt->valid ? "" : "invalid user ", 288 authctxt->user, 289 ssh_remote_ipaddr(ssh), 290 ssh_remote_port(ssh)); 291 packet_disconnect("Too many authentication failures"); 292 /* NOTREACHED */ 293 } 294 295 /* 296 * Check whether root logins are disallowed. 297 */ 298 int 299 auth_root_allowed(const char *method) 300 { 301 struct ssh *ssh = active_state; /* XXX */ 302 303 switch (options.permit_root_login) { 304 case PERMIT_YES: 305 return 1; 306 case PERMIT_NO_PASSWD: 307 if (strcmp(method, "publickey") == 0 || 308 strcmp(method, "hostbased") == 0 || 309 strcmp(method, "gssapi-with-mic") == 0) 310 return 1; 311 break; 312 case PERMIT_FORCED_ONLY: 313 if (forced_command) { 314 logit("Root login accepted for forced command."); 315 return 1; 316 } 317 break; 318 } 319 logit("ROOT LOGIN REFUSED FROM %.200s port %d", 320 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 321 return 0; 322 } 323 324 325 /* 326 * Given a template and a passwd structure, build a filename 327 * by substituting % tokenised options. Currently, %% becomes '%', 328 * %h becomes the home directory and %u the username. 329 * 330 * This returns a buffer allocated by xmalloc. 331 */ 332 char * 333 expand_authorized_keys(const char *filename, struct passwd *pw) 334 { 335 char *file, ret[PATH_MAX]; 336 int i; 337 338 file = percent_expand(filename, "h", pw->pw_dir, 339 "u", pw->pw_name, (char *)NULL); 340 341 /* 342 * Ensure that filename starts anchored. If not, be backward 343 * compatible and prepend the '%h/' 344 */ 345 if (*file == '/') 346 return (file); 347 348 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file); 349 if (i < 0 || (size_t)i >= sizeof(ret)) 350 fatal("expand_authorized_keys: path too long"); 351 free(file); 352 return (xstrdup(ret)); 353 } 354 355 char * 356 authorized_principals_file(struct passwd *pw) 357 { 358 if (options.authorized_principals_file == NULL) 359 return NULL; 360 return expand_authorized_keys(options.authorized_principals_file, pw); 361 } 362 363 /* return ok if key exists in sysfile or userfile */ 364 HostStatus 365 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host, 366 const char *sysfile, const char *userfile) 367 { 368 char *user_hostfile; 369 struct stat st; 370 HostStatus host_status; 371 struct hostkeys *hostkeys; 372 const struct hostkey_entry *found; 373 374 hostkeys = init_hostkeys(); 375 load_hostkeys(hostkeys, host, sysfile); 376 if (userfile != NULL) { 377 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid); 378 if (options.strict_modes && 379 (stat(user_hostfile, &st) == 0) && 380 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) || 381 (st.st_mode & 022) != 0)) { 382 logit("Authentication refused for %.100s: " 383 "bad owner or modes for %.200s", 384 pw->pw_name, user_hostfile); 385 auth_debug_add("Ignored %.200s: bad ownership or modes", 386 user_hostfile); 387 } else { 388 temporarily_use_uid(pw); 389 load_hostkeys(hostkeys, host, user_hostfile); 390 restore_uid(); 391 } 392 free(user_hostfile); 393 } 394 host_status = check_key_in_hostkeys(hostkeys, key, &found); 395 if (host_status == HOST_REVOKED) 396 error("WARNING: revoked key for %s attempted authentication", 397 found->host); 398 else if (host_status == HOST_OK) 399 debug("%s: key for %s found at %s:%ld", __func__, 400 found->host, found->file, found->line); 401 else 402 debug("%s: key for host %s not found", __func__, host); 403 404 free_hostkeys(hostkeys); 405 406 return host_status; 407 } 408 409 /* 410 * Check a given path for security. This is defined as all components 411 * of the path to the file must be owned by either the owner of 412 * of the file or root and no directories must be group or world writable. 413 * 414 * XXX Should any specific check be done for sym links ? 415 * 416 * Takes a file name, its stat information (preferably from fstat() to 417 * avoid races), the uid of the expected owner, their home directory and an 418 * error buffer plus max size as arguments. 419 * 420 * Returns 0 on success and -1 on failure 421 */ 422 int 423 auth_secure_path(const char *name, struct stat *stp, const char *pw_dir, 424 uid_t uid, char *err, size_t errlen) 425 { 426 char buf[PATH_MAX], homedir[PATH_MAX]; 427 char *cp; 428 int comparehome = 0; 429 struct stat st; 430 431 if (realpath(name, buf) == NULL) { 432 snprintf(err, errlen, "realpath %s failed: %s", name, 433 strerror(errno)); 434 return -1; 435 } 436 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL) 437 comparehome = 1; 438 439 if (!S_ISREG(stp->st_mode)) { 440 snprintf(err, errlen, "%s is not a regular file", buf); 441 return -1; 442 } 443 if ((stp->st_uid != 0 && stp->st_uid != uid) || 444 (stp->st_mode & 022) != 0) { 445 snprintf(err, errlen, "bad ownership or modes for file %s", 446 buf); 447 return -1; 448 } 449 450 /* for each component of the canonical path, walking upwards */ 451 for (;;) { 452 if ((cp = dirname(buf)) == NULL) { 453 snprintf(err, errlen, "dirname() failed"); 454 return -1; 455 } 456 strlcpy(buf, cp, sizeof(buf)); 457 458 if (stat(buf, &st) < 0 || 459 (st.st_uid != 0 && st.st_uid != uid) || 460 (st.st_mode & 022) != 0) { 461 snprintf(err, errlen, 462 "bad ownership or modes for directory %s", buf); 463 return -1; 464 } 465 466 /* If are past the homedir then we can stop */ 467 if (comparehome && strcmp(homedir, buf) == 0) 468 break; 469 470 /* 471 * dirname should always complete with a "/" path, 472 * but we can be paranoid and check for "." too 473 */ 474 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0)) 475 break; 476 } 477 return 0; 478 } 479 480 /* 481 * Version of secure_path() that accepts an open file descriptor to 482 * avoid races. 483 * 484 * Returns 0 on success and -1 on failure 485 */ 486 static int 487 secure_filename(FILE *f, const char *file, struct passwd *pw, 488 char *err, size_t errlen) 489 { 490 struct stat st; 491 492 /* check the open file to avoid races */ 493 if (fstat(fileno(f), &st) < 0) { 494 snprintf(err, errlen, "cannot stat file %s: %s", 495 file, strerror(errno)); 496 return -1; 497 } 498 return auth_secure_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen); 499 } 500 501 static FILE * 502 auth_openfile(const char *file, struct passwd *pw, int strict_modes, 503 int log_missing, char *file_type) 504 { 505 char line[1024]; 506 struct stat st; 507 int fd; 508 FILE *f; 509 510 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) { 511 if (log_missing || errno != ENOENT) 512 debug("Could not open %s '%s': %s", file_type, file, 513 strerror(errno)); 514 return NULL; 515 } 516 517 if (fstat(fd, &st) < 0) { 518 close(fd); 519 return NULL; 520 } 521 if (!S_ISREG(st.st_mode)) { 522 logit("User %s %s %s is not a regular file", 523 pw->pw_name, file_type, file); 524 close(fd); 525 return NULL; 526 } 527 unset_nonblock(fd); 528 if ((f = fdopen(fd, "r")) == NULL) { 529 close(fd); 530 return NULL; 531 } 532 if (strict_modes && 533 secure_filename(f, file, pw, line, sizeof(line)) != 0) { 534 fclose(f); 535 logit("Authentication refused: %s", line); 536 auth_debug_add("Ignored %s: %s", file_type, line); 537 return NULL; 538 } 539 540 return f; 541 } 542 543 544 FILE * 545 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes) 546 { 547 return auth_openfile(file, pw, strict_modes, 1, "authorized keys"); 548 } 549 550 FILE * 551 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes) 552 { 553 return auth_openfile(file, pw, strict_modes, 0, 554 "authorized principals"); 555 } 556 557 struct passwd * 558 getpwnamallow(const char *user) 559 { 560 struct ssh *ssh = active_state; /* XXX */ 561 extern login_cap_t *lc; 562 auth_session_t *as; 563 struct passwd *pw; 564 struct connection_info *ci = get_connection_info(1, options.use_dns); 565 566 ci->user = user; 567 parse_server_match_config(&options, ci); 568 log_change_level(options.log_level); 569 570 pw = getpwnam(user); 571 if (pw == NULL) { 572 logit("Invalid user %.100s from %.100s port %d", 573 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 574 return (NULL); 575 } 576 if (!allowed_user(pw)) 577 return (NULL); 578 if ((lc = login_getclass(pw->pw_class)) == NULL) { 579 debug("unable to get login class: %s", user); 580 return (NULL); 581 } 582 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 || 583 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) { 584 debug("Approval failure for %s", user); 585 pw = NULL; 586 } 587 if (as != NULL) 588 auth_close(as); 589 if (pw != NULL) 590 return (pwcopy(pw)); 591 return (NULL); 592 } 593 594 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */ 595 int 596 auth_key_is_revoked(struct sshkey *key) 597 { 598 char *fp = NULL; 599 int r; 600 601 if (options.revoked_keys_file == NULL) 602 return 0; 603 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, 604 SSH_FP_DEFAULT)) == NULL) { 605 r = SSH_ERR_ALLOC_FAIL; 606 error("%s: fingerprint key: %s", __func__, ssh_err(r)); 607 goto out; 608 } 609 610 r = sshkey_check_revoked(key, options.revoked_keys_file); 611 switch (r) { 612 case 0: 613 break; /* not revoked */ 614 case SSH_ERR_KEY_REVOKED: 615 error("Authentication key %s %s revoked by file %s", 616 sshkey_type(key), fp, options.revoked_keys_file); 617 goto out; 618 default: 619 error("Error checking authentication key %s %s in " 620 "revoked keys file %s: %s", sshkey_type(key), fp, 621 options.revoked_keys_file, ssh_err(r)); 622 goto out; 623 } 624 625 /* Success */ 626 r = 0; 627 628 out: 629 free(fp); 630 return r == 0 ? 0 : 1; 631 } 632 633 void 634 auth_debug_add(const char *fmt,...) 635 { 636 char buf[1024]; 637 va_list args; 638 639 if (!auth_debug_init) 640 return; 641 642 va_start(args, fmt); 643 vsnprintf(buf, sizeof(buf), fmt, args); 644 va_end(args); 645 buffer_put_cstring(&auth_debug, buf); 646 } 647 648 void 649 auth_debug_send(void) 650 { 651 char *msg; 652 653 if (!auth_debug_init) 654 return; 655 while (buffer_len(&auth_debug)) { 656 msg = buffer_get_string(&auth_debug, NULL); 657 packet_send_debug("%s", msg); 658 free(msg); 659 } 660 } 661 662 void 663 auth_debug_reset(void) 664 { 665 if (auth_debug_init) 666 buffer_clear(&auth_debug); 667 else { 668 buffer_init(&auth_debug); 669 auth_debug_init = 1; 670 } 671 } 672 673 struct passwd * 674 fakepw(void) 675 { 676 static struct passwd fake; 677 678 memset(&fake, 0, sizeof(fake)); 679 fake.pw_name = "NOUSER"; 680 fake.pw_passwd = 681 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK"; 682 fake.pw_gecos = "NOUSER"; 683 fake.pw_uid = (uid_t)-1; 684 fake.pw_gid = (gid_t)-1; 685 fake.pw_class = ""; 686 fake.pw_dir = "/nonexist"; 687 fake.pw_shell = "/nonexist"; 688 689 return (&fake); 690 } 691 692 /* 693 * Returns the remote DNS hostname as a string. The returned string must not 694 * be freed. NB. this will usually trigger a DNS query the first time it is 695 * called. 696 * This function does additional checks on the hostname to mitigate some 697 * attacks on legacy rhosts-style authentication. 698 * XXX is RhostsRSAAuthentication vulnerable to these? 699 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?) 700 */ 701 702 static char * 703 remote_hostname(struct ssh *ssh) 704 { 705 struct sockaddr_storage from; 706 socklen_t fromlen; 707 struct addrinfo hints, *ai, *aitop; 708 char name[NI_MAXHOST], ntop2[NI_MAXHOST]; 709 const char *ntop = ssh_remote_ipaddr(ssh); 710 711 /* Get IP address of client. */ 712 fromlen = sizeof(from); 713 memset(&from, 0, sizeof(from)); 714 if (getpeername(ssh_packet_get_connection_in(ssh), 715 (struct sockaddr *)&from, &fromlen) < 0) { 716 debug("getpeername failed: %.100s", strerror(errno)); 717 return strdup(ntop); 718 } 719 720 debug3("Trying to reverse map address %.100s.", ntop); 721 /* Map the IP address to a host name. */ 722 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name), 723 NULL, 0, NI_NAMEREQD) != 0) { 724 /* Host name not found. Use ip address. */ 725 return strdup(ntop); 726 } 727 728 /* 729 * if reverse lookup result looks like a numeric hostname, 730 * someone is trying to trick us by PTR record like following: 731 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5 732 */ 733 memset(&hints, 0, sizeof(hints)); 734 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 735 hints.ai_flags = AI_NUMERICHOST; 736 if (getaddrinfo(name, NULL, &hints, &ai) == 0) { 737 logit("Nasty PTR record \"%s\" is set up for %s, ignoring", 738 name, ntop); 739 freeaddrinfo(ai); 740 return strdup(ntop); 741 } 742 743 /* Names are stored in lowercase. */ 744 lowercase(name); 745 746 /* 747 * Map it back to an IP address and check that the given 748 * address actually is an address of this host. This is 749 * necessary because anyone with access to a name server can 750 * define arbitrary names for an IP address. Mapping from 751 * name to IP address can be trusted better (but can still be 752 * fooled if the intruder has access to the name server of 753 * the domain). 754 */ 755 memset(&hints, 0, sizeof(hints)); 756 hints.ai_family = from.ss_family; 757 hints.ai_socktype = SOCK_STREAM; 758 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) { 759 logit("reverse mapping checking getaddrinfo for %.700s " 760 "[%s] failed.", name, ntop); 761 return strdup(ntop); 762 } 763 /* Look for the address from the list of addresses. */ 764 for (ai = aitop; ai; ai = ai->ai_next) { 765 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2, 766 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 && 767 (strcmp(ntop, ntop2) == 0)) 768 break; 769 } 770 freeaddrinfo(aitop); 771 /* If we reached the end of the list, the address was not there. */ 772 if (ai == NULL) { 773 /* Address not found for the host name. */ 774 logit("Address %.100s maps to %.600s, but this does not " 775 "map back to the address.", ntop, name); 776 return strdup(ntop); 777 } 778 return strdup(name); 779 } 780 781 /* 782 * Return the canonical name of the host in the other side of the current 783 * connection. The host name is cached, so it is efficient to call this 784 * several times. 785 */ 786 787 const char * 788 auth_get_canonical_hostname(struct ssh *ssh, int use_dns) 789 { 790 static char *dnsname; 791 792 if (!use_dns) 793 return ssh_remote_ipaddr(ssh); 794 else if (dnsname != NULL) 795 return dnsname; 796 else { 797 dnsname = remote_hostname(ssh); 798 return dnsname; 799 } 800 } 801