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