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