1 /* $NetBSD: auth.c,v 1.33 2022/10/05 22:39:36 christos Exp $ */ 2 /* $OpenBSD: auth.c,v 1.158 2022/06/03 04:47:21 djm Exp $ */ 3 4 /* 5 * Copyright (c) 2000 Markus Friedl. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 */ 27 28 #include "includes.h" 29 __RCSID("$NetBSD: auth.c,v 1.33 2022/10/05 22:39:36 christos Exp $"); 30 #include <sys/types.h> 31 #include <sys/stat.h> 32 #include <sys/socket.h> 33 #include <sys/wait.h> 34 35 #include <stdlib.h> 36 #include <errno.h> 37 #include <fcntl.h> 38 #include <login_cap.h> 39 #include <paths.h> 40 #include <pwd.h> 41 #include <stdarg.h> 42 #include <stdio.h> 43 #include <string.h> 44 #include <unistd.h> 45 #include <limits.h> 46 #include <netdb.h> 47 #include <time.h> 48 49 #include "xmalloc.h" 50 #include "match.h" 51 #include "groupaccess.h" 52 #include "log.h" 53 #include "sshbuf.h" 54 #include "misc.h" 55 #include "servconf.h" 56 #include "sshkey.h" 57 #include "hostfile.h" 58 #include "auth.h" 59 #include "auth-options.h" 60 #include "canohost.h" 61 #include "uidswap.h" 62 #include "packet.h" 63 #ifdef GSSAPI 64 #include "ssh-gss.h" 65 #endif 66 #include "authfile.h" 67 #include "monitor_wrap.h" 68 #include "ssherr.h" 69 #include "compat.h" 70 #include "channels.h" 71 #include "pfilter.h" 72 73 #ifdef HAVE_LOGIN_CAP 74 #include <login_cap.h> 75 #endif 76 77 /* import */ 78 extern ServerOptions options; 79 extern struct include_list includes; 80 extern int use_privsep; 81 extern struct sshauthopt *auth_opts; 82 83 /* Debugging messages */ 84 static struct sshbuf *auth_debug; 85 86 #ifndef HOST_ONLY 87 /* 88 * Check if the user is allowed to log in via ssh. If user is listed 89 * in DenyUsers or one of user's groups is listed in DenyGroups, false 90 * will be returned. If AllowUsers isn't empty and user isn't listed 91 * there, or if AllowGroups isn't empty and one of user's groups isn't 92 * listed there, false will be returned. 93 * If the user's shell is not executable, false will be returned. 94 * Otherwise true is returned. 95 */ 96 int 97 allowed_user(struct ssh *ssh, struct passwd * pw) 98 { 99 #ifdef HAVE_LOGIN_CAP 100 extern login_cap_t *lc; 101 int match_name, match_ip; 102 char *cap_hlist, *hp; 103 #endif 104 struct stat st; 105 const char *hostname = NULL, *ipaddr = NULL; 106 int r; 107 u_int i; 108 109 /* Shouldn't be called if pw is NULL, but better safe than sorry... */ 110 if (!pw || !pw->pw_name) 111 return 0; 112 113 #ifdef HAVE_LOGIN_CAP 114 hostname = auth_get_canonical_hostname(ssh, options.use_dns); 115 ipaddr = ssh_remote_ipaddr(ssh); 116 117 lc = login_getclass(pw->pw_class); 118 119 /* 120 * Check the deny list. 121 */ 122 cap_hlist = login_getcapstr(lc, "host.deny", NULL, NULL); 123 if (cap_hlist != NULL) { 124 hp = strtok(cap_hlist, ","); 125 while (hp != NULL) { 126 match_name = match_hostname(hostname, hp); 127 match_ip = match_hostname(ipaddr, hp); 128 /* 129 * Only a positive match here causes a "deny". 130 */ 131 if (match_name > 0 || match_ip > 0) { 132 free(cap_hlist); 133 login_close(lc); 134 return 0; 135 } 136 hp = strtok(NULL, ","); 137 } 138 free(cap_hlist); 139 } 140 141 /* 142 * Check the allow list. If the allow list exists, and the 143 * remote host is not in it, the user is implicitly denied. 144 */ 145 cap_hlist = login_getcapstr(lc, "host.allow", NULL, NULL); 146 if (cap_hlist != NULL) { 147 hp = strtok(cap_hlist, ","); 148 if (hp == NULL) { 149 /* Just in case there's an empty string... */ 150 free(cap_hlist); 151 login_close(lc); 152 return 0; 153 } 154 while (hp != NULL) { 155 match_name = match_hostname(hostname, hp); 156 match_ip = match_hostname(ipaddr, hp); 157 /* 158 * Negative match causes an immediate "deny". 159 * Positive match causes us to break out 160 * of the loop (allowing a fallthrough). 161 */ 162 if (match_name < 0 || match_ip < 0) { 163 free(cap_hlist); 164 login_close(lc); 165 return 0; 166 } 167 if (match_name > 0 || match_ip > 0) 168 break; 169 hp = strtok(NULL, ","); 170 } 171 free(cap_hlist); 172 if (hp == NULL) { 173 login_close(lc); 174 return 0; 175 } 176 } 177 178 login_close(lc); 179 #endif 180 181 #ifdef USE_PAM 182 if (!options.use_pam) { 183 #endif 184 /* 185 * password/account expiration. 186 */ 187 if (pw->pw_change || pw->pw_expire) { 188 struct timeval tv; 189 190 (void)gettimeofday(&tv, (struct timezone *)NULL); 191 if (pw->pw_expire) { 192 if (tv.tv_sec >= pw->pw_expire) { 193 logit("User %.100s not allowed because account has expired", 194 pw->pw_name); 195 return 0; /* expired */ 196 } 197 } 198 #ifdef _PASSWORD_CHGNOW 199 if (pw->pw_change == _PASSWORD_CHGNOW) { 200 logit("User %.100s not allowed because password needs to be changed", 201 pw->pw_name); 202 203 return 0; /* can't force password change (yet) */ 204 } 205 #endif 206 if (pw->pw_change) { 207 if (tv.tv_sec >= pw->pw_change) { 208 logit("User %.100s not allowed because password has expired", 209 pw->pw_name); 210 return 0; /* expired */ 211 } 212 } 213 } 214 #ifdef USE_PAM 215 } 216 #endif 217 218 /* 219 * Deny if shell does not exist or is not executable unless we 220 * are chrooting. 221 */ 222 /* 223 * XXX Should check to see if it is executable by the 224 * XXX requesting user. --thorpej 225 */ 226 if (options.chroot_directory == NULL || 227 strcasecmp(options.chroot_directory, "none") == 0) { 228 char *shell = xstrdup((pw->pw_shell[0] == '\0') ? 229 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */ 230 231 if (stat(shell, &st) == -1) { 232 logit("User %.100s not allowed because shell %.100s " 233 "does not exist", pw->pw_name, shell); 234 free(shell); 235 return 0; 236 } 237 if (S_ISREG(st.st_mode) == 0 || 238 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) { 239 logit("User %.100s not allowed because shell %.100s " 240 "is not executable", pw->pw_name, shell); 241 free(shell); 242 return 0; 243 } 244 free(shell); 245 } 246 /* 247 * XXX Consider nuking {Allow,Deny}{Users,Groups}. We have the 248 * XXX login_cap(3) mechanism which covers all other types of 249 * XXX logins, too. 250 */ 251 252 if (options.num_deny_users > 0 || options.num_allow_users > 0 || 253 options.num_deny_groups > 0 || options.num_allow_groups > 0) { 254 hostname = auth_get_canonical_hostname(ssh, options.use_dns); 255 ipaddr = ssh_remote_ipaddr(ssh); 256 } 257 258 /* Return false if user is listed in DenyUsers */ 259 if (options.num_deny_users > 0) { 260 for (i = 0; i < options.num_deny_users; i++) { 261 r = match_user(pw->pw_name, hostname, ipaddr, 262 options.deny_users[i]); 263 if (r < 0) { 264 fatal("Invalid DenyUsers pattern \"%.100s\"", 265 options.deny_users[i]); 266 } else if (r != 0) { 267 logit("User %.100s from %.100s not allowed " 268 "because listed in DenyUsers", 269 pw->pw_name, hostname); 270 return 0; 271 } 272 } 273 } 274 /* Return false if AllowUsers isn't empty and user isn't listed there */ 275 if (options.num_allow_users > 0) { 276 for (i = 0; i < options.num_allow_users; i++) { 277 r = match_user(pw->pw_name, hostname, ipaddr, 278 options.allow_users[i]); 279 if (r < 0) { 280 fatal("Invalid AllowUsers pattern \"%.100s\"", 281 options.allow_users[i]); 282 } else if (r == 1) 283 break; 284 } 285 /* i < options.num_allow_users iff we break for loop */ 286 if (i >= options.num_allow_users) { 287 logit("User %.100s from %.100s not allowed because " 288 "not listed in AllowUsers", pw->pw_name, hostname); 289 return 0; 290 } 291 } 292 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) { 293 /* Get the user's group access list (primary and supplementary) */ 294 if (ga_init(pw->pw_name, pw->pw_gid) == 0) { 295 logit("User %.100s from %.100s not allowed because " 296 "not in any group", pw->pw_name, hostname); 297 return 0; 298 } 299 300 /* Return false if one of user's groups is listed in DenyGroups */ 301 if (options.num_deny_groups > 0) 302 if (ga_match(options.deny_groups, 303 options.num_deny_groups)) { 304 ga_free(); 305 logit("User %.100s from %.100s not allowed " 306 "because a group is listed in DenyGroups", 307 pw->pw_name, hostname); 308 return 0; 309 } 310 /* 311 * Return false if AllowGroups isn't empty and one of user's groups 312 * isn't listed there 313 */ 314 if (options.num_allow_groups > 0) 315 if (!ga_match(options.allow_groups, 316 options.num_allow_groups)) { 317 ga_free(); 318 logit("User %.100s from %.100s not allowed " 319 "because none of user's groups are listed " 320 "in AllowGroups", pw->pw_name, hostname); 321 return 0; 322 } 323 ga_free(); 324 } 325 /* We found no reason not to let this user try to log on... */ 326 return 1; 327 } 328 329 /* 330 * Formats any key left in authctxt->auth_method_key for inclusion in 331 * auth_log()'s message. Also includes authxtct->auth_method_info if present. 332 */ 333 static char * 334 format_method_key(Authctxt *authctxt) 335 { 336 const struct sshkey *key = authctxt->auth_method_key; 337 const char *methinfo = authctxt->auth_method_info; 338 char *fp, *cafp, *ret = NULL; 339 340 if (key == NULL) 341 return NULL; 342 343 if (sshkey_is_cert(key)) { 344 fp = sshkey_fingerprint(key, 345 options.fingerprint_hash, SSH_FP_DEFAULT); 346 cafp = sshkey_fingerprint(key->cert->signature_key, 347 options.fingerprint_hash, SSH_FP_DEFAULT); 348 xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s", 349 sshkey_type(key), fp == NULL ? "(null)" : fp, 350 key->cert->key_id, 351 (unsigned long long)key->cert->serial, 352 sshkey_type(key->cert->signature_key), 353 cafp == NULL ? "(null)" : cafp, 354 methinfo == NULL ? "" : ", ", 355 methinfo == NULL ? "" : methinfo); 356 free(fp); 357 free(cafp); 358 } else { 359 fp = sshkey_fingerprint(key, options.fingerprint_hash, 360 SSH_FP_DEFAULT); 361 xasprintf(&ret, "%s %s%s%s", sshkey_type(key), 362 fp == NULL ? "(null)" : fp, 363 methinfo == NULL ? "" : ", ", 364 methinfo == NULL ? "" : methinfo); 365 free(fp); 366 } 367 return ret; 368 } 369 370 void 371 auth_log(struct ssh *ssh, int authenticated, int partial, 372 const char *method, const char *submethod) 373 { 374 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 375 int level = SYSLOG_LEVEL_VERBOSE; 376 const char *authmsg; 377 char *extra = NULL; 378 379 if (use_privsep && !mm_is_monitor() && !authctxt->postponed) 380 return; 381 382 /* Raise logging level */ 383 if (authenticated == 1 || 384 !authctxt->valid || 385 authctxt->failures >= options.max_authtries / 2 || 386 strcmp(method, "password") == 0) 387 level = SYSLOG_LEVEL_INFO; 388 389 if (authctxt->postponed) 390 authmsg = "Postponed"; 391 else if (partial) 392 authmsg = "Partial"; 393 else 394 authmsg = authenticated ? "Accepted" : "Failed"; 395 396 if ((extra = format_method_key(authctxt)) == NULL) { 397 if (authctxt->auth_method_info != NULL) 398 extra = xstrdup(authctxt->auth_method_info); 399 } 400 401 do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s", 402 authmsg, 403 method, 404 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod, 405 authctxt->valid ? "" : "invalid user ", 406 authctxt->user, 407 ssh_remote_ipaddr(ssh), 408 ssh_remote_port(ssh), 409 extra != NULL ? ": " : "", 410 extra != NULL ? extra : ""); 411 412 free(extra); 413 } 414 415 void 416 auth_maxtries_exceeded(struct ssh *ssh) 417 { 418 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 419 420 error("maximum authentication attempts exceeded for " 421 "%s%.100s from %.200s port %d ssh2", 422 authctxt->valid ? "" : "invalid user ", 423 authctxt->user, 424 ssh_remote_ipaddr(ssh), 425 ssh_remote_port(ssh)); 426 ssh_packet_disconnect(ssh, "Too many authentication failures"); 427 /* NOTREACHED */ 428 } 429 430 /* 431 * Check whether root logins are disallowed. 432 */ 433 int 434 auth_root_allowed(struct ssh *ssh, const char *method) 435 { 436 switch (options.permit_root_login) { 437 case PERMIT_YES: 438 return 1; 439 case PERMIT_NO_PASSWD: 440 if (strcmp(method, "publickey") == 0 || 441 strcmp(method, "hostbased") == 0 || 442 strcmp(method, "gssapi-with-mic") == 0) 443 return 1; 444 break; 445 case PERMIT_FORCED_ONLY: 446 if (auth_opts->force_command != NULL) { 447 logit("Root login accepted for forced command."); 448 return 1; 449 } 450 break; 451 } 452 logit("ROOT LOGIN REFUSED FROM %.200s port %d", 453 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 454 return 0; 455 } 456 457 458 /* 459 * Given a template and a passwd structure, build a filename 460 * by substituting % tokenised options. Currently, %% becomes '%', 461 * %h becomes the home directory and %u the username. 462 * 463 * This returns a buffer allocated by xmalloc. 464 */ 465 char * 466 expand_authorized_keys(const char *filename, struct passwd *pw) 467 { 468 char *file, uidstr[32], ret[PATH_MAX]; 469 int i; 470 471 snprintf(uidstr, sizeof(uidstr), "%llu", 472 (unsigned long long)pw->pw_uid); 473 file = percent_expand(filename, "h", pw->pw_dir, 474 "u", pw->pw_name, "U", uidstr, (char *)NULL); 475 476 /* 477 * Ensure that filename starts anchored. If not, be backward 478 * compatible and prepend the '%h/' 479 */ 480 if (path_absolute(file)) 481 return (file); 482 483 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file); 484 if (i < 0 || (size_t)i >= sizeof(ret)) 485 fatal("expand_authorized_keys: path too long"); 486 free(file); 487 return (xstrdup(ret)); 488 } 489 490 char * 491 authorized_principals_file(struct passwd *pw) 492 { 493 if (options.authorized_principals_file == NULL) 494 return NULL; 495 return expand_authorized_keys(options.authorized_principals_file, pw); 496 } 497 498 /* return ok if key exists in sysfile or userfile */ 499 HostStatus 500 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host, 501 const char *sysfile, const char *userfile) 502 { 503 char *user_hostfile; 504 struct stat st; 505 HostStatus host_status; 506 struct hostkeys *hostkeys; 507 const struct hostkey_entry *found; 508 509 hostkeys = init_hostkeys(); 510 load_hostkeys(hostkeys, host, sysfile, 0); 511 if (userfile != NULL) { 512 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid); 513 if (options.strict_modes && 514 (stat(user_hostfile, &st) == 0) && 515 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) || 516 (st.st_mode & 022) != 0)) { 517 logit("Authentication refused for %.100s: " 518 "bad owner or modes for %.200s", 519 pw->pw_name, user_hostfile); 520 auth_debug_add("Ignored %.200s: bad ownership or modes", 521 user_hostfile); 522 } else { 523 temporarily_use_uid(pw); 524 load_hostkeys(hostkeys, host, user_hostfile, 0); 525 restore_uid(); 526 } 527 free(user_hostfile); 528 } 529 host_status = check_key_in_hostkeys(hostkeys, key, &found); 530 if (host_status == HOST_REVOKED) 531 error("WARNING: revoked key for %s attempted authentication", 532 host); 533 else if (host_status == HOST_OK) 534 debug_f("key for %s found at %s:%ld", 535 found->host, found->file, found->line); 536 else 537 debug_f("key for host %s not found", host); 538 539 free_hostkeys(hostkeys); 540 541 return host_status; 542 } 543 544 struct passwd * 545 getpwnamallow(struct ssh *ssh, const char *user) 546 { 547 #ifdef HAVE_LOGIN_CAP 548 extern login_cap_t *lc; 549 #ifdef BSD_AUTH 550 auth_session_t *as; 551 #endif 552 #endif 553 struct passwd *pw; 554 struct connection_info *ci; 555 u_int i; 556 557 ci = get_connection_info(ssh, 1, options.use_dns); 558 ci->user = user; 559 parse_server_match_config(&options, &includes, ci); 560 log_change_level(options.log_level); 561 log_verbose_reset(); 562 for (i = 0; i < options.num_log_verbose; i++) 563 log_verbose_add(options.log_verbose[i]); 564 process_permitopen(ssh, &options); 565 566 pw = getpwnam(user); 567 if (pw == NULL) { 568 pfilter_notify(1); 569 logit("Invalid user %.100s from %.100s port %d", 570 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 571 return (NULL); 572 } 573 if (!allowed_user(ssh, pw)) 574 return (NULL); 575 #ifdef HAVE_LOGIN_CAP 576 if ((lc = login_getclass(pw->pw_class)) == NULL) { 577 debug("unable to get login class: %s", user); 578 return (NULL); 579 } 580 #ifdef BSD_AUTH 581 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 || 582 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) { 583 debug("Approval failure for %s", user); 584 pw = NULL; 585 } 586 if (as != NULL) 587 auth_close(as); 588 #endif 589 #endif 590 if (pw != NULL) 591 return (pwcopy(pw)); 592 return (NULL); 593 } 594 595 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */ 596 int 597 auth_key_is_revoked(struct sshkey *key) 598 { 599 char *fp = NULL; 600 int r; 601 602 if (options.revoked_keys_file == NULL) 603 return 0; 604 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, 605 SSH_FP_DEFAULT)) == NULL) { 606 r = SSH_ERR_ALLOC_FAIL; 607 error_fr(r, "fingerprint key"); 608 goto out; 609 } 610 611 r = sshkey_check_revoked(key, options.revoked_keys_file); 612 switch (r) { 613 case 0: 614 break; /* not revoked */ 615 case SSH_ERR_KEY_REVOKED: 616 error("Authentication key %s %s revoked by file %s", 617 sshkey_type(key), fp, options.revoked_keys_file); 618 goto out; 619 default: 620 error_r(r, "Error checking authentication key %s %s in " 621 "revoked keys file %s", sshkey_type(key), fp, 622 options.revoked_keys_file); 623 goto out; 624 } 625 626 /* Success */ 627 r = 0; 628 629 out: 630 free(fp); 631 return r == 0 ? 0 : 1; 632 } 633 #endif 634 635 void 636 auth_debug_add(const char *fmt,...) 637 { 638 char buf[1024]; 639 va_list args; 640 int r; 641 642 if (auth_debug == NULL) 643 return; 644 645 va_start(args, fmt); 646 vsnprintf(buf, sizeof(buf), fmt, args); 647 va_end(args); 648 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0) 649 fatal_fr(r, "sshbuf_put_cstring"); 650 } 651 652 void 653 auth_debug_send(struct ssh *ssh) 654 { 655 char *msg; 656 int r; 657 658 if (auth_debug == NULL) 659 return; 660 while (sshbuf_len(auth_debug) != 0) { 661 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0) 662 fatal_fr(r, "sshbuf_get_cstring"); 663 ssh_packet_send_debug(ssh, "%s", msg); 664 free(msg); 665 } 666 } 667 668 void 669 auth_debug_reset(void) 670 { 671 if (auth_debug != NULL) 672 sshbuf_reset(auth_debug); 673 else if ((auth_debug = sshbuf_new()) == NULL) 674 fatal_f("sshbuf_new failed"); 675 } 676 677 struct passwd * 678 fakepw(void) 679 { 680 static int done = 0; 681 static struct passwd fake; 682 const char hashchars[] = "./ABCDEFGHIJKLMNOPQRSTUVWXYZ" 683 "abcdefghijklmnopqrstuvwxyz0123456789"; /* from bcrypt.c */ 684 char *cp; 685 686 if (done) 687 return (&fake); 688 689 memset(&fake, 0, sizeof(fake)); 690 fake.pw_name = __UNCONST("NOUSER"); 691 fake.pw_passwd = xstrdup("$2a$10$" 692 "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); 693 for (cp = fake.pw_passwd + 7; *cp != '\0'; cp++) 694 *cp = hashchars[arc4random_uniform(sizeof(hashchars) - 1)]; 695 fake.pw_gecos = __UNCONST("NOUSER"); 696 fake.pw_uid = (uid_t)-1; 697 fake.pw_gid = (gid_t)-1; 698 fake.pw_class = __UNCONST(""); 699 fake.pw_dir = __UNCONST("/nonexist"); 700 fake.pw_shell = __UNCONST("/nonexist"); 701 done = 1; 702 703 return (&fake); 704 } 705 706 /* 707 * Returns the remote DNS hostname as a string. The returned string must not 708 * be freed. NB. this will usually trigger a DNS query the first time it is 709 * called. 710 * This function does additional checks on the hostname to mitigate some 711 * attacks on based on conflation of hostnames and IP addresses. 712 */ 713 714 static char * 715 remote_hostname(struct ssh *ssh) 716 { 717 struct sockaddr_storage from; 718 socklen_t fromlen; 719 struct addrinfo hints, *ai, *aitop; 720 char name[NI_MAXHOST], ntop2[NI_MAXHOST]; 721 const char *ntop = ssh_remote_ipaddr(ssh); 722 723 /* Get IP address of client. */ 724 fromlen = sizeof(from); 725 memset(&from, 0, sizeof(from)); 726 if (getpeername(ssh_packet_get_connection_in(ssh), 727 (struct sockaddr *)&from, &fromlen) == -1) { 728 debug("getpeername failed: %.100s", strerror(errno)); 729 return xstrdup(ntop); 730 } 731 732 debug3("Trying to reverse map address %.100s.", ntop); 733 /* Map the IP address to a host name. */ 734 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name), 735 NULL, 0, NI_NAMEREQD) != 0) { 736 /* Host name not found. Use ip address. */ 737 return xstrdup(ntop); 738 } 739 740 /* 741 * if reverse lookup result looks like a numeric hostname, 742 * someone is trying to trick us by PTR record like following: 743 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5 744 */ 745 memset(&hints, 0, sizeof(hints)); 746 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 747 hints.ai_flags = AI_NUMERICHOST; 748 if (getaddrinfo(name, NULL, &hints, &ai) == 0) { 749 logit("Nasty PTR record \"%s\" is set up for %s, ignoring", 750 name, ntop); 751 freeaddrinfo(ai); 752 return xstrdup(ntop); 753 } 754 755 /* Names are stored in lowercase. */ 756 lowercase(name); 757 758 /* 759 * Map it back to an IP address and check that the given 760 * address actually is an address of this host. This is 761 * necessary because anyone with access to a name server can 762 * define arbitrary names for an IP address. Mapping from 763 * name to IP address can be trusted better (but can still be 764 * fooled if the intruder has access to the name server of 765 * the domain). 766 */ 767 memset(&hints, 0, sizeof(hints)); 768 hints.ai_family = from.ss_family; 769 hints.ai_socktype = SOCK_STREAM; 770 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) { 771 logit("reverse mapping checking getaddrinfo for %.700s " 772 "[%s] failed.", name, ntop); 773 return xstrdup(ntop); 774 } 775 /* Look for the address from the list of addresses. */ 776 for (ai = aitop; ai; ai = ai->ai_next) { 777 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2, 778 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 && 779 (strcmp(ntop, ntop2) == 0)) 780 break; 781 } 782 freeaddrinfo(aitop); 783 /* If we reached the end of the list, the address was not there. */ 784 if (ai == NULL) { 785 /* Address not found for the host name. */ 786 logit("Address %.100s maps to %.600s, but this does not " 787 "map back to the address.", ntop, name); 788 return xstrdup(ntop); 789 } 790 return xstrdup(name); 791 } 792 793 /* 794 * Return the canonical name of the host in the other side of the current 795 * connection. The host name is cached, so it is efficient to call this 796 * several times. 797 */ 798 799 const char * 800 auth_get_canonical_hostname(struct ssh *ssh, int use_dns) 801 { 802 static char *dnsname; 803 804 if (!use_dns) 805 return ssh_remote_ipaddr(ssh); 806 else if (dnsname != NULL) 807 return dnsname; 808 else { 809 dnsname = remote_hostname(ssh); 810 return dnsname; 811 } 812 } 813 814 /* These functions link key/cert options to the auth framework */ 815 816 /* Log sshauthopt options locally and (optionally) for remote transmission */ 817 void 818 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote) 819 { 820 int do_env = options.permit_user_env && opts->nenv > 0; 821 int do_permitopen = opts->npermitopen > 0 && 822 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0; 823 int do_permitlisten = opts->npermitlisten > 0 && 824 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0; 825 size_t i; 826 char msg[1024], buf[64]; 827 828 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device); 829 /* Try to keep this alphabetically sorted */ 830 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", 831 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "", 832 opts->force_command == NULL ? "" : " command", 833 do_env ? " environment" : "", 834 opts->valid_before == 0 ? "" : "expires", 835 opts->no_require_user_presence ? " no-touch-required" : "", 836 do_permitopen ? " permitopen" : "", 837 do_permitlisten ? " permitlisten" : "", 838 opts->permit_port_forwarding_flag ? " port-forwarding" : "", 839 opts->cert_principals == NULL ? "" : " principals", 840 opts->permit_pty_flag ? " pty" : "", 841 opts->require_verify ? " uv" : "", 842 opts->force_tun_device == -1 ? "" : " tun=", 843 opts->force_tun_device == -1 ? "" : buf, 844 opts->permit_user_rc ? " user-rc" : "", 845 opts->permit_x11_forwarding_flag ? " x11-forwarding" : ""); 846 847 debug("%s: %s", loc, msg); 848 if (do_remote) 849 auth_debug_add("%s: %s", loc, msg); 850 851 if (options.permit_user_env) { 852 for (i = 0; i < opts->nenv; i++) { 853 debug("%s: environment: %s", loc, opts->env[i]); 854 if (do_remote) { 855 auth_debug_add("%s: environment: %s", 856 loc, opts->env[i]); 857 } 858 } 859 } 860 861 /* Go into a little more details for the local logs. */ 862 if (opts->valid_before != 0) { 863 format_absolute_time(opts->valid_before, buf, sizeof(buf)); 864 debug("%s: expires at %s", loc, buf); 865 } 866 if (opts->cert_principals != NULL) { 867 debug("%s: authorized principals: \"%s\"", 868 loc, opts->cert_principals); 869 } 870 if (opts->force_command != NULL) 871 debug("%s: forced command: \"%s\"", loc, opts->force_command); 872 if (do_permitopen) { 873 for (i = 0; i < opts->npermitopen; i++) { 874 debug("%s: permitted open: %s", 875 loc, opts->permitopen[i]); 876 } 877 } 878 if (do_permitlisten) { 879 for (i = 0; i < opts->npermitlisten; i++) { 880 debug("%s: permitted listen: %s", 881 loc, opts->permitlisten[i]); 882 } 883 } 884 } 885 886 /* Activate a new set of key/cert options; merging with what is there. */ 887 int 888 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts) 889 { 890 struct sshauthopt *old = auth_opts; 891 const char *emsg = NULL; 892 893 debug_f("setting new authentication options"); 894 if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) { 895 error("Inconsistent authentication options: %s", emsg); 896 return -1; 897 } 898 return 0; 899 } 900 901 /* Disable forwarding, etc for the session */ 902 void 903 auth_restrict_session(struct ssh *ssh) 904 { 905 struct sshauthopt *restricted; 906 907 debug_f("restricting session"); 908 909 /* A blank sshauthopt defaults to permitting nothing */ 910 if ((restricted = sshauthopt_new()) == NULL) 911 fatal_f("sshauthopt_new failed"); 912 restricted->permit_pty_flag = 1; 913 restricted->restricted = 1; 914 915 if (auth_activate_options(ssh, restricted) != 0) 916 fatal_f("failed to restrict session"); 917 sshauthopt_free(restricted); 918 } 919