[BACK]Return to sshd.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sshd.c, Revision 1.99

1.86      markus      1: /*
1.65      deraadt     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: Fri Mar 17 17:09:28 1995 ylo
                      6:  * This program is the ssh daemon.  It listens for connections from clients, and
                      7:  * performs authentication, executes use commands or shell, and forwards
                      8:  * information to/from the application to the user client over an encrypted
                      9:  * connection.  This can also handle forwarding of X11, TCP/IP, and authentication
                     10:  * agent connections.
1.98      markus     11:  *
                     12:  * SSH2 implementation,
                     13:  * Copyright (c) 2000 Markus Friedl. All rights reserved.
1.65      deraadt    14:  */
1.1       deraadt    15:
                     16: #include "includes.h"
1.99    ! markus     17: RCSID("$OpenBSD: sshd.c,v 1.98 2000/04/06 08:55:22 markus Exp $");
1.1       deraadt    18:
                     19: #include "xmalloc.h"
                     20: #include "rsa.h"
                     21: #include "ssh.h"
                     22: #include "pty.h"
                     23: #include "packet.h"
                     24: #include "cipher.h"
                     25: #include "mpaux.h"
                     26: #include "servconf.h"
                     27: #include "uidswap.h"
1.33      markus     28: #include "compat.h"
1.96      markus     29: #include "buffer.h"
                     30:
1.98      markus     31: #include "ssh2.h"
1.96      markus     32: #include <ssl/dh.h>
                     33: #include <ssl/bn.h>
                     34: #include <ssl/hmac.h>
1.98      markus     35: #include "kex.h"
1.96      markus     36: #include <ssl/dsa.h>
                     37: #include <ssl/rsa.h>
                     38: #include "key.h"
1.98      markus     39: #include "dsa.h"
1.96      markus     40:
                     41: #include "auth.h"
1.98      markus     42: #include "myproposal.h"
1.1       deraadt    43:
                     44: #ifdef LIBWRAP
                     45: #include <tcpd.h>
                     46: #include <syslog.h>
                     47: int allow_severity = LOG_INFO;
                     48: int deny_severity = LOG_WARNING;
                     49: #endif /* LIBWRAP */
                     50:
                     51: #ifndef O_NOCTTY
                     52: #define O_NOCTTY       0
                     53: #endif
                     54:
                     55: /* Server configuration options. */
                     56: ServerOptions options;
                     57:
                     58: /* Name of the server configuration file. */
                     59: char *config_file_name = SERVER_CONFIG_FILE;
                     60:
1.75      markus     61: /*
                     62:  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
                     63:  * Default value is AF_UNSPEC means both IPv4 and IPv6.
                     64:  */
                     65: int IPv4or6 = AF_UNSPEC;
                     66:
1.98      markus     67: /* Flag indicating whether SSH2 is enabled */
                     68: int allow_ssh2 = 0;
                     69:
1.65      deraadt    70: /*
                     71:  * Debug mode flag.  This can be set on the command line.  If debug
                     72:  * mode is enabled, extra debugging output will be sent to the system
                     73:  * log, the daemon will not go to background, and will exit after processing
                     74:  * the first connection.
                     75:  */
1.1       deraadt    76: int debug_flag = 0;
                     77:
                     78: /* Flag indicating that the daemon is being started from inetd. */
                     79: int inetd_flag = 0;
                     80:
1.47      markus     81: /* debug goes to stderr unless inetd_flag is set */
                     82: int log_stderr = 0;
                     83:
1.1       deraadt    84: /* argv[0] without path. */
                     85: char *av0;
                     86:
                     87: /* Saved arguments to main(). */
                     88: char **saved_argv;
                     89:
1.66      markus     90: /*
1.75      markus     91:  * The sockets that the server is listening; this is used in the SIGHUP
                     92:  * signal handler.
1.66      markus     93:  */
1.75      markus     94: #define        MAX_LISTEN_SOCKS        16
                     95: int listen_socks[MAX_LISTEN_SOCKS];
                     96: int num_listen_socks = 0;
1.1       deraadt    97:
1.66      markus     98: /*
                     99:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                    100:  * sshd will skip the version-number exchange
                    101:  */
1.61      markus    102: char *client_version_string = NULL;
1.96      markus    103: char *server_version_string = NULL;
1.1       deraadt   104:
1.66      markus    105: /*
                    106:  * Any really sensitive data in the application is contained in this
                    107:  * structure. The idea is that this structure could be locked into memory so
                    108:  * that the pages do not get written into swap.  However, there are some
                    109:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    110:  * have access to the internals of them, and locking just the structure is
                    111:  * not very useful.  Currently, memory locking is not implemented.
                    112:  */
1.64      markus    113: struct {
                    114:        RSA *private_key;        /* Private part of server key. */
                    115:        RSA *host_key;           /* Private part of host key. */
1.1       deraadt   116: } sensitive_data;
                    117:
1.66      markus    118: /*
                    119:  * Flag indicating whether the current session key has been used.  This flag
                    120:  * is set whenever the key is used, and cleared when the key is regenerated.
                    121:  */
1.1       deraadt   122: int key_used = 0;
                    123:
                    124: /* This is set to true when SIGHUP is received. */
                    125: int received_sighup = 0;
                    126:
                    127: /* Public side of the server key.  This value is regenerated regularly with
                    128:    the private key. */
1.2       provos    129: RSA *public_key;
1.1       deraadt   130:
1.96      markus    131: /* session identifier, used by RSA-auth */
                    132: unsigned char session_id[16];
                    133:
1.1       deraadt   134: /* Prototypes for various functions defined later in this file. */
1.96      markus    135: void do_ssh1_kex();
1.98      markus    136: void do_ssh2_kex();
1.87      markus    137:
                    138: /*
1.75      markus    139:  * Close all listening sockets
                    140:  */
                    141: void
                    142: close_listen_socks(void)
                    143: {
                    144:        int i;
                    145:        for (i = 0; i < num_listen_socks; i++)
                    146:                close(listen_socks[i]);
                    147:        num_listen_socks = -1;
                    148: }
                    149:
                    150: /*
1.65      deraadt   151:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    152:  * the effect is to reread the configuration file (and to regenerate
                    153:  * the server key).
                    154:  */
1.64      markus    155: void
                    156: sighup_handler(int sig)
1.1       deraadt   157: {
1.64      markus    158:        received_sighup = 1;
                    159:        signal(SIGHUP, sighup_handler);
1.1       deraadt   160: }
                    161:
1.65      deraadt   162: /*
                    163:  * Called from the main program after receiving SIGHUP.
                    164:  * Restarts the server.
                    165:  */
1.64      markus    166: void
                    167: sighup_restart()
1.1       deraadt   168: {
1.64      markus    169:        log("Received SIGHUP; restarting.");
1.75      markus    170:        close_listen_socks();
1.64      markus    171:        execv(saved_argv[0], saved_argv);
                    172:        log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
                    173:        exit(1);
1.1       deraadt   174: }
                    175:
1.65      deraadt   176: /*
                    177:  * Generic signal handler for terminating signals in the master daemon.
                    178:  * These close the listen socket; not closing it seems to cause "Address
                    179:  * already in use" problems on some machines, which is inconvenient.
                    180:  */
1.64      markus    181: void
                    182: sigterm_handler(int sig)
1.1       deraadt   183: {
1.64      markus    184:        log("Received signal %d; terminating.", sig);
1.75      markus    185:        close_listen_socks();
1.64      markus    186:        exit(255);
1.1       deraadt   187: }
                    188:
1.65      deraadt   189: /*
                    190:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
                    191:  * reap any zombies left by exited c.
                    192:  */
1.64      markus    193: void
                    194: main_sigchld_handler(int sig)
1.1       deraadt   195: {
1.64      markus    196:        int save_errno = errno;
                    197:        int status;
1.60      deraadt   198:
1.64      markus    199:        while (waitpid(-1, &status, WNOHANG) > 0)
                    200:                ;
1.60      deraadt   201:
1.64      markus    202:        signal(SIGCHLD, main_sigchld_handler);
                    203:        errno = save_errno;
1.1       deraadt   204: }
                    205:
1.65      deraadt   206: /*
                    207:  * Signal handler for the alarm after the login grace period has expired.
                    208:  */
1.64      markus    209: void
                    210: grace_alarm_handler(int sig)
1.1       deraadt   211: {
1.64      markus    212:        /* Close the connection. */
                    213:        packet_close();
                    214:
                    215:        /* Log error and exit. */
                    216:        fatal("Timeout before authentication for %s.", get_remote_ipaddr());
1.62      markus    217: }
                    218:
1.65      deraadt   219: /*
                    220:  * Signal handler for the key regeneration alarm.  Note that this
                    221:  * alarm only occurs in the daemon waiting for connections, and it does not
                    222:  * do anything with the private key or random state before forking.
                    223:  * Thus there should be no concurrency control/asynchronous execution
                    224:  * problems.
                    225:  */
1.64      markus    226: void
                    227: key_regeneration_alarm(int sig)
1.1       deraadt   228: {
1.64      markus    229:        int save_errno = errno;
1.18      deraadt   230:
1.64      markus    231:        /* Check if we should generate a new key. */
                    232:        if (key_used) {
                    233:                /* This should really be done in the background. */
                    234:                log("Generating new %d bit RSA key.", options.server_key_bits);
                    235:
                    236:                if (sensitive_data.private_key != NULL)
                    237:                        RSA_free(sensitive_data.private_key);
                    238:                sensitive_data.private_key = RSA_new();
                    239:
                    240:                if (public_key != NULL)
                    241:                        RSA_free(public_key);
                    242:                public_key = RSA_new();
                    243:
                    244:                rsa_generate_key(sensitive_data.private_key, public_key,
                    245:                                 options.server_key_bits);
                    246:                arc4random_stir();
                    247:                key_used = 0;
                    248:                log("RSA key generation complete.");
                    249:        }
                    250:        /* Reschedule the alarm. */
                    251:        signal(SIGALRM, key_regeneration_alarm);
                    252:        alarm(options.key_regeneration_time);
                    253:        errno = save_errno;
1.1       deraadt   254: }
                    255:
1.98      markus    256: char *
                    257: chop(char *s)
                    258: {
                    259:         char *t = s;
                    260:         while (*t) {
                    261:                 if(*t == '\n' || *t == '\r') {
                    262:                         *t = '\0';
                    263:                         return s;
                    264:                 }
                    265:                 t++;
                    266:         }
                    267:         return s;
                    268:
                    269: }
                    270:
1.96      markus    271: void
                    272: sshd_exchange_identification(int sock_in, int sock_out)
                    273: {
                    274:        int i;
                    275:        int remote_major, remote_minor;
                    276:        char *s;
                    277:        char buf[256];                  /* Must not be larger than remote_version. */
                    278:        char remote_version[256];       /* Must be at least as big as buf. */
                    279:
                    280:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1.98      markus    281:                 allow_ssh2 ? 1  : PROTOCOL_MAJOR,
                    282:                 allow_ssh2 ? 99 : PROTOCOL_MINOR,
                    283:                 SSH_VERSION);
1.96      markus    284:        server_version_string = xstrdup(buf);
                    285:
                    286:        if (client_version_string == NULL) {
                    287:                /* Send our protocol version identification. */
                    288:                if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
                    289:                    != strlen(server_version_string)) {
                    290:                        log("Could not write ident string to %s.", get_remote_ipaddr());
                    291:                        fatal_cleanup();
                    292:                }
                    293:
                    294:                /* Read other side\'s version identification. */
                    295:                for (i = 0; i < sizeof(buf) - 1; i++) {
                    296:                        if (read(sock_in, &buf[i], 1) != 1) {
                    297:                                log("Did not receive ident string from %s.", get_remote_ipaddr());
                    298:                                fatal_cleanup();
                    299:                        }
                    300:                        if (buf[i] == '\r') {
                    301:                                buf[i] = '\n';
                    302:                                buf[i + 1] = 0;
                    303:                                continue;
1.98      markus    304:                                //break;
1.96      markus    305:                        }
                    306:                        if (buf[i] == '\n') {
                    307:                                /* buf[i] == '\n' */
                    308:                                buf[i + 1] = 0;
                    309:                                break;
                    310:                        }
                    311:                }
                    312:                buf[sizeof(buf) - 1] = 0;
                    313:                client_version_string = xstrdup(buf);
                    314:        }
                    315:
                    316:        /*
                    317:         * Check that the versions match.  In future this might accept
                    318:         * several versions and set appropriate flags to handle them.
                    319:         */
                    320:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    321:            &remote_major, &remote_minor, remote_version) != 3) {
                    322:                s = "Protocol mismatch.\n";
                    323:                (void) atomicio(write, sock_out, s, strlen(s));
                    324:                close(sock_in);
                    325:                close(sock_out);
                    326:                log("Bad protocol version identification '%.100s' from %s",
                    327:                    client_version_string, get_remote_ipaddr());
                    328:                fatal_cleanup();
                    329:        }
                    330:        debug("Client protocol version %d.%d; client software version %.100s",
                    331:              remote_major, remote_minor, remote_version);
                    332:
1.98      markus    333:        compat_datafellows(remote_version);
                    334:
1.96      markus    335:        switch(remote_major) {
                    336:        case 1:
                    337:                if (remote_minor < 3) {
                    338:                        packet_disconnect("Your ssh version is too old and"
                    339:                            "is no longer supported.  Please install a newer version.");
                    340:                } else if (remote_minor == 3) {
                    341:                        /* note that this disables agent-forwarding */
                    342:                        enable_compat13();
                    343:                }
1.99    ! markus    344:                if (remote_minor != 99)
        !           345:                       break;
        !           346:                /* FALLTHROUGH */
1.98      markus    347:        case 2:
                    348:                if (allow_ssh2) {
                    349:                        enable_compat20();
                    350:                        break;
                    351:                }
1.99    ! markus    352:                /* FALLTHROUGH */
1.96      markus    353:        default:
                    354:                s = "Protocol major versions differ.\n";
                    355:                (void) atomicio(write, sock_out, s, strlen(s));
                    356:                close(sock_in);
                    357:                close(sock_out);
                    358:                log("Protocol major versions differ for %s: %d vs. %d",
                    359:                    get_remote_ipaddr(), PROTOCOL_MAJOR, remote_major);
                    360:                fatal_cleanup();
                    361:                break;
                    362:        }
1.98      markus    363:        chop(server_version_string);
                    364:        chop(client_version_string);
1.96      markus    365: }
                    366:
1.65      deraadt   367: /*
                    368:  * Main program for the daemon.
                    369:  */
1.2       provos    370: int
                    371: main(int ac, char **av)
1.1       deraadt   372: {
1.64      markus    373:        extern char *optarg;
                    374:        extern int optind;
1.75      markus    375:        int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1;
                    376:        socklen_t fromlen;
1.64      markus    377:        int silentrsa = 0;
1.75      markus    378:        fd_set *fdset;
                    379:        struct sockaddr_storage from;
1.64      markus    380:        const char *remote_ip;
                    381:        int remote_port;
                    382:        char *comment;
                    383:        FILE *f;
                    384:        struct linger linger;
1.75      markus    385:        struct addrinfo *ai;
                    386:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                    387:        int listen_sock, maxfd;
1.64      markus    388:
                    389:        /* Save argv[0]. */
                    390:        saved_argv = av;
                    391:        if (strchr(av[0], '/'))
                    392:                av0 = strrchr(av[0], '/') + 1;
                    393:        else
                    394:                av0 = av[0];
                    395:
                    396:        /* Initialize configuration options to their default values. */
                    397:        initialize_server_options(&options);
                    398:
                    399:        /* Parse command-line arguments. */
1.98      markus    400:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ246")) != EOF) {
1.64      markus    401:                switch (opt) {
1.98      markus    402:                case '2':
                    403:                        allow_ssh2 = 1;
                    404:                        break;
1.75      markus    405:                case '4':
                    406:                        IPv4or6 = AF_INET;
                    407:                        break;
                    408:                case '6':
                    409:                        IPv4or6 = AF_INET6;
                    410:                        break;
1.64      markus    411:                case 'f':
                    412:                        config_file_name = optarg;
                    413:                        break;
                    414:                case 'd':
                    415:                        debug_flag = 1;
                    416:                        options.log_level = SYSLOG_LEVEL_DEBUG;
                    417:                        break;
                    418:                case 'i':
                    419:                        inetd_flag = 1;
                    420:                        break;
                    421:                case 'Q':
                    422:                        silentrsa = 1;
                    423:                        break;
                    424:                case 'q':
                    425:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    426:                        break;
                    427:                case 'b':
                    428:                        options.server_key_bits = atoi(optarg);
                    429:                        break;
                    430:                case 'p':
1.75      markus    431:                        options.ports_from_cmdline = 1;
                    432:                        if (options.num_ports >= MAX_PORTS)
                    433:                                fatal("too many ports.\n");
                    434:                        options.ports[options.num_ports++] = atoi(optarg);
1.64      markus    435:                        break;
                    436:                case 'g':
                    437:                        options.login_grace_time = atoi(optarg);
                    438:                        break;
                    439:                case 'k':
                    440:                        options.key_regeneration_time = atoi(optarg);
                    441:                        break;
                    442:                case 'h':
                    443:                        options.host_key_file = optarg;
                    444:                        break;
                    445:                case 'V':
                    446:                        client_version_string = optarg;
                    447:                        /* only makes sense with inetd_flag, i.e. no listen() */
                    448:                        inetd_flag = 1;
                    449:                        break;
                    450:                case '?':
                    451:                default:
                    452:                        fprintf(stderr, "sshd version %s\n", SSH_VERSION);
                    453:                        fprintf(stderr, "Usage: %s [options]\n", av0);
                    454:                        fprintf(stderr, "Options:\n");
1.66      markus    455:                        fprintf(stderr, "  -f file    Configuration file (default %s)\n", SERVER_CONFIG_FILE);
1.64      markus    456:                        fprintf(stderr, "  -d         Debugging mode\n");
                    457:                        fprintf(stderr, "  -i         Started from inetd\n");
                    458:                        fprintf(stderr, "  -q         Quiet (no logging)\n");
                    459:                        fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
                    460:                        fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
                    461:                        fprintf(stderr, "  -g seconds Grace period for authentication (default: 300)\n");
                    462:                        fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
                    463:                        fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
1.75      markus    464:                            HOST_KEY_FILE);
                    465:                        fprintf(stderr, "  -4         Use IPv4 only\n");
                    466:                        fprintf(stderr, "  -6         Use IPv6 only\n");
1.64      markus    467:                        exit(1);
                    468:                }
                    469:        }
                    470:
1.75      markus    471:        /*
                    472:         * Force logging to stderr until we have loaded the private host
                    473:         * key (unless started from inetd)
                    474:         */
                    475:        log_init(av0,
                    476:            options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
                    477:            options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
                    478:            !inetd_flag);
                    479:
1.64      markus    480:        /* check if RSA support exists */
                    481:        if (rsa_alive() == 0) {
                    482:                if (silentrsa == 0)
                    483:                        printf("sshd: no RSA support in libssl and libcrypto -- exiting.  See ssl(8)\n");
                    484:                log("no RSA support in libssl and libcrypto -- exiting.  See ssl(8)");
                    485:                exit(1);
                    486:        }
                    487:        /* Read server configuration options from the configuration file. */
                    488:        read_server_config(&options, config_file_name);
                    489:
                    490:        /* Fill in default values for those options not explicitly set. */
                    491:        fill_default_server_options(&options);
                    492:
                    493:        /* Check certain values for sanity. */
                    494:        if (options.server_key_bits < 512 ||
                    495:            options.server_key_bits > 32768) {
                    496:                fprintf(stderr, "Bad server key size.\n");
                    497:                exit(1);
                    498:        }
                    499:        /* Check that there are no remaining arguments. */
                    500:        if (optind < ac) {
                    501:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                    502:                exit(1);
                    503:        }
                    504:
                    505:        debug("sshd version %.100s", SSH_VERSION);
                    506:
                    507:        sensitive_data.host_key = RSA_new();
                    508:        errno = 0;
                    509:        /* Load the host key.  It must have empty passphrase. */
                    510:        if (!load_private_key(options.host_key_file, "",
                    511:                              sensitive_data.host_key, &comment)) {
                    512:                error("Could not load host key: %.200s: %.100s",
                    513:                      options.host_key_file, strerror(errno));
                    514:                exit(1);
                    515:        }
                    516:        xfree(comment);
                    517:
                    518:        /* Initialize the log (it is reinitialized below in case we
                    519:           forked). */
                    520:        if (debug_flag && !inetd_flag)
                    521:                log_stderr = 1;
                    522:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    523:
                    524:        /* If not in debugging mode, and not started from inetd,
                    525:           disconnect from the controlling terminal, and fork.  The
                    526:           original process exits. */
                    527:        if (!debug_flag && !inetd_flag) {
1.1       deraadt   528: #ifdef TIOCNOTTY
1.64      markus    529:                int fd;
1.1       deraadt   530: #endif /* TIOCNOTTY */
1.64      markus    531:                if (daemon(0, 0) < 0)
                    532:                        fatal("daemon() failed: %.200s", strerror(errno));
                    533:
                    534:                /* Disconnect from the controlling tty. */
1.1       deraadt   535: #ifdef TIOCNOTTY
1.64      markus    536:                fd = open("/dev/tty", O_RDWR | O_NOCTTY);
                    537:                if (fd >= 0) {
                    538:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                    539:                        close(fd);
                    540:                }
                    541: #endif /* TIOCNOTTY */
                    542:        }
                    543:        /* Reinitialize the log (because of the fork above). */
                    544:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    545:
                    546:        /* Check that server and host key lengths differ sufficiently.
                    547:           This is necessary to make double encryption work with rsaref.
                    548:           Oh, I hate software patents. I dont know if this can go? Niels */
                    549:        if (options.server_key_bits >
                    550:        BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
                    551:            options.server_key_bits <
                    552:        BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                    553:                options.server_key_bits =
                    554:                        BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
                    555:                debug("Forcing server key to %d bits to make it differ from host key.",
                    556:                      options.server_key_bits);
1.1       deraadt   557:        }
1.64      markus    558:        /* Do not display messages to stdout in RSA code. */
                    559:        rsa_set_verbose(0);
                    560:
                    561:        /* Initialize the random number generator. */
                    562:        arc4random_stir();
                    563:
                    564:        /* Chdir to the root directory so that the current disk can be
                    565:           unmounted if desired. */
                    566:        chdir("/");
                    567:
                    568:        /* Start listening for a socket, unless started from inetd. */
                    569:        if (inetd_flag) {
                    570:                int s1, s2;
                    571:                s1 = dup(0);    /* Make sure descriptors 0, 1, and 2 are in use. */
                    572:                s2 = dup(s1);
                    573:                sock_in = dup(0);
                    574:                sock_out = dup(1);
                    575:                /* We intentionally do not close the descriptors 0, 1, and 2
                    576:                   as our code for setting the descriptors won\'t work
                    577:                   if ttyfd happens to be one of those. */
                    578:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
                    579:
                    580:                public_key = RSA_new();
                    581:                sensitive_data.private_key = RSA_new();
                    582:
                    583:                log("Generating %d bit RSA key.", options.server_key_bits);
                    584:                rsa_generate_key(sensitive_data.private_key, public_key,
                    585:                                 options.server_key_bits);
                    586:                arc4random_stir();
                    587:                log("RSA key generation complete.");
                    588:        } else {
1.75      markus    589:                for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                    590:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                    591:                                continue;
                    592:                        if (num_listen_socks >= MAX_LISTEN_SOCKS)
                    593:                                fatal("Too many listen sockets. "
                    594:                                    "Enlarge MAX_LISTEN_SOCKS");
                    595:                        if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
                    596:                            ntop, sizeof(ntop), strport, sizeof(strport),
                    597:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                    598:                                error("getnameinfo failed");
                    599:                                continue;
                    600:                        }
                    601:                        /* Create socket for listening. */
                    602:                        listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
                    603:                        if (listen_sock < 0) {
                    604:                                /* kernel may not support ipv6 */
                    605:                                verbose("socket: %.100s", strerror(errno));
                    606:                                continue;
                    607:                        }
                    608:                        if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
                    609:                                error("listen_sock O_NONBLOCK: %s", strerror(errno));
                    610:                                close(listen_sock);
                    611:                                continue;
                    612:                        }
                    613:                        /*
                    614:                         * Set socket options.  We try to make the port
                    615:                         * reusable and have it close as fast as possible
                    616:                         * without waiting in unnecessary wait states on
                    617:                         * close.
                    618:                         */
                    619:                        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                    620:                            (void *) &on, sizeof(on));
                    621:                        linger.l_onoff = 1;
                    622:                        linger.l_linger = 5;
                    623:                        setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
                    624:                            (void *) &linger, sizeof(linger));
                    625:
                    626:                        debug("Bind to port %s on %s.", strport, ntop);
                    627:
                    628:                        /* Bind the socket to the desired port. */
                    629:                        if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                    630:                                error("Bind to port %s on %s failed: %.200s.",
                    631:                                    strport, ntop, strerror(errno));
                    632:                                close(listen_sock);
                    633:                                continue;
                    634:                        }
                    635:                        listen_socks[num_listen_socks] = listen_sock;
                    636:                        num_listen_socks++;
                    637:
                    638:                        /* Start listening on the port. */
                    639:                        log("Server listening on %s port %s.", ntop, strport);
                    640:                        if (listen(listen_sock, 5) < 0)
                    641:                                fatal("listen: %.100s", strerror(errno));
                    642:
1.64      markus    643:                }
1.75      markus    644:                freeaddrinfo(options.listen_addrs);
                    645:
                    646:                if (!num_listen_socks)
                    647:                        fatal("Cannot bind any address.");
                    648:
1.64      markus    649:                if (!debug_flag) {
1.66      markus    650:                        /*
                    651:                         * Record our pid in /etc/sshd_pid to make it easier
                    652:                         * to kill the correct sshd.  We don\'t want to do
                    653:                         * this before the bind above because the bind will
                    654:                         * fail if there already is a daemon, and this will
                    655:                         * overwrite any old pid in the file.
                    656:                         */
1.64      markus    657:                        f = fopen(SSH_DAEMON_PID_FILE, "w");
                    658:                        if (f) {
                    659:                                fprintf(f, "%u\n", (unsigned int) getpid());
                    660:                                fclose(f);
                    661:                        }
                    662:                }
                    663:
                    664:                public_key = RSA_new();
                    665:                sensitive_data.private_key = RSA_new();
                    666:
                    667:                log("Generating %d bit RSA key.", options.server_key_bits);
                    668:                rsa_generate_key(sensitive_data.private_key, public_key,
                    669:                                 options.server_key_bits);
                    670:                arc4random_stir();
                    671:                log("RSA key generation complete.");
                    672:
                    673:                /* Schedule server key regeneration alarm. */
                    674:                signal(SIGALRM, key_regeneration_alarm);
                    675:                alarm(options.key_regeneration_time);
                    676:
                    677:                /* Arrange to restart on SIGHUP.  The handler needs listen_sock. */
                    678:                signal(SIGHUP, sighup_handler);
                    679:                signal(SIGTERM, sigterm_handler);
                    680:                signal(SIGQUIT, sigterm_handler);
                    681:
                    682:                /* Arrange SIGCHLD to be caught. */
                    683:                signal(SIGCHLD, main_sigchld_handler);
                    684:
1.75      markus    685:                /* setup fd set for listen */
                    686:                maxfd = 0;
                    687:                for (i = 0; i < num_listen_socks; i++)
                    688:                        if (listen_socks[i] > maxfd)
                    689:                                maxfd = listen_socks[i];
                    690:                fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
                    691:                fdset = (fd_set *)xmalloc(fdsetsz);
                    692:
1.66      markus    693:                /*
                    694:                 * Stay listening for connections until the system crashes or
                    695:                 * the daemon is killed with a signal.
                    696:                 */
1.64      markus    697:                for (;;) {
                    698:                        if (received_sighup)
                    699:                                sighup_restart();
1.75      markus    700:                        /* Wait in select until there is a connection. */
                    701:                        memset(fdset, 0, fdsetsz);
                    702:                        for (i = 0; i < num_listen_socks; i++)
                    703:                                FD_SET(listen_socks[i], fdset);
                    704:                        if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
                    705:                                if (errno != EINTR)
                    706:                                        error("select: %.100s", strerror(errno));
                    707:                                continue;
                    708:                        }
                    709:                        for (i = 0; i < num_listen_socks; i++) {
                    710:                                if (!FD_ISSET(listen_socks[i], fdset))
1.70      provos    711:                                        continue;
1.75      markus    712:                        fromlen = sizeof(from);
                    713:                        newsock = accept(listen_socks[i], (struct sockaddr *)&from,
                    714:                            &fromlen);
                    715:                        if (newsock < 0) {
                    716:                                if (errno != EINTR && errno != EWOULDBLOCK)
                    717:                                        error("accept: %.100s", strerror(errno));
                    718:                                continue;
1.70      provos    719:                        }
1.75      markus    720:                        if (fcntl(newsock, F_SETFL, 0) < 0) {
                    721:                                error("newsock del O_NONBLOCK: %s", strerror(errno));
1.64      markus    722:                                continue;
                    723:                        }
1.66      markus    724:                        /*
                    725:                         * Got connection.  Fork a child to handle it, unless
                    726:                         * we are in debugging mode.
                    727:                         */
1.64      markus    728:                        if (debug_flag) {
1.66      markus    729:                                /*
                    730:                                 * In debugging mode.  Close the listening
                    731:                                 * socket, and start processing the
                    732:                                 * connection without forking.
                    733:                                 */
1.64      markus    734:                                debug("Server will not fork when running in debugging mode.");
1.75      markus    735:                                close_listen_socks();
1.64      markus    736:                                sock_in = newsock;
                    737:                                sock_out = newsock;
                    738:                                pid = getpid();
                    739:                                break;
                    740:                        } else {
1.66      markus    741:                                /*
                    742:                                 * Normal production daemon.  Fork, and have
                    743:                                 * the child process the connection. The
                    744:                                 * parent continues listening.
                    745:                                 */
1.64      markus    746:                                if ((pid = fork()) == 0) {
1.66      markus    747:                                        /*
                    748:                                         * Child.  Close the listening socket, and start using the
                    749:                                         * accepted socket.  Reinitialize logging (since our pid has
                    750:                                         * changed).  We break out of the loop to handle the connection.
                    751:                                         */
1.75      markus    752:                                        close_listen_socks();
1.64      markus    753:                                        sock_in = newsock;
                    754:                                        sock_out = newsock;
                    755:                                        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    756:                                        break;
                    757:                                }
                    758:                        }
                    759:
                    760:                        /* Parent.  Stay in the loop. */
                    761:                        if (pid < 0)
                    762:                                error("fork: %.100s", strerror(errno));
                    763:                        else
                    764:                                debug("Forked child %d.", pid);
1.1       deraadt   765:
1.64      markus    766:                        /* Mark that the key has been used (it was "given" to the child). */
                    767:                        key_used = 1;
1.1       deraadt   768:
1.64      markus    769:                        arc4random_stir();
1.1       deraadt   770:
1.64      markus    771:                        /* Close the new socket (the child is now taking care of it). */
                    772:                        close(newsock);
1.75      markus    773:                        } /* for (i = 0; i < num_listen_socks; i++) */
                    774:                        /* child process check (or debug mode) */
                    775:                        if (num_listen_socks < 0)
                    776:                                break;
1.64      markus    777:                }
1.1       deraadt   778:        }
                    779:
1.64      markus    780:        /* This is the child processing a new connection. */
                    781:
1.66      markus    782:        /*
                    783:         * Disable the key regeneration alarm.  We will not regenerate the
                    784:         * key since we are no longer in a position to give it to anyone. We
                    785:         * will not restart on SIGHUP since it no longer makes sense.
                    786:         */
1.64      markus    787:        alarm(0);
                    788:        signal(SIGALRM, SIG_DFL);
                    789:        signal(SIGHUP, SIG_DFL);
                    790:        signal(SIGTERM, SIG_DFL);
                    791:        signal(SIGQUIT, SIG_DFL);
                    792:        signal(SIGCHLD, SIG_DFL);
                    793:
1.66      markus    794:        /*
                    795:         * Set socket options for the connection.  We want the socket to
                    796:         * close as fast as possible without waiting for anything.  If the
                    797:         * connection is not a socket, these will do nothing.
                    798:         */
                    799:        /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.64      markus    800:        linger.l_onoff = 1;
                    801:        linger.l_linger = 5;
                    802:        setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
                    803:
1.66      markus    804:        /*
                    805:         * Register our connection.  This turns encryption off because we do
                    806:         * not have a key.
                    807:         */
1.64      markus    808:        packet_set_connection(sock_in, sock_out);
1.1       deraadt   809:
1.64      markus    810:        remote_port = get_remote_port();
                    811:        remote_ip = get_remote_ipaddr();
1.52      markus    812:
1.64      markus    813:        /* Check whether logins are denied from this host. */
1.37      dugsong   814: #ifdef LIBWRAP
1.75      markus    815:        /* XXX LIBWRAP noes not know about IPv6 */
1.64      markus    816:        {
                    817:                struct request_info req;
1.37      dugsong   818:
1.64      markus    819:                request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
                    820:                fromhost(&req);
1.37      dugsong   821:
1.64      markus    822:                if (!hosts_access(&req)) {
                    823:                        close(sock_in);
                    824:                        close(sock_out);
                    825:                        refuse(&req);
                    826:                }
1.75      markus    827: /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
1.64      markus    828:        }
1.75      markus    829: #endif /* LIBWRAP */
1.64      markus    830:        /* Log the connection. */
                    831:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1       deraadt   832:
1.66      markus    833:        /*
                    834:         * We don\'t want to listen forever unless the other side
                    835:         * successfully authenticates itself.  So we set up an alarm which is
                    836:         * cleared after successful authentication.  A limit of zero
                    837:         * indicates no limit. Note that we don\'t set the alarm in debugging
                    838:         * mode; it is just annoying to have the server exit just when you
                    839:         * are about to discover the bug.
                    840:         */
1.64      markus    841:        signal(SIGALRM, grace_alarm_handler);
                    842:        if (!debug_flag)
                    843:                alarm(options.login_grace_time);
                    844:
1.96      markus    845:        sshd_exchange_identification(sock_in, sock_out);
1.66      markus    846:        /*
                    847:         * Check that the connection comes from a privileged port.  Rhosts-
                    848:         * and Rhosts-RSA-Authentication only make sense from priviledged
                    849:         * programs.  Of course, if the intruder has root access on his local
                    850:         * machine, he can connect from any port.  So do not use these
                    851:         * authentication methods from machines that you do not trust.
                    852:         */
1.64      markus    853:        if (remote_port >= IPPORT_RESERVED ||
                    854:            remote_port < IPPORT_RESERVED / 2) {
                    855:                options.rhosts_authentication = 0;
                    856:                options.rhosts_rsa_authentication = 0;
                    857:        }
1.76      markus    858: #ifdef KRB4
                    859:        if (!packet_connection_is_ipv4() &&
                    860:            options.kerberos_authentication) {
                    861:                debug("Kerberos Authentication disabled, only available for IPv4.");
                    862:                options.kerberos_authentication = 0;
                    863:        }
                    864: #endif /* KRB4 */
                    865:
1.64      markus    866:        packet_set_nonblocking();
1.1       deraadt   867:
1.77      markus    868:        /* perform the key exchange */
                    869:        /* authenticate user and start session */
1.98      markus    870:        if (compat20) {
                    871:                do_ssh2_kex();
                    872:                do_authentication2();
                    873:        } else {
                    874:                do_ssh1_kex();
                    875:                do_authentication();
                    876:        }
1.1       deraadt   877:
                    878: #ifdef KRB4
1.64      markus    879:        /* Cleanup user's ticket cache file. */
                    880:        if (options.kerberos_ticket_cleanup)
                    881:                (void) dest_tkt();
1.1       deraadt   882: #endif /* KRB4 */
                    883:
1.64      markus    884:        /* The connection has been terminated. */
                    885:        verbose("Closing connection to %.100s", remote_ip);
                    886:        packet_close();
                    887:        exit(0);
1.1       deraadt   888: }
                    889:
1.65      deraadt   890: /*
1.77      markus    891:  * SSH1 key exchange
1.65      deraadt   892:  */
1.52      markus    893: void
1.96      markus    894: do_ssh1_kex()
1.1       deraadt   895: {
1.64      markus    896:        int i, len;
1.77      markus    897:        int plen, slen;
1.64      markus    898:        BIGNUM *session_key_int;
                    899:        unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1.77      markus    900:        unsigned char cookie[8];
1.64      markus    901:        unsigned int cipher_type, auth_mask, protocol_flags;
                    902:        u_int32_t rand = 0;
                    903:
1.66      markus    904:        /*
                    905:         * Generate check bytes that the client must send back in the user
                    906:         * packet in order for it to be accepted; this is used to defy ip
                    907:         * spoofing attacks.  Note that this only works against somebody
                    908:         * doing IP spoofing from a remote machine; any machine on the local
                    909:         * network can still see outgoing packets and catch the random
                    910:         * cookie.  This only affects rhosts authentication, and this is one
                    911:         * of the reasons why it is inherently insecure.
                    912:         */
1.64      markus    913:        for (i = 0; i < 8; i++) {
                    914:                if (i % 4 == 0)
                    915:                        rand = arc4random();
1.77      markus    916:                cookie[i] = rand & 0xff;
1.64      markus    917:                rand >>= 8;
                    918:        }
                    919:
1.66      markus    920:        /*
                    921:         * Send our public key.  We include in the packet 64 bits of random
                    922:         * data that must be matched in the reply in order to prevent IP
                    923:         * spoofing.
                    924:         */
1.64      markus    925:        packet_start(SSH_SMSG_PUBLIC_KEY);
                    926:        for (i = 0; i < 8; i++)
1.77      markus    927:                packet_put_char(cookie[i]);
1.64      markus    928:
                    929:        /* Store our public server RSA key. */
                    930:        packet_put_int(BN_num_bits(public_key->n));
                    931:        packet_put_bignum(public_key->e);
                    932:        packet_put_bignum(public_key->n);
                    933:
                    934:        /* Store our public host RSA key. */
                    935:        packet_put_int(BN_num_bits(sensitive_data.host_key->n));
                    936:        packet_put_bignum(sensitive_data.host_key->e);
                    937:        packet_put_bignum(sensitive_data.host_key->n);
                    938:
                    939:        /* Put protocol flags. */
                    940:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                    941:
                    942:        /* Declare which ciphers we support. */
1.97      markus    943:        packet_put_int(cipher_mask1());
1.64      markus    944:
                    945:        /* Declare supported authentication types. */
                    946:        auth_mask = 0;
                    947:        if (options.rhosts_authentication)
                    948:                auth_mask |= 1 << SSH_AUTH_RHOSTS;
                    949:        if (options.rhosts_rsa_authentication)
                    950:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                    951:        if (options.rsa_authentication)
                    952:                auth_mask |= 1 << SSH_AUTH_RSA;
1.1       deraadt   953: #ifdef KRB4
1.64      markus    954:        if (options.kerberos_authentication)
                    955:                auth_mask |= 1 << SSH_AUTH_KERBEROS;
1.1       deraadt   956: #endif
1.5       dugsong   957: #ifdef AFS
1.64      markus    958:        if (options.kerberos_tgt_passing)
                    959:                auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
                    960:        if (options.afs_token_passing)
                    961:                auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1.1       deraadt   962: #endif
1.63      markus    963: #ifdef SKEY
1.64      markus    964:        if (options.skey_authentication == 1)
                    965:                auth_mask |= 1 << SSH_AUTH_TIS;
1.63      markus    966: #endif
1.64      markus    967:        if (options.password_authentication)
                    968:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                    969:        packet_put_int(auth_mask);
                    970:
                    971:        /* Send the packet and wait for it to be sent. */
                    972:        packet_send();
                    973:        packet_write_wait();
                    974:
                    975:        debug("Sent %d bit public key and %d bit host key.",
                    976:              BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
                    977:
                    978:        /* Read clients reply (cipher type and session key). */
                    979:        packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
                    980:
1.69      markus    981:        /* Get cipher type and check whether we accept this. */
1.64      markus    982:        cipher_type = packet_get_char();
1.69      markus    983:
                    984:         if (!(cipher_mask() & (1 << cipher_type)))
                    985:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus    986:
                    987:        /* Get check bytes from the packet.  These must match those we
                    988:           sent earlier with the public key packet. */
                    989:        for (i = 0; i < 8; i++)
1.77      markus    990:                if (cookie[i] != packet_get_char())
1.64      markus    991:                        packet_disconnect("IP Spoofing check bytes do not match.");
                    992:
                    993:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                    994:
                    995:        /* Get the encrypted integer. */
                    996:        session_key_int = BN_new();
                    997:        packet_get_bignum(session_key_int, &slen);
                    998:
                    999:        protocol_flags = packet_get_int();
                   1000:        packet_set_protocol_flags(protocol_flags);
                   1001:
                   1002:        packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
                   1003:
1.66      markus   1004:        /*
                   1005:         * Decrypt it using our private server key and private host key (key
                   1006:         * with larger modulus first).
                   1007:         */
1.64      markus   1008:        if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
                   1009:                /* Private key has bigger modulus. */
                   1010:                if (BN_num_bits(sensitive_data.private_key->n) <
                   1011:                    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                   1012:                        fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                   1013:                              get_remote_ipaddr(),
                   1014:                              BN_num_bits(sensitive_data.private_key->n),
                   1015:                              BN_num_bits(sensitive_data.host_key->n),
                   1016:                              SSH_KEY_BITS_RESERVED);
                   1017:                }
                   1018:                rsa_private_decrypt(session_key_int, session_key_int,
                   1019:                                    sensitive_data.private_key);
                   1020:                rsa_private_decrypt(session_key_int, session_key_int,
                   1021:                                    sensitive_data.host_key);
                   1022:        } else {
                   1023:                /* Host key has bigger modulus (or they are equal). */
                   1024:                if (BN_num_bits(sensitive_data.host_key->n) <
                   1025:                    BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
                   1026:                        fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
                   1027:                              get_remote_ipaddr(),
                   1028:                              BN_num_bits(sensitive_data.host_key->n),
                   1029:                              BN_num_bits(sensitive_data.private_key->n),
                   1030:                              SSH_KEY_BITS_RESERVED);
                   1031:                }
                   1032:                rsa_private_decrypt(session_key_int, session_key_int,
                   1033:                                    sensitive_data.host_key);
                   1034:                rsa_private_decrypt(session_key_int, session_key_int,
                   1035:                                    sensitive_data.private_key);
                   1036:        }
                   1037:
1.77      markus   1038:        compute_session_id(session_id, cookie,
1.64      markus   1039:                           sensitive_data.host_key->n,
                   1040:                           sensitive_data.private_key->n);
                   1041:
1.77      markus   1042:        /* Destroy the private and public keys.  They will no longer be needed. */
                   1043:        RSA_free(public_key);
                   1044:        RSA_free(sensitive_data.private_key);
                   1045:        RSA_free(sensitive_data.host_key);
                   1046:
1.66      markus   1047:        /*
                   1048:         * Extract session key from the decrypted integer.  The key is in the
                   1049:         * least significant 256 bits of the integer; the first byte of the
                   1050:         * key is in the highest bits.
                   1051:         */
1.64      markus   1052:        BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   1053:        len = BN_num_bytes(session_key_int);
                   1054:        if (len < 0 || len > sizeof(session_key))
                   1055:                fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
                   1056:                      get_remote_ipaddr(),
                   1057:                      len, sizeof(session_key));
                   1058:        memset(session_key, 0, sizeof(session_key));
                   1059:        BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
                   1060:
1.77      markus   1061:        /* Destroy the decrypted integer.  It is no longer needed. */
                   1062:        BN_clear_free(session_key_int);
                   1063:
1.64      markus   1064:        /* Xor the first 16 bytes of the session key with the session id. */
                   1065:        for (i = 0; i < 16; i++)
                   1066:                session_key[i] ^= session_id[i];
                   1067:
                   1068:        /* Set the session key.  From this on all communications will be encrypted. */
                   1069:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   1070:
                   1071:        /* Destroy our copy of the session key.  It is no longer needed. */
                   1072:        memset(session_key, 0, sizeof(session_key));
                   1073:
                   1074:        debug("Received session key; encryption turned on.");
                   1075:
                   1076:        /* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
                   1077:        packet_start(SSH_SMSG_SUCCESS);
                   1078:        packet_send();
                   1079:        packet_write_wait();
1.98      markus   1080: }
                   1081:
                   1082: /*
                   1083:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   1084:  */
                   1085: void
                   1086: do_ssh2_kex()
                   1087: {
                   1088:        Buffer *server_kexinit;
                   1089:        Buffer *client_kexinit;
                   1090:        int payload_len, dlen;
                   1091:        int slen;
                   1092:        unsigned int klen, kout;
                   1093:        char *ptr;
                   1094:        unsigned char *signature = NULL;
                   1095:        unsigned char *server_host_key_blob = NULL;
                   1096:        unsigned int sbloblen;
                   1097:        DH *dh;
                   1098:        BIGNUM *dh_client_pub = 0;
                   1099:        BIGNUM *shared_secret = 0;
                   1100:        int i;
                   1101:        unsigned char *kbuf;
                   1102:        unsigned char *hash;
                   1103:        Kex *kex;
                   1104:        Key *server_host_key;
                   1105:        char *cprop[PROPOSAL_MAX];
                   1106:        char *sprop[PROPOSAL_MAX];
                   1107:
                   1108: /* KEXINIT */
                   1109:
                   1110:        debug("Sending KEX init.");
                   1111:
                   1112:        for (i = 0; i < PROPOSAL_MAX; i++)
                   1113:                sprop[i] = xstrdup(myproposal[i]);
                   1114:        server_kexinit = kex_init(sprop);
                   1115:        packet_start(SSH2_MSG_KEXINIT);
                   1116:        packet_put_raw(buffer_ptr(server_kexinit), buffer_len(server_kexinit));
                   1117:        packet_send();
                   1118:        packet_write_wait();
                   1119:
                   1120:        debug("done");
                   1121:
                   1122:        packet_read_expect(&payload_len, SSH2_MSG_KEXINIT);
                   1123:
                   1124:        /*
                   1125:         * save raw KEXINIT payload in buffer. this is used during
                   1126:         * computation of the session_id and the session keys.
                   1127:         */
                   1128:        client_kexinit = xmalloc(sizeof(*client_kexinit));
                   1129:        buffer_init(client_kexinit);
                   1130:        ptr = packet_get_raw(&payload_len);
                   1131:        buffer_append(client_kexinit, ptr, payload_len);
                   1132:
                   1133:        /* skip cookie */
                   1134:        for (i = 0; i < 16; i++)
                   1135:                (void) packet_get_char();
                   1136:        /* save kex init proposal strings */
                   1137:        for (i = 0; i < PROPOSAL_MAX; i++) {
                   1138:                cprop[i] = packet_get_string(NULL);
                   1139:                debug("got kexinit string: %s", cprop[i]);
                   1140:        }
                   1141:
                   1142:        i = (int) packet_get_char();
                   1143:        debug("first kex follow == %d", i);
                   1144:        i = packet_get_int();
                   1145:        debug("reserved == %d", i);
                   1146:
                   1147:        debug("done read kexinit");
                   1148:        kex = kex_choose_conf(cprop, sprop, 1);
                   1149:
                   1150: /* KEXDH */
                   1151:
                   1152:        debug("Wait SSH2_MSG_KEXDH_INIT.");
                   1153:        packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
                   1154:
                   1155:        /* key, cert */
                   1156:        dh_client_pub = BN_new();
                   1157:        if (dh_client_pub == NULL)
                   1158:                fatal("dh_client_pub == NULL");
                   1159:        packet_get_bignum2(dh_client_pub, &dlen);
                   1160:
                   1161: #ifdef DEBUG_KEXDH
                   1162:        fprintf(stderr, "\ndh_client_pub= ");
                   1163:        bignum_print(dh_client_pub);
                   1164:        fprintf(stderr, "\n");
                   1165:        debug("bits %d", BN_num_bits(dh_client_pub));
                   1166: #endif
                   1167:
                   1168:        /* generate DH key */
                   1169:        dh = new_dh_group1();                   /* XXX depends on 'kex' */
                   1170:
                   1171: #ifdef DEBUG_KEXDH
                   1172:        fprintf(stderr, "\np= ");
                   1173:        bignum_print(dh->p);
                   1174:        fprintf(stderr, "\ng= ");
                   1175:        bignum_print(dh->g);
                   1176:        fprintf(stderr, "\npub= ");
                   1177:        bignum_print(dh->pub_key);
                   1178:        fprintf(stderr, "\n");
                   1179: #endif
                   1180:
                   1181:        klen = DH_size(dh);
                   1182:        kbuf = xmalloc(klen);
                   1183:        kout = DH_compute_key(kbuf, dh_client_pub, dh);
                   1184:
                   1185: #ifdef DEBUG_KEXDH
                   1186:        debug("shared secret: len %d/%d", klen, kout);
                   1187:        fprintf(stderr, "shared secret == ");
                   1188:        for (i = 0; i< kout; i++)
                   1189:                fprintf(stderr, "%02x", (kbuf[i])&0xff);
                   1190:        fprintf(stderr, "\n");
                   1191: #endif
                   1192:        shared_secret = BN_new();
                   1193:
                   1194:        BN_bin2bn(kbuf, kout, shared_secret);
                   1195:        memset(kbuf, 0, klen);
                   1196:        xfree(kbuf);
                   1197:
                   1198:        server_host_key = dsa_get_serverkey(options.dsa_key_file);
                   1199:        dsa_make_serverkey_blob(server_host_key, &server_host_key_blob, &sbloblen);
                   1200:
                   1201:        /* calc H */                    /* XXX depends on 'kex' */
                   1202:        hash = kex_hash(
                   1203:            client_version_string,
                   1204:            server_version_string,
                   1205:            buffer_ptr(client_kexinit), buffer_len(client_kexinit),
                   1206:            buffer_ptr(server_kexinit), buffer_len(server_kexinit),
                   1207:            (char *)server_host_key_blob, sbloblen,
                   1208:            dh_client_pub,
                   1209:            dh->pub_key,
                   1210:            shared_secret
                   1211:        );
                   1212:        buffer_free(client_kexinit);
                   1213:        buffer_free(server_kexinit);
                   1214:        xfree(client_kexinit);
                   1215:        xfree(server_kexinit);
                   1216: #ifdef DEBUG_KEXDH
                   1217:         fprintf(stderr, "hash == ");
                   1218:         for (i = 0; i< 20; i++)
                   1219:                 fprintf(stderr, "%02x", (hash[i])&0xff);
                   1220:         fprintf(stderr, "\n");
                   1221: #endif
                   1222:        /* sign H */
                   1223:        dsa_sign(server_host_key, &signature, &slen, hash, 20);
                   1224:                /* hashlen depends on KEX */
                   1225:        key_free(server_host_key);
                   1226:
                   1227:        /* send server hostkey, DH pubkey 'f' and singed H */
                   1228:        packet_start(SSH2_MSG_KEXDH_REPLY);
                   1229:        packet_put_string((char *)server_host_key_blob, sbloblen);
                   1230:        packet_put_bignum2(dh->pub_key);        // f
                   1231:        packet_put_string((char *)signature, slen);
                   1232:        packet_send();
                   1233:        packet_write_wait();
                   1234:
                   1235:        kex_derive_keys(kex, hash, shared_secret);
                   1236:        packet_set_kex(kex);
                   1237:
                   1238:        /* have keys, free DH */
                   1239:        DH_free(dh);
                   1240:
                   1241:        debug("send SSH2_MSG_NEWKEYS.");
                   1242:        packet_start(SSH2_MSG_NEWKEYS);
                   1243:        packet_send();
                   1244:        packet_write_wait();
                   1245:        debug("done: send SSH2_MSG_NEWKEYS.");
                   1246:
                   1247:        debug("Wait SSH2_MSG_NEWKEYS.");
                   1248:        packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
                   1249:        debug("GOT SSH2_MSG_NEWKEYS.");
                   1250:
                   1251:        /* send 1st encrypted/maced/compressed message */
                   1252:        packet_start(SSH2_MSG_IGNORE);
                   1253:        packet_put_cstring("markus");
                   1254:        packet_send();
                   1255:        packet_write_wait();
                   1256:
                   1257:        debug("done: KEX2.");
1.1       deraadt  1258: }