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