1 /* $NetBSD: auth.c,v 1.24 2019/04/20 17:16:40 christos Exp $ */ 2 /* $OpenBSD: auth.c,v 1.138 2019/01/19 21:41:18 djm 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.24 2019/04/20 17:16:40 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 <errno.h> 35 #include <fcntl.h> 36 #include <login_cap.h> 37 #include <paths.h> 38 #include <pwd.h> 39 #include <stdarg.h> 40 #include <stdio.h> 41 #include <string.h> 42 #include <unistd.h> 43 #include <limits.h> 44 #include <netdb.h> 45 #include <time.h> 46 47 #include "xmalloc.h" 48 #include "match.h" 49 #include "groupaccess.h" 50 #include "log.h" 51 #include "sshbuf.h" 52 #include "misc.h" 53 #include "servconf.h" 54 #include "sshkey.h" 55 #include "hostfile.h" 56 #include "auth.h" 57 #include "auth-options.h" 58 #include "canohost.h" 59 #include "uidswap.h" 60 #include "packet.h" 61 #ifdef GSSAPI 62 #include "ssh-gss.h" 63 #endif 64 #include "authfile.h" 65 #include "monitor_wrap.h" 66 #include "authfile.h" 67 #include "ssherr.h" 68 #include "compat.h" 69 #include "channels.h" 70 #include "pfilter.h" 71 72 #ifdef HAVE_LOGIN_CAP 73 #include <login_cap.h> 74 #endif 75 76 /* import */ 77 extern ServerOptions options; 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) != 0) { 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 if (!authctxt->postponed) 412 pfilter_notify(!authenticated); 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); 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); 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 found->host); 533 else if (host_status == HOST_OK) 534 debug("%s: key for %s found at %s:%ld", __func__, 535 found->host, found->file, found->line); 536 else 537 debug("%s: key for host %s not found", __func__, 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) < 0) { 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 612 ci = get_connection_info(ssh, 1, options.use_dns); 613 ci->user = user; 614 parse_server_match_config(&options, ci); 615 log_change_level(options.log_level); 616 process_permitopen(ssh, &options); 617 618 pw = getpwnam(user); 619 if (pw == NULL) { 620 pfilter_notify(1); 621 logit("Invalid user %.100s from %.100s port %d", 622 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 623 return (NULL); 624 } 625 if (!allowed_user(ssh, pw)) 626 return (NULL); 627 #ifdef HAVE_LOGIN_CAP 628 if ((lc = login_getclass(pw->pw_class)) == NULL) { 629 debug("unable to get login class: %s", user); 630 return (NULL); 631 } 632 #ifdef BSD_AUTH 633 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 || 634 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) { 635 debug("Approval failure for %s", user); 636 pw = NULL; 637 } 638 if (as != NULL) 639 auth_close(as); 640 #endif 641 #endif 642 if (pw != NULL) 643 return (pwcopy(pw)); 644 return (NULL); 645 } 646 647 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */ 648 int 649 auth_key_is_revoked(struct sshkey *key) 650 { 651 char *fp = NULL; 652 int r; 653 654 if (options.revoked_keys_file == NULL) 655 return 0; 656 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, 657 SSH_FP_DEFAULT)) == NULL) { 658 r = SSH_ERR_ALLOC_FAIL; 659 error("%s: fingerprint key: %s", __func__, ssh_err(r)); 660 goto out; 661 } 662 663 r = sshkey_check_revoked(key, options.revoked_keys_file); 664 switch (r) { 665 case 0: 666 break; /* not revoked */ 667 case SSH_ERR_KEY_REVOKED: 668 error("Authentication key %s %s revoked by file %s", 669 sshkey_type(key), fp, options.revoked_keys_file); 670 goto out; 671 default: 672 error("Error checking authentication key %s %s in " 673 "revoked keys file %s: %s", sshkey_type(key), fp, 674 options.revoked_keys_file, ssh_err(r)); 675 goto out; 676 } 677 678 /* Success */ 679 r = 0; 680 681 out: 682 free(fp); 683 return r == 0 ? 0 : 1; 684 } 685 #endif 686 687 void 688 auth_debug_add(const char *fmt,...) 689 { 690 char buf[1024]; 691 va_list args; 692 int r; 693 694 if (auth_debug == NULL) 695 return; 696 697 va_start(args, fmt); 698 vsnprintf(buf, sizeof(buf), fmt, args); 699 va_end(args); 700 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0) 701 fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r)); 702 } 703 704 void 705 auth_debug_send(struct ssh *ssh) 706 { 707 char *msg; 708 int r; 709 710 if (auth_debug == NULL) 711 return; 712 while (sshbuf_len(auth_debug) != 0) { 713 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0) 714 fatal("%s: sshbuf_get_cstring: %s", 715 __func__, ssh_err(r)); 716 ssh_packet_send_debug(ssh, "%s", msg); 717 free(msg); 718 } 719 } 720 721 void 722 auth_debug_reset(void) 723 { 724 if (auth_debug != NULL) 725 sshbuf_reset(auth_debug); 726 else if ((auth_debug = sshbuf_new()) == NULL) 727 fatal("%s: sshbuf_new failed", __func__); 728 } 729 730 struct passwd * 731 fakepw(void) 732 { 733 static struct passwd fake; 734 static char nouser[] = "NOUSER"; 735 static char nonexist[] = "/nonexist"; 736 737 memset(&fake, 0, sizeof(fake)); 738 fake.pw_name = nouser; 739 fake.pw_passwd = __UNCONST( 740 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK"); 741 fake.pw_gecos = nouser; 742 fake.pw_uid = (uid_t)-1; 743 fake.pw_gid = (gid_t)-1; 744 fake.pw_class = __UNCONST(""); 745 fake.pw_dir = nonexist; 746 fake.pw_shell = nonexist; 747 748 return (&fake); 749 } 750 751 /* 752 * Returns the remote DNS hostname as a string. The returned string must not 753 * be freed. NB. this will usually trigger a DNS query the first time it is 754 * called. 755 * This function does additional checks on the hostname to mitigate some 756 * attacks on legacy rhosts-style authentication. 757 * XXX is RhostsRSAAuthentication vulnerable to these? 758 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?) 759 */ 760 761 static char * 762 remote_hostname(struct ssh *ssh) 763 { 764 struct sockaddr_storage from; 765 socklen_t fromlen; 766 struct addrinfo hints, *ai, *aitop; 767 char name[NI_MAXHOST], ntop2[NI_MAXHOST]; 768 const char *ntop = ssh_remote_ipaddr(ssh); 769 770 /* Get IP address of client. */ 771 fromlen = sizeof(from); 772 memset(&from, 0, sizeof(from)); 773 if (getpeername(ssh_packet_get_connection_in(ssh), 774 (struct sockaddr *)&from, &fromlen) < 0) { 775 debug("getpeername failed: %.100s", strerror(errno)); 776 return strdup(ntop); 777 } 778 779 debug3("Trying to reverse map address %.100s.", ntop); 780 /* Map the IP address to a host name. */ 781 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name), 782 NULL, 0, NI_NAMEREQD) != 0) { 783 /* Host name not found. Use ip address. */ 784 return strdup(ntop); 785 } 786 787 /* 788 * if reverse lookup result looks like a numeric hostname, 789 * someone is trying to trick us by PTR record like following: 790 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5 791 */ 792 memset(&hints, 0, sizeof(hints)); 793 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 794 hints.ai_flags = AI_NUMERICHOST; 795 if (getaddrinfo(name, NULL, &hints, &ai) == 0) { 796 logit("Nasty PTR record \"%s\" is set up for %s, ignoring", 797 name, ntop); 798 freeaddrinfo(ai); 799 return strdup(ntop); 800 } 801 802 /* Names are stored in lowercase. */ 803 lowercase(name); 804 805 /* 806 * Map it back to an IP address and check that the given 807 * address actually is an address of this host. This is 808 * necessary because anyone with access to a name server can 809 * define arbitrary names for an IP address. Mapping from 810 * name to IP address can be trusted better (but can still be 811 * fooled if the intruder has access to the name server of 812 * the domain). 813 */ 814 memset(&hints, 0, sizeof(hints)); 815 hints.ai_family = from.ss_family; 816 hints.ai_socktype = SOCK_STREAM; 817 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) { 818 logit("reverse mapping checking getaddrinfo for %.700s " 819 "[%s] failed.", name, ntop); 820 return strdup(ntop); 821 } 822 /* Look for the address from the list of addresses. */ 823 for (ai = aitop; ai; ai = ai->ai_next) { 824 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2, 825 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 && 826 (strcmp(ntop, ntop2) == 0)) 827 break; 828 } 829 freeaddrinfo(aitop); 830 /* If we reached the end of the list, the address was not there. */ 831 if (ai == NULL) { 832 /* Address not found for the host name. */ 833 logit("Address %.100s maps to %.600s, but this does not " 834 "map back to the address.", ntop, name); 835 return strdup(ntop); 836 } 837 return strdup(name); 838 } 839 840 /* 841 * Return the canonical name of the host in the other side of the current 842 * connection. The host name is cached, so it is efficient to call this 843 * several times. 844 */ 845 846 const char * 847 auth_get_canonical_hostname(struct ssh *ssh, int use_dns) 848 { 849 static char *dnsname; 850 851 if (!use_dns) 852 return ssh_remote_ipaddr(ssh); 853 else if (dnsname != NULL) 854 return dnsname; 855 else { 856 dnsname = remote_hostname(ssh); 857 return dnsname; 858 } 859 } 860 861 /* 862 * Runs command in a subprocess with a minimal environment. 863 * Returns pid on success, 0 on failure. 864 * The child stdout and stderr maybe captured, left attached or sent to 865 * /dev/null depending on the contents of flags. 866 * "tag" is prepended to log messages. 867 * NB. "command" is only used for logging; the actual command executed is 868 * av[0]. 869 */ 870 pid_t 871 subprocess(const char *tag, struct passwd *pw, const char *command, 872 int ac, char **av, FILE **child, u_int flags) 873 { 874 FILE *f = NULL; 875 struct stat st; 876 int fd, devnull, p[2], i; 877 pid_t pid; 878 char *cp, errmsg[512]; 879 u_int envsize; 880 char **child_env; 881 882 if (child != NULL) 883 *child = NULL; 884 885 debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__, 886 tag, command, pw->pw_name, flags); 887 888 /* Check consistency */ 889 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 && 890 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) { 891 error("%s: inconsistent flags", __func__); 892 return 0; 893 } 894 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) { 895 error("%s: inconsistent flags/output", __func__); 896 return 0; 897 } 898 899 /* 900 * If executing an explicit binary, then verify the it exists 901 * and appears safe-ish to execute 902 */ 903 if (!path_absolute(av[0])) { 904 error("%s path is not absolute", tag); 905 return 0; 906 } 907 temporarily_use_uid(pw); 908 if (stat(av[0], &st) < 0) { 909 error("Could not stat %s \"%s\": %s", tag, 910 av[0], strerror(errno)); 911 restore_uid(); 912 return 0; 913 } 914 if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) { 915 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg); 916 restore_uid(); 917 return 0; 918 } 919 /* Prepare to keep the child's stdout if requested */ 920 if (pipe(p) != 0) { 921 error("%s: pipe: %s", tag, strerror(errno)); 922 restore_uid(); 923 return 0; 924 } 925 restore_uid(); 926 927 switch ((pid = fork())) { 928 case -1: /* error */ 929 error("%s: fork: %s", tag, strerror(errno)); 930 close(p[0]); 931 close(p[1]); 932 return 0; 933 case 0: /* child */ 934 /* Prepare a minimal environment for the child. */ 935 envsize = 5; 936 child_env = xcalloc(sizeof(*child_env), envsize); 937 child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH); 938 child_set_env(&child_env, &envsize, "USER", pw->pw_name); 939 child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name); 940 child_set_env(&child_env, &envsize, "HOME", pw->pw_dir); 941 if ((cp = getenv("LANG")) != NULL) 942 child_set_env(&child_env, &envsize, "LANG", cp); 943 944 for (i = 0; i < NSIG; i++) 945 signal(i, SIG_DFL); 946 947 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 948 error("%s: open %s: %s", tag, _PATH_DEVNULL, 949 strerror(errno)); 950 _exit(1); 951 } 952 if (dup2(devnull, STDIN_FILENO) == -1) { 953 error("%s: dup2: %s", tag, strerror(errno)); 954 _exit(1); 955 } 956 957 /* Set up stdout as requested; leave stderr in place for now. */ 958 fd = -1; 959 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) 960 fd = p[1]; 961 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0) 962 fd = devnull; 963 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) { 964 error("%s: dup2: %s", tag, strerror(errno)); 965 _exit(1); 966 } 967 closefrom(STDERR_FILENO + 1); 968 969 /* Don't use permanently_set_uid() here to avoid fatal() */ 970 #ifdef __NetBSD__ 971 #define setresgid(a, b, c) setgid(a) 972 #define setresuid(a, b, c) setuid(a) 973 #endif 974 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) { 975 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid, 976 strerror(errno)); 977 _exit(1); 978 } 979 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) { 980 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid, 981 strerror(errno)); 982 _exit(1); 983 } 984 /* stdin is pointed to /dev/null at this point */ 985 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 && 986 dup2(STDIN_FILENO, STDERR_FILENO) == -1) { 987 error("%s: dup2: %s", tag, strerror(errno)); 988 _exit(1); 989 } 990 991 execve(av[0], av, child_env); 992 error("%s exec \"%s\": %s", tag, command, strerror(errno)); 993 _exit(127); 994 default: /* parent */ 995 break; 996 } 997 998 close(p[1]); 999 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) 1000 close(p[0]); 1001 else if ((f = fdopen(p[0], "r")) == NULL) { 1002 error("%s: fdopen: %s", tag, strerror(errno)); 1003 close(p[0]); 1004 /* Don't leave zombie child */ 1005 kill(pid, SIGTERM); 1006 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR) 1007 ; 1008 return 0; 1009 } 1010 /* Success */ 1011 debug3("%s: %s pid %ld", __func__, tag, (long)pid); 1012 if (child != NULL) 1013 *child = f; 1014 return pid; 1015 } 1016 1017 /* These functions link key/cert options to the auth framework */ 1018 1019 /* Log sshauthopt options locally and (optionally) for remote transmission */ 1020 void 1021 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote) 1022 { 1023 int do_env = options.permit_user_env && opts->nenv > 0; 1024 int do_permitopen = opts->npermitopen > 0 && 1025 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0; 1026 int do_permitlisten = opts->npermitlisten > 0 && 1027 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0; 1028 size_t i; 1029 char msg[1024], buf[64]; 1030 1031 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device); 1032 /* Try to keep this alphabetically sorted */ 1033 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s", 1034 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "", 1035 opts->force_command == NULL ? "" : " command", 1036 do_env ? " environment" : "", 1037 opts->valid_before == 0 ? "" : "expires", 1038 do_permitopen ? " permitopen" : "", 1039 do_permitlisten ? " permitlisten" : "", 1040 opts->permit_port_forwarding_flag ? " port-forwarding" : "", 1041 opts->cert_principals == NULL ? "" : " principals", 1042 opts->permit_pty_flag ? " pty" : "", 1043 opts->force_tun_device == -1 ? "" : " tun=", 1044 opts->force_tun_device == -1 ? "" : buf, 1045 opts->permit_user_rc ? " user-rc" : "", 1046 opts->permit_x11_forwarding_flag ? " x11-forwarding" : ""); 1047 1048 debug("%s: %s", loc, msg); 1049 if (do_remote) 1050 auth_debug_add("%s: %s", loc, msg); 1051 1052 if (options.permit_user_env) { 1053 for (i = 0; i < opts->nenv; i++) { 1054 debug("%s: environment: %s", loc, opts->env[i]); 1055 if (do_remote) { 1056 auth_debug_add("%s: environment: %s", 1057 loc, opts->env[i]); 1058 } 1059 } 1060 } 1061 1062 /* Go into a little more details for the local logs. */ 1063 if (opts->valid_before != 0) { 1064 format_absolute_time(opts->valid_before, buf, sizeof(buf)); 1065 debug("%s: expires at %s", loc, buf); 1066 } 1067 if (opts->cert_principals != NULL) { 1068 debug("%s: authorized principals: \"%s\"", 1069 loc, opts->cert_principals); 1070 } 1071 if (opts->force_command != NULL) 1072 debug("%s: forced command: \"%s\"", loc, opts->force_command); 1073 if (do_permitopen) { 1074 for (i = 0; i < opts->npermitopen; i++) { 1075 debug("%s: permitted open: %s", 1076 loc, opts->permitopen[i]); 1077 } 1078 } 1079 if (do_permitlisten) { 1080 for (i = 0; i < opts->npermitlisten; i++) { 1081 debug("%s: permitted listen: %s", 1082 loc, opts->permitlisten[i]); 1083 } 1084 } 1085 } 1086 1087 #ifndef HOST_ONLY 1088 /* Activate a new set of key/cert options; merging with what is there. */ 1089 int 1090 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts) 1091 { 1092 struct sshauthopt *old = auth_opts; 1093 const char *emsg = NULL; 1094 1095 debug("%s: setting new authentication options", __func__); 1096 if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) { 1097 error("Inconsistent authentication options: %s", emsg); 1098 return -1; 1099 } 1100 return 0; 1101 } 1102 1103 /* Disable forwarding, etc for the session */ 1104 void 1105 auth_restrict_session(struct ssh *ssh) 1106 { 1107 struct sshauthopt *restricted; 1108 1109 debug("%s: restricting session", __func__); 1110 1111 /* A blank sshauthopt defaults to permitting nothing */ 1112 restricted = sshauthopt_new(); 1113 restricted->permit_pty_flag = 1; 1114 restricted->restricted = 1; 1115 1116 if (auth_activate_options(ssh, restricted) != 0) 1117 fatal("%s: failed to restrict session", __func__); 1118 sshauthopt_free(restricted); 1119 } 1120 1121 int 1122 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw, 1123 struct sshauthopt *opts, int allow_cert_authority, const char *loc) 1124 { 1125 const char *remote_ip = ssh_remote_ipaddr(ssh); 1126 const char *remote_host = auth_get_canonical_hostname(ssh, 1127 options.use_dns); 1128 time_t now = time(NULL); 1129 char buf[64]; 1130 1131 /* 1132 * Check keys/principals file expiry time. 1133 * NB. validity interval in certificate is handled elsewhere. 1134 */ 1135 if (opts->valid_before && now > 0 && 1136 opts->valid_before < (uint64_t)now) { 1137 format_absolute_time(opts->valid_before, buf, sizeof(buf)); 1138 debug("%s: entry expired at %s", loc, buf); 1139 auth_debug_add("%s: entry expired at %s", loc, buf); 1140 return -1; 1141 } 1142 /* Consistency checks */ 1143 if (opts->cert_principals != NULL && !opts->cert_authority) { 1144 debug("%s: principals on non-CA key", loc); 1145 auth_debug_add("%s: principals on non-CA key", loc); 1146 /* deny access */ 1147 return -1; 1148 } 1149 /* cert-authority flag isn't valid in authorized_principals files */ 1150 if (!allow_cert_authority && opts->cert_authority) { 1151 debug("%s: cert-authority flag invalid here", loc); 1152 auth_debug_add("%s: cert-authority flag invalid here", loc); 1153 /* deny access */ 1154 return -1; 1155 } 1156 1157 /* Perform from= checks */ 1158 if (opts->required_from_host_keys != NULL) { 1159 switch (match_host_and_ip(remote_host, remote_ip, 1160 opts->required_from_host_keys )) { 1161 case 1: 1162 /* Host name matches. */ 1163 break; 1164 case -1: 1165 default: 1166 debug("%s: invalid from criteria", loc); 1167 auth_debug_add("%s: invalid from criteria", loc); 1168 /* FALLTHROUGH */ 1169 case 0: 1170 logit("%s: Authentication tried for %.100s with " 1171 "correct key but not from a permitted " 1172 "host (host=%.200s, ip=%.200s, required=%.200s).", 1173 loc, pw->pw_name, remote_host, remote_ip, 1174 opts->required_from_host_keys); 1175 auth_debug_add("%s: Your host '%.200s' is not " 1176 "permitted to use this key for login.", 1177 loc, remote_host); 1178 /* deny access */ 1179 return -1; 1180 } 1181 } 1182 /* Check source-address restriction from certificate */ 1183 if (opts->required_from_host_cert != NULL) { 1184 switch (addr_match_cidr_list(remote_ip, 1185 opts->required_from_host_cert)) { 1186 case 1: 1187 /* accepted */ 1188 break; 1189 case -1: 1190 default: 1191 /* invalid */ 1192 error("%s: Certificate source-address invalid", 1193 loc); 1194 /* FALLTHROUGH */ 1195 case 0: 1196 logit("%s: Authentication tried for %.100s with valid " 1197 "certificate but not from a permitted source " 1198 "address (%.200s).", loc, pw->pw_name, remote_ip); 1199 auth_debug_add("%s: Your address '%.200s' is not " 1200 "permitted to use this certificate for login.", 1201 loc, remote_ip); 1202 return -1; 1203 } 1204 } 1205 /* 1206 * 1207 * XXX this is spammy. We should report remotely only for keys 1208 * that are successful in actual auth attempts, and not PK_OK 1209 * tests. 1210 */ 1211 auth_log_authopts(loc, opts, 1); 1212 1213 return 0; 1214 } 1215 #endif 1216