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