440 if (sensitive_data.dsa_host_key != NULL) 441 key_free(sensitive_data.dsa_host_key); 442} 443 444/* 445 * Main program for the daemon. 446 */ 447int 448main(int ac, char **av) 449{ 450 extern char *optarg; 451 extern int optind; 452 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, on = 1; 453 pid_t pid; 454 socklen_t fromlen; 455 int silent = 0; 456 fd_set *fdset; 457 struct sockaddr_storage from; 458 const char *remote_ip; 459 int remote_port; 460 FILE *f; 461 struct linger linger; 462 struct addrinfo *ai; 463 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 464 int listen_sock, maxfd; 465 int connections_per_period_exceeded = 0; 466 467 /* Save argv[0]. */ 468 saved_argv = av; 469 if (strchr(av[0], '/')) 470 av0 = strrchr(av[0], '/') + 1; 471 else 472 av0 = av[0]; 473 474 /* Initialize configuration options to their default values. */ 475 initialize_server_options(&options); 476 477 /* Parse command-line arguments. */ 478 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) { 479 switch (opt) { 480 case '4': 481 IPv4or6 = AF_INET; 482 break; 483 case '6': 484 IPv4or6 = AF_INET6; 485 break; 486 case 'f': 487 config_file_name = optarg; 488 break; 489 case 'd': 490 debug_flag = 1; 491 options.log_level = SYSLOG_LEVEL_DEBUG; 492 break; 493 case 'i': 494 inetd_flag = 1; 495 break; 496 case 'Q': 497 silent = 1; 498 break; 499 case 'q': 500 options.log_level = SYSLOG_LEVEL_QUIET; 501 break; 502 case 'b': 503 options.server_key_bits = atoi(optarg); 504 break; 505 case 'p': 506 options.ports_from_cmdline = 1; 507 if (options.num_ports >= MAX_PORTS) 508 fatal("too many ports.\n"); 509 options.ports[options.num_ports++] = atoi(optarg); 510 break; 511 case 'g': 512 options.login_grace_time = atoi(optarg); 513 break; 514 case 'k': 515 options.key_regeneration_time = atoi(optarg); 516 break; 517 case 'h': 518 options.host_key_file = optarg; 519 break; 520 case 'V': 521 client_version_string = optarg; 522 /* only makes sense with inetd_flag, i.e. no listen() */ 523 inetd_flag = 1; 524 break; 525 case '?': 526 default: 527 fprintf(stderr, "sshd version %s\n", SSH_VERSION); 528 fprintf(stderr, "Usage: %s [options]\n", av0); 529 fprintf(stderr, "Options:\n"); 530 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE); 531 fprintf(stderr, " -d Debugging mode\n"); 532 fprintf(stderr, " -i Started from inetd\n"); 533 fprintf(stderr, " -q Quiet (no logging)\n"); 534 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n"); 535 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n"); 536 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n"); 537 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n"); 538 fprintf(stderr, " -h file File from which to read host key (default: %s)\n", 539 HOST_KEY_FILE); 540 fprintf(stderr, " -4 Use IPv4 only\n"); 541 fprintf(stderr, " -6 Use IPv6 only\n"); 542 exit(1); 543 } 544 } 545 546 /* 547 * Force logging to stderr until we have loaded the private host 548 * key (unless started from inetd) 549 */ 550 log_init(av0, 551 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, 552 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility, 553 !silent && !inetd_flag); 554 555 /* Read server configuration options from the configuration file. */ 556 read_server_config(&options, config_file_name); 557 558 /* Fill in default values for those options not explicitly set. */ 559 fill_default_server_options(&options); 560 561 /* Check that there are no remaining arguments. */ 562 if (optind < ac) { 563 fprintf(stderr, "Extra argument %s.\n", av[optind]); 564 exit(1); 565 } 566 567 debug("sshd version %.100s", SSH_VERSION); 568 569 sensitive_data.dsa_host_key = NULL; 570 sensitive_data.host_key = NULL; 571 572 /* check if RSA support exists */ 573 if ((options.protocol & SSH_PROTO_1) && 574 rsa_alive() == 0) { 575 log("no RSA support in libssl and libcrypto. See ssl(8)"); 576 log("Disabling protocol version 1"); 577 options.protocol &= ~SSH_PROTO_1; 578 } 579 /* Load the RSA/DSA host key. It must have empty passphrase. */ 580 if (options.protocol & SSH_PROTO_1) { 581 Key k; 582 sensitive_data.host_key = RSA_new(); 583 k.type = KEY_RSA; 584 k.rsa = sensitive_data.host_key; 585 errno = 0; 586 if (!load_private_key(options.host_key_file, "", &k, NULL)) { 587 error("Could not load host key: %.200s: %.100s", 588 options.host_key_file, strerror(errno)); 589 log("Disabling protocol version 1"); 590 options.protocol &= ~SSH_PROTO_1; 591 } 592 k.rsa = NULL; 593 } 594 if (options.protocol & SSH_PROTO_2) { 595 sensitive_data.dsa_host_key = key_new(KEY_DSA); 596 if (!load_private_key(options.host_dsa_key_file, "", sensitive_data.dsa_host_key, NULL)) { 597 598 error("Could not load DSA host key: %.200s", options.host_dsa_key_file); 599 log("Disabling protocol version 2"); 600 options.protocol &= ~SSH_PROTO_2; 601 } 602 } 603 if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) { 604 if (silent == 0) 605 fprintf(stderr, "sshd: no hostkeys available -- exiting.\n"); 606 log("sshd: no hostkeys available -- exiting.\n"); 607 exit(1); 608 } 609 610 /* Check certain values for sanity. */ 611 if (options.protocol & SSH_PROTO_1) { 612 if (options.server_key_bits < 512 || 613 options.server_key_bits > 32768) { 614 fprintf(stderr, "Bad server key size.\n"); 615 exit(1); 616 } 617 /* 618 * Check that server and host key lengths differ sufficiently. This 619 * is necessary to make double encryption work with rsaref. Oh, I 620 * hate software patents. I dont know if this can go? Niels 621 */ 622 if (options.server_key_bits > 623 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED && 624 options.server_key_bits < 625 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) { 626 options.server_key_bits = 627 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED; 628 debug("Forcing server key to %d bits to make it differ from host key.", 629 options.server_key_bits); 630 } 631 } 632 633 /* Initialize the log (it is reinitialized below in case we forked). */ 634 if (debug_flag && !inetd_flag) 635 log_stderr = 1; 636 log_init(av0, options.log_level, options.log_facility, log_stderr); 637 638 /* 639 * If not in debugging mode, and not started from inetd, disconnect 640 * from the controlling terminal, and fork. The original process 641 * exits. 642 */ 643 if (!debug_flag && !inetd_flag) { 644#ifdef TIOCNOTTY 645 int fd; 646#endif /* TIOCNOTTY */ 647 if (daemon(0, 0) < 0) 648 fatal("daemon() failed: %.200s", strerror(errno)); 649 650 /* Disconnect from the controlling tty. */ 651#ifdef TIOCNOTTY 652 fd = open("/dev/tty", O_RDWR | O_NOCTTY); 653 if (fd >= 0) { 654 (void) ioctl(fd, TIOCNOTTY, NULL); 655 close(fd); 656 } 657#endif /* TIOCNOTTY */ 658 } 659 /* Reinitialize the log (because of the fork above). */ 660 log_init(av0, options.log_level, options.log_facility, log_stderr); 661 662 /* Do not display messages to stdout in RSA code. */ 663 rsa_set_verbose(0); 664 665 /* Initialize the random number generator. */ 666 arc4random_stir(); 667 668 /* Chdir to the root directory so that the current disk can be 669 unmounted if desired. */ 670 chdir("/"); 671 672 /* Start listening for a socket, unless started from inetd. */ 673 if (inetd_flag) { 674 int s1, s2; 675 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */ 676 s2 = dup(s1); 677 sock_in = dup(0); 678 sock_out = dup(1); 679 /* 680 * We intentionally do not close the descriptors 0, 1, and 2 681 * as our code for setting the descriptors won\'t work if 682 * ttyfd happens to be one of those. 683 */ 684 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out); 685 686 if (options.protocol & SSH_PROTO_1) { 687 public_key = RSA_new(); 688 sensitive_data.private_key = RSA_new(); 689 log("Generating %d bit RSA key.", options.server_key_bits); 690 rsa_generate_key(sensitive_data.private_key, public_key, 691 options.server_key_bits); 692 arc4random_stir(); 693 log("RSA key generation complete."); 694 } 695 } else { 696 for (ai = options.listen_addrs; ai; ai = ai->ai_next) { 697 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 698 continue; 699 if (num_listen_socks >= MAX_LISTEN_SOCKS) 700 fatal("Too many listen sockets. " 701 "Enlarge MAX_LISTEN_SOCKS"); 702 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, 703 ntop, sizeof(ntop), strport, sizeof(strport), 704 NI_NUMERICHOST|NI_NUMERICSERV) != 0) { 705 error("getnameinfo failed"); 706 continue; 707 } 708 /* Create socket for listening. */ 709 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0); 710 if (listen_sock < 0) { 711 /* kernel may not support ipv6 */ 712 verbose("socket: %.100s", strerror(errno)); 713 continue; 714 } 715 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) { 716 error("listen_sock O_NONBLOCK: %s", strerror(errno)); 717 close(listen_sock); 718 continue; 719 } 720 /* 721 * Set socket options. We try to make the port 722 * reusable and have it close as fast as possible 723 * without waiting in unnecessary wait states on 724 * close. 725 */ 726 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, 727 (void *) &on, sizeof(on)); 728 linger.l_onoff = 1; 729 linger.l_linger = 5; 730 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, 731 (void *) &linger, sizeof(linger)); 732 733 debug("Bind to port %s on %s.", strport, ntop); 734 735 /* Bind the socket to the desired port. */ 736 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) { 737 error("Bind to port %s on %s failed: %.200s.", 738 strport, ntop, strerror(errno)); 739 close(listen_sock); 740 continue; 741 } 742 listen_socks[num_listen_socks] = listen_sock; 743 num_listen_socks++; 744 745 /* Start listening on the port. */ 746 log("Server listening on %s port %s.", ntop, strport); 747 if (listen(listen_sock, 5) < 0) 748 fatal("listen: %.100s", strerror(errno)); 749 750 } 751 freeaddrinfo(options.listen_addrs); 752 753 if (!num_listen_socks) 754 fatal("Cannot bind any address."); 755 756 if (!debug_flag) { 757 /* 758 * Record our pid in /etc/sshd_pid to make it easier 759 * to kill the correct sshd. We don\'t want to do 760 * this before the bind above because the bind will 761 * fail if there already is a daemon, and this will 762 * overwrite any old pid in the file. 763 */ 764 f = fopen(options.pid_file, "w"); 765 if (f) { 766 fprintf(f, "%u\n", (unsigned int) getpid()); 767 fclose(f); 768 } 769 } 770 if (options.protocol & SSH_PROTO_1) { 771 public_key = RSA_new(); 772 sensitive_data.private_key = RSA_new(); 773 774 log("Generating %d bit RSA key.", options.server_key_bits); 775 rsa_generate_key(sensitive_data.private_key, public_key, 776 options.server_key_bits); 777 arc4random_stir(); 778 log("RSA key generation complete."); 779 780 /* Schedule server key regeneration alarm. */ 781 signal(SIGALRM, key_regeneration_alarm); 782 alarm(options.key_regeneration_time); 783 } 784 785 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */ 786 signal(SIGHUP, sighup_handler); 787 signal(SIGTERM, sigterm_handler); 788 signal(SIGQUIT, sigterm_handler); 789 790 /* Arrange SIGCHLD to be caught. */ 791 signal(SIGCHLD, main_sigchld_handler); 792 793 /* setup fd set for listen */ 794 maxfd = 0; 795 for (i = 0; i < num_listen_socks; i++) 796 if (listen_socks[i] > maxfd) 797 maxfd = listen_socks[i]; 798 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask); 799 fdset = (fd_set *)xmalloc(fdsetsz); 800 801 /* Initialize the magic_connections table. It's magical! */ 802 magic_connections = calloc(MAGIC_CONNECTIONS_SIZE, 803 sizeof(struct magic_connection)); 804 if (magic_connections == NULL) 805 fatal("calloc: %s", strerror(errno)); 806 807 /* 808 * Stay listening for connections until the system crashes or 809 * the daemon is killed with a signal. 810 */ 811 for (;;) { 812 if (received_sighup) 813 sighup_restart(); 814 /* Wait in select until there is a connection. */ 815 memset(fdset, 0, fdsetsz); 816 for (i = 0; i < num_listen_socks; i++) 817 FD_SET(listen_socks[i], fdset); 818 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) { 819 if (errno != EINTR) 820 error("select: %.100s", strerror(errno)); 821 continue; 822 } 823 for (i = 0; i < num_listen_socks; i++) { 824 if (!FD_ISSET(listen_socks[i], fdset)) 825 continue; 826 fromlen = sizeof(from); 827 newsock = accept(listen_socks[i], (struct sockaddr *)&from, 828 &fromlen); 829 if (newsock < 0) { 830 if (errno != EINTR && errno != EWOULDBLOCK) 831 error("accept: %.100s", strerror(errno)); 832 continue; 833 } 834 if (fcntl(newsock, F_SETFL, 0) < 0) { 835 error("newsock del O_NONBLOCK: %s", strerror(errno)); 836 continue; 837 } 838 if (options.connections_per_period != 0) { 839 struct timeval diff, connections_end; 840 struct magic_connection *mc; 841 842 (void)gettimeofday(&connections_end, NULL); 843 mc = &magic_connections[magic_hash((struct sockaddr *)0)]; 844 diff = timevaldiff(&mc->connections_begin, &connections_end); 845 if (diff.tv_sec >= options.connections_period) { 846 /* 847 * Slide the window forward only after completely 848 * leaving it. 849 */ 850 mc->connections_begin = connections_end; 851 mc->connections_this_period = 1; 852 } else { 853 if (++mc->connections_this_period > 854 options.connections_per_period) 855 connections_per_period_exceeded = 1; 856 } 857 } 858 859 /* 860 * Got connection. Fork a child to handle it unless 861 * we are in debugging mode or the maximum number of 862 * connections per period has been exceeded. 863 */ 864 if (debug_flag) { 865 /* 866 * In debugging mode. Close the listening 867 * socket, and start processing the 868 * connection without forking. 869 */ 870 debug("Server will not fork when running in debugging mode."); 871 close_listen_socks(); 872 sock_in = newsock; 873 sock_out = newsock; 874 pid = getpid(); 875 break; 876 } else if (connections_per_period_exceeded) { 877 log("Connection rate limit of %u/%us has been exceeded; " 878 "dropping connection from %s.", 879 options.connections_per_period, options.connections_period, 880 ntop); 881 connections_per_period_exceeded = 0; 882 } else { 883 /* 884 * Normal production daemon. Fork, and have 885 * the child process the connection. The 886 * parent continues listening. 887 */ 888 if ((pid = fork()) == 0) { 889 /* 890 * Child. Close the listening socket, and start using the 891 * accepted socket. Reinitialize logging (since our pid has 892 * changed). We break out of the loop to handle the connection. 893 */ 894 close_listen_socks(); 895 sock_in = newsock; 896 sock_out = newsock; 897 log_init(av0, options.log_level, options.log_facility, log_stderr); 898 break; 899 } 900 } 901 902 /* Parent. Stay in the loop. */ 903 if (pid < 0) 904 error("fork: %.100s", strerror(errno)); 905 else 906 debug("Forked child %d.", pid); 907 908 /* Mark that the key has been used (it was "given" to the child). */ 909 key_used = 1; 910 911 arc4random_stir(); 912 913 /* Close the new socket (the child is now taking care of it). */ 914 close(newsock); 915 } /* for (i = 0; i < num_listen_socks; i++) */ 916 /* child process check (or debug mode) */ 917 if (num_listen_socks < 0) 918 break; 919 } 920 } 921 922 /* This is the child processing a new connection. */ 923 924 /* 925 * Disable the key regeneration alarm. We will not regenerate the 926 * key since we are no longer in a position to give it to anyone. We 927 * will not restart on SIGHUP since it no longer makes sense. 928 */ 929 alarm(0); 930 signal(SIGALRM, SIG_DFL); 931 signal(SIGHUP, SIG_DFL); 932 signal(SIGTERM, SIG_DFL); 933 signal(SIGQUIT, SIG_DFL); 934 signal(SIGCHLD, SIG_DFL); 935 936 /* 937 * Set socket options for the connection. We want the socket to 938 * close as fast as possible without waiting for anything. If the 939 * connection is not a socket, these will do nothing. 940 */ 941 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */ 942 linger.l_onoff = 1; 943 linger.l_linger = 5; 944 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger)); 945 946 /* 947 * Register our connection. This turns encryption off because we do 948 * not have a key. 949 */ 950 packet_set_connection(sock_in, sock_out); 951 952 remote_port = get_remote_port(); 953 remote_ip = get_remote_ipaddr(); 954 955 /* Check whether logins are denied from this host. */ 956#ifdef LIBWRAP 957 { 958 struct request_info req; 959 960 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL); 961 fromhost(&req); 962 963 if (!hosts_access(&req)) { 964 close(sock_in); 965 close(sock_out); 966 refuse(&req); 967 } 968 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); 969 } 970#endif /* LIBWRAP */ 971 /* Log the connection. */ 972 verbose("Connection from %.500s port %d", remote_ip, remote_port); 973 974 /* 975 * We don\'t want to listen forever unless the other side 976 * successfully authenticates itself. So we set up an alarm which is 977 * cleared after successful authentication. A limit of zero 978 * indicates no limit. Note that we don\'t set the alarm in debugging 979 * mode; it is just annoying to have the server exit just when you 980 * are about to discover the bug. 981 */ 982 signal(SIGALRM, grace_alarm_handler); 983 if (!debug_flag) 984 alarm(options.login_grace_time); 985 986 sshd_exchange_identification(sock_in, sock_out); 987 /* 988 * Check that the connection comes from a privileged port. Rhosts- 989 * and Rhosts-RSA-Authentication only make sense from priviledged 990 * programs. Of course, if the intruder has root access on his local 991 * machine, he can connect from any port. So do not use these 992 * authentication methods from machines that you do not trust. 993 */ 994 if (remote_port >= IPPORT_RESERVED || 995 remote_port < IPPORT_RESERVED / 2) { 996 options.rhosts_authentication = 0; 997 options.rhosts_rsa_authentication = 0; 998 } 999#ifdef KRB4 1000 if (!packet_connection_is_ipv4() && 1001 options.krb4_authentication) { 1002 debug("Kerberos Authentication disabled, only available for IPv4."); 1003 options.krb4_authentication = 0; 1004 } 1005#endif /* KRB4 */ 1006 1007 packet_set_nonblocking(); 1008 1009 /* perform the key exchange */ 1010 /* authenticate user and start session */ 1011 if (compat20) { 1012 do_ssh2_kex(); 1013 do_authentication2(); 1014 } else { 1015 do_ssh1_kex(); 1016 do_authentication(); 1017 } 1018 1019#ifdef KRB4 1020 /* Cleanup user's ticket cache file. */ 1021 if (options.krb4_ticket_cleanup) 1022 (void) dest_tkt(); 1023#endif /* KRB4 */ 1024 1025 /* The connection has been terminated. */ 1026 verbose("Closing connection to %.100s", remote_ip); 1027 packet_close(); 1028 exit(0); 1029} 1030 1031/* 1032 * SSH1 key exchange 1033 */ 1034void 1035do_ssh1_kex() 1036{ 1037 int i, len; 1038 int plen, slen; 1039 BIGNUM *session_key_int; 1040 unsigned char session_key[SSH_SESSION_KEY_LENGTH]; 1041 unsigned char cookie[8]; 1042 unsigned int cipher_type, auth_mask, protocol_flags; 1043 u_int32_t rand = 0; 1044 1045 /* 1046 * Generate check bytes that the client must send back in the user 1047 * packet in order for it to be accepted; this is used to defy ip 1048 * spoofing attacks. Note that this only works against somebody 1049 * doing IP spoofing from a remote machine; any machine on the local 1050 * network can still see outgoing packets and catch the random 1051 * cookie. This only affects rhosts authentication, and this is one 1052 * of the reasons why it is inherently insecure. 1053 */ 1054 for (i = 0; i < 8; i++) { 1055 if (i % 4 == 0) 1056 rand = arc4random(); 1057 cookie[i] = rand & 0xff; 1058 rand >>= 8; 1059 } 1060 1061 /* 1062 * Send our public key. We include in the packet 64 bits of random 1063 * data that must be matched in the reply in order to prevent IP 1064 * spoofing. 1065 */ 1066 packet_start(SSH_SMSG_PUBLIC_KEY); 1067 for (i = 0; i < 8; i++) 1068 packet_put_char(cookie[i]); 1069 1070 /* Store our public server RSA key. */ 1071 packet_put_int(BN_num_bits(public_key->n)); 1072 packet_put_bignum(public_key->e); 1073 packet_put_bignum(public_key->n); 1074 1075 /* Store our public host RSA key. */ 1076 packet_put_int(BN_num_bits(sensitive_data.host_key->n)); 1077 packet_put_bignum(sensitive_data.host_key->e); 1078 packet_put_bignum(sensitive_data.host_key->n); 1079 1080 /* Put protocol flags. */ 1081 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN); 1082 1083 /* Declare which ciphers we support. */ 1084 packet_put_int(cipher_mask1()); 1085 1086 /* Declare supported authentication types. */ 1087 auth_mask = 0; 1088 if (options.rhosts_authentication) 1089 auth_mask |= 1 << SSH_AUTH_RHOSTS; 1090 if (options.rhosts_rsa_authentication) 1091 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA; 1092 if (options.rsa_authentication) 1093 auth_mask |= 1 << SSH_AUTH_RSA; 1094#ifdef KRB4 1095 if (options.krb4_authentication) 1096 auth_mask |= 1 << SSH_AUTH_KRB4; 1097#endif 1098#ifdef KRB5 1099 if (options.krb5_authentication) { 1100 auth_mask |= 1 << SSH_AUTH_KRB5; 1101 /* compatibility with MetaCentre ssh */ 1102 auth_mask |= 1 << SSH_AUTH_KRB4; 1103 } 1104 if (options.krb5_tgt_passing) 1105 auth_mask |= 1 << SSH_PASS_KRB5_TGT; 1106#endif /* KRB5 */ 1107 1108#ifdef AFS 1109 if (options.krb4_tgt_passing) 1110 auth_mask |= 1 << SSH_PASS_KRB4_TGT; 1111 if (options.afs_token_passing) 1112 auth_mask |= 1 << SSH_PASS_AFS_TOKEN; 1113#endif 1114#ifdef SKEY 1115 if (options.skey_authentication == 1) 1116 auth_mask |= 1 << SSH_AUTH_TIS; 1117#endif 1118 if (options.password_authentication) 1119 auth_mask |= 1 << SSH_AUTH_PASSWORD; 1120 packet_put_int(auth_mask); 1121 1122 /* Send the packet and wait for it to be sent. */ 1123 packet_send(); 1124 packet_write_wait(); 1125 1126 debug("Sent %d bit public key and %d bit host key.", 1127 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n)); 1128 1129 /* Read clients reply (cipher type and session key). */ 1130 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY); 1131 1132 /* Get cipher type and check whether we accept this. */ 1133 cipher_type = packet_get_char(); 1134 1135 if (!(cipher_mask() & (1 << cipher_type))) 1136 packet_disconnect("Warning: client selects unsupported cipher."); 1137 1138 /* Get check bytes from the packet. These must match those we 1139 sent earlier with the public key packet. */ 1140 for (i = 0; i < 8; i++) 1141 if (cookie[i] != packet_get_char()) 1142 packet_disconnect("IP Spoofing check bytes do not match."); 1143 1144 debug("Encryption type: %.200s", cipher_name(cipher_type)); 1145 1146 /* Get the encrypted integer. */ 1147 session_key_int = BN_new(); 1148 packet_get_bignum(session_key_int, &slen); 1149 1150 protocol_flags = packet_get_int(); 1151 packet_set_protocol_flags(protocol_flags); 1152 1153 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY); 1154 1155 /* 1156 * Decrypt it using our private server key and private host key (key 1157 * with larger modulus first). 1158 */ 1159 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) { 1160 /* Private key has bigger modulus. */ 1161 if (BN_num_bits(sensitive_data.private_key->n) < 1162 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) { 1163 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d", 1164 get_remote_ipaddr(), 1165 BN_num_bits(sensitive_data.private_key->n), 1166 BN_num_bits(sensitive_data.host_key->n), 1167 SSH_KEY_BITS_RESERVED); 1168 } 1169 rsa_private_decrypt(session_key_int, session_key_int, 1170 sensitive_data.private_key); 1171 rsa_private_decrypt(session_key_int, session_key_int, 1172 sensitive_data.host_key); 1173 } else { 1174 /* Host key has bigger modulus (or they are equal). */ 1175 if (BN_num_bits(sensitive_data.host_key->n) < 1176 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) { 1177 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d", 1178 get_remote_ipaddr(), 1179 BN_num_bits(sensitive_data.host_key->n), 1180 BN_num_bits(sensitive_data.private_key->n), 1181 SSH_KEY_BITS_RESERVED); 1182 } 1183 rsa_private_decrypt(session_key_int, session_key_int, 1184 sensitive_data.host_key); 1185 rsa_private_decrypt(session_key_int, session_key_int, 1186 sensitive_data.private_key); 1187 } 1188 1189 compute_session_id(session_id, cookie, 1190 sensitive_data.host_key->n, 1191 sensitive_data.private_key->n); 1192 1193 /* Destroy the private and public keys. They will no longer be needed. */ 1194 destroy_sensitive_data(); 1195 1196 /* 1197 * Extract session key from the decrypted integer. The key is in the 1198 * least significant 256 bits of the integer; the first byte of the 1199 * key is in the highest bits. 1200 */ 1201 BN_mask_bits(session_key_int, sizeof(session_key) * 8); 1202 len = BN_num_bytes(session_key_int); 1203 if (len < 0 || len > sizeof(session_key)) 1204 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d", 1205 get_remote_ipaddr(), 1206 len, sizeof(session_key)); 1207 memset(session_key, 0, sizeof(session_key)); 1208 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len); 1209 1210 /* Destroy the decrypted integer. It is no longer needed. */ 1211 BN_clear_free(session_key_int); 1212 1213 /* Xor the first 16 bytes of the session key with the session id. */ 1214 for (i = 0; i < 16; i++) 1215 session_key[i] ^= session_id[i]; 1216 1217 /* Set the session key. From this on all communications will be encrypted. */ 1218 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type); 1219 1220 /* Destroy our copy of the session key. It is no longer needed. */ 1221 memset(session_key, 0, sizeof(session_key)); 1222 1223 debug("Received session key; encryption turned on."); 1224 1225 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */ 1226 packet_start(SSH_SMSG_SUCCESS); 1227 packet_send(); 1228 packet_write_wait(); 1229} 1230 1231/* 1232 * SSH2 key exchange: diffie-hellman-group1-sha1 1233 */ 1234void 1235do_ssh2_kex() 1236{ 1237 Buffer *server_kexinit; 1238 Buffer *client_kexinit; 1239 int payload_len, dlen; 1240 int slen; 1241 unsigned int klen, kout;
| 428 if (sensitive_data.dsa_host_key != NULL) 429 key_free(sensitive_data.dsa_host_key); 430} 431 432/* 433 * Main program for the daemon. 434 */ 435int 436main(int ac, char **av) 437{ 438 extern char *optarg; 439 extern int optind; 440 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, on = 1; 441 pid_t pid; 442 socklen_t fromlen; 443 int silent = 0; 444 fd_set *fdset; 445 struct sockaddr_storage from; 446 const char *remote_ip; 447 int remote_port; 448 FILE *f; 449 struct linger linger; 450 struct addrinfo *ai; 451 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 452 int listen_sock, maxfd; 453 int connections_per_period_exceeded = 0; 454 455 /* Save argv[0]. */ 456 saved_argv = av; 457 if (strchr(av[0], '/')) 458 av0 = strrchr(av[0], '/') + 1; 459 else 460 av0 = av[0]; 461 462 /* Initialize configuration options to their default values. */ 463 initialize_server_options(&options); 464 465 /* Parse command-line arguments. */ 466 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) { 467 switch (opt) { 468 case '4': 469 IPv4or6 = AF_INET; 470 break; 471 case '6': 472 IPv4or6 = AF_INET6; 473 break; 474 case 'f': 475 config_file_name = optarg; 476 break; 477 case 'd': 478 debug_flag = 1; 479 options.log_level = SYSLOG_LEVEL_DEBUG; 480 break; 481 case 'i': 482 inetd_flag = 1; 483 break; 484 case 'Q': 485 silent = 1; 486 break; 487 case 'q': 488 options.log_level = SYSLOG_LEVEL_QUIET; 489 break; 490 case 'b': 491 options.server_key_bits = atoi(optarg); 492 break; 493 case 'p': 494 options.ports_from_cmdline = 1; 495 if (options.num_ports >= MAX_PORTS) 496 fatal("too many ports.\n"); 497 options.ports[options.num_ports++] = atoi(optarg); 498 break; 499 case 'g': 500 options.login_grace_time = atoi(optarg); 501 break; 502 case 'k': 503 options.key_regeneration_time = atoi(optarg); 504 break; 505 case 'h': 506 options.host_key_file = optarg; 507 break; 508 case 'V': 509 client_version_string = optarg; 510 /* only makes sense with inetd_flag, i.e. no listen() */ 511 inetd_flag = 1; 512 break; 513 case '?': 514 default: 515 fprintf(stderr, "sshd version %s\n", SSH_VERSION); 516 fprintf(stderr, "Usage: %s [options]\n", av0); 517 fprintf(stderr, "Options:\n"); 518 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE); 519 fprintf(stderr, " -d Debugging mode\n"); 520 fprintf(stderr, " -i Started from inetd\n"); 521 fprintf(stderr, " -q Quiet (no logging)\n"); 522 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n"); 523 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n"); 524 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n"); 525 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n"); 526 fprintf(stderr, " -h file File from which to read host key (default: %s)\n", 527 HOST_KEY_FILE); 528 fprintf(stderr, " -4 Use IPv4 only\n"); 529 fprintf(stderr, " -6 Use IPv6 only\n"); 530 exit(1); 531 } 532 } 533 534 /* 535 * Force logging to stderr until we have loaded the private host 536 * key (unless started from inetd) 537 */ 538 log_init(av0, 539 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, 540 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility, 541 !silent && !inetd_flag); 542 543 /* Read server configuration options from the configuration file. */ 544 read_server_config(&options, config_file_name); 545 546 /* Fill in default values for those options not explicitly set. */ 547 fill_default_server_options(&options); 548 549 /* Check that there are no remaining arguments. */ 550 if (optind < ac) { 551 fprintf(stderr, "Extra argument %s.\n", av[optind]); 552 exit(1); 553 } 554 555 debug("sshd version %.100s", SSH_VERSION); 556 557 sensitive_data.dsa_host_key = NULL; 558 sensitive_data.host_key = NULL; 559 560 /* check if RSA support exists */ 561 if ((options.protocol & SSH_PROTO_1) && 562 rsa_alive() == 0) { 563 log("no RSA support in libssl and libcrypto. See ssl(8)"); 564 log("Disabling protocol version 1"); 565 options.protocol &= ~SSH_PROTO_1; 566 } 567 /* Load the RSA/DSA host key. It must have empty passphrase. */ 568 if (options.protocol & SSH_PROTO_1) { 569 Key k; 570 sensitive_data.host_key = RSA_new(); 571 k.type = KEY_RSA; 572 k.rsa = sensitive_data.host_key; 573 errno = 0; 574 if (!load_private_key(options.host_key_file, "", &k, NULL)) { 575 error("Could not load host key: %.200s: %.100s", 576 options.host_key_file, strerror(errno)); 577 log("Disabling protocol version 1"); 578 options.protocol &= ~SSH_PROTO_1; 579 } 580 k.rsa = NULL; 581 } 582 if (options.protocol & SSH_PROTO_2) { 583 sensitive_data.dsa_host_key = key_new(KEY_DSA); 584 if (!load_private_key(options.host_dsa_key_file, "", sensitive_data.dsa_host_key, NULL)) { 585 586 error("Could not load DSA host key: %.200s", options.host_dsa_key_file); 587 log("Disabling protocol version 2"); 588 options.protocol &= ~SSH_PROTO_2; 589 } 590 } 591 if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) { 592 if (silent == 0) 593 fprintf(stderr, "sshd: no hostkeys available -- exiting.\n"); 594 log("sshd: no hostkeys available -- exiting.\n"); 595 exit(1); 596 } 597 598 /* Check certain values for sanity. */ 599 if (options.protocol & SSH_PROTO_1) { 600 if (options.server_key_bits < 512 || 601 options.server_key_bits > 32768) { 602 fprintf(stderr, "Bad server key size.\n"); 603 exit(1); 604 } 605 /* 606 * Check that server and host key lengths differ sufficiently. This 607 * is necessary to make double encryption work with rsaref. Oh, I 608 * hate software patents. I dont know if this can go? Niels 609 */ 610 if (options.server_key_bits > 611 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED && 612 options.server_key_bits < 613 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) { 614 options.server_key_bits = 615 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED; 616 debug("Forcing server key to %d bits to make it differ from host key.", 617 options.server_key_bits); 618 } 619 } 620 621 /* Initialize the log (it is reinitialized below in case we forked). */ 622 if (debug_flag && !inetd_flag) 623 log_stderr = 1; 624 log_init(av0, options.log_level, options.log_facility, log_stderr); 625 626 /* 627 * If not in debugging mode, and not started from inetd, disconnect 628 * from the controlling terminal, and fork. The original process 629 * exits. 630 */ 631 if (!debug_flag && !inetd_flag) { 632#ifdef TIOCNOTTY 633 int fd; 634#endif /* TIOCNOTTY */ 635 if (daemon(0, 0) < 0) 636 fatal("daemon() failed: %.200s", strerror(errno)); 637 638 /* Disconnect from the controlling tty. */ 639#ifdef TIOCNOTTY 640 fd = open("/dev/tty", O_RDWR | O_NOCTTY); 641 if (fd >= 0) { 642 (void) ioctl(fd, TIOCNOTTY, NULL); 643 close(fd); 644 } 645#endif /* TIOCNOTTY */ 646 } 647 /* Reinitialize the log (because of the fork above). */ 648 log_init(av0, options.log_level, options.log_facility, log_stderr); 649 650 /* Do not display messages to stdout in RSA code. */ 651 rsa_set_verbose(0); 652 653 /* Initialize the random number generator. */ 654 arc4random_stir(); 655 656 /* Chdir to the root directory so that the current disk can be 657 unmounted if desired. */ 658 chdir("/"); 659 660 /* Start listening for a socket, unless started from inetd. */ 661 if (inetd_flag) { 662 int s1, s2; 663 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */ 664 s2 = dup(s1); 665 sock_in = dup(0); 666 sock_out = dup(1); 667 /* 668 * We intentionally do not close the descriptors 0, 1, and 2 669 * as our code for setting the descriptors won\'t work if 670 * ttyfd happens to be one of those. 671 */ 672 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out); 673 674 if (options.protocol & SSH_PROTO_1) { 675 public_key = RSA_new(); 676 sensitive_data.private_key = RSA_new(); 677 log("Generating %d bit RSA key.", options.server_key_bits); 678 rsa_generate_key(sensitive_data.private_key, public_key, 679 options.server_key_bits); 680 arc4random_stir(); 681 log("RSA key generation complete."); 682 } 683 } else { 684 for (ai = options.listen_addrs; ai; ai = ai->ai_next) { 685 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 686 continue; 687 if (num_listen_socks >= MAX_LISTEN_SOCKS) 688 fatal("Too many listen sockets. " 689 "Enlarge MAX_LISTEN_SOCKS"); 690 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, 691 ntop, sizeof(ntop), strport, sizeof(strport), 692 NI_NUMERICHOST|NI_NUMERICSERV) != 0) { 693 error("getnameinfo failed"); 694 continue; 695 } 696 /* Create socket for listening. */ 697 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0); 698 if (listen_sock < 0) { 699 /* kernel may not support ipv6 */ 700 verbose("socket: %.100s", strerror(errno)); 701 continue; 702 } 703 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) { 704 error("listen_sock O_NONBLOCK: %s", strerror(errno)); 705 close(listen_sock); 706 continue; 707 } 708 /* 709 * Set socket options. We try to make the port 710 * reusable and have it close as fast as possible 711 * without waiting in unnecessary wait states on 712 * close. 713 */ 714 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, 715 (void *) &on, sizeof(on)); 716 linger.l_onoff = 1; 717 linger.l_linger = 5; 718 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, 719 (void *) &linger, sizeof(linger)); 720 721 debug("Bind to port %s on %s.", strport, ntop); 722 723 /* Bind the socket to the desired port. */ 724 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) { 725 error("Bind to port %s on %s failed: %.200s.", 726 strport, ntop, strerror(errno)); 727 close(listen_sock); 728 continue; 729 } 730 listen_socks[num_listen_socks] = listen_sock; 731 num_listen_socks++; 732 733 /* Start listening on the port. */ 734 log("Server listening on %s port %s.", ntop, strport); 735 if (listen(listen_sock, 5) < 0) 736 fatal("listen: %.100s", strerror(errno)); 737 738 } 739 freeaddrinfo(options.listen_addrs); 740 741 if (!num_listen_socks) 742 fatal("Cannot bind any address."); 743 744 if (!debug_flag) { 745 /* 746 * Record our pid in /etc/sshd_pid to make it easier 747 * to kill the correct sshd. We don\'t want to do 748 * this before the bind above because the bind will 749 * fail if there already is a daemon, and this will 750 * overwrite any old pid in the file. 751 */ 752 f = fopen(options.pid_file, "w"); 753 if (f) { 754 fprintf(f, "%u\n", (unsigned int) getpid()); 755 fclose(f); 756 } 757 } 758 if (options.protocol & SSH_PROTO_1) { 759 public_key = RSA_new(); 760 sensitive_data.private_key = RSA_new(); 761 762 log("Generating %d bit RSA key.", options.server_key_bits); 763 rsa_generate_key(sensitive_data.private_key, public_key, 764 options.server_key_bits); 765 arc4random_stir(); 766 log("RSA key generation complete."); 767 768 /* Schedule server key regeneration alarm. */ 769 signal(SIGALRM, key_regeneration_alarm); 770 alarm(options.key_regeneration_time); 771 } 772 773 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */ 774 signal(SIGHUP, sighup_handler); 775 signal(SIGTERM, sigterm_handler); 776 signal(SIGQUIT, sigterm_handler); 777 778 /* Arrange SIGCHLD to be caught. */ 779 signal(SIGCHLD, main_sigchld_handler); 780 781 /* setup fd set for listen */ 782 maxfd = 0; 783 for (i = 0; i < num_listen_socks; i++) 784 if (listen_socks[i] > maxfd) 785 maxfd = listen_socks[i]; 786 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask); 787 fdset = (fd_set *)xmalloc(fdsetsz); 788 789 /* Initialize the magic_connections table. It's magical! */ 790 magic_connections = calloc(MAGIC_CONNECTIONS_SIZE, 791 sizeof(struct magic_connection)); 792 if (magic_connections == NULL) 793 fatal("calloc: %s", strerror(errno)); 794 795 /* 796 * Stay listening for connections until the system crashes or 797 * the daemon is killed with a signal. 798 */ 799 for (;;) { 800 if (received_sighup) 801 sighup_restart(); 802 /* Wait in select until there is a connection. */ 803 memset(fdset, 0, fdsetsz); 804 for (i = 0; i < num_listen_socks; i++) 805 FD_SET(listen_socks[i], fdset); 806 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) { 807 if (errno != EINTR) 808 error("select: %.100s", strerror(errno)); 809 continue; 810 } 811 for (i = 0; i < num_listen_socks; i++) { 812 if (!FD_ISSET(listen_socks[i], fdset)) 813 continue; 814 fromlen = sizeof(from); 815 newsock = accept(listen_socks[i], (struct sockaddr *)&from, 816 &fromlen); 817 if (newsock < 0) { 818 if (errno != EINTR && errno != EWOULDBLOCK) 819 error("accept: %.100s", strerror(errno)); 820 continue; 821 } 822 if (fcntl(newsock, F_SETFL, 0) < 0) { 823 error("newsock del O_NONBLOCK: %s", strerror(errno)); 824 continue; 825 } 826 if (options.connections_per_period != 0) { 827 struct timeval diff, connections_end; 828 struct magic_connection *mc; 829 830 (void)gettimeofday(&connections_end, NULL); 831 mc = &magic_connections[magic_hash((struct sockaddr *)0)]; 832 diff = timevaldiff(&mc->connections_begin, &connections_end); 833 if (diff.tv_sec >= options.connections_period) { 834 /* 835 * Slide the window forward only after completely 836 * leaving it. 837 */ 838 mc->connections_begin = connections_end; 839 mc->connections_this_period = 1; 840 } else { 841 if (++mc->connections_this_period > 842 options.connections_per_period) 843 connections_per_period_exceeded = 1; 844 } 845 } 846 847 /* 848 * Got connection. Fork a child to handle it unless 849 * we are in debugging mode or the maximum number of 850 * connections per period has been exceeded. 851 */ 852 if (debug_flag) { 853 /* 854 * In debugging mode. Close the listening 855 * socket, and start processing the 856 * connection without forking. 857 */ 858 debug("Server will not fork when running in debugging mode."); 859 close_listen_socks(); 860 sock_in = newsock; 861 sock_out = newsock; 862 pid = getpid(); 863 break; 864 } else if (connections_per_period_exceeded) { 865 log("Connection rate limit of %u/%us has been exceeded; " 866 "dropping connection from %s.", 867 options.connections_per_period, options.connections_period, 868 ntop); 869 connections_per_period_exceeded = 0; 870 } else { 871 /* 872 * Normal production daemon. Fork, and have 873 * the child process the connection. The 874 * parent continues listening. 875 */ 876 if ((pid = fork()) == 0) { 877 /* 878 * Child. Close the listening socket, and start using the 879 * accepted socket. Reinitialize logging (since our pid has 880 * changed). We break out of the loop to handle the connection. 881 */ 882 close_listen_socks(); 883 sock_in = newsock; 884 sock_out = newsock; 885 log_init(av0, options.log_level, options.log_facility, log_stderr); 886 break; 887 } 888 } 889 890 /* Parent. Stay in the loop. */ 891 if (pid < 0) 892 error("fork: %.100s", strerror(errno)); 893 else 894 debug("Forked child %d.", pid); 895 896 /* Mark that the key has been used (it was "given" to the child). */ 897 key_used = 1; 898 899 arc4random_stir(); 900 901 /* Close the new socket (the child is now taking care of it). */ 902 close(newsock); 903 } /* for (i = 0; i < num_listen_socks; i++) */ 904 /* child process check (or debug mode) */ 905 if (num_listen_socks < 0) 906 break; 907 } 908 } 909 910 /* This is the child processing a new connection. */ 911 912 /* 913 * Disable the key regeneration alarm. We will not regenerate the 914 * key since we are no longer in a position to give it to anyone. We 915 * will not restart on SIGHUP since it no longer makes sense. 916 */ 917 alarm(0); 918 signal(SIGALRM, SIG_DFL); 919 signal(SIGHUP, SIG_DFL); 920 signal(SIGTERM, SIG_DFL); 921 signal(SIGQUIT, SIG_DFL); 922 signal(SIGCHLD, SIG_DFL); 923 924 /* 925 * Set socket options for the connection. We want the socket to 926 * close as fast as possible without waiting for anything. If the 927 * connection is not a socket, these will do nothing. 928 */ 929 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */ 930 linger.l_onoff = 1; 931 linger.l_linger = 5; 932 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger)); 933 934 /* 935 * Register our connection. This turns encryption off because we do 936 * not have a key. 937 */ 938 packet_set_connection(sock_in, sock_out); 939 940 remote_port = get_remote_port(); 941 remote_ip = get_remote_ipaddr(); 942 943 /* Check whether logins are denied from this host. */ 944#ifdef LIBWRAP 945 { 946 struct request_info req; 947 948 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL); 949 fromhost(&req); 950 951 if (!hosts_access(&req)) { 952 close(sock_in); 953 close(sock_out); 954 refuse(&req); 955 } 956 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); 957 } 958#endif /* LIBWRAP */ 959 /* Log the connection. */ 960 verbose("Connection from %.500s port %d", remote_ip, remote_port); 961 962 /* 963 * We don\'t want to listen forever unless the other side 964 * successfully authenticates itself. So we set up an alarm which is 965 * cleared after successful authentication. A limit of zero 966 * indicates no limit. Note that we don\'t set the alarm in debugging 967 * mode; it is just annoying to have the server exit just when you 968 * are about to discover the bug. 969 */ 970 signal(SIGALRM, grace_alarm_handler); 971 if (!debug_flag) 972 alarm(options.login_grace_time); 973 974 sshd_exchange_identification(sock_in, sock_out); 975 /* 976 * Check that the connection comes from a privileged port. Rhosts- 977 * and Rhosts-RSA-Authentication only make sense from priviledged 978 * programs. Of course, if the intruder has root access on his local 979 * machine, he can connect from any port. So do not use these 980 * authentication methods from machines that you do not trust. 981 */ 982 if (remote_port >= IPPORT_RESERVED || 983 remote_port < IPPORT_RESERVED / 2) { 984 options.rhosts_authentication = 0; 985 options.rhosts_rsa_authentication = 0; 986 } 987#ifdef KRB4 988 if (!packet_connection_is_ipv4() && 989 options.krb4_authentication) { 990 debug("Kerberos Authentication disabled, only available for IPv4."); 991 options.krb4_authentication = 0; 992 } 993#endif /* KRB4 */ 994 995 packet_set_nonblocking(); 996 997 /* perform the key exchange */ 998 /* authenticate user and start session */ 999 if (compat20) { 1000 do_ssh2_kex(); 1001 do_authentication2(); 1002 } else { 1003 do_ssh1_kex(); 1004 do_authentication(); 1005 } 1006 1007#ifdef KRB4 1008 /* Cleanup user's ticket cache file. */ 1009 if (options.krb4_ticket_cleanup) 1010 (void) dest_tkt(); 1011#endif /* KRB4 */ 1012 1013 /* The connection has been terminated. */ 1014 verbose("Closing connection to %.100s", remote_ip); 1015 packet_close(); 1016 exit(0); 1017} 1018 1019/* 1020 * SSH1 key exchange 1021 */ 1022void 1023do_ssh1_kex() 1024{ 1025 int i, len; 1026 int plen, slen; 1027 BIGNUM *session_key_int; 1028 unsigned char session_key[SSH_SESSION_KEY_LENGTH]; 1029 unsigned char cookie[8]; 1030 unsigned int cipher_type, auth_mask, protocol_flags; 1031 u_int32_t rand = 0; 1032 1033 /* 1034 * Generate check bytes that the client must send back in the user 1035 * packet in order for it to be accepted; this is used to defy ip 1036 * spoofing attacks. Note that this only works against somebody 1037 * doing IP spoofing from a remote machine; any machine on the local 1038 * network can still see outgoing packets and catch the random 1039 * cookie. This only affects rhosts authentication, and this is one 1040 * of the reasons why it is inherently insecure. 1041 */ 1042 for (i = 0; i < 8; i++) { 1043 if (i % 4 == 0) 1044 rand = arc4random(); 1045 cookie[i] = rand & 0xff; 1046 rand >>= 8; 1047 } 1048 1049 /* 1050 * Send our public key. We include in the packet 64 bits of random 1051 * data that must be matched in the reply in order to prevent IP 1052 * spoofing. 1053 */ 1054 packet_start(SSH_SMSG_PUBLIC_KEY); 1055 for (i = 0; i < 8; i++) 1056 packet_put_char(cookie[i]); 1057 1058 /* Store our public server RSA key. */ 1059 packet_put_int(BN_num_bits(public_key->n)); 1060 packet_put_bignum(public_key->e); 1061 packet_put_bignum(public_key->n); 1062 1063 /* Store our public host RSA key. */ 1064 packet_put_int(BN_num_bits(sensitive_data.host_key->n)); 1065 packet_put_bignum(sensitive_data.host_key->e); 1066 packet_put_bignum(sensitive_data.host_key->n); 1067 1068 /* Put protocol flags. */ 1069 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN); 1070 1071 /* Declare which ciphers we support. */ 1072 packet_put_int(cipher_mask1()); 1073 1074 /* Declare supported authentication types. */ 1075 auth_mask = 0; 1076 if (options.rhosts_authentication) 1077 auth_mask |= 1 << SSH_AUTH_RHOSTS; 1078 if (options.rhosts_rsa_authentication) 1079 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA; 1080 if (options.rsa_authentication) 1081 auth_mask |= 1 << SSH_AUTH_RSA; 1082#ifdef KRB4 1083 if (options.krb4_authentication) 1084 auth_mask |= 1 << SSH_AUTH_KRB4; 1085#endif 1086#ifdef KRB5 1087 if (options.krb5_authentication) { 1088 auth_mask |= 1 << SSH_AUTH_KRB5; 1089 /* compatibility with MetaCentre ssh */ 1090 auth_mask |= 1 << SSH_AUTH_KRB4; 1091 } 1092 if (options.krb5_tgt_passing) 1093 auth_mask |= 1 << SSH_PASS_KRB5_TGT; 1094#endif /* KRB5 */ 1095 1096#ifdef AFS 1097 if (options.krb4_tgt_passing) 1098 auth_mask |= 1 << SSH_PASS_KRB4_TGT; 1099 if (options.afs_token_passing) 1100 auth_mask |= 1 << SSH_PASS_AFS_TOKEN; 1101#endif 1102#ifdef SKEY 1103 if (options.skey_authentication == 1) 1104 auth_mask |= 1 << SSH_AUTH_TIS; 1105#endif 1106 if (options.password_authentication) 1107 auth_mask |= 1 << SSH_AUTH_PASSWORD; 1108 packet_put_int(auth_mask); 1109 1110 /* Send the packet and wait for it to be sent. */ 1111 packet_send(); 1112 packet_write_wait(); 1113 1114 debug("Sent %d bit public key and %d bit host key.", 1115 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n)); 1116 1117 /* Read clients reply (cipher type and session key). */ 1118 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY); 1119 1120 /* Get cipher type and check whether we accept this. */ 1121 cipher_type = packet_get_char(); 1122 1123 if (!(cipher_mask() & (1 << cipher_type))) 1124 packet_disconnect("Warning: client selects unsupported cipher."); 1125 1126 /* Get check bytes from the packet. These must match those we 1127 sent earlier with the public key packet. */ 1128 for (i = 0; i < 8; i++) 1129 if (cookie[i] != packet_get_char()) 1130 packet_disconnect("IP Spoofing check bytes do not match."); 1131 1132 debug("Encryption type: %.200s", cipher_name(cipher_type)); 1133 1134 /* Get the encrypted integer. */ 1135 session_key_int = BN_new(); 1136 packet_get_bignum(session_key_int, &slen); 1137 1138 protocol_flags = packet_get_int(); 1139 packet_set_protocol_flags(protocol_flags); 1140 1141 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY); 1142 1143 /* 1144 * Decrypt it using our private server key and private host key (key 1145 * with larger modulus first). 1146 */ 1147 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) { 1148 /* Private key has bigger modulus. */ 1149 if (BN_num_bits(sensitive_data.private_key->n) < 1150 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) { 1151 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d", 1152 get_remote_ipaddr(), 1153 BN_num_bits(sensitive_data.private_key->n), 1154 BN_num_bits(sensitive_data.host_key->n), 1155 SSH_KEY_BITS_RESERVED); 1156 } 1157 rsa_private_decrypt(session_key_int, session_key_int, 1158 sensitive_data.private_key); 1159 rsa_private_decrypt(session_key_int, session_key_int, 1160 sensitive_data.host_key); 1161 } else { 1162 /* Host key has bigger modulus (or they are equal). */ 1163 if (BN_num_bits(sensitive_data.host_key->n) < 1164 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) { 1165 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d", 1166 get_remote_ipaddr(), 1167 BN_num_bits(sensitive_data.host_key->n), 1168 BN_num_bits(sensitive_data.private_key->n), 1169 SSH_KEY_BITS_RESERVED); 1170 } 1171 rsa_private_decrypt(session_key_int, session_key_int, 1172 sensitive_data.host_key); 1173 rsa_private_decrypt(session_key_int, session_key_int, 1174 sensitive_data.private_key); 1175 } 1176 1177 compute_session_id(session_id, cookie, 1178 sensitive_data.host_key->n, 1179 sensitive_data.private_key->n); 1180 1181 /* Destroy the private and public keys. They will no longer be needed. */ 1182 destroy_sensitive_data(); 1183 1184 /* 1185 * Extract session key from the decrypted integer. The key is in the 1186 * least significant 256 bits of the integer; the first byte of the 1187 * key is in the highest bits. 1188 */ 1189 BN_mask_bits(session_key_int, sizeof(session_key) * 8); 1190 len = BN_num_bytes(session_key_int); 1191 if (len < 0 || len > sizeof(session_key)) 1192 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d", 1193 get_remote_ipaddr(), 1194 len, sizeof(session_key)); 1195 memset(session_key, 0, sizeof(session_key)); 1196 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len); 1197 1198 /* Destroy the decrypted integer. It is no longer needed. */ 1199 BN_clear_free(session_key_int); 1200 1201 /* Xor the first 16 bytes of the session key with the session id. */ 1202 for (i = 0; i < 16; i++) 1203 session_key[i] ^= session_id[i]; 1204 1205 /* Set the session key. From this on all communications will be encrypted. */ 1206 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type); 1207 1208 /* Destroy our copy of the session key. It is no longer needed. */ 1209 memset(session_key, 0, sizeof(session_key)); 1210 1211 debug("Received session key; encryption turned on."); 1212 1213 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */ 1214 packet_start(SSH_SMSG_SUCCESS); 1215 packet_send(); 1216 packet_write_wait(); 1217} 1218 1219/* 1220 * SSH2 key exchange: diffie-hellman-group1-sha1 1221 */ 1222void 1223do_ssh2_kex() 1224{ 1225 Buffer *server_kexinit; 1226 Buffer *client_kexinit; 1227 int payload_len, dlen; 1228 int slen; 1229 unsigned int klen, kout;
|
1303/* KEXDH */ 1304 1305 debug("Wait SSH2_MSG_KEXDH_INIT."); 1306 packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT); 1307 1308 /* key, cert */ 1309 dh_client_pub = BN_new(); 1310 if (dh_client_pub == NULL) 1311 fatal("dh_client_pub == NULL"); 1312 packet_get_bignum2(dh_client_pub, &dlen); 1313 1314#ifdef DEBUG_KEXDH 1315 fprintf(stderr, "\ndh_client_pub= "); 1316 bignum_print(dh_client_pub); 1317 fprintf(stderr, "\n"); 1318 debug("bits %d", BN_num_bits(dh_client_pub)); 1319#endif 1320 1321 /* generate DH key */ 1322 dh = dh_new_group1(); /* XXX depends on 'kex' */ 1323 1324#ifdef DEBUG_KEXDH 1325 fprintf(stderr, "\np= "); 1326 bignum_print(dh->p); 1327 fprintf(stderr, "\ng= "); 1328 bignum_print(dh->g); 1329 fprintf(stderr, "\npub= "); 1330 bignum_print(dh->pub_key); 1331 fprintf(stderr, "\n"); 1332#endif 1333 if (!dh_pub_is_valid(dh, dh_client_pub)) 1334 packet_disconnect("bad client public DH value"); 1335 1336 klen = DH_size(dh); 1337 kbuf = xmalloc(klen); 1338 kout = DH_compute_key(kbuf, dh_client_pub, dh); 1339 1340#ifdef DEBUG_KEXDH 1341 debug("shared secret: len %d/%d", klen, kout); 1342 fprintf(stderr, "shared secret == "); 1343 for (i = 0; i< kout; i++) 1344 fprintf(stderr, "%02x", (kbuf[i])&0xff); 1345 fprintf(stderr, "\n"); 1346#endif 1347 shared_secret = BN_new(); 1348 1349 BN_bin2bn(kbuf, kout, shared_secret); 1350 memset(kbuf, 0, klen); 1351 xfree(kbuf); 1352 1353 /* XXX precompute? */ 1354 dsa_make_key_blob(sensitive_data.dsa_host_key, &server_host_key_blob, &sbloblen); 1355 1356 /* calc H */ /* XXX depends on 'kex' */ 1357 hash = kex_hash( 1358 client_version_string, 1359 server_version_string, 1360 buffer_ptr(client_kexinit), buffer_len(client_kexinit), 1361 buffer_ptr(server_kexinit), buffer_len(server_kexinit), 1362 (char *)server_host_key_blob, sbloblen, 1363 dh_client_pub, 1364 dh->pub_key, 1365 shared_secret 1366 ); 1367 buffer_free(client_kexinit); 1368 buffer_free(server_kexinit); 1369 xfree(client_kexinit); 1370 xfree(server_kexinit); 1371#ifdef DEBUG_KEXDH 1372 fprintf(stderr, "hash == "); 1373 for (i = 0; i< 20; i++) 1374 fprintf(stderr, "%02x", (hash[i])&0xff); 1375 fprintf(stderr, "\n"); 1376#endif 1377 /* save session id := H */ 1378 /* XXX hashlen depends on KEX */ 1379 session_id2_len = 20; 1380 session_id2 = xmalloc(session_id2_len); 1381 memcpy(session_id2, hash, session_id2_len); 1382 1383 /* sign H */ 1384 /* XXX hashlen depends on KEX */ 1385 dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20); 1386 1387 destroy_sensitive_data(); 1388 1389 /* send server hostkey, DH pubkey 'f' and singed H */ 1390 packet_start(SSH2_MSG_KEXDH_REPLY); 1391 packet_put_string((char *)server_host_key_blob, sbloblen); 1392 packet_put_bignum2(dh->pub_key); /* f */ 1393 packet_put_string((char *)signature, slen); 1394 packet_send(); 1395 xfree(signature); 1396 xfree(server_host_key_blob); 1397 packet_write_wait(); 1398 1399 kex_derive_keys(kex, hash, shared_secret); 1400 packet_set_kex(kex); 1401 1402 /* have keys, free DH */ 1403 DH_free(dh); 1404 1405 debug("send SSH2_MSG_NEWKEYS."); 1406 packet_start(SSH2_MSG_NEWKEYS); 1407 packet_send(); 1408 packet_write_wait(); 1409 debug("done: send SSH2_MSG_NEWKEYS."); 1410 1411 debug("Wait SSH2_MSG_NEWKEYS."); 1412 packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS); 1413 debug("GOT SSH2_MSG_NEWKEYS."); 1414 1415#ifdef DEBUG_KEXDH 1416 /* send 1st encrypted/maced/compressed message */ 1417 packet_start(SSH2_MSG_IGNORE); 1418 packet_put_cstring("markus"); 1419 packet_send(); 1420 packet_write_wait(); 1421#endif 1422 debug("done: KEX2."); 1423}
| 1258/* KEXDH */ 1259 1260 debug("Wait SSH2_MSG_KEXDH_INIT."); 1261 packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT); 1262 1263 /* key, cert */ 1264 dh_client_pub = BN_new(); 1265 if (dh_client_pub == NULL) 1266 fatal("dh_client_pub == NULL"); 1267 packet_get_bignum2(dh_client_pub, &dlen); 1268 1269#ifdef DEBUG_KEXDH 1270 fprintf(stderr, "\ndh_client_pub= "); 1271 bignum_print(dh_client_pub); 1272 fprintf(stderr, "\n"); 1273 debug("bits %d", BN_num_bits(dh_client_pub)); 1274#endif 1275 1276 /* generate DH key */ 1277 dh = dh_new_group1(); /* XXX depends on 'kex' */ 1278 1279#ifdef DEBUG_KEXDH 1280 fprintf(stderr, "\np= "); 1281 bignum_print(dh->p); 1282 fprintf(stderr, "\ng= "); 1283 bignum_print(dh->g); 1284 fprintf(stderr, "\npub= "); 1285 bignum_print(dh->pub_key); 1286 fprintf(stderr, "\n"); 1287#endif 1288 if (!dh_pub_is_valid(dh, dh_client_pub)) 1289 packet_disconnect("bad client public DH value"); 1290 1291 klen = DH_size(dh); 1292 kbuf = xmalloc(klen); 1293 kout = DH_compute_key(kbuf, dh_client_pub, dh); 1294 1295#ifdef DEBUG_KEXDH 1296 debug("shared secret: len %d/%d", klen, kout); 1297 fprintf(stderr, "shared secret == "); 1298 for (i = 0; i< kout; i++) 1299 fprintf(stderr, "%02x", (kbuf[i])&0xff); 1300 fprintf(stderr, "\n"); 1301#endif 1302 shared_secret = BN_new(); 1303 1304 BN_bin2bn(kbuf, kout, shared_secret); 1305 memset(kbuf, 0, klen); 1306 xfree(kbuf); 1307 1308 /* XXX precompute? */ 1309 dsa_make_key_blob(sensitive_data.dsa_host_key, &server_host_key_blob, &sbloblen); 1310 1311 /* calc H */ /* XXX depends on 'kex' */ 1312 hash = kex_hash( 1313 client_version_string, 1314 server_version_string, 1315 buffer_ptr(client_kexinit), buffer_len(client_kexinit), 1316 buffer_ptr(server_kexinit), buffer_len(server_kexinit), 1317 (char *)server_host_key_blob, sbloblen, 1318 dh_client_pub, 1319 dh->pub_key, 1320 shared_secret 1321 ); 1322 buffer_free(client_kexinit); 1323 buffer_free(server_kexinit); 1324 xfree(client_kexinit); 1325 xfree(server_kexinit); 1326#ifdef DEBUG_KEXDH 1327 fprintf(stderr, "hash == "); 1328 for (i = 0; i< 20; i++) 1329 fprintf(stderr, "%02x", (hash[i])&0xff); 1330 fprintf(stderr, "\n"); 1331#endif 1332 /* save session id := H */ 1333 /* XXX hashlen depends on KEX */ 1334 session_id2_len = 20; 1335 session_id2 = xmalloc(session_id2_len); 1336 memcpy(session_id2, hash, session_id2_len); 1337 1338 /* sign H */ 1339 /* XXX hashlen depends on KEX */ 1340 dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20); 1341 1342 destroy_sensitive_data(); 1343 1344 /* send server hostkey, DH pubkey 'f' and singed H */ 1345 packet_start(SSH2_MSG_KEXDH_REPLY); 1346 packet_put_string((char *)server_host_key_blob, sbloblen); 1347 packet_put_bignum2(dh->pub_key); /* f */ 1348 packet_put_string((char *)signature, slen); 1349 packet_send(); 1350 xfree(signature); 1351 xfree(server_host_key_blob); 1352 packet_write_wait(); 1353 1354 kex_derive_keys(kex, hash, shared_secret); 1355 packet_set_kex(kex); 1356 1357 /* have keys, free DH */ 1358 DH_free(dh); 1359 1360 debug("send SSH2_MSG_NEWKEYS."); 1361 packet_start(SSH2_MSG_NEWKEYS); 1362 packet_send(); 1363 packet_write_wait(); 1364 debug("done: send SSH2_MSG_NEWKEYS."); 1365 1366 debug("Wait SSH2_MSG_NEWKEYS."); 1367 packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS); 1368 debug("GOT SSH2_MSG_NEWKEYS."); 1369 1370#ifdef DEBUG_KEXDH 1371 /* send 1st encrypted/maced/compressed message */ 1372 packet_start(SSH2_MSG_IGNORE); 1373 packet_put_cstring("markus"); 1374 packet_send(); 1375 packet_write_wait(); 1376#endif 1377 debug("done: KEX2."); 1378}
|