[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.106

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