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