1 /* $NetBSD: sshconnect.c,v 1.7 2012/04/27 15:45:37 tls Exp $ */ 2 /* $OpenBSD: sshconnect.c,v 1.234 2011/05/24 07:15:47 djm Exp $ */ 3 /* 4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 6 * All rights reserved 7 * Code to connect to a remote host, and to perform the client side of the 8 * login (authentication) dialog. 9 * 10 * As far as I am concerned, the code I have written for this software 11 * can be used freely for any purpose. Any derived versions of this 12 * software must be clearly marked as such, and if the derived work is 13 * incompatible with the protocol description in the RFC file, it must be 14 * called by a name other than "ssh" or "Secure Shell". 15 */ 16 17 #include "includes.h" 18 __RCSID("$NetBSD: sshconnect.c,v 1.7 2012/04/27 15:45:37 tls Exp $"); 19 #include <sys/types.h> 20 #include <sys/param.h> 21 #include <sys/wait.h> 22 #include <sys/stat.h> 23 #include <sys/socket.h> 24 #include <sys/time.h> 25 26 #include <netinet/in.h> 27 28 #include <ctype.h> 29 #include <errno.h> 30 #include <fcntl.h> 31 #include <netdb.h> 32 #include <paths.h> 33 #include <signal.h> 34 #include <pwd.h> 35 #include <stdio.h> 36 #include <stdlib.h> 37 #include <string.h> 38 #include <unistd.h> 39 40 #include "xmalloc.h" 41 #include "ssh.h" 42 #include "rsa.h" 43 #include "buffer.h" 44 #include "packet.h" 45 #include "uidswap.h" 46 #include "compat.h" 47 #include "key.h" 48 #include "sshconnect.h" 49 #include "hostfile.h" 50 #include "log.h" 51 #include "readconf.h" 52 #include "atomicio.h" 53 #include "misc.h" 54 #include "dns.h" 55 #include "roaming.h" 56 #include "ssh2.h" 57 #include "version.h" 58 59 char *client_version_string = NULL; 60 char *server_version_string = NULL; 61 62 static int matching_host_key_dns = 0; 63 64 static pid_t proxy_command_pid = 0; 65 66 /* import */ 67 extern Options options; 68 extern char *__progname; 69 extern uid_t original_real_uid; 70 extern uid_t original_effective_uid; 71 72 static int show_other_keys(struct hostkeys *, Key *); 73 static void warn_changed_key(Key *); 74 75 /* 76 * Connect to the given ssh server using a proxy command. 77 */ 78 static int 79 ssh_proxy_connect(const char *host, u_short port, const char *proxy_command) 80 { 81 char *command_string, *tmp; 82 int pin[2], pout[2]; 83 pid_t pid; 84 char *shell, strport[NI_MAXSERV]; 85 86 if ((shell = getenv("SHELL")) == NULL || *shell == '\0') 87 shell = __UNCONST(_PATH_BSHELL); 88 89 /* Convert the port number into a string. */ 90 snprintf(strport, sizeof strport, "%hu", port); 91 92 /* 93 * Build the final command string in the buffer by making the 94 * appropriate substitutions to the given proxy command. 95 * 96 * Use "exec" to avoid "sh -c" processes on some platforms 97 * (e.g. Solaris) 98 */ 99 xasprintf(&tmp, "exec %s", proxy_command); 100 command_string = percent_expand(tmp, "h", host, "p", strport, 101 "r", options.user, (char *)NULL); 102 xfree(tmp); 103 104 /* Create pipes for communicating with the proxy. */ 105 if (pipe(pin) < 0 || pipe(pout) < 0) 106 fatal("Could not create pipes to communicate with the proxy: %.100s", 107 strerror(errno)); 108 109 debug("Executing proxy command: %.500s", command_string); 110 111 /* Fork and execute the proxy command. */ 112 if ((pid = fork()) == 0) { 113 char *argv[10]; 114 115 /* Child. Permanently give up superuser privileges. */ 116 permanently_drop_suid(original_real_uid); 117 118 /* Redirect stdin and stdout. */ 119 close(pin[1]); 120 if (pin[0] != 0) { 121 if (dup2(pin[0], 0) < 0) 122 perror("dup2 stdin"); 123 close(pin[0]); 124 } 125 close(pout[0]); 126 if (dup2(pout[1], 1) < 0) 127 perror("dup2 stdout"); 128 /* Cannot be 1 because pin allocated two descriptors. */ 129 close(pout[1]); 130 131 /* Stderr is left as it is so that error messages get 132 printed on the user's terminal. */ 133 argv[0] = shell; 134 argv[1] = __UNCONST("-c"); 135 argv[2] = command_string; 136 argv[3] = NULL; 137 138 /* Execute the proxy command. Note that we gave up any 139 extra privileges above. */ 140 signal(SIGPIPE, SIG_DFL); 141 execv(argv[0], argv); 142 perror(argv[0]); 143 exit(1); 144 } 145 /* Parent. */ 146 if (pid < 0) 147 fatal("fork failed: %.100s", strerror(errno)); 148 else 149 proxy_command_pid = pid; /* save pid to clean up later */ 150 151 /* Close child side of the descriptors. */ 152 close(pin[0]); 153 close(pout[1]); 154 155 /* Free the command name. */ 156 xfree(command_string); 157 158 /* Set the connection file descriptors. */ 159 packet_set_connection(pout[0], pin[1]); 160 packet_set_timeout(options.server_alive_interval, 161 options.server_alive_count_max); 162 163 /* Indicate OK return */ 164 return 0; 165 } 166 167 void 168 ssh_kill_proxy_command(void) 169 { 170 /* 171 * Send SIGHUP to proxy command if used. We don't wait() in 172 * case it hangs and instead rely on init to reap the child 173 */ 174 if (proxy_command_pid > 1) 175 kill(proxy_command_pid, SIGHUP); 176 } 177 178 /* 179 * Set TCP receive buffer if requested. 180 * Note: tuning needs to happen after the socket is 181 * created but before the connection happens 182 * so winscale is negotiated properly -cjr 183 */ 184 static void 185 ssh_set_socket_recvbuf(int sock) 186 { 187 void *buf = (void *)&options.tcp_rcv_buf; 188 int sz = sizeof(options.tcp_rcv_buf); 189 int socksize; 190 socklen_t socksizelen = sizeof(int); 191 192 debug("setsockopt Attempting to set SO_RCVBUF to %d", options.tcp_rcv_buf); 193 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, buf, sz) >= 0) { 194 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &socksize, &socksizelen); 195 debug("setsockopt SO_RCVBUF: %.100s %d", strerror(errno), socksize); 196 } 197 else 198 error("Couldn't set socket receive buffer to %d: %.100s", 199 options.tcp_rcv_buf, strerror(errno)); 200 } 201 202 /* 203 * Creates a (possibly privileged) socket for use as the ssh connection. 204 */ 205 static int 206 ssh_create_socket(int privileged, struct addrinfo *ai) 207 { 208 int sock, gaierr; 209 struct addrinfo hints, *res; 210 211 /* 212 * If we are running as root and want to connect to a privileged 213 * port, bind our own socket to a privileged port. 214 */ 215 if (privileged) { 216 int p = IPPORT_RESERVED - 1; 217 PRIV_START; 218 sock = rresvport_af(&p, ai->ai_family); 219 PRIV_END; 220 if (sock < 0) 221 error("rresvport: af=%d %.100s", ai->ai_family, 222 strerror(errno)); 223 else 224 debug("Allocated local port %d.", p); 225 226 if (options.tcp_rcv_buf > 0) 227 ssh_set_socket_recvbuf(sock); 228 return sock; 229 } 230 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); 231 if (sock < 0) { 232 switch (errno) { 233 case EAFNOSUPPORT: 234 debug("socket: %.100s", strerror(errno)); 235 break; 236 default: 237 error("socket: %.100s", strerror(errno)); 238 } 239 return -1; 240 } 241 fcntl(sock, F_SETFD, FD_CLOEXEC); 242 243 if (options.tcp_rcv_buf > 0) 244 ssh_set_socket_recvbuf(sock); 245 246 /* Bind the socket to an alternative local IP address */ 247 if (options.bind_address == NULL) 248 return sock; 249 250 memset(&hints, 0, sizeof(hints)); 251 hints.ai_family = ai->ai_family; 252 hints.ai_socktype = ai->ai_socktype; 253 hints.ai_protocol = ai->ai_protocol; 254 hints.ai_flags = AI_PASSIVE; 255 gaierr = getaddrinfo(options.bind_address, NULL, &hints, &res); 256 if (gaierr) { 257 error("getaddrinfo: %s: %s", options.bind_address, 258 ssh_gai_strerror(gaierr)); 259 close(sock); 260 return -1; 261 } 262 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) { 263 error("bind: %s: %s", options.bind_address, strerror(errno)); 264 close(sock); 265 freeaddrinfo(res); 266 return -1; 267 } 268 freeaddrinfo(res); 269 return sock; 270 } 271 272 static int 273 timeout_connect(int sockfd, const struct sockaddr *serv_addr, 274 socklen_t addrlen, int *timeoutp) 275 { 276 fd_set *fdset; 277 struct timeval tv, t_start; 278 socklen_t optlen; 279 int optval, rc, result = -1; 280 281 gettimeofday(&t_start, NULL); 282 283 if (*timeoutp <= 0) { 284 result = connect(sockfd, serv_addr, addrlen); 285 goto done; 286 } 287 288 set_nonblock(sockfd); 289 rc = connect(sockfd, serv_addr, addrlen); 290 if (rc == 0) { 291 unset_nonblock(sockfd); 292 result = 0; 293 goto done; 294 } 295 if (errno != EINPROGRESS) { 296 result = -1; 297 goto done; 298 } 299 300 fdset = (fd_set *)xcalloc(howmany(sockfd + 1, NFDBITS), 301 sizeof(fd_mask)); 302 FD_SET(sockfd, fdset); 303 ms_to_timeval(&tv, *timeoutp); 304 305 for (;;) { 306 rc = select(sockfd + 1, NULL, fdset, NULL, &tv); 307 if (rc != -1 || errno != EINTR) 308 break; 309 } 310 311 switch (rc) { 312 case 0: 313 /* Timed out */ 314 errno = ETIMEDOUT; 315 break; 316 case -1: 317 /* Select error */ 318 debug("select: %s", strerror(errno)); 319 break; 320 case 1: 321 /* Completed or failed */ 322 optval = 0; 323 optlen = sizeof(optval); 324 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, 325 &optlen) == -1) { 326 debug("getsockopt: %s", strerror(errno)); 327 break; 328 } 329 if (optval != 0) { 330 errno = optval; 331 break; 332 } 333 result = 0; 334 unset_nonblock(sockfd); 335 break; 336 default: 337 /* Should not occur */ 338 fatal("Bogus return (%d) from select()", rc); 339 } 340 341 xfree(fdset); 342 343 done: 344 if (result == 0 && *timeoutp > 0) { 345 ms_subtract_diff(&t_start, timeoutp); 346 if (*timeoutp <= 0) { 347 errno = ETIMEDOUT; 348 result = -1; 349 } 350 } 351 352 return (result); 353 } 354 355 /* 356 * Opens a TCP/IP connection to the remote server on the given host. 357 * The address of the remote host will be returned in hostaddr. 358 * If port is 0, the default port will be used. If needpriv is true, 359 * a privileged port will be allocated to make the connection. 360 * This requires super-user privileges if needpriv is true. 361 * Connection_attempts specifies the maximum number of tries (one per 362 * second). If proxy_command is non-NULL, it specifies the command (with %h 363 * and %p substituted for host and port, respectively) to use to contact 364 * the daemon. 365 */ 366 int 367 ssh_connect(const char *host, struct sockaddr_storage * hostaddr, 368 u_short port, int family, int connection_attempts, int *timeout_ms, 369 int want_keepalive, int needpriv, const char *proxy_command) 370 { 371 int gaierr; 372 int on = 1; 373 int sock = -1, attempt; 374 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 375 struct addrinfo hints, *ai, *aitop; 376 377 debug2("ssh_connect: needpriv %d", needpriv); 378 379 /* If a proxy command is given, connect using it. */ 380 if (proxy_command != NULL) 381 return ssh_proxy_connect(host, port, proxy_command); 382 383 /* No proxy command. */ 384 385 memset(&hints, 0, sizeof(hints)); 386 hints.ai_family = family; 387 hints.ai_socktype = SOCK_STREAM; 388 snprintf(strport, sizeof strport, "%u", port); 389 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) 390 fatal("%s: Could not resolve hostname %.100s: %s", __progname, 391 host, ssh_gai_strerror(gaierr)); 392 393 for (attempt = 0; attempt < connection_attempts; attempt++) { 394 if (attempt > 0) { 395 /* Sleep a moment before retrying. */ 396 sleep(1); 397 debug("Trying again..."); 398 } 399 /* 400 * Loop through addresses for this host, and try each one in 401 * sequence until the connection succeeds. 402 */ 403 for (ai = aitop; ai; ai = ai->ai_next) { 404 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 405 continue; 406 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, 407 ntop, sizeof(ntop), strport, sizeof(strport), 408 NI_NUMERICHOST|NI_NUMERICSERV) != 0) { 409 error("ssh_connect: getnameinfo failed"); 410 continue; 411 } 412 debug("Connecting to %.200s [%.100s] port %s.", 413 host, ntop, strport); 414 415 /* Create a socket for connecting. */ 416 sock = ssh_create_socket(needpriv, ai); 417 if (sock < 0) 418 /* 419 * Any serious error is already output, 420 * at least in the debug case. 421 */ 422 continue; 423 424 if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen, 425 timeout_ms) >= 0) { 426 /* Successful connection. */ 427 memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen); 428 break; 429 } else { 430 debug("connect to address %s port %s: %s", 431 ntop, strport, strerror(errno)); 432 close(sock); 433 sock = -1; 434 } 435 } 436 if (sock != -1) 437 break; /* Successful connection. */ 438 } 439 440 freeaddrinfo(aitop); 441 442 /* Return failure if we didn't get a successful connection. */ 443 if (sock == -1) { 444 error("ssh: connect to host %s port %s: %s", 445 host, strport, strerror(errno)); 446 return (-1); 447 } 448 449 debug("Connection established."); 450 451 /* Set SO_KEEPALIVE if requested. */ 452 if (want_keepalive && 453 setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, 454 sizeof(on)) < 0) 455 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno)); 456 457 /* Set the connection. */ 458 packet_set_connection(sock, sock); 459 packet_set_timeout(options.server_alive_interval, 460 options.server_alive_count_max); 461 462 return 0; 463 } 464 465 /* 466 * Waits for the server identification string, and sends our own 467 * identification string. 468 */ 469 void 470 ssh_exchange_identification(int timeout_ms) 471 { 472 char buf[256], remote_version[256]; /* must be same size! */ 473 int remote_major, remote_minor, mismatch; 474 int connection_in = packet_get_connection_in(); 475 int connection_out = packet_get_connection_out(); 476 int minor1 = PROTOCOL_MINOR_1; 477 int mefirst = 0; 478 u_int i, n; 479 size_t len; 480 int fdsetsz, remaining, rc; 481 struct timeval t_start, t_remaining; 482 fd_set *fdset; 483 484 fdsetsz = howmany(connection_in + 1, NFDBITS) * sizeof(fd_mask); 485 fdset = xcalloc(1, fdsetsz); 486 487 /* 488 * If we are configured to do version 2 only, we can send our 489 * own version string first in order to work around borken 490 * proxies that elsewise impose a delay while trying to figure 491 * out what protocol we are speaking. 492 */ 493 494 if (options.send_version_first == 1 && 495 ((options.protocol & SSH_PROTO_2) && 496 !(options.protocol & SSH_PROTO_1) && 497 !(options.protocol & SSH_PROTO_1_PREFERRED))) { 498 499 /* Send our own protocol version identification. */ 500 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", 501 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, 502 SSH_VERSION, "\r\n"); 503 if (roaming_atomicio(vwrite, connection_out, buf, 504 strlen(buf)) != strlen(buf)) 505 fatal("write: %.100s", strerror(errno)); 506 client_version_string = xstrdup(buf); 507 chop(client_version_string); 508 debug("Local version string %.100s", client_version_string); 509 510 mefirst = 1; 511 } 512 513 /* Read other side's version identification. */ 514 remaining = timeout_ms; 515 for (n = 0;;) { 516 for (i = 0; i < sizeof(buf) - 1; i++) { 517 if (timeout_ms > 0) { 518 gettimeofday(&t_start, NULL); 519 ms_to_timeval(&t_remaining, remaining); 520 FD_SET(connection_in, fdset); 521 rc = select(connection_in + 1, fdset, NULL, 522 fdset, &t_remaining); 523 ms_subtract_diff(&t_start, &remaining); 524 if (rc == 0 || remaining <= 0) 525 fatal("Connection timed out during " 526 "banner exchange"); 527 if (rc == -1) { 528 if (errno == EINTR) 529 continue; 530 fatal("ssh_exchange_identification: " 531 "select: %s", strerror(errno)); 532 } 533 } 534 535 len = roaming_atomicio(read, connection_in, &buf[i], 1); 536 537 if (len != 1 && errno == EPIPE) 538 fatal("ssh_exchange_identification: " 539 "Connection closed by remote host"); 540 else if (len != 1) 541 fatal("ssh_exchange_identification: " 542 "read: %.100s", strerror(errno)); 543 if (buf[i] == '\r') { 544 buf[i] = '\n'; 545 buf[i + 1] = 0; 546 continue; /**XXX wait for \n */ 547 } 548 if (buf[i] == '\n') { 549 buf[i + 1] = 0; 550 break; 551 } 552 if (++n > 65536) 553 fatal("ssh_exchange_identification: " 554 "No banner received"); 555 } 556 buf[sizeof(buf) - 1] = 0; 557 if (strncmp(buf, "SSH-", 4) == 0) 558 break; 559 debug("ssh_exchange_identification: %s", buf); 560 } 561 server_version_string = xstrdup(buf); 562 xfree(fdset); 563 564 /* 565 * Check that the versions match. In future this might accept 566 * several versions and set appropriate flags to handle them. 567 */ 568 if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n", 569 &remote_major, &remote_minor, remote_version) != 3) 570 fatal("Bad remote protocol version identification: '%.100s'", buf); 571 debug("Remote protocol version %d.%d, remote software version %.100s", 572 remote_major, remote_minor, remote_version); 573 574 compat_datafellows(remote_version); 575 mismatch = 0; 576 577 switch (remote_major) { 578 case 1: 579 if (remote_minor == 99 && 580 (options.protocol & SSH_PROTO_2) && 581 !(options.protocol & SSH_PROTO_1_PREFERRED)) { 582 enable_compat20(); 583 break; 584 } 585 if (!(options.protocol & SSH_PROTO_1)) { 586 mismatch = 1; 587 break; 588 } 589 if (remote_minor < 3) { 590 fatal("Remote machine has too old SSH software version."); 591 } else if (remote_minor == 3 || remote_minor == 4) { 592 /* We speak 1.3, too. */ 593 enable_compat13(); 594 minor1 = 3; 595 if (options.forward_agent) { 596 logit("Agent forwarding disabled for protocol 1.3"); 597 options.forward_agent = 0; 598 } 599 } 600 break; 601 case 2: 602 if (options.protocol & SSH_PROTO_2) { 603 enable_compat20(); 604 break; 605 } 606 /* FALLTHROUGH */ 607 default: 608 mismatch = 1; 609 break; 610 } 611 if (mismatch) 612 fatal("Protocol major versions differ: %d vs. %d", 613 (options.protocol & SSH_PROTO_2) ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1, 614 remote_major); 615 if (!mefirst) { 616 /* Send our own protocol version identification. */ 617 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", 618 compat20 ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1, 619 compat20 ? PROTOCOL_MINOR_2 : minor1, 620 SSH_RELEASE, compat20 ? "\r\n" : "\n"); 621 if (roaming_atomicio(vwrite, connection_out, buf, strlen(buf)) 622 != strlen(buf)) 623 fatal("write: %.100s", strerror(errno)); 624 client_version_string = xstrdup(buf); 625 chop(client_version_string); 626 } 627 chop(server_version_string); 628 debug("Local version string %.100s", client_version_string); 629 } 630 631 /* defaults to 'no' */ 632 static int 633 confirm(const char *prompt) 634 { 635 const char *msg, *again = "Please type 'yes' or 'no': "; 636 char *p; 637 int ret = -1; 638 639 if (options.batch_mode) 640 return 0; 641 for (msg = prompt;;msg = again) { 642 p = read_passphrase(msg, RP_ECHO); 643 if (p == NULL || 644 (p[0] == '\0') || (p[0] == '\n') || 645 strncasecmp(p, "no", 2) == 0) 646 ret = 0; 647 if (p && strncasecmp(p, "yes", 3) == 0) 648 ret = 1; 649 if (p) 650 xfree(p); 651 if (ret != -1) 652 return ret; 653 } 654 } 655 656 static int 657 check_host_cert(const char *host, const Key *host_key) 658 { 659 const char *reason; 660 661 if (key_cert_check_authority(host_key, 1, 0, host, &reason) != 0) { 662 error("%s", reason); 663 return 0; 664 } 665 if (buffer_len(&host_key->cert->critical) != 0) { 666 error("Certificate for %s contains unsupported " 667 "critical options(s)", host); 668 return 0; 669 } 670 return 1; 671 } 672 673 static int 674 sockaddr_is_local(struct sockaddr *hostaddr) 675 { 676 switch (hostaddr->sa_family) { 677 case AF_INET: 678 return (ntohl(((struct sockaddr_in *)hostaddr)-> 679 sin_addr.s_addr) >> 24) == IN_LOOPBACKNET; 680 case AF_INET6: 681 return IN6_IS_ADDR_LOOPBACK( 682 &(((struct sockaddr_in6 *)hostaddr)->sin6_addr)); 683 default: 684 return 0; 685 } 686 } 687 688 /* 689 * Prepare the hostname and ip address strings that are used to lookup 690 * host keys in known_hosts files. These may have a port number appended. 691 */ 692 void 693 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr, 694 u_short port, char **hostfile_hostname, char **hostfile_ipaddr) 695 { 696 char ntop[NI_MAXHOST]; 697 698 /* 699 * We don't have the remote ip-address for connections 700 * using a proxy command 701 */ 702 if (hostfile_ipaddr != NULL) { 703 if (options.proxy_command == NULL) { 704 if (getnameinfo(hostaddr, hostaddr->sa_len, 705 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0) 706 fatal("check_host_key: getnameinfo failed"); 707 *hostfile_ipaddr = put_host_port(ntop, port); 708 } else { 709 *hostfile_ipaddr = xstrdup("<no hostip for proxy " 710 "command>"); 711 } 712 } 713 714 /* 715 * Allow the user to record the key under a different name or 716 * differentiate a non-standard port. This is useful for ssh 717 * tunneling over forwarded connections or if you run multiple 718 * sshd's on different ports on the same machine. 719 */ 720 if (hostfile_hostname != NULL) { 721 if (options.host_key_alias != NULL) { 722 *hostfile_hostname = xstrdup(options.host_key_alias); 723 debug("using hostkeyalias: %s", *hostfile_hostname); 724 } else { 725 *hostfile_hostname = put_host_port(hostname, port); 726 } 727 } 728 } 729 730 /* 731 * check whether the supplied host key is valid, return -1 if the key 732 * is not valid. user_hostfile[0] will not be updated if 'readonly' is true. 733 */ 734 #define RDRW 0 735 #define RDONLY 1 736 #define ROQUIET 2 737 static int 738 check_host_key(char *hostname, struct sockaddr *hostaddr, u_short port, 739 Key *host_key, int readonly, 740 char **user_hostfiles, u_int num_user_hostfiles, 741 char **system_hostfiles, u_int num_system_hostfiles) 742 { 743 HostStatus host_status; 744 HostStatus ip_status; 745 Key *raw_key = NULL; 746 char *ip = NULL, *host = NULL; 747 char hostline[1000], *hostp, *fp, *ra; 748 char msg[1024]; 749 const char *type; 750 const struct hostkey_entry *host_found, *ip_found; 751 int len, cancelled_forwarding = 0; 752 int local = sockaddr_is_local(hostaddr); 753 int r, want_cert = key_is_cert(host_key), host_ip_differ = 0; 754 struct hostkeys *host_hostkeys, *ip_hostkeys; 755 u_int i; 756 757 /* 758 * Force accepting of the host key for loopback/localhost. The 759 * problem is that if the home directory is NFS-mounted to multiple 760 * machines, localhost will refer to a different machine in each of 761 * them, and the user will get bogus HOST_CHANGED warnings. This 762 * essentially disables host authentication for localhost; however, 763 * this is probably not a real problem. 764 */ 765 if (options.no_host_authentication_for_localhost == 1 && local && 766 options.host_key_alias == NULL) { 767 debug("Forcing accepting of host key for " 768 "loopback/localhost."); 769 return 0; 770 } 771 772 /* 773 * Prepare the hostname and address strings used for hostkey lookup. 774 * In some cases, these will have a port number appended. 775 */ 776 get_hostfile_hostname_ipaddr(hostname, hostaddr, port, &host, &ip); 777 778 /* 779 * Turn off check_host_ip if the connection is to localhost, via proxy 780 * command or if we don't have a hostname to compare with 781 */ 782 if (options.check_host_ip && (local || 783 strcmp(hostname, ip) == 0 || options.proxy_command != NULL)) 784 options.check_host_ip = 0; 785 786 host_hostkeys = init_hostkeys(); 787 for (i = 0; i < num_user_hostfiles; i++) 788 load_hostkeys(host_hostkeys, host, user_hostfiles[i]); 789 for (i = 0; i < num_system_hostfiles; i++) 790 load_hostkeys(host_hostkeys, host, system_hostfiles[i]); 791 792 ip_hostkeys = NULL; 793 if (!want_cert && options.check_host_ip) { 794 ip_hostkeys = init_hostkeys(); 795 for (i = 0; i < num_user_hostfiles; i++) 796 load_hostkeys(ip_hostkeys, ip, user_hostfiles[i]); 797 for (i = 0; i < num_system_hostfiles; i++) 798 load_hostkeys(ip_hostkeys, ip, system_hostfiles[i]); 799 } 800 801 retry: 802 /* Reload these as they may have changed on cert->key downgrade */ 803 want_cert = key_is_cert(host_key); 804 type = key_type(host_key); 805 806 /* 807 * Check if the host key is present in the user's list of known 808 * hosts or in the systemwide list. 809 */ 810 host_status = check_key_in_hostkeys(host_hostkeys, host_key, 811 &host_found); 812 813 /* 814 * Also perform check for the ip address, skip the check if we are 815 * localhost, looking for a certificate, or the hostname was an ip 816 * address to begin with. 817 */ 818 if (!want_cert && ip_hostkeys != NULL) { 819 ip_status = check_key_in_hostkeys(ip_hostkeys, host_key, 820 &ip_found); 821 if (host_status == HOST_CHANGED && 822 (ip_status != HOST_CHANGED || 823 (ip_found != NULL && 824 !key_equal(ip_found->key, host_found->key)))) 825 host_ip_differ = 1; 826 } else 827 ip_status = host_status; 828 829 switch (host_status) { 830 case HOST_OK: 831 /* The host is known and the key matches. */ 832 debug("Host '%.200s' is known and matches the %s host %s.", 833 host, type, want_cert ? "certificate" : "key"); 834 debug("Found %s in %s:%lu", want_cert ? "CA key" : "key", 835 host_found->file, host_found->line); 836 if (want_cert && !check_host_cert(hostname, host_key)) 837 goto fail; 838 if (options.check_host_ip && ip_status == HOST_NEW) { 839 if (readonly || want_cert) 840 logit("%s host key for IP address " 841 "'%.128s' not in list of known hosts.", 842 type, ip); 843 else if (!add_host_to_hostfile(user_hostfiles[0], ip, 844 host_key, options.hash_known_hosts)) 845 logit("Failed to add the %s host key for IP " 846 "address '%.128s' to the list of known " 847 "hosts (%.30s).", type, ip, 848 user_hostfiles[0]); 849 else 850 logit("Warning: Permanently added the %s host " 851 "key for IP address '%.128s' to the list " 852 "of known hosts.", type, ip); 853 } else if (options.visual_host_key) { 854 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX); 855 ra = key_fingerprint(host_key, SSH_FP_MD5, 856 SSH_FP_RANDOMART); 857 logit("Host key fingerprint is %s\n%s\n", fp, ra); 858 xfree(ra); 859 xfree(fp); 860 } 861 break; 862 case HOST_NEW: 863 if (options.host_key_alias == NULL && port != 0 && 864 port != SSH_DEFAULT_PORT) { 865 debug("checking without port identifier"); 866 if (check_host_key(hostname, hostaddr, 0, host_key, 867 ROQUIET, user_hostfiles, num_user_hostfiles, 868 system_hostfiles, num_system_hostfiles) == 0) { 869 debug("found matching key w/out port"); 870 break; 871 } 872 } 873 if (readonly || want_cert) 874 goto fail; 875 /* The host is new. */ 876 if (options.strict_host_key_checking == 1) { 877 /* 878 * User has requested strict host key checking. We 879 * will not add the host key automatically. The only 880 * alternative left is to abort. 881 */ 882 error("No %s host key is known for %.200s and you " 883 "have requested strict checking.", type, host); 884 goto fail; 885 } else if (options.strict_host_key_checking == 2) { 886 char msg1[1024], msg2[1024]; 887 888 if (show_other_keys(host_hostkeys, host_key)) 889 snprintf(msg1, sizeof(msg1), 890 "\nbut keys of different type are already" 891 " known for this host."); 892 else 893 snprintf(msg1, sizeof(msg1), "."); 894 /* The default */ 895 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX); 896 ra = key_fingerprint(host_key, SSH_FP_MD5, 897 SSH_FP_RANDOMART); 898 msg2[0] = '\0'; 899 if (options.verify_host_key_dns) { 900 if (matching_host_key_dns) 901 snprintf(msg2, sizeof(msg2), 902 "Matching host key fingerprint" 903 " found in DNS.\n"); 904 else 905 snprintf(msg2, sizeof(msg2), 906 "No matching host key fingerprint" 907 " found in DNS.\n"); 908 } 909 snprintf(msg, sizeof(msg), 910 "The authenticity of host '%.200s (%s)' can't be " 911 "established%s\n" 912 "%s key fingerprint is %s.%s%s\n%s" 913 "Are you sure you want to continue connecting " 914 "(yes/no)? ", 915 host, ip, msg1, type, fp, 916 options.visual_host_key ? "\n" : "", 917 options.visual_host_key ? ra : "", 918 msg2); 919 xfree(ra); 920 xfree(fp); 921 if (!confirm(msg)) 922 goto fail; 923 } 924 /* 925 * If not in strict mode, add the key automatically to the 926 * local known_hosts file. 927 */ 928 if (options.check_host_ip && ip_status == HOST_NEW) { 929 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip); 930 hostp = hostline; 931 if (options.hash_known_hosts) { 932 /* Add hash of host and IP separately */ 933 r = add_host_to_hostfile(user_hostfiles[0], 934 host, host_key, options.hash_known_hosts) && 935 add_host_to_hostfile(user_hostfiles[0], ip, 936 host_key, options.hash_known_hosts); 937 } else { 938 /* Add unhashed "host,ip" */ 939 r = add_host_to_hostfile(user_hostfiles[0], 940 hostline, host_key, 941 options.hash_known_hosts); 942 } 943 } else { 944 r = add_host_to_hostfile(user_hostfiles[0], host, 945 host_key, options.hash_known_hosts); 946 hostp = host; 947 } 948 949 if (!r) 950 logit("Failed to add the host to the list of known " 951 "hosts (%.500s).", user_hostfiles[0]); 952 else 953 logit("Warning: Permanently added '%.200s' (%s) to the " 954 "list of known hosts.", hostp, type); 955 break; 956 case HOST_REVOKED: 957 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 958 error("@ WARNING: REVOKED HOST KEY DETECTED! @"); 959 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 960 error("The %s host key for %s is marked as revoked.", type, host); 961 error("This could mean that a stolen key is being used to"); 962 error("impersonate this host."); 963 964 /* 965 * If strict host key checking is in use, the user will have 966 * to edit the key manually and we can only abort. 967 */ 968 if (options.strict_host_key_checking) { 969 error("%s host key for %.200s was revoked and you have " 970 "requested strict checking.", type, host); 971 goto fail; 972 } 973 goto continue_unsafe; 974 975 case HOST_CHANGED: 976 if (want_cert) { 977 /* 978 * This is only a debug() since it is valid to have 979 * CAs with wildcard DNS matches that don't match 980 * all hosts that one might visit. 981 */ 982 debug("Host certificate authority does not " 983 "match %s in %s:%lu", CA_MARKER, 984 host_found->file, host_found->line); 985 goto fail; 986 } 987 if (readonly == ROQUIET) 988 goto fail; 989 if (options.check_host_ip && host_ip_differ) { 990 const char *key_msg; 991 if (ip_status == HOST_NEW) 992 key_msg = "is unknown"; 993 else if (ip_status == HOST_OK) 994 key_msg = "is unchanged"; 995 else 996 key_msg = "has a different value"; 997 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 998 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @"); 999 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 1000 error("The %s host key for %s has changed,", type, host); 1001 error("and the key for the corresponding IP address %s", ip); 1002 error("%s. This could either mean that", key_msg); 1003 error("DNS SPOOFING is happening or the IP address for the host"); 1004 error("and its host key have changed at the same time."); 1005 if (ip_status != HOST_NEW) 1006 error("Offending key for IP in %s:%lu", 1007 ip_found->file, ip_found->line); 1008 } 1009 /* The host key has changed. */ 1010 warn_changed_key(host_key); 1011 error("Add correct host key in %.100s to get rid of this message.", 1012 user_hostfiles[0]); 1013 error("Offending %s key in %s:%lu", key_type(host_found->key), 1014 host_found->file, host_found->line); 1015 1016 /* 1017 * If strict host key checking is in use, the user will have 1018 * to edit the key manually and we can only abort. 1019 */ 1020 if (options.strict_host_key_checking) { 1021 error("%s host key for %.200s has changed and you have " 1022 "requested strict checking.", type, host); 1023 goto fail; 1024 } 1025 1026 continue_unsafe: 1027 /* 1028 * If strict host key checking has not been requested, allow 1029 * the connection but without MITM-able authentication or 1030 * forwarding. 1031 */ 1032 if (options.password_authentication) { 1033 error("Password authentication is disabled to avoid " 1034 "man-in-the-middle attacks."); 1035 options.password_authentication = 0; 1036 cancelled_forwarding = 1; 1037 } 1038 if (options.kbd_interactive_authentication) { 1039 error("Keyboard-interactive authentication is disabled" 1040 " to avoid man-in-the-middle attacks."); 1041 options.kbd_interactive_authentication = 0; 1042 options.challenge_response_authentication = 0; 1043 cancelled_forwarding = 1; 1044 } 1045 if (options.challenge_response_authentication) { 1046 error("Challenge/response authentication is disabled" 1047 " to avoid man-in-the-middle attacks."); 1048 options.challenge_response_authentication = 0; 1049 cancelled_forwarding = 1; 1050 } 1051 if (options.forward_agent) { 1052 error("Agent forwarding is disabled to avoid " 1053 "man-in-the-middle attacks."); 1054 options.forward_agent = 0; 1055 cancelled_forwarding = 1; 1056 } 1057 if (options.forward_x11) { 1058 error("X11 forwarding is disabled to avoid " 1059 "man-in-the-middle attacks."); 1060 options.forward_x11 = 0; 1061 cancelled_forwarding = 1; 1062 } 1063 if (options.num_local_forwards > 0 || 1064 options.num_remote_forwards > 0) { 1065 error("Port forwarding is disabled to avoid " 1066 "man-in-the-middle attacks."); 1067 options.num_local_forwards = 1068 options.num_remote_forwards = 0; 1069 cancelled_forwarding = 1; 1070 } 1071 if (options.tun_open != SSH_TUNMODE_NO) { 1072 error("Tunnel forwarding is disabled to avoid " 1073 "man-in-the-middle attacks."); 1074 options.tun_open = SSH_TUNMODE_NO; 1075 cancelled_forwarding = 1; 1076 } 1077 if (options.exit_on_forward_failure && cancelled_forwarding) 1078 fatal("Error: forwarding disabled due to host key " 1079 "check failure"); 1080 1081 /* 1082 * XXX Should permit the user to change to use the new id. 1083 * This could be done by converting the host key to an 1084 * identifying sentence, tell that the host identifies itself 1085 * by that sentence, and ask the user if he/she wishes to 1086 * accept the authentication. 1087 */ 1088 break; 1089 case HOST_FOUND: 1090 fatal("internal error"); 1091 break; 1092 } 1093 1094 if (options.check_host_ip && host_status != HOST_CHANGED && 1095 ip_status == HOST_CHANGED) { 1096 snprintf(msg, sizeof(msg), 1097 "Warning: the %s host key for '%.200s' " 1098 "differs from the key for the IP address '%.128s'" 1099 "\nOffending key for IP in %s:%lu", 1100 type, host, ip, ip_found->file, ip_found->line); 1101 if (host_status == HOST_OK) { 1102 len = strlen(msg); 1103 snprintf(msg + len, sizeof(msg) - len, 1104 "\nMatching host key in %s:%lu", 1105 host_found->file, host_found->line); 1106 } 1107 if (options.strict_host_key_checking == 1) { 1108 logit("%s", msg); 1109 error("Exiting, you have requested strict checking."); 1110 goto fail; 1111 } else if (options.strict_host_key_checking == 2) { 1112 strlcat(msg, "\nAre you sure you want " 1113 "to continue connecting (yes/no)? ", sizeof(msg)); 1114 if (!confirm(msg)) 1115 goto fail; 1116 } else { 1117 logit("%s", msg); 1118 } 1119 } 1120 1121 xfree(ip); 1122 xfree(host); 1123 if (host_hostkeys != NULL) 1124 free_hostkeys(host_hostkeys); 1125 if (ip_hostkeys != NULL) 1126 free_hostkeys(ip_hostkeys); 1127 return 0; 1128 1129 fail: 1130 if (want_cert && host_status != HOST_REVOKED) { 1131 /* 1132 * No matching certificate. Downgrade cert to raw key and 1133 * search normally. 1134 */ 1135 debug("No matching CA found. Retry with plain key"); 1136 raw_key = key_from_private(host_key); 1137 if (key_drop_cert(raw_key) != 0) 1138 fatal("Couldn't drop certificate"); 1139 host_key = raw_key; 1140 goto retry; 1141 } 1142 if (raw_key != NULL) 1143 key_free(raw_key); 1144 xfree(ip); 1145 xfree(host); 1146 if (host_hostkeys != NULL) 1147 free_hostkeys(host_hostkeys); 1148 if (ip_hostkeys != NULL) 1149 free_hostkeys(ip_hostkeys); 1150 return -1; 1151 } 1152 1153 /* returns 0 if key verifies or -1 if key does NOT verify */ 1154 int 1155 verify_host_key(char *host, struct sockaddr *hostaddr, Key *host_key) 1156 { 1157 int flags = 0; 1158 char *fp; 1159 1160 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX); 1161 debug("Server host key: %s %s", key_type(host_key), fp); 1162 xfree(fp); 1163 1164 /* XXX certs are not yet supported for DNS */ 1165 if (!key_is_cert(host_key) && options.verify_host_key_dns && 1166 verify_host_key_dns(host, hostaddr, host_key, &flags) == 0) { 1167 if (flags & DNS_VERIFY_FOUND) { 1168 1169 if (options.verify_host_key_dns == 1 && 1170 flags & DNS_VERIFY_MATCH && 1171 flags & DNS_VERIFY_SECURE) 1172 return 0; 1173 1174 if (flags & DNS_VERIFY_MATCH) { 1175 matching_host_key_dns = 1; 1176 } else { 1177 warn_changed_key(host_key); 1178 error("Update the SSHFP RR in DNS with the new " 1179 "host key to get rid of this message."); 1180 } 1181 } 1182 } 1183 1184 return check_host_key(host, hostaddr, options.port, host_key, RDRW, 1185 options.user_hostfiles, options.num_user_hostfiles, 1186 options.system_hostfiles, options.num_system_hostfiles); 1187 } 1188 1189 /* 1190 * Starts a dialog with the server, and authenticates the current user on the 1191 * server. This does not need any extra privileges. The basic connection 1192 * to the server must already have been established before this is called. 1193 * If login fails, this function prints an error and never returns. 1194 * This function does not require super-user privileges. 1195 */ 1196 void 1197 ssh_login(Sensitive *sensitive, const char *orighost, 1198 struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms) 1199 { 1200 char *host, *cp; 1201 char *server_user, *local_user; 1202 1203 local_user = xstrdup(pw->pw_name); 1204 server_user = options.user ? options.user : local_user; 1205 1206 /* Convert the user-supplied hostname into all lowercase. */ 1207 host = xstrdup(orighost); 1208 for (cp = host; *cp; cp++) 1209 if (isupper((unsigned char)*cp)) 1210 *cp = (char)tolower((unsigned char)*cp); 1211 1212 /* Exchange protocol version identification strings with the server. */ 1213 ssh_exchange_identification(timeout_ms); 1214 1215 /* Put the connection into non-blocking mode. */ 1216 packet_set_nonblocking(); 1217 1218 /* key exchange */ 1219 /* authenticate user */ 1220 if (compat20) { 1221 ssh_kex2(host, hostaddr, port); 1222 ssh_userauth2(local_user, server_user, host, sensitive); 1223 } else { 1224 ssh_kex(host, hostaddr); 1225 ssh_userauth1(local_user, server_user, host, sensitive); 1226 } 1227 xfree(local_user); 1228 } 1229 1230 void 1231 ssh_put_password(char *password) 1232 { 1233 int size; 1234 char *padded; 1235 1236 if (datafellows & SSH_BUG_PASSWORDPAD) { 1237 packet_put_cstring(password); 1238 return; 1239 } 1240 size = roundup(strlen(password) + 1, 32); 1241 padded = xcalloc(1, size); 1242 strlcpy(padded, password, size); 1243 packet_put_string(padded, size); 1244 memset(padded, 0, size); 1245 xfree(padded); 1246 } 1247 1248 /* print all known host keys for a given host, but skip keys of given type */ 1249 static int 1250 show_other_keys(struct hostkeys *hostkeys, Key *key) 1251 { 1252 int type[] = { KEY_RSA1, KEY_RSA, KEY_DSA, KEY_ECDSA, -1}; 1253 int i, ret = 0; 1254 char *fp, *ra; 1255 const struct hostkey_entry *found; 1256 1257 for (i = 0; type[i] != -1; i++) { 1258 if (type[i] == key->type) 1259 continue; 1260 if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i], &found)) 1261 continue; 1262 fp = key_fingerprint(found->key, SSH_FP_MD5, SSH_FP_HEX); 1263 ra = key_fingerprint(found->key, SSH_FP_MD5, SSH_FP_RANDOMART); 1264 logit("WARNING: %s key found for host %s\n" 1265 "in %s:%lu\n" 1266 "%s key fingerprint %s.", 1267 key_type(found->key), 1268 found->host, found->file, found->line, 1269 key_type(found->key), fp); 1270 if (options.visual_host_key) 1271 logit("%s", ra); 1272 xfree(ra); 1273 xfree(fp); 1274 ret = 1; 1275 } 1276 return ret; 1277 } 1278 1279 static void 1280 warn_changed_key(Key *host_key) 1281 { 1282 char *fp; 1283 1284 fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX); 1285 1286 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 1287 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @"); 1288 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 1289 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!"); 1290 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!"); 1291 error("It is also possible that a host key has just been changed."); 1292 error("The fingerprint for the %s key sent by the remote host is\n%s.", 1293 key_type(host_key), fp); 1294 error("Please contact your system administrator."); 1295 1296 xfree(fp); 1297 } 1298 1299 /* 1300 * Execute a local command 1301 */ 1302 int 1303 ssh_local_cmd(const char *args) 1304 { 1305 const char *shell; 1306 pid_t pid; 1307 int status; 1308 void (*osighand)(int); 1309 1310 if (!options.permit_local_command || 1311 args == NULL || !*args) 1312 return (1); 1313 1314 if ((shell = getenv("SHELL")) == NULL || *shell == '\0') 1315 shell = _PATH_BSHELL; 1316 1317 osighand = signal(SIGCHLD, SIG_DFL); 1318 pid = fork(); 1319 if (pid == 0) { 1320 signal(SIGPIPE, SIG_DFL); 1321 debug3("Executing %s -c \"%s\"", shell, args); 1322 execl(shell, shell, "-c", args, (char *)NULL); 1323 error("Couldn't execute %s -c \"%s\": %s", 1324 shell, args, strerror(errno)); 1325 _exit(1); 1326 } else if (pid == -1) 1327 fatal("fork failed: %.100s", strerror(errno)); 1328 while (waitpid(pid, &status, 0) == -1) 1329 if (errno != EINTR) 1330 fatal("Couldn't wait for child: %s", strerror(errno)); 1331 signal(SIGCHLD, osighand); 1332 1333 if (!WIFEXITED(status)) 1334 return (1); 1335 1336 return (WEXITSTATUS(status)); 1337 } 1338