1 /* $NetBSD: auth.c,v 1.30 2021/04/19 14:40:15 christos Exp $ */ 2 /* $OpenBSD: auth.c,v 1.152 2021/04/03 06:18:40 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.30 2021/04/19 14:40:15 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 static FILE * 545 auth_openfile(const char *file, struct passwd *pw, int strict_modes, 546 int log_missing, const char *file_type) 547 { 548 char line[1024]; 549 struct stat st; 550 int fd; 551 FILE *f; 552 553 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) { 554 if (log_missing || errno != ENOENT) 555 debug("Could not open %s '%s': %s", file_type, file, 556 strerror(errno)); 557 return NULL; 558 } 559 560 if (fstat(fd, &st) == -1) { 561 close(fd); 562 return NULL; 563 } 564 if (!S_ISREG(st.st_mode)) { 565 logit("User %s %s %s is not a regular file", 566 pw->pw_name, file_type, file); 567 close(fd); 568 return NULL; 569 } 570 unset_nonblock(fd); 571 if ((f = fdopen(fd, "r")) == NULL) { 572 close(fd); 573 return NULL; 574 } 575 if (strict_modes && 576 safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) { 577 fclose(f); 578 logit("Authentication refused: %s", line); 579 auth_debug_add("Ignored %s: %s", file_type, line); 580 return NULL; 581 } 582 583 return f; 584 } 585 586 587 FILE * 588 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes) 589 { 590 return auth_openfile(file, pw, strict_modes, 1, "authorized keys"); 591 } 592 593 FILE * 594 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes) 595 { 596 return auth_openfile(file, pw, strict_modes, 0, 597 "authorized principals"); 598 } 599 600 struct passwd * 601 getpwnamallow(struct ssh *ssh, const char *user) 602 { 603 #ifdef HAVE_LOGIN_CAP 604 extern login_cap_t *lc; 605 #ifdef BSD_AUTH 606 auth_session_t *as; 607 #endif 608 #endif 609 struct passwd *pw; 610 struct connection_info *ci; 611 u_int i; 612 613 ci = get_connection_info(ssh, 1, options.use_dns); 614 ci->user = user; 615 parse_server_match_config(&options, &includes, ci); 616 log_change_level(options.log_level); 617 log_verbose_reset(); 618 for (i = 0; i < options.num_log_verbose; i++) 619 log_verbose_add(options.log_verbose[i]); 620 process_permitopen(ssh, &options); 621 622 pw = getpwnam(user); 623 if (pw == NULL) { 624 pfilter_notify(1); 625 logit("Invalid user %.100s from %.100s port %d", 626 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 627 return (NULL); 628 } 629 if (!allowed_user(ssh, pw)) 630 return (NULL); 631 #ifdef HAVE_LOGIN_CAP 632 if ((lc = login_getclass(pw->pw_class)) == NULL) { 633 debug("unable to get login class: %s", user); 634 return (NULL); 635 } 636 #ifdef BSD_AUTH 637 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 || 638 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) { 639 debug("Approval failure for %s", user); 640 pw = NULL; 641 } 642 if (as != NULL) 643 auth_close(as); 644 #endif 645 #endif 646 if (pw != NULL) 647 return (pwcopy(pw)); 648 return (NULL); 649 } 650 651 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */ 652 int 653 auth_key_is_revoked(struct sshkey *key) 654 { 655 char *fp = NULL; 656 int r; 657 658 if (options.revoked_keys_file == NULL) 659 return 0; 660 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, 661 SSH_FP_DEFAULT)) == NULL) { 662 r = SSH_ERR_ALLOC_FAIL; 663 error_fr(r, "fingerprint key"); 664 goto out; 665 } 666 667 r = sshkey_check_revoked(key, options.revoked_keys_file); 668 switch (r) { 669 case 0: 670 break; /* not revoked */ 671 case SSH_ERR_KEY_REVOKED: 672 error("Authentication key %s %s revoked by file %s", 673 sshkey_type(key), fp, options.revoked_keys_file); 674 goto out; 675 default: 676 error_r(r, "Error checking authentication key %s %s in " 677 "revoked keys file %s", sshkey_type(key), fp, 678 options.revoked_keys_file); 679 goto out; 680 } 681 682 /* Success */ 683 r = 0; 684 685 out: 686 free(fp); 687 return r == 0 ? 0 : 1; 688 } 689 #endif 690 691 void 692 auth_debug_add(const char *fmt,...) 693 { 694 char buf[1024]; 695 va_list args; 696 int r; 697 698 if (auth_debug == NULL) 699 return; 700 701 va_start(args, fmt); 702 vsnprintf(buf, sizeof(buf), fmt, args); 703 va_end(args); 704 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0) 705 fatal_fr(r, "sshbuf_put_cstring"); 706 } 707 708 void 709 auth_debug_send(struct ssh *ssh) 710 { 711 char *msg; 712 int r; 713 714 if (auth_debug == NULL) 715 return; 716 while (sshbuf_len(auth_debug) != 0) { 717 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0) 718 fatal_fr(r, "sshbuf_get_cstring"); 719 ssh_packet_send_debug(ssh, "%s", msg); 720 free(msg); 721 } 722 } 723 724 void 725 auth_debug_reset(void) 726 { 727 if (auth_debug != NULL) 728 sshbuf_reset(auth_debug); 729 else if ((auth_debug = sshbuf_new()) == NULL) 730 fatal_f("sshbuf_new failed"); 731 } 732 733 struct passwd * 734 fakepw(void) 735 { 736 static struct passwd fake; 737 static char nouser[] = "NOUSER"; 738 static char nonexist[] = "/nonexist"; 739 740 memset(&fake, 0, sizeof(fake)); 741 fake.pw_name = nouser; 742 fake.pw_passwd = __UNCONST( 743 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK"); 744 fake.pw_gecos = nouser; 745 fake.pw_uid = (uid_t)-1; 746 fake.pw_gid = (gid_t)-1; 747 fake.pw_class = __UNCONST(""); 748 fake.pw_dir = nonexist; 749 fake.pw_shell = nonexist; 750 751 return (&fake); 752 } 753 754 /* 755 * Returns the remote DNS hostname as a string. The returned string must not 756 * be freed. NB. this will usually trigger a DNS query the first time it is 757 * called. 758 * This function does additional checks on the hostname to mitigate some 759 * attacks on legacy rhosts-style authentication. 760 * XXX is RhostsRSAAuthentication vulnerable to these? 761 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?) 762 */ 763 764 static char * 765 remote_hostname(struct ssh *ssh) 766 { 767 struct sockaddr_storage from; 768 socklen_t fromlen; 769 struct addrinfo hints, *ai, *aitop; 770 char name[NI_MAXHOST], ntop2[NI_MAXHOST]; 771 const char *ntop = ssh_remote_ipaddr(ssh); 772 773 /* Get IP address of client. */ 774 fromlen = sizeof(from); 775 memset(&from, 0, sizeof(from)); 776 if (getpeername(ssh_packet_get_connection_in(ssh), 777 (struct sockaddr *)&from, &fromlen) == -1) { 778 debug("getpeername failed: %.100s", strerror(errno)); 779 return xstrdup(ntop); 780 } 781 782 debug3("Trying to reverse map address %.100s.", ntop); 783 /* Map the IP address to a host name. */ 784 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name), 785 NULL, 0, NI_NAMEREQD) != 0) { 786 /* Host name not found. Use ip address. */ 787 return xstrdup(ntop); 788 } 789 790 /* 791 * if reverse lookup result looks like a numeric hostname, 792 * someone is trying to trick us by PTR record like following: 793 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5 794 */ 795 memset(&hints, 0, sizeof(hints)); 796 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 797 hints.ai_flags = AI_NUMERICHOST; 798 if (getaddrinfo(name, NULL, &hints, &ai) == 0) { 799 logit("Nasty PTR record \"%s\" is set up for %s, ignoring", 800 name, ntop); 801 freeaddrinfo(ai); 802 return xstrdup(ntop); 803 } 804 805 /* Names are stored in lowercase. */ 806 lowercase(name); 807 808 /* 809 * Map it back to an IP address and check that the given 810 * address actually is an address of this host. This is 811 * necessary because anyone with access to a name server can 812 * define arbitrary names for an IP address. Mapping from 813 * name to IP address can be trusted better (but can still be 814 * fooled if the intruder has access to the name server of 815 * the domain). 816 */ 817 memset(&hints, 0, sizeof(hints)); 818 hints.ai_family = from.ss_family; 819 hints.ai_socktype = SOCK_STREAM; 820 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) { 821 logit("reverse mapping checking getaddrinfo for %.700s " 822 "[%s] failed.", name, ntop); 823 return xstrdup(ntop); 824 } 825 /* Look for the address from the list of addresses. */ 826 for (ai = aitop; ai; ai = ai->ai_next) { 827 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2, 828 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 && 829 (strcmp(ntop, ntop2) == 0)) 830 break; 831 } 832 freeaddrinfo(aitop); 833 /* If we reached the end of the list, the address was not there. */ 834 if (ai == NULL) { 835 /* Address not found for the host name. */ 836 logit("Address %.100s maps to %.600s, but this does not " 837 "map back to the address.", ntop, name); 838 return xstrdup(ntop); 839 } 840 return xstrdup(name); 841 } 842 843 /* 844 * Return the canonical name of the host in the other side of the current 845 * connection. The host name is cached, so it is efficient to call this 846 * several times. 847 */ 848 849 const char * 850 auth_get_canonical_hostname(struct ssh *ssh, int use_dns) 851 { 852 static char *dnsname; 853 854 if (!use_dns) 855 return ssh_remote_ipaddr(ssh); 856 else if (dnsname != NULL) 857 return dnsname; 858 else { 859 dnsname = remote_hostname(ssh); 860 return dnsname; 861 } 862 } 863 864 /* These functions link key/cert options to the auth framework */ 865 866 /* Log sshauthopt options locally and (optionally) for remote transmission */ 867 void 868 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote) 869 { 870 int do_env = options.permit_user_env && opts->nenv > 0; 871 int do_permitopen = opts->npermitopen > 0 && 872 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0; 873 int do_permitlisten = opts->npermitlisten > 0 && 874 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0; 875 size_t i; 876 char msg[1024], buf[64]; 877 878 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device); 879 /* Try to keep this alphabetically sorted */ 880 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", 881 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "", 882 opts->force_command == NULL ? "" : " command", 883 do_env ? " environment" : "", 884 opts->valid_before == 0 ? "" : "expires", 885 opts->no_require_user_presence ? " no-touch-required" : "", 886 do_permitopen ? " permitopen" : "", 887 do_permitlisten ? " permitlisten" : "", 888 opts->permit_port_forwarding_flag ? " port-forwarding" : "", 889 opts->cert_principals == NULL ? "" : " principals", 890 opts->permit_pty_flag ? " pty" : "", 891 opts->require_verify ? " uv" : "", 892 opts->force_tun_device == -1 ? "" : " tun=", 893 opts->force_tun_device == -1 ? "" : buf, 894 opts->permit_user_rc ? " user-rc" : "", 895 opts->permit_x11_forwarding_flag ? " x11-forwarding" : ""); 896 897 debug("%s: %s", loc, msg); 898 if (do_remote) 899 auth_debug_add("%s: %s", loc, msg); 900 901 if (options.permit_user_env) { 902 for (i = 0; i < opts->nenv; i++) { 903 debug("%s: environment: %s", loc, opts->env[i]); 904 if (do_remote) { 905 auth_debug_add("%s: environment: %s", 906 loc, opts->env[i]); 907 } 908 } 909 } 910 911 /* Go into a little more details for the local logs. */ 912 if (opts->valid_before != 0) { 913 format_absolute_time(opts->valid_before, buf, sizeof(buf)); 914 debug("%s: expires at %s", loc, buf); 915 } 916 if (opts->cert_principals != NULL) { 917 debug("%s: authorized principals: \"%s\"", 918 loc, opts->cert_principals); 919 } 920 if (opts->force_command != NULL) 921 debug("%s: forced command: \"%s\"", loc, opts->force_command); 922 if (do_permitopen) { 923 for (i = 0; i < opts->npermitopen; i++) { 924 debug("%s: permitted open: %s", 925 loc, opts->permitopen[i]); 926 } 927 } 928 if (do_permitlisten) { 929 for (i = 0; i < opts->npermitlisten; i++) { 930 debug("%s: permitted listen: %s", 931 loc, opts->permitlisten[i]); 932 } 933 } 934 } 935 936 #ifndef HOST_ONLY 937 /* Activate a new set of key/cert options; merging with what is there. */ 938 int 939 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts) 940 { 941 struct sshauthopt *old = auth_opts; 942 const char *emsg = NULL; 943 944 debug_f("setting new authentication options"); 945 if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) { 946 error("Inconsistent authentication options: %s", emsg); 947 return -1; 948 } 949 return 0; 950 } 951 952 /* Disable forwarding, etc for the session */ 953 void 954 auth_restrict_session(struct ssh *ssh) 955 { 956 struct sshauthopt *restricted; 957 958 debug_f("restricting session"); 959 960 /* A blank sshauthopt defaults to permitting nothing */ 961 restricted = sshauthopt_new(); 962 restricted->permit_pty_flag = 1; 963 restricted->restricted = 1; 964 965 if (auth_activate_options(ssh, restricted) != 0) 966 fatal_f("failed to restrict session"); 967 sshauthopt_free(restricted); 968 } 969 970 int 971 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw, 972 struct sshauthopt *opts, int allow_cert_authority, const char *loc) 973 { 974 const char *remote_ip = ssh_remote_ipaddr(ssh); 975 const char *remote_host = auth_get_canonical_hostname(ssh, 976 options.use_dns); 977 time_t now = time(NULL); 978 char buf[64]; 979 980 /* 981 * Check keys/principals file expiry time. 982 * NB. validity interval in certificate is handled elsewhere. 983 */ 984 if (opts->valid_before && now > 0 && 985 opts->valid_before < (uint64_t)now) { 986 format_absolute_time(opts->valid_before, buf, sizeof(buf)); 987 debug("%s: entry expired at %s", loc, buf); 988 auth_debug_add("%s: entry expired at %s", loc, buf); 989 return -1; 990 } 991 /* Consistency checks */ 992 if (opts->cert_principals != NULL && !opts->cert_authority) { 993 debug("%s: principals on non-CA key", loc); 994 auth_debug_add("%s: principals on non-CA key", loc); 995 /* deny access */ 996 return -1; 997 } 998 /* cert-authority flag isn't valid in authorized_principals files */ 999 if (!allow_cert_authority && opts->cert_authority) { 1000 debug("%s: cert-authority flag invalid here", loc); 1001 auth_debug_add("%s: cert-authority flag invalid here", loc); 1002 /* deny access */ 1003 return -1; 1004 } 1005 1006 /* Perform from= checks */ 1007 if (opts->required_from_host_keys != NULL) { 1008 switch (match_host_and_ip(remote_host, remote_ip, 1009 opts->required_from_host_keys )) { 1010 case 1: 1011 /* Host name matches. */ 1012 break; 1013 case -1: 1014 default: 1015 debug("%s: invalid from criteria", loc); 1016 auth_debug_add("%s: invalid from criteria", loc); 1017 /* FALLTHROUGH */ 1018 case 0: 1019 logit("%s: Authentication tried for %.100s with " 1020 "correct key but not from a permitted " 1021 "host (host=%.200s, ip=%.200s, required=%.200s).", 1022 loc, pw->pw_name, remote_host, remote_ip, 1023 opts->required_from_host_keys); 1024 auth_debug_add("%s: Your host '%.200s' is not " 1025 "permitted to use this key for login.", 1026 loc, remote_host); 1027 /* deny access */ 1028 return -1; 1029 } 1030 } 1031 /* Check source-address restriction from certificate */ 1032 if (opts->required_from_host_cert != NULL) { 1033 switch (addr_match_cidr_list(remote_ip, 1034 opts->required_from_host_cert)) { 1035 case 1: 1036 /* accepted */ 1037 break; 1038 case -1: 1039 default: 1040 /* invalid */ 1041 error("%s: Certificate source-address invalid", loc); 1042 /* FALLTHROUGH */ 1043 case 0: 1044 logit("%s: Authentication tried for %.100s with valid " 1045 "certificate but not from a permitted source " 1046 "address (%.200s).", loc, pw->pw_name, remote_ip); 1047 auth_debug_add("%s: Your address '%.200s' is not " 1048 "permitted to use this certificate for login.", 1049 loc, remote_ip); 1050 return -1; 1051 } 1052 } 1053 /* 1054 * 1055 * XXX this is spammy. We should report remotely only for keys 1056 * that are successful in actual auth attempts, and not PK_OK 1057 * tests. 1058 */ 1059 auth_log_authopts(loc, opts, 1); 1060 1061 return 0; 1062 } 1063 #endif 1064