1 /* 2 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * All rights reserved 5 * Created: Sat Mar 18 22:15:47 1995 ylo 6 * Code to connect to a remote host, and to perform the client side of the 7 * login (authentication) dialog. 8 * 9 * $FreeBSD$ 10 */ 11 12 #include "includes.h" 13 RCSID("$OpenBSD: sshconnect.c,v 1.58 2000/03/23 22:15:33 markus Exp $"); 14 15 #include <openssl/bn.h> 16 #include "xmalloc.h" 17 #include "rsa.h" 18 #include "ssh.h" 19 #include "packet.h" 20 #include "authfd.h" 21 #include "cipher.h" 22 #include "mpaux.h" 23 #include "uidswap.h" 24 #include "compat.h" 25 #include "readconf.h" 26 27 #include <openssl/rsa.h> 28 #include <openssl/dsa.h> 29 #include <openssl/md5.h> 30 #include "key.h" 31 #include "hostfile.h" 32 33 /* Session id for the current session. */ 34 unsigned char session_id[16]; 35 36 /* authentications supported by server */ 37 unsigned int supported_authentications; 38 39 extern Options options; 40 extern char *__progname; 41 42 /* 43 * Connect to the given ssh server using a proxy command. 44 */ 45 int 46 ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid, 47 const char *proxy_command) 48 { 49 Buffer command; 50 const char *cp; 51 char *command_string; 52 int pin[2], pout[2]; 53 int pid; 54 char strport[NI_MAXSERV]; 55 56 /* Convert the port number into a string. */ 57 snprintf(strport, sizeof strport, "%hu", port); 58 59 /* Build the final command string in the buffer by making the 60 appropriate substitutions to the given proxy command. */ 61 buffer_init(&command); 62 for (cp = proxy_command; *cp; cp++) { 63 if (cp[0] == '%' && cp[1] == '%') { 64 buffer_append(&command, "%", 1); 65 cp++; 66 continue; 67 } 68 if (cp[0] == '%' && cp[1] == 'h') { 69 buffer_append(&command, host, strlen(host)); 70 cp++; 71 continue; 72 } 73 if (cp[0] == '%' && cp[1] == 'p') { 74 buffer_append(&command, strport, strlen(strport)); 75 cp++; 76 continue; 77 } 78 buffer_append(&command, cp, 1); 79 } 80 buffer_append(&command, "\0", 1); 81 82 /* Get the final command string. */ 83 command_string = buffer_ptr(&command); 84 85 /* Create pipes for communicating with the proxy. */ 86 if (pipe(pin) < 0 || pipe(pout) < 0) 87 fatal("Could not create pipes to communicate with the proxy: %.100s", 88 strerror(errno)); 89 90 debug("Executing proxy command: %.500s", command_string); 91 92 /* Fork and execute the proxy command. */ 93 if ((pid = fork()) == 0) { 94 char *argv[10]; 95 96 /* Child. Permanently give up superuser privileges. */ 97 permanently_set_uid(original_real_uid); 98 99 /* Redirect stdin and stdout. */ 100 close(pin[1]); 101 if (pin[0] != 0) { 102 if (dup2(pin[0], 0) < 0) 103 perror("dup2 stdin"); 104 close(pin[0]); 105 } 106 close(pout[0]); 107 if (dup2(pout[1], 1) < 0) 108 perror("dup2 stdout"); 109 /* Cannot be 1 because pin allocated two descriptors. */ 110 close(pout[1]); 111 112 /* Stderr is left as it is so that error messages get 113 printed on the user's terminal. */ 114 argv[0] = "/bin/sh"; 115 argv[1] = "-c"; 116 argv[2] = command_string; 117 argv[3] = NULL; 118 119 /* Execute the proxy command. Note that we gave up any 120 extra privileges above. */ 121 execv("/bin/sh", argv); 122 perror("/bin/sh"); 123 exit(1); 124 } 125 /* Parent. */ 126 if (pid < 0) 127 fatal("fork failed: %.100s", strerror(errno)); 128 129 /* Close child side of the descriptors. */ 130 close(pin[0]); 131 close(pout[1]); 132 133 /* Free the command name. */ 134 buffer_free(&command); 135 136 /* Set the connection file descriptors. */ 137 packet_set_connection(pout[0], pin[1]); 138 139 return 1; 140 } 141 142 /* 143 * Creates a (possibly privileged) socket for use as the ssh connection. 144 */ 145 int 146 ssh_create_socket(uid_t original_real_uid, int privileged, int family) 147 { 148 int sock; 149 150 /* 151 * If we are running as root and want to connect to a privileged 152 * port, bind our own socket to a privileged port. 153 */ 154 if (privileged) { 155 int p = IPPORT_RESERVED - 1; 156 sock = rresvport_af(&p, family); 157 if (sock < 0) 158 error("rresvport: af=%d %.100s", family, strerror(errno)); 159 else 160 debug("Allocated local port %d.", p); 161 } else { 162 /* 163 * Just create an ordinary socket on arbitrary port. We use 164 * the user's uid to create the socket. 165 */ 166 temporarily_use_uid(original_real_uid); 167 sock = socket(family, SOCK_STREAM, 0); 168 if (sock < 0) 169 error("socket: %.100s", strerror(errno)); 170 restore_uid(); 171 } 172 return sock; 173 } 174 175 /* 176 * Opens a TCP/IP connection to the remote server on the given host. 177 * The address of the remote host will be returned in hostaddr. 178 * If port is 0, the default port will be used. If anonymous is zero, 179 * a privileged port will be allocated to make the connection. 180 * This requires super-user privileges if anonymous is false. 181 * Connection_attempts specifies the maximum number of tries (one per 182 * second). If proxy_command is non-NULL, it specifies the command (with %h 183 * and %p substituted for host and port, respectively) to use to contact 184 * the daemon. 185 */ 186 int 187 ssh_connect(const char *host, struct sockaddr_storage * hostaddr, 188 u_short port, int connection_attempts, 189 int anonymous, uid_t original_real_uid, 190 const char *proxy_command) 191 { 192 int sock = -1, attempt; 193 struct servent *sp; 194 struct addrinfo hints, *ai, *aitop; 195 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 196 int gaierr; 197 struct linger linger; 198 199 debug("ssh_connect: getuid %d geteuid %d anon %d", 200 (int) getuid(), (int) geteuid(), anonymous); 201 202 /* Get default port if port has not been set. */ 203 if (port == 0) { 204 sp = getservbyname(SSH_SERVICE_NAME, "tcp"); 205 if (sp) 206 port = ntohs(sp->s_port); 207 else 208 port = SSH_DEFAULT_PORT; 209 } 210 /* If a proxy command is given, connect using it. */ 211 if (proxy_command != NULL) 212 return ssh_proxy_connect(host, port, original_real_uid, proxy_command); 213 214 /* No proxy command. */ 215 216 memset(&hints, 0, sizeof(hints)); 217 hints.ai_family = IPv4or6; 218 hints.ai_socktype = SOCK_STREAM; 219 snprintf(strport, sizeof strport, "%d", port); 220 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) 221 fatal("%s: %.100s: %s", __progname, host, 222 gai_strerror(gaierr)); 223 224 /* 225 * Try to connect several times. On some machines, the first time 226 * will sometimes fail. In general socket code appears to behave 227 * quite magically on many machines. 228 */ 229 for (attempt = 0; attempt < connection_attempts; attempt++) { 230 if (attempt > 0) 231 debug("Trying again..."); 232 233 /* Loop through addresses for this host, and try each one in 234 sequence until the connection succeeds. */ 235 for (ai = aitop; ai; ai = ai->ai_next) { 236 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 237 continue; 238 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, 239 ntop, sizeof(ntop), strport, sizeof(strport), 240 NI_NUMERICHOST|NI_NUMERICSERV) != 0) { 241 error("ssh_connect: getnameinfo failed"); 242 continue; 243 } 244 debug("Connecting to %.200s [%.100s] port %s.", 245 host, ntop, strport); 246 247 /* Create a socket for connecting. */ 248 sock = ssh_create_socket(original_real_uid, 249 !anonymous && geteuid() == 0 && port < IPPORT_RESERVED, 250 ai->ai_family); 251 if (sock < 0) 252 continue; 253 254 /* Connect to the host. We use the user's uid in the 255 * hope that it will help with tcp_wrappers showing 256 * the remote uid as root. 257 */ 258 temporarily_use_uid(original_real_uid); 259 if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) { 260 /* Successful connection. */ 261 memcpy(hostaddr, ai->ai_addr, sizeof(*hostaddr)); 262 restore_uid(); 263 break; 264 } else { 265 debug("connect: %.100s", strerror(errno)); 266 restore_uid(); 267 /* 268 * Close the failed socket; there appear to 269 * be some problems when reusing a socket for 270 * which connect() has already returned an 271 * error. 272 */ 273 shutdown(sock, SHUT_RDWR); 274 close(sock); 275 } 276 } 277 if (ai) 278 break; /* Successful connection. */ 279 280 /* Sleep a moment before retrying. */ 281 sleep(1); 282 } 283 284 freeaddrinfo(aitop); 285 286 /* Return failure if we didn't get a successful connection. */ 287 if (attempt >= connection_attempts) 288 return 0; 289 290 debug("Connection established."); 291 292 /* 293 * Set socket options. We would like the socket to disappear as soon 294 * as it has been closed for whatever reason. 295 */ 296 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */ 297 linger.l_onoff = 1; 298 linger.l_linger = 5; 299 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger)); 300 301 /* Set the connection. */ 302 packet_set_connection(sock, sock); 303 304 return 1; 305 } 306 307 /* 308 * Checks if the user has an authentication agent, and if so, tries to 309 * authenticate using the agent. 310 */ 311 int 312 try_agent_authentication() 313 { 314 int status, type; 315 char *comment; 316 AuthenticationConnection *auth; 317 unsigned char response[16]; 318 unsigned int i; 319 BIGNUM *e, *n, *challenge; 320 321 /* Get connection to the agent. */ 322 auth = ssh_get_authentication_connection(); 323 if (!auth) 324 return 0; 325 326 e = BN_new(); 327 n = BN_new(); 328 challenge = BN_new(); 329 330 /* Loop through identities served by the agent. */ 331 for (status = ssh_get_first_identity(auth, e, n, &comment); 332 status; 333 status = ssh_get_next_identity(auth, e, n, &comment)) { 334 int plen, clen; 335 336 /* Try this identity. */ 337 debug("Trying RSA authentication via agent with '%.100s'", comment); 338 xfree(comment); 339 340 /* Tell the server that we are willing to authenticate using this key. */ 341 packet_start(SSH_CMSG_AUTH_RSA); 342 packet_put_bignum(n); 343 packet_send(); 344 packet_write_wait(); 345 346 /* Wait for server's response. */ 347 type = packet_read(&plen); 348 349 /* The server sends failure if it doesn\'t like our key or 350 does not support RSA authentication. */ 351 if (type == SSH_SMSG_FAILURE) { 352 debug("Server refused our key."); 353 continue; 354 } 355 /* Otherwise it should have sent a challenge. */ 356 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE) 357 packet_disconnect("Protocol error during RSA authentication: %d", 358 type); 359 360 packet_get_bignum(challenge, &clen); 361 362 packet_integrity_check(plen, clen, type); 363 364 debug("Received RSA challenge from server."); 365 366 /* Ask the agent to decrypt the challenge. */ 367 if (!ssh_decrypt_challenge(auth, e, n, challenge, 368 session_id, 1, response)) { 369 /* The agent failed to authenticate this identifier although it 370 advertised it supports this. Just return a wrong value. */ 371 log("Authentication agent failed to decrypt challenge."); 372 memset(response, 0, sizeof(response)); 373 } 374 debug("Sending response to RSA challenge."); 375 376 /* Send the decrypted challenge back to the server. */ 377 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE); 378 for (i = 0; i < 16; i++) 379 packet_put_char(response[i]); 380 packet_send(); 381 packet_write_wait(); 382 383 /* Wait for response from the server. */ 384 type = packet_read(&plen); 385 386 /* The server returns success if it accepted the authentication. */ 387 if (type == SSH_SMSG_SUCCESS) { 388 debug("RSA authentication accepted by server."); 389 BN_clear_free(e); 390 BN_clear_free(n); 391 BN_clear_free(challenge); 392 return 1; 393 } 394 /* Otherwise it should return failure. */ 395 if (type != SSH_SMSG_FAILURE) 396 packet_disconnect("Protocol error waiting RSA auth response: %d", 397 type); 398 } 399 400 BN_clear_free(e); 401 BN_clear_free(n); 402 BN_clear_free(challenge); 403 404 debug("RSA authentication using agent refused."); 405 return 0; 406 } 407 408 /* 409 * Computes the proper response to a RSA challenge, and sends the response to 410 * the server. 411 */ 412 void 413 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv) 414 { 415 unsigned char buf[32], response[16]; 416 MD5_CTX md; 417 int i, len; 418 419 /* Decrypt the challenge using the private key. */ 420 rsa_private_decrypt(challenge, challenge, prv); 421 422 /* Compute the response. */ 423 /* The response is MD5 of decrypted challenge plus session id. */ 424 len = BN_num_bytes(challenge); 425 if (len <= 0 || len > sizeof(buf)) 426 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d", 427 len); 428 429 memset(buf, 0, sizeof(buf)); 430 BN_bn2bin(challenge, buf + sizeof(buf) - len); 431 MD5_Init(&md); 432 MD5_Update(&md, buf, 32); 433 MD5_Update(&md, session_id, 16); 434 MD5_Final(response, &md); 435 436 debug("Sending response to host key RSA challenge."); 437 438 /* Send the response back to the server. */ 439 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE); 440 for (i = 0; i < 16; i++) 441 packet_put_char(response[i]); 442 packet_send(); 443 packet_write_wait(); 444 445 memset(buf, 0, sizeof(buf)); 446 memset(response, 0, sizeof(response)); 447 memset(&md, 0, sizeof(md)); 448 } 449 450 /* 451 * Checks if the user has authentication file, and if so, tries to authenticate 452 * the user using it. 453 */ 454 int 455 try_rsa_authentication(const char *authfile) 456 { 457 BIGNUM *challenge; 458 RSA *private_key; 459 RSA *public_key; 460 char *passphrase, *comment; 461 int type, i; 462 int plen, clen; 463 464 /* Try to load identification for the authentication key. */ 465 public_key = RSA_new(); 466 if (!load_public_key(authfile, public_key, &comment)) { 467 RSA_free(public_key); 468 /* Could not load it. Fail. */ 469 return 0; 470 } 471 debug("Trying RSA authentication with key '%.100s'", comment); 472 473 /* Tell the server that we are willing to authenticate using this key. */ 474 packet_start(SSH_CMSG_AUTH_RSA); 475 packet_put_bignum(public_key->n); 476 packet_send(); 477 packet_write_wait(); 478 479 /* We no longer need the public key. */ 480 RSA_free(public_key); 481 482 /* Wait for server's response. */ 483 type = packet_read(&plen); 484 485 /* 486 * The server responds with failure if it doesn\'t like our key or 487 * doesn\'t support RSA authentication. 488 */ 489 if (type == SSH_SMSG_FAILURE) { 490 debug("Server refused our key."); 491 xfree(comment); 492 return 0; 493 } 494 /* Otherwise, the server should respond with a challenge. */ 495 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE) 496 packet_disconnect("Protocol error during RSA authentication: %d", type); 497 498 /* Get the challenge from the packet. */ 499 challenge = BN_new(); 500 packet_get_bignum(challenge, &clen); 501 502 packet_integrity_check(plen, clen, type); 503 504 debug("Received RSA challenge from server."); 505 506 private_key = RSA_new(); 507 /* 508 * Load the private key. Try first with empty passphrase; if it 509 * fails, ask for a passphrase. 510 */ 511 if (!load_private_key(authfile, "", private_key, NULL)) { 512 char buf[300]; 513 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ", 514 comment); 515 if (!options.batch_mode) 516 passphrase = read_passphrase(buf, 0); 517 else { 518 debug("Will not query passphrase for %.100s in batch mode.", 519 comment); 520 passphrase = xstrdup(""); 521 } 522 523 /* Load the authentication file using the pasphrase. */ 524 if (!load_private_key(authfile, passphrase, private_key, NULL)) { 525 memset(passphrase, 0, strlen(passphrase)); 526 xfree(passphrase); 527 error("Bad passphrase."); 528 529 /* Send a dummy response packet to avoid protocol error. */ 530 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE); 531 for (i = 0; i < 16; i++) 532 packet_put_char(0); 533 packet_send(); 534 packet_write_wait(); 535 536 /* Expect the server to reject it... */ 537 packet_read_expect(&plen, SSH_SMSG_FAILURE); 538 xfree(comment); 539 return 0; 540 } 541 /* Destroy the passphrase. */ 542 memset(passphrase, 0, strlen(passphrase)); 543 xfree(passphrase); 544 } 545 /* We no longer need the comment. */ 546 xfree(comment); 547 548 /* Compute and send a response to the challenge. */ 549 respond_to_rsa_challenge(challenge, private_key); 550 551 /* Destroy the private key. */ 552 RSA_free(private_key); 553 554 /* We no longer need the challenge. */ 555 BN_clear_free(challenge); 556 557 /* Wait for response from the server. */ 558 type = packet_read(&plen); 559 if (type == SSH_SMSG_SUCCESS) { 560 debug("RSA authentication accepted by server."); 561 return 1; 562 } 563 if (type != SSH_SMSG_FAILURE) 564 packet_disconnect("Protocol error waiting RSA auth response: %d", type); 565 debug("RSA authentication refused."); 566 return 0; 567 } 568 569 /* 570 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv 571 * authentication and RSA host authentication. 572 */ 573 int 574 try_rhosts_rsa_authentication(const char *local_user, RSA * host_key) 575 { 576 int type; 577 BIGNUM *challenge; 578 int plen, clen; 579 580 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication."); 581 582 /* Tell the server that we are willing to authenticate using this key. */ 583 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA); 584 packet_put_string(local_user, strlen(local_user)); 585 packet_put_int(BN_num_bits(host_key->n)); 586 packet_put_bignum(host_key->e); 587 packet_put_bignum(host_key->n); 588 packet_send(); 589 packet_write_wait(); 590 591 /* Wait for server's response. */ 592 type = packet_read(&plen); 593 594 /* The server responds with failure if it doesn't admit our 595 .rhosts authentication or doesn't know our host key. */ 596 if (type == SSH_SMSG_FAILURE) { 597 debug("Server refused our rhosts authentication or host key."); 598 return 0; 599 } 600 /* Otherwise, the server should respond with a challenge. */ 601 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE) 602 packet_disconnect("Protocol error during RSA authentication: %d", type); 603 604 /* Get the challenge from the packet. */ 605 challenge = BN_new(); 606 packet_get_bignum(challenge, &clen); 607 608 packet_integrity_check(plen, clen, type); 609 610 debug("Received RSA challenge for host key from server."); 611 612 /* Compute a response to the challenge. */ 613 respond_to_rsa_challenge(challenge, host_key); 614 615 /* We no longer need the challenge. */ 616 BN_clear_free(challenge); 617 618 /* Wait for response from the server. */ 619 type = packet_read(&plen); 620 if (type == SSH_SMSG_SUCCESS) { 621 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server."); 622 return 1; 623 } 624 if (type != SSH_SMSG_FAILURE) 625 packet_disconnect("Protocol error waiting RSA auth response: %d", type); 626 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused."); 627 return 0; 628 } 629 630 #ifdef KRB4 631 int 632 try_krb4_authentication() 633 { 634 KTEXT_ST auth; /* Kerberos data */ 635 char *reply; 636 char inst[INST_SZ]; 637 char *realm; 638 CREDENTIALS cred; 639 int r, type, plen; 640 socklen_t slen; 641 Key_schedule schedule; 642 u_long checksum, cksum; 643 MSG_DAT msg_data; 644 struct sockaddr_in local, foreign; 645 struct stat st; 646 647 /* Don't do anything if we don't have any tickets. */ 648 if (stat(tkt_string(), &st) < 0) 649 return 0; 650 651 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ); 652 653 realm = (char *) krb_realmofhost(get_canonical_hostname()); 654 if (!realm) { 655 debug("Kerberos V4: no realm for %s", get_canonical_hostname()); 656 return 0; 657 } 658 /* This can really be anything. */ 659 checksum = (u_long) getpid(); 660 661 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum); 662 if (r != KSUCCESS) { 663 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]); 664 return 0; 665 } 666 /* Get session key to decrypt the server's reply with. */ 667 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred); 668 if (r != KSUCCESS) { 669 debug("get_cred failed: %s", krb_err_txt[r]); 670 return 0; 671 } 672 des_key_sched((des_cblock *) cred.session, schedule); 673 674 /* Send authentication info to server. */ 675 packet_start(SSH_CMSG_AUTH_KRB4); 676 packet_put_string((char *) auth.dat, auth.length); 677 packet_send(); 678 packet_write_wait(); 679 680 /* Zero the buffer. */ 681 (void) memset(auth.dat, 0, MAX_KTXT_LEN); 682 683 slen = sizeof(local); 684 memset(&local, 0, sizeof(local)); 685 if (getsockname(packet_get_connection_in(), 686 (struct sockaddr *) & local, &slen) < 0) 687 debug("getsockname failed: %s", strerror(errno)); 688 689 slen = sizeof(foreign); 690 memset(&foreign, 0, sizeof(foreign)); 691 if (getpeername(packet_get_connection_in(), 692 (struct sockaddr *) & foreign, &slen) < 0) { 693 debug("getpeername failed: %s", strerror(errno)); 694 fatal_cleanup(); 695 } 696 /* Get server reply. */ 697 type = packet_read(&plen); 698 switch (type) { 699 case SSH_SMSG_FAILURE: 700 /* Should really be SSH_SMSG_AUTH_KRB4_FAILURE */ 701 debug("Kerberos V4 authentication failed."); 702 return 0; 703 break; 704 705 case SSH_SMSG_AUTH_KRB4_RESPONSE: 706 /* SSH_SMSG_AUTH_KRB4_SUCCESS */ 707 debug("Kerberos V4 authentication accepted."); 708 709 /* Get server's response. */ 710 reply = packet_get_string((unsigned int *) &auth.length); 711 memcpy(auth.dat, reply, auth.length); 712 xfree(reply); 713 714 packet_integrity_check(plen, 4 + auth.length, type); 715 716 /* 717 * If his response isn't properly encrypted with the session 718 * key, and the decrypted checksum fails to match, he's 719 * bogus. Bail out. 720 */ 721 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session, 722 &foreign, &local, &msg_data); 723 if (r != KSUCCESS) { 724 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]); 725 packet_disconnect("Kerberos V4 challenge failed!"); 726 } 727 /* Fetch the (incremented) checksum that we supplied in the request. */ 728 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum)); 729 cksum = ntohl(cksum); 730 731 /* If it matches, we're golden. */ 732 if (cksum == checksum + 1) { 733 debug("Kerberos V4 challenge successful."); 734 return 1; 735 } else 736 packet_disconnect("Kerberos V4 challenge failed!"); 737 break; 738 739 default: 740 packet_disconnect("Protocol error on Kerberos V4 response: %d", type); 741 } 742 return 0; 743 } 744 745 #endif /* KRB4 */ 746 747 #ifdef AFS 748 int 749 send_krb4_tgt() 750 { 751 CREDENTIALS *creds; 752 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ]; 753 int r, type, plen; 754 char buffer[8192]; 755 struct stat st; 756 757 /* Don't do anything if we don't have any tickets. */ 758 if (stat(tkt_string(), &st) < 0) 759 return 0; 760 761 creds = xmalloc(sizeof(*creds)); 762 763 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) { 764 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]); 765 return 0; 766 } 767 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) { 768 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]); 769 return 0; 770 } 771 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) { 772 debug("Kerberos V4 ticket expired: %s", TKT_FILE); 773 return 0; 774 } 775 creds_to_radix(creds, (unsigned char *)buffer); 776 xfree(creds); 777 778 packet_start(SSH_CMSG_HAVE_KRB4_TGT); 779 packet_put_string((char *) buffer, strlen(buffer)); 780 packet_send(); 781 packet_write_wait(); 782 783 type = packet_read(&plen); 784 785 if (type == SSH_SMSG_FAILURE) 786 debug("Kerberos TGT for realm %s rejected.", prealm); 787 else if (type != SSH_SMSG_SUCCESS) 788 packet_disconnect("Protocol error on Kerberos TGT response: %d", type); 789 790 return 1; 791 } 792 793 void 794 send_afs_tokens(void) 795 { 796 CREDENTIALS creds; 797 struct ViceIoctl parms; 798 struct ClearToken ct; 799 int i, type, len, plen; 800 char buf[2048], *p, *server_cell; 801 char buffer[8192]; 802 803 /* Move over ktc_GetToken, here's something leaner. */ 804 for (i = 0; i < 100; i++) { /* just in case */ 805 parms.in = (char *) &i; 806 parms.in_size = sizeof(i); 807 parms.out = buf; 808 parms.out_size = sizeof(buf); 809 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0) 810 break; 811 p = buf; 812 813 /* Get secret token. */ 814 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int)); 815 if (creds.ticket_st.length > MAX_KTXT_LEN) 816 break; 817 p += sizeof(unsigned int); 818 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length); 819 p += creds.ticket_st.length; 820 821 /* Get clear token. */ 822 memcpy(&len, p, sizeof(len)); 823 if (len != sizeof(struct ClearToken)) 824 break; 825 p += sizeof(len); 826 memcpy(&ct, p, len); 827 p += len; 828 p += sizeof(len); /* primary flag */ 829 server_cell = p; 830 831 /* Flesh out our credentials. */ 832 strlcpy(creds.service, "afs", sizeof creds.service); 833 creds.instance[0] = '\0'; 834 strlcpy(creds.realm, server_cell, REALM_SZ); 835 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ); 836 creds.issue_date = ct.BeginTimestamp; 837 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp); 838 creds.kvno = ct.AuthHandle; 839 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId); 840 creds.pinst[0] = '\0'; 841 842 /* Encode token, ship it off. */ 843 if (!creds_to_radix(&creds, (unsigned char*) buffer)) 844 break; 845 packet_start(SSH_CMSG_HAVE_AFS_TOKEN); 846 packet_put_string(buffer, strlen(buffer)); 847 packet_send(); 848 packet_write_wait(); 849 850 /* Roger, Roger. Clearance, Clarence. What's your vector, 851 Victor? */ 852 type = packet_read(&plen); 853 854 if (type == SSH_SMSG_FAILURE) 855 debug("AFS token for cell %s rejected.", server_cell); 856 else if (type != SSH_SMSG_SUCCESS) 857 packet_disconnect("Protocol error on AFS token response: %d", type); 858 } 859 } 860 861 #endif /* AFS */ 862 863 #ifdef KRB5 864 int 865 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context) 866 { 867 krb5_error_code problem; 868 const char *tkfile; 869 struct stat buf; 870 krb5_ccache ccache = NULL; 871 krb5_creds req_creds; 872 krb5_creds *new_creds = NULL; 873 const char *remotehost; 874 krb5_data ap; 875 int type, payload_len; 876 krb5_ap_rep_enc_part *reply = NULL; 877 int ret; 878 879 memset(&ap, 0, sizeof(ap)); 880 881 problem = krb5_init_context(context); 882 if (problem) { 883 ret = 0; 884 goto out; 885 } 886 887 tkfile = krb5_cc_default_name(*context); 888 if (strncmp(tkfile, "FILE:", 5) == 0) 889 tkfile += 5; 890 891 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) { 892 debug("Kerberos V5: could not get default ccache (permission denied)."); 893 ret = 0; 894 goto out; 895 } 896 897 problem = krb5_cc_default(*context, &ccache); 898 if (problem) { 899 ret = 0; 900 goto out; 901 } 902 903 memset(&req_creds, 0, sizeof(req_creds)); 904 905 remotehost = get_canonical_hostname(); 906 907 problem = krb5_sname_to_principal(*context, remotehost, 908 "host", KRB5_NT_SRV_HST, 909 &req_creds.server); 910 if (problem) { 911 ret = 0; 912 goto out; 913 914 } 915 916 problem = krb5_cc_get_principal(*context, ccache, &req_creds.client); 917 if (problem) { 918 ret = 0; 919 goto out; 920 } 921 922 /* creds.session.keytype=ETYPE_DES_CBC_CRC; */ 923 924 problem = krb5_get_credentials(*context, 0, ccache, &req_creds, &new_creds); 925 if (problem) { 926 ret = 0; 927 goto out; 928 } 929 930 problem = krb5_auth_con_init(*context, auth_context); 931 if (problem) { 932 ret = 0; 933 goto out; 934 } 935 936 /* krb5_auth_con_setflags(ssh_context, auth_context, 937 KRB5_AUTH_CONTEXT_RET_TIME); 938 */ 939 problem = krb5_mk_req_extended(*context, auth_context, 940 AP_OPTS_MUTUAL_REQUIRED /*| AP_OPTS_USE_SUBKEY*/ , 941 NULL, new_creds, &ap); 942 if (problem) { 943 ret = 0; 944 goto out; 945 } 946 947 packet_start(SSH_CMSG_AUTH_KRB5); 948 packet_put_string((char *) ap.data, ap.length); 949 packet_send(); 950 packet_write_wait(); 951 952 xfree(ap.data); 953 ap.length = 0; 954 955 type = packet_read(&payload_len); 956 switch (type) { 957 case SSH_SMSG_FAILURE: 958 /* Should really be SSH_SMSG_AUTH_KRB5_FAILURE */ 959 debug("Kerberos V5 authentication failed."); 960 ret = 0; 961 break; 962 963 case SSH_SMSG_AUTH_KRB5_RESPONSE: 964 /* SSH_SMSG_AUTH_KRB5_SUCCESS */ 965 debug("Kerberos V5 authentication accepted."); 966 967 /* Get server's response. */ 968 ap.data = packet_get_string((unsigned int *) &ap.length); 969 970 packet_integrity_check(payload_len, 4 + ap.length, type); 971 /* XXX je to dobre? */ 972 973 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply); 974 if (problem) { 975 ret = 0; 976 } 977 ret = 1; 978 break; 979 980 default: 981 packet_disconnect("Protocol error on Kerberos V5 response: %d", type); 982 ret = 0; 983 break; 984 985 } 986 987 out: 988 if (req_creds.server != NULL) 989 krb5_free_principal(*context, req_creds.server); 990 if (req_creds.client != NULL) 991 krb5_free_principal(*context, req_creds.client); 992 if (new_creds != NULL) 993 krb5_free_creds(*context, new_creds); 994 if (ccache != NULL) 995 krb5_cc_close(*context, ccache); 996 if (reply != NULL) 997 krb5_free_ap_rep_enc_part(*context, reply); 998 if (ap.length > 0) 999 krb5_data_free(&ap); 1000 1001 return ret; 1002 1003 } 1004 1005 void 1006 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context) 1007 { 1008 int fd; 1009 int type, payload_len; 1010 krb5_error_code problem; 1011 krb5_data outbuf; 1012 krb5_ccache ccache = NULL; 1013 krb5_creds creds; 1014 krb5_kdc_flags flags; 1015 const char* remotehost = get_canonical_hostname(); 1016 1017 memset(&creds, 0, sizeof(creds)); 1018 memset(&outbuf, 0, sizeof(outbuf)); 1019 1020 fd = packet_get_connection_in(); 1021 problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd); 1022 if (problem) { 1023 goto out; 1024 } 1025 1026 #if 0 1027 tkfile = krb5_cc_default_name(context); 1028 if (strncmp(tkfile, "FILE:", 5) == 0) 1029 tkfile += 5; 1030 1031 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) { 1032 debug("Kerberos V5: could not get default ccache (permission denied)."); 1033 goto out; 1034 } 1035 #endif 1036 1037 problem = krb5_cc_default(context, &ccache); 1038 if (problem) { 1039 goto out; 1040 } 1041 1042 problem = krb5_cc_get_principal(context, ccache, &creds.client); 1043 if (problem) { 1044 goto out; 1045 } 1046 1047 problem = krb5_build_principal(context, &creds.server, 1048 strlen(creds.client->realm), 1049 creds.client->realm, 1050 "krbtgt", 1051 creds.client->realm, 1052 NULL); 1053 if (problem) { 1054 goto out; 1055 } 1056 1057 creds.times.endtime = 0; 1058 1059 flags.i = 0; 1060 flags.b.forwarded = 1; 1061 flags.b.forwardable = krb5_config_get_bool(context, NULL, 1062 "libdefaults", "forwardable", NULL); 1063 1064 problem = krb5_get_forwarded_creds (context, 1065 auth_context, 1066 ccache, 1067 flags.i, 1068 remotehost, 1069 &creds, 1070 &outbuf); 1071 if (problem) { 1072 goto out; 1073 } 1074 1075 packet_start(SSH_CMSG_HAVE_KRB5_TGT); 1076 packet_put_string((char *)outbuf.data, outbuf.length); 1077 packet_send(); 1078 packet_write_wait(); 1079 1080 type = packet_read(&payload_len); 1081 switch (type) { 1082 case SSH_SMSG_SUCCESS: 1083 break; 1084 case SSH_SMSG_FAILURE: 1085 break; 1086 default: 1087 break; 1088 } 1089 1090 out: 1091 if (creds.client) 1092 krb5_free_principal(context, creds.client); 1093 if (creds.server) 1094 krb5_free_principal(context, creds.server); 1095 if (ccache) 1096 krb5_cc_close(context, ccache); 1097 if (outbuf.data) 1098 xfree(outbuf.data); 1099 1100 return; 1101 } 1102 #endif /* KRB5 */ 1103 1104 /* 1105 * Tries to authenticate with any string-based challenge/response system. 1106 * Note that the client code is not tied to s/key or TIS. 1107 */ 1108 int 1109 try_skey_authentication() 1110 { 1111 int type, i; 1112 int payload_len; 1113 unsigned int clen; 1114 char *challenge, *response; 1115 1116 debug("Doing skey authentication."); 1117 1118 /* request a challenge */ 1119 packet_start(SSH_CMSG_AUTH_TIS); 1120 packet_send(); 1121 packet_write_wait(); 1122 1123 type = packet_read(&payload_len); 1124 if (type != SSH_SMSG_FAILURE && 1125 type != SSH_SMSG_AUTH_TIS_CHALLENGE) { 1126 packet_disconnect("Protocol error: got %d in response " 1127 "to skey-auth", type); 1128 } 1129 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) { 1130 debug("No challenge for skey authentication."); 1131 return 0; 1132 } 1133 challenge = packet_get_string(&clen); 1134 packet_integrity_check(payload_len, (4 + clen), type); 1135 if (options.cipher == SSH_CIPHER_NONE) 1136 log("WARNING: Encryption is disabled! " 1137 "Reponse will be transmitted in clear text."); 1138 fprintf(stderr, "%s\n", challenge); 1139 xfree(challenge); 1140 fflush(stderr); 1141 for (i = 0; i < options.number_of_password_prompts; i++) { 1142 if (i != 0) 1143 error("Permission denied, please try again."); 1144 response = read_passphrase("Response: ", 0); 1145 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE); 1146 packet_put_string(response, strlen(response)); 1147 memset(response, 0, strlen(response)); 1148 xfree(response); 1149 packet_send(); 1150 packet_write_wait(); 1151 type = packet_read(&payload_len); 1152 if (type == SSH_SMSG_SUCCESS) 1153 return 1; 1154 if (type != SSH_SMSG_FAILURE) 1155 packet_disconnect("Protocol error: got %d in response " 1156 "to skey-auth-reponse", type); 1157 } 1158 /* failure */ 1159 return 0; 1160 } 1161 1162 /* 1163 * Tries to authenticate with plain passwd authentication. 1164 */ 1165 int 1166 try_password_authentication(char *prompt) 1167 { 1168 int type, i, payload_len; 1169 char *password; 1170 1171 debug("Doing password authentication."); 1172 if (options.cipher == SSH_CIPHER_NONE) 1173 log("WARNING: Encryption is disabled! Password will be transmitted in clear text."); 1174 for (i = 0; i < options.number_of_password_prompts; i++) { 1175 if (i != 0) 1176 error("Permission denied, please try again."); 1177 password = read_passphrase(prompt, 0); 1178 packet_start(SSH_CMSG_AUTH_PASSWORD); 1179 packet_put_string(password, strlen(password)); 1180 memset(password, 0, strlen(password)); 1181 xfree(password); 1182 packet_send(); 1183 packet_write_wait(); 1184 1185 type = packet_read(&payload_len); 1186 if (type == SSH_SMSG_SUCCESS) 1187 return 1; 1188 if (type != SSH_SMSG_FAILURE) 1189 packet_disconnect("Protocol error: got %d in response to passwd auth", type); 1190 } 1191 /* failure */ 1192 return 0; 1193 } 1194 1195 /* 1196 * Waits for the server identification string, and sends our own 1197 * identification string. 1198 */ 1199 void 1200 ssh_exchange_identification() 1201 { 1202 char buf[256], remote_version[256]; /* must be same size! */ 1203 int remote_major, remote_minor, i; 1204 int connection_in = packet_get_connection_in(); 1205 int connection_out = packet_get_connection_out(); 1206 1207 /* Read other side\'s version identification. */ 1208 for (i = 0; i < sizeof(buf) - 1; i++) { 1209 int len = read(connection_in, &buf[i], 1); 1210 if (len < 0) 1211 fatal("ssh_exchange_identification: read: %.100s", strerror(errno)); 1212 if (len != 1) 1213 fatal("ssh_exchange_identification: Connection closed by remote host"); 1214 if (buf[i] == '\r') { 1215 buf[i] = '\n'; 1216 buf[i + 1] = 0; 1217 break; 1218 } 1219 if (buf[i] == '\n') { 1220 buf[i + 1] = 0; 1221 break; 1222 } 1223 } 1224 buf[sizeof(buf) - 1] = 0; 1225 1226 /* 1227 * Check that the versions match. In future this might accept 1228 * several versions and set appropriate flags to handle them. 1229 */ 1230 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor, 1231 remote_version) != 3) 1232 fatal("Bad remote protocol version identification: '%.100s'", buf); 1233 debug("Remote protocol version %d.%d, remote software version %.100s", 1234 remote_major, remote_minor, remote_version); 1235 1236 /* Check if the remote protocol version is too old. */ 1237 if (remote_major == 1 && remote_minor < 3) 1238 fatal("Remote machine has too old SSH software version."); 1239 1240 /* We speak 1.3, too. */ 1241 if (remote_major == 1 && remote_minor == 3) { 1242 enable_compat13(); 1243 if (options.forward_agent) { 1244 log("Agent forwarding disabled for protocol 1.3"); 1245 options.forward_agent = 0; 1246 } 1247 } 1248 #if 0 1249 /* 1250 * Removed for now, to permit compatibility with latter versions. The 1251 * server will reject our version and disconnect if it doesn't 1252 * support it. 1253 */ 1254 if (remote_major != PROTOCOL_MAJOR) 1255 fatal("Protocol major versions differ: %d vs. %d", 1256 PROTOCOL_MAJOR, remote_major); 1257 #endif 1258 1259 /* Send our own protocol version identification. */ 1260 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", 1261 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION); 1262 if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf)) 1263 fatal("write: %.100s", strerror(errno)); 1264 } 1265 1266 int ssh_cipher_default = SSH_CIPHER_3DES; 1267 1268 int 1269 read_yes_or_no(const char *prompt, int defval) 1270 { 1271 char buf[1024]; 1272 FILE *f; 1273 int retval = -1; 1274 1275 if (isatty(0)) 1276 f = stdin; 1277 else 1278 f = fopen("/dev/tty", "rw"); 1279 1280 if (f == NULL) 1281 return 0; 1282 1283 fflush(stdout); 1284 1285 while (1) { 1286 fprintf(stderr, "%s", prompt); 1287 if (fgets(buf, sizeof(buf), f) == NULL) { 1288 /* Print a newline (the prompt probably didn\'t have one). */ 1289 fprintf(stderr, "\n"); 1290 strlcpy(buf, "no", sizeof buf); 1291 } 1292 /* Remove newline from response. */ 1293 if (strchr(buf, '\n')) 1294 *strchr(buf, '\n') = 0; 1295 1296 if (buf[0] == 0) 1297 retval = defval; 1298 if (strcmp(buf, "yes") == 0) 1299 retval = 1; 1300 if (strcmp(buf, "no") == 0) 1301 retval = 0; 1302 1303 if (retval != -1) { 1304 if (f != stdin) 1305 fclose(f); 1306 return retval; 1307 } 1308 } 1309 } 1310 1311 /* 1312 * check whether the supplied host key is valid, return only if ok. 1313 */ 1314 1315 void 1316 check_host_key(char *host, struct sockaddr *hostaddr, Key *host_key) 1317 { 1318 Key *file_key; 1319 char *ip = NULL; 1320 char hostline[1000], *hostp; 1321 HostStatus host_status; 1322 HostStatus ip_status; 1323 int local = 0, host_ip_differ = 0; 1324 char ntop[NI_MAXHOST]; 1325 1326 /* 1327 * Force accepting of the host key for loopback/localhost. The 1328 * problem is that if the home directory is NFS-mounted to multiple 1329 * machines, localhost will refer to a different machine in each of 1330 * them, and the user will get bogus HOST_CHANGED warnings. This 1331 * essentially disables host authentication for localhost; however, 1332 * this is probably not a real problem. 1333 */ 1334 switch (hostaddr->sa_family) { 1335 case AF_INET: 1336 local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET; 1337 break; 1338 case AF_INET6: 1339 local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr)); 1340 break; 1341 default: 1342 local = 0; 1343 break; 1344 } 1345 if (local) { 1346 debug("Forcing accepting of host key for loopback/localhost."); 1347 return; 1348 } 1349 1350 /* 1351 * Turn off check_host_ip for proxy connects, since 1352 * we don't have the remote ip-address 1353 */ 1354 if (options.proxy_command != NULL && options.check_host_ip) 1355 options.check_host_ip = 0; 1356 1357 if (options.check_host_ip) { 1358 if (getnameinfo(hostaddr, hostaddr->sa_len, ntop, sizeof(ntop), 1359 NULL, 0, NI_NUMERICHOST) != 0) 1360 fatal("check_host_key: getnameinfo failed"); 1361 ip = xstrdup(ntop); 1362 } 1363 1364 /* 1365 * Store the host key from the known host file in here so that we can 1366 * compare it with the key for the IP address. 1367 */ 1368 file_key = key_new(host_key->type); 1369 1370 /* 1371 * Check if the host key is present in the user\'s list of known 1372 * hosts or in the systemwide list. 1373 */ 1374 host_status = check_host_in_hostfile(options.user_hostfile, host, host_key, file_key); 1375 if (host_status == HOST_NEW) 1376 host_status = check_host_in_hostfile(options.system_hostfile, host, host_key, file_key); 1377 /* 1378 * Also perform check for the ip address, skip the check if we are 1379 * localhost or the hostname was an ip address to begin with 1380 */ 1381 if (options.check_host_ip && !local && strcmp(host, ip)) { 1382 Key *ip_key = key_new(host_key->type); 1383 ip_status = check_host_in_hostfile(options.user_hostfile, ip, host_key, ip_key); 1384 1385 if (ip_status == HOST_NEW) 1386 ip_status = check_host_in_hostfile(options.system_hostfile, ip, host_key, ip_key); 1387 if (host_status == HOST_CHANGED && 1388 (ip_status != HOST_CHANGED || !key_equal(ip_key, file_key))) 1389 host_ip_differ = 1; 1390 1391 key_free(ip_key); 1392 } else 1393 ip_status = host_status; 1394 1395 key_free(file_key); 1396 1397 switch (host_status) { 1398 case HOST_OK: 1399 /* The host is known and the key matches. */ 1400 debug("Host '%.200s' is known and matches the host key.", host); 1401 if (options.check_host_ip) { 1402 if (ip_status == HOST_NEW) { 1403 if (!add_host_to_hostfile(options.user_hostfile, ip, host_key)) 1404 log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).", 1405 ip, options.user_hostfile); 1406 else 1407 log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.", 1408 ip); 1409 } else if (ip_status != HOST_OK) 1410 log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'", 1411 host, ip); 1412 } 1413 break; 1414 case HOST_NEW: 1415 /* The host is new. */ 1416 if (options.strict_host_key_checking == 1) { 1417 /* User has requested strict host key checking. We will not add the host key 1418 automatically. The only alternative left is to abort. */ 1419 fatal("No host key is known for %.200s and you have requested strict checking.", host); 1420 } else if (options.strict_host_key_checking == 2) { 1421 /* The default */ 1422 char prompt[1024]; 1423 char *fp = key_fingerprint(host_key); 1424 snprintf(prompt, sizeof(prompt), 1425 "The authenticity of host '%.200s' can't be established.\n" 1426 "Key fingerprint is %s.\n" 1427 "Are you sure you want to continue connecting (yes/no)? ", 1428 host, fp); 1429 if (!read_yes_or_no(prompt, -1)) 1430 fatal("Aborted by user!\n"); 1431 } 1432 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) { 1433 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip); 1434 hostp = hostline; 1435 } else 1436 hostp = host; 1437 1438 /* If not in strict mode, add the key automatically to the local known_hosts file. */ 1439 if (!add_host_to_hostfile(options.user_hostfile, hostp, host_key)) 1440 log("Failed to add the host to the list of known hosts (%.500s).", 1441 options.user_hostfile); 1442 else 1443 log("Warning: Permanently added '%.200s' to the list of known hosts.", 1444 hostp); 1445 break; 1446 case HOST_CHANGED: 1447 if (options.check_host_ip && host_ip_differ) { 1448 char *msg; 1449 if (ip_status == HOST_NEW) 1450 msg = "is unknown"; 1451 else if (ip_status == HOST_OK) 1452 msg = "is unchanged"; 1453 else 1454 msg = "has a different value"; 1455 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 1456 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @"); 1457 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 1458 error("The host key for %s has changed,", host); 1459 error("and the key for the according IP address %s", ip); 1460 error("%s. This could either mean that", msg); 1461 error("DNS SPOOFING is happening or the IP address for the host"); 1462 error("and its host key have changed at the same time"); 1463 } 1464 /* The host key has changed. */ 1465 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 1466 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @"); 1467 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); 1468 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!"); 1469 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!"); 1470 error("It is also possible that the host key has just been changed."); 1471 error("Please contact your system administrator."); 1472 error("Add correct host key in %.100s to get rid of this message.", 1473 options.user_hostfile); 1474 1475 /* 1476 * If strict host key checking is in use, the user will have 1477 * to edit the key manually and we can only abort. 1478 */ 1479 if (options.strict_host_key_checking) 1480 fatal("Host key for %.200s has changed and you have requested strict checking.", host); 1481 1482 /* 1483 * If strict host key checking has not been requested, allow 1484 * the connection but without password authentication or 1485 * agent forwarding. 1486 */ 1487 if (options.password_authentication) { 1488 error("Password authentication is disabled to avoid trojan horses."); 1489 options.password_authentication = 0; 1490 } 1491 if (options.forward_agent) { 1492 error("Agent forwarding is disabled to avoid trojan horses."); 1493 options.forward_agent = 0; 1494 } 1495 /* 1496 * XXX Should permit the user to change to use the new id. 1497 * This could be done by converting the host key to an 1498 * identifying sentence, tell that the host identifies itself 1499 * by that sentence, and ask the user if he/she whishes to 1500 * accept the authentication. 1501 */ 1502 break; 1503 } 1504 if (options.check_host_ip) 1505 xfree(ip); 1506 } 1507 void 1508 check_rsa_host_key(char *host, struct sockaddr *hostaddr, RSA *host_key) 1509 { 1510 Key k; 1511 k.type = KEY_RSA; 1512 k.rsa = host_key; 1513 check_host_key(host, hostaddr, &k); 1514 } 1515 1516 /* 1517 * SSH1 key exchange 1518 */ 1519 void 1520 ssh_kex(char *host, struct sockaddr *hostaddr) 1521 { 1522 int i; 1523 BIGNUM *key; 1524 RSA *host_key; 1525 RSA *public_key; 1526 int bits, rbits; 1527 unsigned char session_key[SSH_SESSION_KEY_LENGTH]; 1528 unsigned char cookie[8]; 1529 unsigned int supported_ciphers; 1530 unsigned int server_flags, client_flags; 1531 int payload_len, clen, sum_len = 0; 1532 u_int32_t rand = 0; 1533 1534 debug("Waiting for server public key."); 1535 1536 /* Wait for a public key packet from the server. */ 1537 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY); 1538 1539 /* Get cookie from the packet. */ 1540 for (i = 0; i < 8; i++) 1541 cookie[i] = packet_get_char(); 1542 1543 /* Get the public key. */ 1544 public_key = RSA_new(); 1545 bits = packet_get_int();/* bits */ 1546 public_key->e = BN_new(); 1547 packet_get_bignum(public_key->e, &clen); 1548 sum_len += clen; 1549 public_key->n = BN_new(); 1550 packet_get_bignum(public_key->n, &clen); 1551 sum_len += clen; 1552 1553 rbits = BN_num_bits(public_key->n); 1554 if (bits != rbits) { 1555 log("Warning: Server lies about size of server public key: " 1556 "actual size is %d bits vs. announced %d.", rbits, bits); 1557 log("Warning: This may be due to an old implementation of ssh."); 1558 } 1559 /* Get the host key. */ 1560 host_key = RSA_new(); 1561 bits = packet_get_int();/* bits */ 1562 host_key->e = BN_new(); 1563 packet_get_bignum(host_key->e, &clen); 1564 sum_len += clen; 1565 host_key->n = BN_new(); 1566 packet_get_bignum(host_key->n, &clen); 1567 sum_len += clen; 1568 1569 rbits = BN_num_bits(host_key->n); 1570 if (bits != rbits) { 1571 log("Warning: Server lies about size of server host key: " 1572 "actual size is %d bits vs. announced %d.", rbits, bits); 1573 log("Warning: This may be due to an old implementation of ssh."); 1574 } 1575 1576 /* Get protocol flags. */ 1577 server_flags = packet_get_int(); 1578 packet_set_protocol_flags(server_flags); 1579 1580 supported_ciphers = packet_get_int(); 1581 supported_authentications = packet_get_int(); 1582 1583 debug("Received server public key (%d bits) and host key (%d bits).", 1584 BN_num_bits(public_key->n), BN_num_bits(host_key->n)); 1585 1586 packet_integrity_check(payload_len, 1587 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4, 1588 SSH_SMSG_PUBLIC_KEY); 1589 1590 check_rsa_host_key(host, hostaddr, host_key); 1591 1592 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN; 1593 1594 compute_session_id(session_id, cookie, host_key->n, public_key->n); 1595 1596 /* Generate a session key. */ 1597 arc4random_stir(); 1598 1599 /* 1600 * Generate an encryption key for the session. The key is a 256 bit 1601 * random number, interpreted as a 32-byte key, with the least 1602 * significant 8 bits being the first byte of the key. 1603 */ 1604 for (i = 0; i < 32; i++) { 1605 if (i % 4 == 0) 1606 rand = arc4random(); 1607 session_key[i] = rand & 0xff; 1608 rand >>= 8; 1609 } 1610 1611 /* 1612 * According to the protocol spec, the first byte of the session key 1613 * is the highest byte of the integer. The session key is xored with 1614 * the first 16 bytes of the session id. 1615 */ 1616 key = BN_new(); 1617 BN_set_word(key, 0); 1618 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) { 1619 BN_lshift(key, key, 8); 1620 if (i < 16) 1621 BN_add_word(key, session_key[i] ^ session_id[i]); 1622 else 1623 BN_add_word(key, session_key[i]); 1624 } 1625 1626 /* 1627 * Encrypt the integer using the public key and host key of the 1628 * server (key with smaller modulus first). 1629 */ 1630 if (BN_cmp(public_key->n, host_key->n) < 0) { 1631 /* Public key has smaller modulus. */ 1632 if (BN_num_bits(host_key->n) < 1633 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) { 1634 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + " 1635 "SSH_KEY_BITS_RESERVED %d", 1636 BN_num_bits(host_key->n), 1637 BN_num_bits(public_key->n), 1638 SSH_KEY_BITS_RESERVED); 1639 } 1640 rsa_public_encrypt(key, key, public_key); 1641 rsa_public_encrypt(key, key, host_key); 1642 } else { 1643 /* Host key has smaller modulus (or they are equal). */ 1644 if (BN_num_bits(public_key->n) < 1645 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) { 1646 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + " 1647 "SSH_KEY_BITS_RESERVED %d", 1648 BN_num_bits(public_key->n), 1649 BN_num_bits(host_key->n), 1650 SSH_KEY_BITS_RESERVED); 1651 } 1652 rsa_public_encrypt(key, key, host_key); 1653 rsa_public_encrypt(key, key, public_key); 1654 } 1655 1656 /* Destroy the public keys since we no longer need them. */ 1657 RSA_free(public_key); 1658 RSA_free(host_key); 1659 1660 if (options.cipher == SSH_CIPHER_NOT_SET) { 1661 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default)) 1662 options.cipher = ssh_cipher_default; 1663 else { 1664 debug("Cipher %s not supported, using %.100s instead.", 1665 cipher_name(ssh_cipher_default), 1666 cipher_name(SSH_FALLBACK_CIPHER)); 1667 options.cipher = SSH_FALLBACK_CIPHER; 1668 } 1669 } 1670 /* Check that the selected cipher is supported. */ 1671 if (!(supported_ciphers & (1 << options.cipher))) 1672 fatal("Selected cipher type %.100s not supported by server.", 1673 cipher_name(options.cipher)); 1674 1675 debug("Encryption type: %.100s", cipher_name(options.cipher)); 1676 1677 /* Send the encrypted session key to the server. */ 1678 packet_start(SSH_CMSG_SESSION_KEY); 1679 packet_put_char(options.cipher); 1680 1681 /* Send the cookie back to the server. */ 1682 for (i = 0; i < 8; i++) 1683 packet_put_char(cookie[i]); 1684 1685 /* Send and destroy the encrypted encryption key integer. */ 1686 packet_put_bignum(key); 1687 BN_clear_free(key); 1688 1689 /* Send protocol flags. */ 1690 packet_put_int(client_flags); 1691 1692 /* Send the packet now. */ 1693 packet_send(); 1694 packet_write_wait(); 1695 1696 debug("Sent encrypted session key."); 1697 1698 /* Set the encryption key. */ 1699 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher); 1700 1701 /* We will no longer need the session key here. Destroy any extra copies. */ 1702 memset(session_key, 0, sizeof(session_key)); 1703 1704 /* 1705 * Expect a success message from the server. Note that this message 1706 * will be received in encrypted form. 1707 */ 1708 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS); 1709 1710 debug("Received encrypted confirmation."); 1711 } 1712 1713 /* 1714 * Authenticate user 1715 */ 1716 void 1717 ssh_userauth(int host_key_valid, RSA *own_host_key, 1718 uid_t original_real_uid, char *host) 1719 { 1720 int i, type; 1721 int payload_len; 1722 struct passwd *pw; 1723 const char *server_user, *local_user; 1724 1725 /* Get local user name. Use it as server user if no user name was given. */ 1726 pw = getpwuid(original_real_uid); 1727 if (!pw) 1728 fatal("User id %d not found from user database.", original_real_uid); 1729 local_user = xstrdup(pw->pw_name); 1730 server_user = options.user ? options.user : local_user; 1731 1732 /* Send the name of the user to log in as on the server. */ 1733 packet_start(SSH_CMSG_USER); 1734 packet_put_string(server_user, strlen(server_user)); 1735 packet_send(); 1736 packet_write_wait(); 1737 1738 /* 1739 * The server should respond with success if no authentication is 1740 * needed (the user has no password). Otherwise the server responds 1741 * with failure. 1742 */ 1743 type = packet_read(&payload_len); 1744 1745 /* check whether the connection was accepted without authentication. */ 1746 if (type == SSH_SMSG_SUCCESS) 1747 return; 1748 if (type != SSH_SMSG_FAILURE) 1749 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", 1750 type); 1751 1752 #ifdef AFS 1753 /* Try Kerberos tgt passing if the server supports it. */ 1754 if ((supported_authentications & (1 << SSH_PASS_KRB4_TGT)) && 1755 options.krb4_tgt_passing) { 1756 if (options.cipher == SSH_CIPHER_NONE) 1757 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!"); 1758 (void) send_krb4_tgt(); 1759 } 1760 /* Try AFS token passing if the server supports it. */ 1761 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) && 1762 options.afs_token_passing && k_hasafs()) { 1763 if (options.cipher == SSH_CIPHER_NONE) 1764 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!"); 1765 send_afs_tokens(); 1766 } 1767 #endif /* AFS */ 1768 1769 #ifdef KRB4 1770 if ((supported_authentications & (1 << SSH_AUTH_KRB4)) && 1771 options.krb4_authentication) { 1772 debug("Trying Kerberos authentication."); 1773 if (try_krb4_authentication()) { 1774 /* The server should respond with success or failure. */ 1775 type = packet_read(&payload_len); 1776 if (type == SSH_SMSG_SUCCESS) 1777 return; 1778 if (type != SSH_SMSG_FAILURE) 1779 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type); 1780 } 1781 } 1782 #endif /* KRB4 */ 1783 1784 #ifdef KRB5 1785 if ((supported_authentications & (1 << SSH_AUTH_KRB5)) && 1786 options.krb5_authentication){ 1787 krb5_context ssh_context = NULL; 1788 krb5_auth_context auth_context = NULL; 1789 1790 debug("Trying Kerberos V5 authentication."); 1791 1792 if (try_krb5_authentication(&ssh_context, &auth_context)) { 1793 type = packet_read(&payload_len); 1794 if (type == SSH_SMSG_SUCCESS) { 1795 if ((supported_authentications & (1 << SSH_PASS_KRB5_TGT)) && 1796 options.krb5_tgt_passing) { 1797 if (options.cipher == SSH_CIPHER_NONE) 1798 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!"); 1799 send_krb5_tgt(ssh_context, auth_context); 1800 1801 } 1802 krb5_auth_con_free(ssh_context, auth_context); 1803 krb5_free_context(ssh_context); 1804 return; 1805 } 1806 if (type != SSH_SMSG_FAILURE) 1807 packet_disconnect("Protocol error: got %d in response to Kerberos5 auth", type); 1808 1809 } 1810 } 1811 #endif /* KRB5 */ 1812 1813 /* 1814 * Use rhosts authentication if running in privileged socket and we 1815 * do not wish to remain anonymous. 1816 */ 1817 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) && 1818 options.rhosts_authentication) { 1819 debug("Trying rhosts authentication."); 1820 packet_start(SSH_CMSG_AUTH_RHOSTS); 1821 packet_put_string(local_user, strlen(local_user)); 1822 packet_send(); 1823 packet_write_wait(); 1824 1825 /* The server should respond with success or failure. */ 1826 type = packet_read(&payload_len); 1827 if (type == SSH_SMSG_SUCCESS) 1828 return; 1829 if (type != SSH_SMSG_FAILURE) 1830 packet_disconnect("Protocol error: got %d in response to rhosts auth", 1831 type); 1832 } 1833 /* 1834 * Try .rhosts or /etc/hosts.equiv authentication with RSA host 1835 * authentication. 1836 */ 1837 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) && 1838 options.rhosts_rsa_authentication && host_key_valid) { 1839 if (try_rhosts_rsa_authentication(local_user, own_host_key)) 1840 return; 1841 } 1842 /* Try RSA authentication if the server supports it. */ 1843 if ((supported_authentications & (1 << SSH_AUTH_RSA)) && 1844 options.rsa_authentication) { 1845 /* 1846 * Try RSA authentication using the authentication agent. The 1847 * agent is tried first because no passphrase is needed for 1848 * it, whereas identity files may require passphrases. 1849 */ 1850 if (try_agent_authentication()) 1851 return; 1852 1853 /* Try RSA authentication for each identity. */ 1854 for (i = 0; i < options.num_identity_files; i++) 1855 if (try_rsa_authentication(options.identity_files[i])) 1856 return; 1857 } 1858 /* Try skey authentication if the server supports it. */ 1859 if ((supported_authentications & (1 << SSH_AUTH_TIS)) && 1860 options.skey_authentication && !options.batch_mode) { 1861 if (try_skey_authentication()) 1862 return; 1863 } 1864 /* Try password authentication if the server supports it. */ 1865 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) && 1866 options.password_authentication && !options.batch_mode) { 1867 char prompt[80]; 1868 1869 snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ", 1870 server_user, host); 1871 if (try_password_authentication(prompt)) 1872 return; 1873 } 1874 /* All authentication methods have failed. Exit with an error message. */ 1875 fatal("Permission denied."); 1876 /* NOTREACHED */ 1877 } 1878 /* 1879 * Starts a dialog with the server, and authenticates the current user on the 1880 * server. This does not need any extra privileges. The basic connection 1881 * to the server must already have been established before this is called. 1882 * If login fails, this function prints an error and never returns. 1883 * This function does not require super-user privileges. 1884 */ 1885 void 1886 ssh_login(int host_key_valid, RSA *own_host_key, const char *orighost, 1887 struct sockaddr *hostaddr, uid_t original_real_uid) 1888 { 1889 char *host, *cp; 1890 1891 /* Convert the user-supplied hostname into all lowercase. */ 1892 host = xstrdup(orighost); 1893 for (cp = host; *cp; cp++) 1894 if (isupper(*cp)) 1895 *cp = tolower(*cp); 1896 1897 /* Exchange protocol version identification strings with the server. */ 1898 ssh_exchange_identification(); 1899 1900 /* Put the connection into non-blocking mode. */ 1901 packet_set_nonblocking(); 1902 1903 supported_authentications = 0; 1904 /* key exchange */ 1905 ssh_kex(host, hostaddr); 1906 if (supported_authentications == 0) 1907 fatal("supported_authentications == 0."); 1908 1909 /* authenticate user */ 1910 ssh_userauth(host_key_valid, own_host_key, original_real_uid, host); 1911 } 1912