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