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