1 /* $NetBSD: auth.c,v 1.27 2020/02/27 00:24:40 christos Exp $ */ 2 /* $OpenBSD: auth.c,v 1.146 2020/01/31 22:42:45 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.27 2020/02/27 00:24: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 <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 "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 struct include_list includes; 79 extern int use_privsep; 80 extern struct sshauthopt *auth_opts; 81 82 /* Debugging messages */ 83 static struct sshbuf *auth_debug; 84 85 #ifndef HOST_ONLY 86 /* 87 * Check if the user is allowed to log in via ssh. If user is listed 88 * in DenyUsers or one of user's groups is listed in DenyGroups, false 89 * will be returned. If AllowUsers isn't empty and user isn't listed 90 * there, or if AllowGroups isn't empty and one of user's groups isn't 91 * listed there, false will be returned. 92 * If the user's shell is not executable, false will be returned. 93 * Otherwise true is returned. 94 */ 95 int 96 allowed_user(struct ssh *ssh, struct passwd * pw) 97 { 98 #ifdef HAVE_LOGIN_CAP 99 extern login_cap_t *lc; 100 int match_name, match_ip; 101 char *cap_hlist, *hp; 102 #endif 103 struct stat st; 104 const char *hostname = NULL, *ipaddr = NULL; 105 int r; 106 u_int i; 107 108 /* Shouldn't be called if pw is NULL, but better safe than sorry... */ 109 if (!pw || !pw->pw_name) 110 return 0; 111 112 #ifdef HAVE_LOGIN_CAP 113 hostname = auth_get_canonical_hostname(ssh, options.use_dns); 114 ipaddr = ssh_remote_ipaddr(ssh); 115 116 lc = login_getclass(pw->pw_class); 117 118 /* 119 * Check the deny list. 120 */ 121 cap_hlist = login_getcapstr(lc, "host.deny", NULL, NULL); 122 if (cap_hlist != NULL) { 123 hp = strtok(cap_hlist, ","); 124 while (hp != NULL) { 125 match_name = match_hostname(hostname, hp); 126 match_ip = match_hostname(ipaddr, hp); 127 /* 128 * Only a positive match here causes a "deny". 129 */ 130 if (match_name > 0 || match_ip > 0) { 131 free(cap_hlist); 132 login_close(lc); 133 return 0; 134 } 135 hp = strtok(NULL, ","); 136 } 137 free(cap_hlist); 138 } 139 140 /* 141 * Check the allow list. If the allow list exists, and the 142 * remote host is not in it, the user is implicitly denied. 143 */ 144 cap_hlist = login_getcapstr(lc, "host.allow", NULL, NULL); 145 if (cap_hlist != NULL) { 146 hp = strtok(cap_hlist, ","); 147 if (hp == NULL) { 148 /* Just in case there's an empty string... */ 149 free(cap_hlist); 150 login_close(lc); 151 return 0; 152 } 153 while (hp != NULL) { 154 match_name = match_hostname(hostname, hp); 155 match_ip = match_hostname(ipaddr, hp); 156 /* 157 * Negative match causes an immediate "deny". 158 * Positive match causes us to break out 159 * of the loop (allowing a fallthrough). 160 */ 161 if (match_name < 0 || match_ip < 0) { 162 free(cap_hlist); 163 login_close(lc); 164 return 0; 165 } 166 if (match_name > 0 || match_ip > 0) 167 break; 168 hp = strtok(NULL, ","); 169 } 170 free(cap_hlist); 171 if (hp == NULL) { 172 login_close(lc); 173 return 0; 174 } 175 } 176 177 login_close(lc); 178 #endif 179 180 #ifdef USE_PAM 181 if (!options.use_pam) { 182 #endif 183 /* 184 * password/account expiration. 185 */ 186 if (pw->pw_change || pw->pw_expire) { 187 struct timeval tv; 188 189 (void)gettimeofday(&tv, (struct timezone *)NULL); 190 if (pw->pw_expire) { 191 if (tv.tv_sec >= pw->pw_expire) { 192 logit("User %.100s not allowed because account has expired", 193 pw->pw_name); 194 return 0; /* expired */ 195 } 196 } 197 #ifdef _PASSWORD_CHGNOW 198 if (pw->pw_change == _PASSWORD_CHGNOW) { 199 logit("User %.100s not allowed because password needs to be changed", 200 pw->pw_name); 201 202 return 0; /* can't force password change (yet) */ 203 } 204 #endif 205 if (pw->pw_change) { 206 if (tv.tv_sec >= pw->pw_change) { 207 logit("User %.100s not allowed because password has expired", 208 pw->pw_name); 209 return 0; /* expired */ 210 } 211 } 212 } 213 #ifdef USE_PAM 214 } 215 #endif 216 217 /* 218 * Deny if shell does not exist or is not executable unless we 219 * are chrooting. 220 */ 221 /* 222 * XXX Should check to see if it is executable by the 223 * XXX requesting user. --thorpej 224 */ 225 if (options.chroot_directory == NULL || 226 strcasecmp(options.chroot_directory, "none") == 0) { 227 char *shell = xstrdup((pw->pw_shell[0] == '\0') ? 228 _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */ 229 230 if (stat(shell, &st) == -1) { 231 logit("User %.100s not allowed because shell %.100s " 232 "does not exist", pw->pw_name, shell); 233 free(shell); 234 return 0; 235 } 236 if (S_ISREG(st.st_mode) == 0 || 237 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) { 238 logit("User %.100s not allowed because shell %.100s " 239 "is not executable", pw->pw_name, shell); 240 free(shell); 241 return 0; 242 } 243 free(shell); 244 } 245 /* 246 * XXX Consider nuking {Allow,Deny}{Users,Groups}. We have the 247 * XXX login_cap(3) mechanism which covers all other types of 248 * XXX logins, too. 249 */ 250 251 if (options.num_deny_users > 0 || options.num_allow_users > 0 || 252 options.num_deny_groups > 0 || options.num_allow_groups > 0) { 253 hostname = auth_get_canonical_hostname(ssh, options.use_dns); 254 ipaddr = ssh_remote_ipaddr(ssh); 255 } 256 257 /* Return false if user is listed in DenyUsers */ 258 if (options.num_deny_users > 0) { 259 for (i = 0; i < options.num_deny_users; i++) { 260 r = match_user(pw->pw_name, hostname, ipaddr, 261 options.deny_users[i]); 262 if (r < 0) { 263 fatal("Invalid DenyUsers pattern \"%.100s\"", 264 options.deny_users[i]); 265 } else if (r != 0) { 266 logit("User %.100s from %.100s not allowed " 267 "because listed in DenyUsers", 268 pw->pw_name, hostname); 269 return 0; 270 } 271 } 272 } 273 /* Return false if AllowUsers isn't empty and user isn't listed there */ 274 if (options.num_allow_users > 0) { 275 for (i = 0; i < options.num_allow_users; i++) { 276 r = match_user(pw->pw_name, hostname, ipaddr, 277 options.allow_users[i]); 278 if (r < 0) { 279 fatal("Invalid AllowUsers pattern \"%.100s\"", 280 options.allow_users[i]); 281 } else if (r == 1) 282 break; 283 } 284 /* i < options.num_allow_users iff we break for loop */ 285 if (i >= options.num_allow_users) { 286 logit("User %.100s from %.100s not allowed because " 287 "not listed in AllowUsers", pw->pw_name, hostname); 288 return 0; 289 } 290 } 291 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) { 292 /* Get the user's group access list (primary and supplementary) */ 293 if (ga_init(pw->pw_name, pw->pw_gid) == 0) { 294 logit("User %.100s from %.100s not allowed because " 295 "not in any group", pw->pw_name, hostname); 296 return 0; 297 } 298 299 /* Return false if one of user's groups is listed in DenyGroups */ 300 if (options.num_deny_groups > 0) 301 if (ga_match(options.deny_groups, 302 options.num_deny_groups)) { 303 ga_free(); 304 logit("User %.100s from %.100s not allowed " 305 "because a group is listed in DenyGroups", 306 pw->pw_name, hostname); 307 return 0; 308 } 309 /* 310 * Return false if AllowGroups isn't empty and one of user's groups 311 * isn't listed there 312 */ 313 if (options.num_allow_groups > 0) 314 if (!ga_match(options.allow_groups, 315 options.num_allow_groups)) { 316 ga_free(); 317 logit("User %.100s from %.100s not allowed " 318 "because none of user's groups are listed " 319 "in AllowGroups", pw->pw_name, hostname); 320 return 0; 321 } 322 ga_free(); 323 } 324 /* We found no reason not to let this user try to log on... */ 325 return 1; 326 } 327 328 /* 329 * Formats any key left in authctxt->auth_method_key for inclusion in 330 * auth_log()'s message. Also includes authxtct->auth_method_info if present. 331 */ 332 static char * 333 format_method_key(Authctxt *authctxt) 334 { 335 const struct sshkey *key = authctxt->auth_method_key; 336 const char *methinfo = authctxt->auth_method_info; 337 char *fp, *cafp, *ret = NULL; 338 339 if (key == NULL) 340 return NULL; 341 342 if (sshkey_is_cert(key)) { 343 fp = sshkey_fingerprint(key, 344 options.fingerprint_hash, SSH_FP_DEFAULT); 345 cafp = sshkey_fingerprint(key->cert->signature_key, 346 options.fingerprint_hash, SSH_FP_DEFAULT); 347 xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s", 348 sshkey_type(key), fp == NULL ? "(null)" : fp, 349 key->cert->key_id, 350 (unsigned long long)key->cert->serial, 351 sshkey_type(key->cert->signature_key), 352 cafp == NULL ? "(null)" : cafp, 353 methinfo == NULL ? "" : ", ", 354 methinfo == NULL ? "" : methinfo); 355 free(fp); 356 free(cafp); 357 } else { 358 fp = sshkey_fingerprint(key, options.fingerprint_hash, 359 SSH_FP_DEFAULT); 360 xasprintf(&ret, "%s %s%s%s", sshkey_type(key), 361 fp == NULL ? "(null)" : fp, 362 methinfo == NULL ? "" : ", ", 363 methinfo == NULL ? "" : methinfo); 364 free(fp); 365 } 366 return ret; 367 } 368 369 void 370 auth_log(struct ssh *ssh, int authenticated, int partial, 371 const char *method, const char *submethod) 372 { 373 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 374 int level = SYSLOG_LEVEL_VERBOSE; 375 const char *authmsg; 376 char *extra = NULL; 377 378 if (use_privsep && !mm_is_monitor() && !authctxt->postponed) 379 return; 380 381 /* Raise logging level */ 382 if (authenticated == 1 || 383 !authctxt->valid || 384 authctxt->failures >= options.max_authtries / 2 || 385 strcmp(method, "password") == 0) 386 level = SYSLOG_LEVEL_INFO; 387 388 if (authctxt->postponed) 389 authmsg = "Postponed"; 390 else if (partial) 391 authmsg = "Partial"; 392 else 393 authmsg = authenticated ? "Accepted" : "Failed"; 394 395 if ((extra = format_method_key(authctxt)) == NULL) { 396 if (authctxt->auth_method_info != NULL) 397 extra = xstrdup(authctxt->auth_method_info); 398 } 399 400 do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s", 401 authmsg, 402 method, 403 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod, 404 authctxt->valid ? "" : "invalid user ", 405 authctxt->user, 406 ssh_remote_ipaddr(ssh), 407 ssh_remote_port(ssh), 408 extra != NULL ? ": " : "", 409 extra != NULL ? extra : ""); 410 411 free(extra); 412 } 413 414 void 415 auth_maxtries_exceeded(struct ssh *ssh) 416 { 417 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 418 419 error("maximum authentication attempts exceeded for " 420 "%s%.100s from %.200s port %d ssh2", 421 authctxt->valid ? "" : "invalid user ", 422 authctxt->user, 423 ssh_remote_ipaddr(ssh), 424 ssh_remote_port(ssh)); 425 ssh_packet_disconnect(ssh, "Too many authentication failures"); 426 /* NOTREACHED */ 427 } 428 429 /* 430 * Check whether root logins are disallowed. 431 */ 432 int 433 auth_root_allowed(struct ssh *ssh, const char *method) 434 { 435 switch (options.permit_root_login) { 436 case PERMIT_YES: 437 return 1; 438 case PERMIT_NO_PASSWD: 439 if (strcmp(method, "publickey") == 0 || 440 strcmp(method, "hostbased") == 0 || 441 strcmp(method, "gssapi-with-mic") == 0) 442 return 1; 443 break; 444 case PERMIT_FORCED_ONLY: 445 if (auth_opts->force_command != NULL) { 446 logit("Root login accepted for forced command."); 447 return 1; 448 } 449 break; 450 } 451 logit("ROOT LOGIN REFUSED FROM %.200s port %d", 452 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 453 return 0; 454 } 455 456 457 /* 458 * Given a template and a passwd structure, build a filename 459 * by substituting % tokenised options. Currently, %% becomes '%', 460 * %h becomes the home directory and %u the username. 461 * 462 * This returns a buffer allocated by xmalloc. 463 */ 464 char * 465 expand_authorized_keys(const char *filename, struct passwd *pw) 466 { 467 char *file, uidstr[32], ret[PATH_MAX]; 468 int i; 469 470 snprintf(uidstr, sizeof(uidstr), "%llu", 471 (unsigned long long)pw->pw_uid); 472 file = percent_expand(filename, "h", pw->pw_dir, 473 "u", pw->pw_name, "U", uidstr, (char *)NULL); 474 475 /* 476 * Ensure that filename starts anchored. If not, be backward 477 * compatible and prepend the '%h/' 478 */ 479 if (path_absolute(file)) 480 return (file); 481 482 i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file); 483 if (i < 0 || (size_t)i >= sizeof(ret)) 484 fatal("expand_authorized_keys: path too long"); 485 free(file); 486 return (xstrdup(ret)); 487 } 488 489 char * 490 authorized_principals_file(struct passwd *pw) 491 { 492 if (options.authorized_principals_file == NULL) 493 return NULL; 494 return expand_authorized_keys(options.authorized_principals_file, pw); 495 } 496 497 /* return ok if key exists in sysfile or userfile */ 498 HostStatus 499 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host, 500 const char *sysfile, const char *userfile) 501 { 502 char *user_hostfile; 503 struct stat st; 504 HostStatus host_status; 505 struct hostkeys *hostkeys; 506 const struct hostkey_entry *found; 507 508 hostkeys = init_hostkeys(); 509 load_hostkeys(hostkeys, host, sysfile); 510 if (userfile != NULL) { 511 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid); 512 if (options.strict_modes && 513 (stat(user_hostfile, &st) == 0) && 514 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) || 515 (st.st_mode & 022) != 0)) { 516 logit("Authentication refused for %.100s: " 517 "bad owner or modes for %.200s", 518 pw->pw_name, user_hostfile); 519 auth_debug_add("Ignored %.200s: bad ownership or modes", 520 user_hostfile); 521 } else { 522 temporarily_use_uid(pw); 523 load_hostkeys(hostkeys, host, user_hostfile); 524 restore_uid(); 525 } 526 free(user_hostfile); 527 } 528 host_status = check_key_in_hostkeys(hostkeys, key, &found); 529 if (host_status == HOST_REVOKED) 530 error("WARNING: revoked key for %s attempted authentication", 531 host); 532 else if (host_status == HOST_OK) 533 debug("%s: key for %s found at %s:%ld", __func__, 534 found->host, found->file, found->line); 535 else 536 debug("%s: key for host %s not found", __func__, host); 537 538 free_hostkeys(hostkeys); 539 540 return host_status; 541 } 542 543 static FILE * 544 auth_openfile(const char *file, struct passwd *pw, int strict_modes, 545 int log_missing, const char *file_type) 546 { 547 char line[1024]; 548 struct stat st; 549 int fd; 550 FILE *f; 551 552 if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) { 553 if (log_missing || errno != ENOENT) 554 debug("Could not open %s '%s': %s", file_type, file, 555 strerror(errno)); 556 return NULL; 557 } 558 559 if (fstat(fd, &st) == -1) { 560 close(fd); 561 return NULL; 562 } 563 if (!S_ISREG(st.st_mode)) { 564 logit("User %s %s %s is not a regular file", 565 pw->pw_name, file_type, file); 566 close(fd); 567 return NULL; 568 } 569 unset_nonblock(fd); 570 if ((f = fdopen(fd, "r")) == NULL) { 571 close(fd); 572 return NULL; 573 } 574 if (strict_modes && 575 safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) { 576 fclose(f); 577 logit("Authentication refused: %s", line); 578 auth_debug_add("Ignored %s: %s", file_type, line); 579 return NULL; 580 } 581 582 return f; 583 } 584 585 586 FILE * 587 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes) 588 { 589 return auth_openfile(file, pw, strict_modes, 1, "authorized keys"); 590 } 591 592 FILE * 593 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes) 594 { 595 return auth_openfile(file, pw, strict_modes, 0, 596 "authorized principals"); 597 } 598 599 struct passwd * 600 getpwnamallow(struct ssh *ssh, const char *user) 601 { 602 #ifdef HAVE_LOGIN_CAP 603 extern login_cap_t *lc; 604 #ifdef BSD_AUTH 605 auth_session_t *as; 606 #endif 607 #endif 608 struct passwd *pw; 609 struct connection_info *ci; 610 611 ci = get_connection_info(ssh, 1, options.use_dns); 612 ci->user = user; 613 parse_server_match_config(&options, &includes, ci); 614 log_change_level(options.log_level); 615 process_permitopen(ssh, &options); 616 617 pw = getpwnam(user); 618 if (pw == NULL) { 619 pfilter_notify(1); 620 logit("Invalid user %.100s from %.100s port %d", 621 user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 622 return (NULL); 623 } 624 if (!allowed_user(ssh, pw)) 625 return (NULL); 626 #ifdef HAVE_LOGIN_CAP 627 if ((lc = login_getclass(pw->pw_class)) == NULL) { 628 debug("unable to get login class: %s", user); 629 return (NULL); 630 } 631 #ifdef BSD_AUTH 632 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 || 633 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) { 634 debug("Approval failure for %s", user); 635 pw = NULL; 636 } 637 if (as != NULL) 638 auth_close(as); 639 #endif 640 #endif 641 if (pw != NULL) 642 return (pwcopy(pw)); 643 return (NULL); 644 } 645 646 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */ 647 int 648 auth_key_is_revoked(struct sshkey *key) 649 { 650 char *fp = NULL; 651 int r; 652 653 if (options.revoked_keys_file == NULL) 654 return 0; 655 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, 656 SSH_FP_DEFAULT)) == NULL) { 657 r = SSH_ERR_ALLOC_FAIL; 658 error("%s: fingerprint key: %s", __func__, ssh_err(r)); 659 goto out; 660 } 661 662 r = sshkey_check_revoked(key, options.revoked_keys_file); 663 switch (r) { 664 case 0: 665 break; /* not revoked */ 666 case SSH_ERR_KEY_REVOKED: 667 error("Authentication key %s %s revoked by file %s", 668 sshkey_type(key), fp, options.revoked_keys_file); 669 goto out; 670 default: 671 error("Error checking authentication key %s %s in " 672 "revoked keys file %s: %s", sshkey_type(key), fp, 673 options.revoked_keys_file, ssh_err(r)); 674 goto out; 675 } 676 677 /* Success */ 678 r = 0; 679 680 out: 681 free(fp); 682 return r == 0 ? 0 : 1; 683 } 684 #endif 685 686 void 687 auth_debug_add(const char *fmt,...) 688 { 689 char buf[1024]; 690 va_list args; 691 int r; 692 693 if (auth_debug == NULL) 694 return; 695 696 va_start(args, fmt); 697 vsnprintf(buf, sizeof(buf), fmt, args); 698 va_end(args); 699 if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0) 700 fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r)); 701 } 702 703 void 704 auth_debug_send(struct ssh *ssh) 705 { 706 char *msg; 707 int r; 708 709 if (auth_debug == NULL) 710 return; 711 while (sshbuf_len(auth_debug) != 0) { 712 if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0) 713 fatal("%s: sshbuf_get_cstring: %s", 714 __func__, ssh_err(r)); 715 ssh_packet_send_debug(ssh, "%s", msg); 716 free(msg); 717 } 718 } 719 720 void 721 auth_debug_reset(void) 722 { 723 if (auth_debug != NULL) 724 sshbuf_reset(auth_debug); 725 else if ((auth_debug = sshbuf_new()) == NULL) 726 fatal("%s: sshbuf_new failed", __func__); 727 } 728 729 struct passwd * 730 fakepw(void) 731 { 732 static struct passwd fake; 733 static char nouser[] = "NOUSER"; 734 static char nonexist[] = "/nonexist"; 735 736 memset(&fake, 0, sizeof(fake)); 737 fake.pw_name = nouser; 738 fake.pw_passwd = __UNCONST( 739 "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK"); 740 fake.pw_gecos = nouser; 741 fake.pw_uid = (uid_t)-1; 742 fake.pw_gid = (gid_t)-1; 743 fake.pw_class = __UNCONST(""); 744 fake.pw_dir = nonexist; 745 fake.pw_shell = nonexist; 746 747 return (&fake); 748 } 749 750 /* 751 * Returns the remote DNS hostname as a string. The returned string must not 752 * be freed. NB. this will usually trigger a DNS query the first time it is 753 * called. 754 * This function does additional checks on the hostname to mitigate some 755 * attacks on legacy rhosts-style authentication. 756 * XXX is RhostsRSAAuthentication vulnerable to these? 757 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?) 758 */ 759 760 static char * 761 remote_hostname(struct ssh *ssh) 762 { 763 struct sockaddr_storage from; 764 socklen_t fromlen; 765 struct addrinfo hints, *ai, *aitop; 766 char name[NI_MAXHOST], ntop2[NI_MAXHOST]; 767 const char *ntop = ssh_remote_ipaddr(ssh); 768 769 /* Get IP address of client. */ 770 fromlen = sizeof(from); 771 memset(&from, 0, sizeof(from)); 772 if (getpeername(ssh_packet_get_connection_in(ssh), 773 (struct sockaddr *)&from, &fromlen) == -1) { 774 debug("getpeername failed: %.100s", strerror(errno)); 775 return xstrdup(ntop); 776 } 777 778 debug3("Trying to reverse map address %.100s.", ntop); 779 /* Map the IP address to a host name. */ 780 if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name), 781 NULL, 0, NI_NAMEREQD) != 0) { 782 /* Host name not found. Use ip address. */ 783 return xstrdup(ntop); 784 } 785 786 /* 787 * if reverse lookup result looks like a numeric hostname, 788 * someone is trying to trick us by PTR record like following: 789 * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5 790 */ 791 memset(&hints, 0, sizeof(hints)); 792 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 793 hints.ai_flags = AI_NUMERICHOST; 794 if (getaddrinfo(name, NULL, &hints, &ai) == 0) { 795 logit("Nasty PTR record \"%s\" is set up for %s, ignoring", 796 name, ntop); 797 freeaddrinfo(ai); 798 return xstrdup(ntop); 799 } 800 801 /* Names are stored in lowercase. */ 802 lowercase(name); 803 804 /* 805 * Map it back to an IP address and check that the given 806 * address actually is an address of this host. This is 807 * necessary because anyone with access to a name server can 808 * define arbitrary names for an IP address. Mapping from 809 * name to IP address can be trusted better (but can still be 810 * fooled if the intruder has access to the name server of 811 * the domain). 812 */ 813 memset(&hints, 0, sizeof(hints)); 814 hints.ai_family = from.ss_family; 815 hints.ai_socktype = SOCK_STREAM; 816 if (getaddrinfo(name, NULL, &hints, &aitop) != 0) { 817 logit("reverse mapping checking getaddrinfo for %.700s " 818 "[%s] failed.", name, ntop); 819 return xstrdup(ntop); 820 } 821 /* Look for the address from the list of addresses. */ 822 for (ai = aitop; ai; ai = ai->ai_next) { 823 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2, 824 sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 && 825 (strcmp(ntop, ntop2) == 0)) 826 break; 827 } 828 freeaddrinfo(aitop); 829 /* If we reached the end of the list, the address was not there. */ 830 if (ai == NULL) { 831 /* Address not found for the host name. */ 832 logit("Address %.100s maps to %.600s, but this does not " 833 "map back to the address.", ntop, name); 834 return xstrdup(ntop); 835 } 836 return xstrdup(name); 837 } 838 839 /* 840 * Return the canonical name of the host in the other side of the current 841 * connection. The host name is cached, so it is efficient to call this 842 * several times. 843 */ 844 845 const char * 846 auth_get_canonical_hostname(struct ssh *ssh, int use_dns) 847 { 848 static char *dnsname; 849 850 if (!use_dns) 851 return ssh_remote_ipaddr(ssh); 852 else if (dnsname != NULL) 853 return dnsname; 854 else { 855 dnsname = remote_hostname(ssh); 856 return dnsname; 857 } 858 } 859 860 /* 861 * Runs command in a subprocess with a minimal environment. 862 * Returns pid on success, 0 on failure. 863 * The child stdout and stderr maybe captured, left attached or sent to 864 * /dev/null depending on the contents of flags. 865 * "tag" is prepended to log messages. 866 * NB. "command" is only used for logging; the actual command executed is 867 * av[0]. 868 */ 869 pid_t 870 subprocess(const char *tag, struct passwd *pw, const char *command, 871 int ac, char **av, FILE **child, u_int flags) 872 { 873 FILE *f = NULL; 874 struct stat st; 875 int fd, devnull, p[2], i; 876 pid_t pid; 877 char *cp, errmsg[512]; 878 u_int envsize; 879 char **child_env; 880 881 if (child != NULL) 882 *child = NULL; 883 884 debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__, 885 tag, command, pw->pw_name, flags); 886 887 /* Check consistency */ 888 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 && 889 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) { 890 error("%s: inconsistent flags", __func__); 891 return 0; 892 } 893 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) { 894 error("%s: inconsistent flags/output", __func__); 895 return 0; 896 } 897 898 /* 899 * If executing an explicit binary, then verify the it exists 900 * and appears safe-ish to execute 901 */ 902 if (!path_absolute(av[0])) { 903 error("%s path is not absolute", tag); 904 return 0; 905 } 906 temporarily_use_uid(pw); 907 if (stat(av[0], &st) == -1) { 908 error("Could not stat %s \"%s\": %s", tag, 909 av[0], strerror(errno)); 910 restore_uid(); 911 return 0; 912 } 913 if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) { 914 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg); 915 restore_uid(); 916 return 0; 917 } 918 /* Prepare to keep the child's stdout if requested */ 919 if (pipe(p) == -1) { 920 error("%s: pipe: %s", tag, strerror(errno)); 921 restore_uid(); 922 return 0; 923 } 924 restore_uid(); 925 926 switch ((pid = fork())) { 927 case -1: /* error */ 928 error("%s: fork: %s", tag, strerror(errno)); 929 close(p[0]); 930 close(p[1]); 931 return 0; 932 case 0: /* child */ 933 /* Prepare a minimal environment for the child. */ 934 envsize = 5; 935 child_env = xcalloc(sizeof(*child_env), envsize); 936 child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH); 937 child_set_env(&child_env, &envsize, "USER", pw->pw_name); 938 child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name); 939 child_set_env(&child_env, &envsize, "HOME", pw->pw_dir); 940 if ((cp = getenv("LANG")) != NULL) 941 child_set_env(&child_env, &envsize, "LANG", cp); 942 943 for (i = 0; i < NSIG; i++) 944 ssh_signal(i, SIG_DFL); 945 946 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { 947 error("%s: open %s: %s", tag, _PATH_DEVNULL, 948 strerror(errno)); 949 _exit(1); 950 } 951 if (dup2(devnull, STDIN_FILENO) == -1) { 952 error("%s: dup2: %s", tag, strerror(errno)); 953 _exit(1); 954 } 955 956 /* Set up stdout as requested; leave stderr in place for now. */ 957 fd = -1; 958 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) 959 fd = p[1]; 960 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0) 961 fd = devnull; 962 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) { 963 error("%s: dup2: %s", tag, strerror(errno)); 964 _exit(1); 965 } 966 closefrom(STDERR_FILENO + 1); 967 968 /* Don't use permanently_set_uid() here to avoid fatal() */ 969 #ifdef __NetBSD__ 970 #define setresgid(a, b, c) setgid(a) 971 #define setresuid(a, b, c) setuid(a) 972 #endif 973 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) { 974 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid, 975 strerror(errno)); 976 _exit(1); 977 } 978 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) { 979 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid, 980 strerror(errno)); 981 _exit(1); 982 } 983 /* stdin is pointed to /dev/null at this point */ 984 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 && 985 dup2(STDIN_FILENO, STDERR_FILENO) == -1) { 986 error("%s: dup2: %s", tag, strerror(errno)); 987 _exit(1); 988 } 989 990 execve(av[0], av, child_env); 991 error("%s exec \"%s\": %s", tag, command, strerror(errno)); 992 _exit(127); 993 default: /* parent */ 994 break; 995 } 996 997 close(p[1]); 998 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) 999 close(p[0]); 1000 else if ((f = fdopen(p[0], "r")) == NULL) { 1001 error("%s: fdopen: %s", tag, strerror(errno)); 1002 close(p[0]); 1003 /* Don't leave zombie child */ 1004 kill(pid, SIGTERM); 1005 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR) 1006 ; 1007 return 0; 1008 } 1009 /* Success */ 1010 debug3("%s: %s pid %ld", __func__, tag, (long)pid); 1011 if (child != NULL) 1012 *child = f; 1013 return pid; 1014 } 1015 1016 /* These functions link key/cert options to the auth framework */ 1017 1018 /* Log sshauthopt options locally and (optionally) for remote transmission */ 1019 void 1020 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote) 1021 { 1022 int do_env = options.permit_user_env && opts->nenv > 0; 1023 int do_permitopen = opts->npermitopen > 0 && 1024 (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0; 1025 int do_permitlisten = opts->npermitlisten > 0 && 1026 (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0; 1027 size_t i; 1028 char msg[1024], buf[64]; 1029 1030 snprintf(buf, sizeof(buf), "%d", opts->force_tun_device); 1031 /* Try to keep this alphabetically sorted */ 1032 snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s", 1033 opts->permit_agent_forwarding_flag ? " agent-forwarding" : "", 1034 opts->force_command == NULL ? "" : " command", 1035 do_env ? " environment" : "", 1036 opts->valid_before == 0 ? "" : "expires", 1037 do_permitopen ? " permitopen" : "", 1038 do_permitlisten ? " permitlisten" : "", 1039 opts->permit_port_forwarding_flag ? " port-forwarding" : "", 1040 opts->cert_principals == NULL ? "" : " principals", 1041 opts->permit_pty_flag ? " pty" : "", 1042 opts->force_tun_device == -1 ? "" : " tun=", 1043 opts->force_tun_device == -1 ? "" : buf, 1044 opts->permit_user_rc ? " user-rc" : "", 1045 opts->permit_x11_forwarding_flag ? " x11-forwarding" : "", 1046 opts->no_require_user_presence ? " no-touch-required" : ""); 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