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

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
1.126     deraadt     5:  * This program is the ssh daemon.  It listens for connections from clients,
                      6:  * and performs authentication, executes use commands or shell, and forwards
1.65      deraadt     7:  * information to/from the application to the user client over an encrypted
1.126     deraadt     8:  * connection.  This can also handle forwarding of X11, TCP/IP, and
                      9:  * authentication agent connections.
1.98      markus     10:  *
1.126     deraadt    11:  * As far as I am concerned, the code I have written for this software
                     12:  * can be used freely for any purpose.  Any derived versions of this
                     13:  * software must be clearly marked as such, and if the derived work is
                     14:  * incompatible with the protocol description in the RFC file, it must be
                     15:  * called by a name other than "ssh" or "Secure Shell".
                     16:  *
                     17:  * SSH2 implementation:
                     18:  *
                     19:  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
                     20:  *
                     21:  * Redistribution and use in source and binary forms, with or without
                     22:  * modification, are permitted provided that the following conditions
                     23:  * are met:
                     24:  * 1. Redistributions of source code must retain the above copyright
                     25:  *    notice, this list of conditions and the following disclaimer.
                     26:  * 2. Redistributions in binary form must reproduce the above copyright
                     27:  *    notice, this list of conditions and the following disclaimer in the
                     28:  *    documentation and/or other materials provided with the distribution.
                     29:  *
                     30:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     31:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     32:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     33:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     34:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     35:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     36:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     37:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     38:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     39:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.65      deraadt    40:  */
1.1       deraadt    41:
                     42: #include "includes.h"
1.129   ! provos     43: RCSID("$OpenBSD: sshd.c,v 1.128 2000/09/17 15:38:59 markus Exp $");
1.1       deraadt    44:
                     45: #include "xmalloc.h"
                     46: #include "rsa.h"
                     47: #include "ssh.h"
                     48: #include "pty.h"
                     49: #include "packet.h"
                     50: #include "cipher.h"
                     51: #include "mpaux.h"
                     52: #include "servconf.h"
                     53: #include "uidswap.h"
1.33      markus     54: #include "compat.h"
1.96      markus     55: #include "buffer.h"
                     56:
1.98      markus     57: #include "ssh2.h"
1.104     markus     58: #include <openssl/dh.h>
                     59: #include <openssl/bn.h>
                     60: #include <openssl/hmac.h>
1.98      markus     61: #include "kex.h"
1.104     markus     62: #include <openssl/dsa.h>
                     63: #include <openssl/rsa.h>
1.96      markus     64: #include "key.h"
1.98      markus     65: #include "dsa.h"
1.129   ! provos     66: #include "dh.h"
1.96      markus     67:
                     68: #include "auth.h"
1.98      markus     69: #include "myproposal.h"
1.108     markus     70: #include "authfile.h"
1.1       deraadt    71:
                     72: #ifdef LIBWRAP
                     73: #include <tcpd.h>
                     74: #include <syslog.h>
                     75: int allow_severity = LOG_INFO;
                     76: int deny_severity = LOG_WARNING;
                     77: #endif /* LIBWRAP */
                     78:
                     79: #ifndef O_NOCTTY
                     80: #define O_NOCTTY       0
                     81: #endif
                     82:
                     83: /* Server configuration options. */
                     84: ServerOptions options;
                     85:
                     86: /* Name of the server configuration file. */
                     87: char *config_file_name = SERVER_CONFIG_FILE;
                     88:
1.105     markus     89: /*
1.75      markus     90:  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
                     91:  * Default value is AF_UNSPEC means both IPv4 and IPv6.
                     92:  */
                     93: int IPv4or6 = AF_UNSPEC;
                     94:
1.65      deraadt    95: /*
                     96:  * Debug mode flag.  This can be set on the command line.  If debug
                     97:  * mode is enabled, extra debugging output will be sent to the system
                     98:  * log, the daemon will not go to background, and will exit after processing
                     99:  * the first connection.
                    100:  */
1.1       deraadt   101: int debug_flag = 0;
                    102:
                    103: /* Flag indicating that the daemon is being started from inetd. */
                    104: int inetd_flag = 0;
                    105:
1.47      markus    106: /* debug goes to stderr unless inetd_flag is set */
                    107: int log_stderr = 0;
                    108:
1.1       deraadt   109: /* argv[0] without path. */
                    110: char *av0;
                    111:
                    112: /* Saved arguments to main(). */
                    113: char **saved_argv;
                    114:
1.66      markus    115: /*
1.75      markus    116:  * The sockets that the server is listening; this is used in the SIGHUP
                    117:  * signal handler.
1.66      markus    118:  */
1.75      markus    119: #define        MAX_LISTEN_SOCKS        16
                    120: int listen_socks[MAX_LISTEN_SOCKS];
                    121: int num_listen_socks = 0;
1.1       deraadt   122:
1.66      markus    123: /*
                    124:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                    125:  * sshd will skip the version-number exchange
                    126:  */
1.61      markus    127: char *client_version_string = NULL;
1.96      markus    128: char *server_version_string = NULL;
1.1       deraadt   129:
1.66      markus    130: /*
                    131:  * Any really sensitive data in the application is contained in this
                    132:  * structure. The idea is that this structure could be locked into memory so
                    133:  * that the pages do not get written into swap.  However, there are some
                    134:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    135:  * have access to the internals of them, and locking just the structure is
                    136:  * not very useful.  Currently, memory locking is not implemented.
                    137:  */
1.64      markus    138: struct {
1.108     markus    139:        RSA *private_key;        /* Private part of empheral server key. */
1.64      markus    140:        RSA *host_key;           /* Private part of host key. */
1.108     markus    141:        Key *dsa_host_key;       /* Private DSA host key. */
1.1       deraadt   142: } sensitive_data;
                    143:
1.66      markus    144: /*
                    145:  * Flag indicating whether the current session key has been used.  This flag
                    146:  * is set whenever the key is used, and cleared when the key is regenerated.
                    147:  */
1.1       deraadt   148: int key_used = 0;
                    149:
                    150: /* This is set to true when SIGHUP is received. */
                    151: int received_sighup = 0;
                    152:
                    153: /* Public side of the server key.  This value is regenerated regularly with
                    154:    the private key. */
1.2       provos    155: RSA *public_key;
1.1       deraadt   156:
1.96      markus    157: /* session identifier, used by RSA-auth */
                    158: unsigned char session_id[16];
                    159:
1.108     markus    160: /* same for ssh2 */
                    161: unsigned char *session_id2 = NULL;
                    162: int session_id2_len = 0;
                    163:
1.125     markus    164: /* record remote hostname or ip */
                    165: unsigned int utmp_len = MAXHOSTNAMELEN;
                    166:
1.1       deraadt   167: /* Prototypes for various functions defined later in this file. */
1.96      markus    168: void do_ssh1_kex();
1.98      markus    169: void do_ssh2_kex();
1.87      markus    170:
1.129   ! provos    171: void ssh_dh1_server(Kex *, Buffer *_kexinit, Buffer *);
        !           172: void ssh_dhgex_server(Kex *, Buffer *_kexinit, Buffer *);
        !           173:
1.87      markus    174: /*
1.75      markus    175:  * Close all listening sockets
                    176:  */
                    177: void
                    178: close_listen_socks(void)
                    179: {
                    180:        int i;
                    181:        for (i = 0; i < num_listen_socks; i++)
                    182:                close(listen_socks[i]);
                    183:        num_listen_socks = -1;
                    184: }
                    185:
                    186: /*
1.65      deraadt   187:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    188:  * the effect is to reread the configuration file (and to regenerate
                    189:  * the server key).
                    190:  */
1.105     markus    191: void
1.64      markus    192: sighup_handler(int sig)
1.1       deraadt   193: {
1.64      markus    194:        received_sighup = 1;
                    195:        signal(SIGHUP, sighup_handler);
1.1       deraadt   196: }
                    197:
1.65      deraadt   198: /*
                    199:  * Called from the main program after receiving SIGHUP.
                    200:  * Restarts the server.
                    201:  */
1.105     markus    202: void
1.64      markus    203: sighup_restart()
1.1       deraadt   204: {
1.64      markus    205:        log("Received SIGHUP; restarting.");
1.75      markus    206:        close_listen_socks();
1.64      markus    207:        execv(saved_argv[0], saved_argv);
                    208:        log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
                    209:        exit(1);
1.1       deraadt   210: }
                    211:
1.65      deraadt   212: /*
                    213:  * Generic signal handler for terminating signals in the master daemon.
                    214:  * These close the listen socket; not closing it seems to cause "Address
                    215:  * already in use" problems on some machines, which is inconvenient.
                    216:  */
1.105     markus    217: void
1.64      markus    218: sigterm_handler(int sig)
1.1       deraadt   219: {
1.64      markus    220:        log("Received signal %d; terminating.", sig);
1.75      markus    221:        close_listen_socks();
1.113     markus    222:        unlink(options.pid_file);
1.64      markus    223:        exit(255);
1.1       deraadt   224: }
                    225:
1.65      deraadt   226: /*
                    227:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
                    228:  * reap any zombies left by exited c.
                    229:  */
1.105     markus    230: void
1.64      markus    231: main_sigchld_handler(int sig)
1.1       deraadt   232: {
1.64      markus    233:        int save_errno = errno;
                    234:        int status;
1.60      deraadt   235:
1.64      markus    236:        while (waitpid(-1, &status, WNOHANG) > 0)
                    237:                ;
1.60      deraadt   238:
1.64      markus    239:        signal(SIGCHLD, main_sigchld_handler);
                    240:        errno = save_errno;
1.1       deraadt   241: }
                    242:
1.65      deraadt   243: /*
                    244:  * Signal handler for the alarm after the login grace period has expired.
                    245:  */
1.105     markus    246: void
1.64      markus    247: grace_alarm_handler(int sig)
1.1       deraadt   248: {
1.64      markus    249:        /* Close the connection. */
                    250:        packet_close();
                    251:
                    252:        /* Log error and exit. */
                    253:        fatal("Timeout before authentication for %s.", get_remote_ipaddr());
1.62      markus    254: }
                    255:
1.65      deraadt   256: /*
                    257:  * Signal handler for the key regeneration alarm.  Note that this
                    258:  * alarm only occurs in the daemon waiting for connections, and it does not
                    259:  * do anything with the private key or random state before forking.
                    260:  * Thus there should be no concurrency control/asynchronous execution
                    261:  * problems.
                    262:  */
1.108     markus    263: /* XXX do we really want this work to be done in a signal handler ? -m */
1.105     markus    264: void
1.64      markus    265: key_regeneration_alarm(int sig)
1.1       deraadt   266: {
1.64      markus    267:        int save_errno = errno;
1.18      deraadt   268:
1.64      markus    269:        /* Check if we should generate a new key. */
                    270:        if (key_used) {
                    271:                /* This should really be done in the background. */
                    272:                log("Generating new %d bit RSA key.", options.server_key_bits);
                    273:
                    274:                if (sensitive_data.private_key != NULL)
                    275:                        RSA_free(sensitive_data.private_key);
                    276:                sensitive_data.private_key = RSA_new();
                    277:
                    278:                if (public_key != NULL)
                    279:                        RSA_free(public_key);
                    280:                public_key = RSA_new();
                    281:
                    282:                rsa_generate_key(sensitive_data.private_key, public_key,
                    283:                                 options.server_key_bits);
                    284:                arc4random_stir();
                    285:                key_used = 0;
                    286:                log("RSA key generation complete.");
                    287:        }
                    288:        /* Reschedule the alarm. */
                    289:        signal(SIGALRM, key_regeneration_alarm);
                    290:        alarm(options.key_regeneration_time);
                    291:        errno = save_errno;
1.98      markus    292: }
                    293:
1.96      markus    294: void
                    295: sshd_exchange_identification(int sock_in, int sock_out)
                    296: {
1.102     markus    297:        int i, mismatch;
1.96      markus    298:        int remote_major, remote_minor;
1.102     markus    299:        int major, minor;
1.96      markus    300:        char *s;
                    301:        char buf[256];                  /* Must not be larger than remote_version. */
                    302:        char remote_version[256];       /* Must be at least as big as buf. */
                    303:
1.103     markus    304:        if ((options.protocol & SSH_PROTO_1) &&
                    305:            (options.protocol & SSH_PROTO_2)) {
1.102     markus    306:                major = PROTOCOL_MAJOR_1;
                    307:                minor = 99;
                    308:        } else if (options.protocol & SSH_PROTO_2) {
                    309:                major = PROTOCOL_MAJOR_2;
                    310:                minor = PROTOCOL_MINOR_2;
                    311:        } else {
                    312:                major = PROTOCOL_MAJOR_1;
                    313:                minor = PROTOCOL_MINOR_1;
                    314:        }
                    315:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
1.96      markus    316:        server_version_string = xstrdup(buf);
                    317:
                    318:        if (client_version_string == NULL) {
                    319:                /* Send our protocol version identification. */
                    320:                if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
                    321:                    != strlen(server_version_string)) {
                    322:                        log("Could not write ident string to %s.", get_remote_ipaddr());
                    323:                        fatal_cleanup();
                    324:                }
                    325:
                    326:                /* Read other side\'s version identification. */
                    327:                for (i = 0; i < sizeof(buf) - 1; i++) {
1.119     markus    328:                        if (atomicio(read, sock_in, &buf[i], 1) != 1) {
1.96      markus    329:                                log("Did not receive ident string from %s.", get_remote_ipaddr());
                    330:                                fatal_cleanup();
                    331:                        }
                    332:                        if (buf[i] == '\r') {
                    333:                                buf[i] = '\n';
                    334:                                buf[i + 1] = 0;
                    335:                                continue;
                    336:                        }
                    337:                        if (buf[i] == '\n') {
                    338:                                /* buf[i] == '\n' */
                    339:                                buf[i + 1] = 0;
                    340:                                break;
                    341:                        }
                    342:                }
                    343:                buf[sizeof(buf) - 1] = 0;
                    344:                client_version_string = xstrdup(buf);
                    345:        }
                    346:
                    347:        /*
                    348:         * Check that the versions match.  In future this might accept
                    349:         * several versions and set appropriate flags to handle them.
                    350:         */
                    351:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    352:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    353:                s = "Protocol mismatch.\n";
1.96      markus    354:                (void) atomicio(write, sock_out, s, strlen(s));
                    355:                close(sock_in);
                    356:                close(sock_out);
                    357:                log("Bad protocol version identification '%.100s' from %s",
                    358:                    client_version_string, get_remote_ipaddr());
                    359:                fatal_cleanup();
                    360:        }
                    361:        debug("Client protocol version %d.%d; client software version %.100s",
                    362:              remote_major, remote_minor, remote_version);
                    363:
1.98      markus    364:        compat_datafellows(remote_version);
                    365:
1.102     markus    366:        mismatch = 0;
1.96      markus    367:        switch(remote_major) {
                    368:        case 1:
1.108     markus    369:                if (remote_minor == 99) {
                    370:                        if (options.protocol & SSH_PROTO_2)
                    371:                                enable_compat20();
                    372:                        else
                    373:                                mismatch = 1;
                    374:                        break;
                    375:                }
1.102     markus    376:                if (!(options.protocol & SSH_PROTO_1)) {
                    377:                        mismatch = 1;
                    378:                        break;
                    379:                }
1.96      markus    380:                if (remote_minor < 3) {
1.121     provos    381:                        packet_disconnect("Your ssh version is too old and "
1.96      markus    382:                            "is no longer supported.  Please install a newer version.");
                    383:                } else if (remote_minor == 3) {
                    384:                        /* note that this disables agent-forwarding */
                    385:                        enable_compat13();
                    386:                }
1.102     markus    387:                break;
1.98      markus    388:        case 2:
1.102     markus    389:                if (options.protocol & SSH_PROTO_2) {
1.98      markus    390:                        enable_compat20();
                    391:                        break;
                    392:                }
1.99      markus    393:                /* FALLTHROUGH */
1.105     markus    394:        default:
1.102     markus    395:                mismatch = 1;
                    396:                break;
                    397:        }
                    398:        chop(server_version_string);
                    399:        chop(client_version_string);
                    400:        debug("Local version string %.200s", server_version_string);
                    401:
                    402:        if (mismatch) {
1.96      markus    403:                s = "Protocol major versions differ.\n";
                    404:                (void) atomicio(write, sock_out, s, strlen(s));
                    405:                close(sock_in);
                    406:                close(sock_out);
1.102     markus    407:                log("Protocol major versions differ for %s: %.200s vs. %.200s",
                    408:                    get_remote_ipaddr(),
                    409:                    server_version_string, client_version_string);
1.96      markus    410:                fatal_cleanup();
                    411:        }
1.108     markus    412:        if (compat20)
                    413:                packet_set_ssh2_format();
                    414: }
                    415:
                    416:
                    417: void
                    418: destroy_sensitive_data(void)
                    419: {
                    420:        /* Destroy the private and public keys.  They will no longer be needed. */
1.117     djm       421:        if (public_key)
                    422:                RSA_free(public_key);
                    423:        if (sensitive_data.private_key)
                    424:                RSA_free(sensitive_data.private_key);
                    425:        if (sensitive_data.host_key)
                    426:                RSA_free(sensitive_data.host_key);
1.108     markus    427:        if (sensitive_data.dsa_host_key != NULL)
                    428:                key_free(sensitive_data.dsa_host_key);
1.96      markus    429: }
                    430:
1.124     markus    431: /*
                    432:  * returns 1 if connection should be dropped, 0 otherwise.
                    433:  * dropping starts at connection #max_startups_begin with a probability
                    434:  * of (max_startups_rate/100). the probability increases linearly until
                    435:  * all connections are dropped for startups > max_startups
                    436:  */
                    437: int
                    438: drop_connection(int startups)
                    439: {
                    440:        double p, r;
                    441:
                    442:        if (startups < options.max_startups_begin)
                    443:                return 0;
                    444:        if (startups >= options.max_startups)
                    445:                return 1;
                    446:        if (options.max_startups_rate == 100)
                    447:                return 1;
                    448:
                    449:        p  = 100 - options.max_startups_rate;
                    450:        p *= startups - options.max_startups_begin;
                    451:        p /= (double) (options.max_startups - options.max_startups_begin);
                    452:        p += options.max_startups_rate;
                    453:        p /= 100.0;
                    454:        r = arc4random() / (double) UINT_MAX;
                    455:
                    456:        debug("drop_connection: p %g, r %g", p, r);
                    457:        return (r < p) ? 1 : 0;
                    458: }
                    459:
1.120     markus    460: int *startup_pipes = NULL;     /* options.max_startup sized array of fd ints */
                    461: int startup_pipe;              /* in child */
                    462:
1.65      deraadt   463: /*
                    464:  * Main program for the daemon.
                    465:  */
1.2       provos    466: int
                    467: main(int ac, char **av)
1.1       deraadt   468: {
1.64      markus    469:        extern char *optarg;
                    470:        extern int optind;
1.120     markus    471:        int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
1.107     deraadt   472:        pid_t pid;
1.75      markus    473:        socklen_t fromlen;
1.110     markus    474:        int silent = 0;
1.75      markus    475:        fd_set *fdset;
                    476:        struct sockaddr_storage from;
1.64      markus    477:        const char *remote_ip;
                    478:        int remote_port;
                    479:        FILE *f;
                    480:        struct linger linger;
1.75      markus    481:        struct addrinfo *ai;
                    482:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                    483:        int listen_sock, maxfd;
1.120     markus    484:        int startup_p[2];
                    485:        int startups = 0;
1.64      markus    486:
                    487:        /* Save argv[0]. */
                    488:        saved_argv = av;
                    489:        if (strchr(av[0], '/'))
                    490:                av0 = strrchr(av[0], '/') + 1;
                    491:        else
                    492:                av0 = av[0];
                    493:
                    494:        /* Initialize configuration options to their default values. */
                    495:        initialize_server_options(&options);
                    496:
                    497:        /* Parse command-line arguments. */
1.125     markus    498:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:diqQ46")) != EOF) {
1.64      markus    499:                switch (opt) {
1.75      markus    500:                case '4':
                    501:                        IPv4or6 = AF_INET;
                    502:                        break;
                    503:                case '6':
                    504:                        IPv4or6 = AF_INET6;
                    505:                        break;
1.64      markus    506:                case 'f':
                    507:                        config_file_name = optarg;
                    508:                        break;
                    509:                case 'd':
1.127     markus    510:                        if (0 == debug_flag) {
                    511:                                debug_flag = 1;
                    512:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
                    513:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
                    514:                                options.log_level++;
                    515:                        } else {
                    516:                                fprintf(stderr, "Too high debugging level.\n");
                    517:                                exit(1);
                    518:                        }
1.64      markus    519:                        break;
                    520:                case 'i':
                    521:                        inetd_flag = 1;
                    522:                        break;
                    523:                case 'Q':
1.110     markus    524:                        silent = 1;
1.64      markus    525:                        break;
                    526:                case 'q':
                    527:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    528:                        break;
                    529:                case 'b':
                    530:                        options.server_key_bits = atoi(optarg);
                    531:                        break;
                    532:                case 'p':
1.75      markus    533:                        options.ports_from_cmdline = 1;
1.127     markus    534:                        if (options.num_ports >= MAX_PORTS) {
                    535:                                fprintf(stderr, "too many ports.\n");
                    536:                                exit(1);
                    537:                        }
1.75      markus    538:                        options.ports[options.num_ports++] = atoi(optarg);
1.64      markus    539:                        break;
                    540:                case 'g':
                    541:                        options.login_grace_time = atoi(optarg);
                    542:                        break;
                    543:                case 'k':
                    544:                        options.key_regeneration_time = atoi(optarg);
                    545:                        break;
                    546:                case 'h':
                    547:                        options.host_key_file = optarg;
                    548:                        break;
                    549:                case 'V':
                    550:                        client_version_string = optarg;
                    551:                        /* only makes sense with inetd_flag, i.e. no listen() */
                    552:                        inetd_flag = 1;
                    553:                        break;
1.125     markus    554:                case 'u':
                    555:                        utmp_len = atoi(optarg);
                    556:                        break;
1.64      markus    557:                case '?':
                    558:                default:
                    559:                        fprintf(stderr, "sshd version %s\n", SSH_VERSION);
                    560:                        fprintf(stderr, "Usage: %s [options]\n", av0);
                    561:                        fprintf(stderr, "Options:\n");
1.66      markus    562:                        fprintf(stderr, "  -f file    Configuration file (default %s)\n", SERVER_CONFIG_FILE);
1.127     markus    563:                        fprintf(stderr, "  -d         Debugging mode (multiple -d means more debugging)\n");
1.64      markus    564:                        fprintf(stderr, "  -i         Started from inetd\n");
                    565:                        fprintf(stderr, "  -q         Quiet (no logging)\n");
                    566:                        fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
                    567:                        fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
                    568:                        fprintf(stderr, "  -g seconds Grace period for authentication (default: 300)\n");
                    569:                        fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
                    570:                        fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
1.75      markus    571:                            HOST_KEY_FILE);
1.125     markus    572:                        fprintf(stderr, "  -u len     Maximum hostname length for utmp recording\n");
1.75      markus    573:                        fprintf(stderr, "  -4         Use IPv4 only\n");
                    574:                        fprintf(stderr, "  -6         Use IPv6 only\n");
1.64      markus    575:                        exit(1);
                    576:                }
                    577:        }
                    578:
1.75      markus    579:        /*
                    580:         * Force logging to stderr until we have loaded the private host
                    581:         * key (unless started from inetd)
                    582:         */
                    583:        log_init(av0,
                    584:            options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
                    585:            options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
1.110     markus    586:            !silent && !inetd_flag);
1.75      markus    587:
1.64      markus    588:        /* Read server configuration options from the configuration file. */
                    589:        read_server_config(&options, config_file_name);
                    590:
                    591:        /* Fill in default values for those options not explicitly set. */
                    592:        fill_default_server_options(&options);
                    593:
                    594:        /* Check that there are no remaining arguments. */
                    595:        if (optind < ac) {
                    596:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                    597:                exit(1);
                    598:        }
                    599:
                    600:        debug("sshd version %.100s", SSH_VERSION);
                    601:
1.108     markus    602:        sensitive_data.dsa_host_key = NULL;
                    603:        sensitive_data.host_key = NULL;
                    604:
                    605:        /* check if RSA support exists */
                    606:        if ((options.protocol & SSH_PROTO_1) &&
                    607:            rsa_alive() == 0) {
                    608:                log("no RSA support in libssl and libcrypto.  See ssl(8)");
                    609:                log("Disabling protocol version 1");
                    610:                options.protocol &= ~SSH_PROTO_1;
                    611:        }
                    612:        /* Load the RSA/DSA host key.  It must have empty passphrase. */
                    613:        if (options.protocol & SSH_PROTO_1) {
                    614:                Key k;
                    615:                sensitive_data.host_key = RSA_new();
                    616:                k.type = KEY_RSA;
                    617:                k.rsa = sensitive_data.host_key;
                    618:                errno = 0;
1.109     markus    619:                if (!load_private_key(options.host_key_file, "", &k, NULL)) {
1.108     markus    620:                        error("Could not load host key: %.200s: %.100s",
                    621:                            options.host_key_file, strerror(errno));
                    622:                        log("Disabling protocol version 1");
                    623:                        options.protocol &= ~SSH_PROTO_1;
                    624:                }
                    625:                k.rsa = NULL;
                    626:        }
                    627:        if (options.protocol & SSH_PROTO_2) {
                    628:                sensitive_data.dsa_host_key = key_new(KEY_DSA);
1.115     markus    629:                if (!load_private_key(options.host_dsa_key_file, "", sensitive_data.dsa_host_key, NULL)) {
                    630:
                    631:                        error("Could not load DSA host key: %.200s", options.host_dsa_key_file);
1.108     markus    632:                        log("Disabling protocol version 2");
                    633:                        options.protocol &= ~SSH_PROTO_2;
                    634:                }
                    635:        }
                    636:        if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
1.110     markus    637:                if (silent == 0)
                    638:                        fprintf(stderr, "sshd: no hostkeys available -- exiting.\n");
1.108     markus    639:                log("sshd: no hostkeys available -- exiting.\n");
1.64      markus    640:                exit(1);
                    641:        }
                    642:
1.108     markus    643:        /* Check certain values for sanity. */
                    644:        if (options.protocol & SSH_PROTO_1) {
                    645:                if (options.server_key_bits < 512 ||
                    646:                    options.server_key_bits > 32768) {
                    647:                        fprintf(stderr, "Bad server key size.\n");
                    648:                        exit(1);
                    649:                }
                    650:                /*
                    651:                 * Check that server and host key lengths differ sufficiently. This
                    652:                 * is necessary to make double encryption work with rsaref. Oh, I
                    653:                 * hate software patents. I dont know if this can go? Niels
                    654:                 */
                    655:                if (options.server_key_bits >
                    656:                    BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
                    657:                    options.server_key_bits <
                    658:                    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                    659:                        options.server_key_bits =
                    660:                            BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
                    661:                        debug("Forcing server key to %d bits to make it differ from host key.",
                    662:                            options.server_key_bits);
                    663:                }
                    664:        }
                    665:
                    666:        /* Initialize the log (it is reinitialized below in case we forked). */
1.64      markus    667:        if (debug_flag && !inetd_flag)
                    668:                log_stderr = 1;
                    669:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    670:
1.108     markus    671:        /*
                    672:         * If not in debugging mode, and not started from inetd, disconnect
                    673:         * from the controlling terminal, and fork.  The original process
                    674:         * exits.
                    675:         */
1.64      markus    676:        if (!debug_flag && !inetd_flag) {
1.1       deraadt   677: #ifdef TIOCNOTTY
1.64      markus    678:                int fd;
1.1       deraadt   679: #endif /* TIOCNOTTY */
1.64      markus    680:                if (daemon(0, 0) < 0)
                    681:                        fatal("daemon() failed: %.200s", strerror(errno));
                    682:
                    683:                /* Disconnect from the controlling tty. */
1.1       deraadt   684: #ifdef TIOCNOTTY
1.64      markus    685:                fd = open("/dev/tty", O_RDWR | O_NOCTTY);
                    686:                if (fd >= 0) {
                    687:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                    688:                        close(fd);
                    689:                }
                    690: #endif /* TIOCNOTTY */
                    691:        }
                    692:        /* Reinitialize the log (because of the fork above). */
                    693:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    694:
                    695:        /* Do not display messages to stdout in RSA code. */
                    696:        rsa_set_verbose(0);
                    697:
                    698:        /* Initialize the random number generator. */
                    699:        arc4random_stir();
                    700:
                    701:        /* Chdir to the root directory so that the current disk can be
                    702:           unmounted if desired. */
                    703:        chdir("/");
                    704:
                    705:        /* Start listening for a socket, unless started from inetd. */
                    706:        if (inetd_flag) {
                    707:                int s1, s2;
                    708:                s1 = dup(0);    /* Make sure descriptors 0, 1, and 2 are in use. */
                    709:                s2 = dup(s1);
                    710:                sock_in = dup(0);
                    711:                sock_out = dup(1);
1.123     djm       712:                startup_pipe = -1;
1.108     markus    713:                /*
                    714:                 * We intentionally do not close the descriptors 0, 1, and 2
                    715:                 * as our code for setting the descriptors won\'t work if
                    716:                 * ttyfd happens to be one of those.
                    717:                 */
1.64      markus    718:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
                    719:
1.108     markus    720:                if (options.protocol & SSH_PROTO_1) {
                    721:                        public_key = RSA_new();
                    722:                        sensitive_data.private_key = RSA_new();
                    723:                        log("Generating %d bit RSA key.", options.server_key_bits);
                    724:                        rsa_generate_key(sensitive_data.private_key, public_key,
                    725:                            options.server_key_bits);
                    726:                        arc4random_stir();
                    727:                        log("RSA key generation complete.");
                    728:                }
1.64      markus    729:        } else {
1.75      markus    730:                for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                    731:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                    732:                                continue;
                    733:                        if (num_listen_socks >= MAX_LISTEN_SOCKS)
                    734:                                fatal("Too many listen sockets. "
                    735:                                    "Enlarge MAX_LISTEN_SOCKS");
                    736:                        if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
                    737:                            ntop, sizeof(ntop), strport, sizeof(strport),
                    738:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                    739:                                error("getnameinfo failed");
                    740:                                continue;
                    741:                        }
                    742:                        /* Create socket for listening. */
                    743:                        listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
                    744:                        if (listen_sock < 0) {
                    745:                                /* kernel may not support ipv6 */
                    746:                                verbose("socket: %.100s", strerror(errno));
                    747:                                continue;
                    748:                        }
                    749:                        if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
                    750:                                error("listen_sock O_NONBLOCK: %s", strerror(errno));
                    751:                                close(listen_sock);
                    752:                                continue;
                    753:                        }
                    754:                        /*
                    755:                         * Set socket options.  We try to make the port
                    756:                         * reusable and have it close as fast as possible
                    757:                         * without waiting in unnecessary wait states on
                    758:                         * close.
                    759:                         */
                    760:                        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                    761:                            (void *) &on, sizeof(on));
                    762:                        linger.l_onoff = 1;
                    763:                        linger.l_linger = 5;
                    764:                        setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
                    765:                            (void *) &linger, sizeof(linger));
                    766:
                    767:                        debug("Bind to port %s on %s.", strport, ntop);
                    768:
                    769:                        /* Bind the socket to the desired port. */
                    770:                        if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                    771:                                error("Bind to port %s on %s failed: %.200s.",
                    772:                                    strport, ntop, strerror(errno));
                    773:                                close(listen_sock);
                    774:                                continue;
                    775:                        }
                    776:                        listen_socks[num_listen_socks] = listen_sock;
                    777:                        num_listen_socks++;
                    778:
                    779:                        /* Start listening on the port. */
                    780:                        log("Server listening on %s port %s.", ntop, strport);
                    781:                        if (listen(listen_sock, 5) < 0)
                    782:                                fatal("listen: %.100s", strerror(errno));
                    783:
1.64      markus    784:                }
1.75      markus    785:                freeaddrinfo(options.listen_addrs);
                    786:
                    787:                if (!num_listen_socks)
                    788:                        fatal("Cannot bind any address.");
                    789:
1.64      markus    790:                if (!debug_flag) {
1.66      markus    791:                        /*
                    792:                         * Record our pid in /etc/sshd_pid to make it easier
                    793:                         * to kill the correct sshd.  We don\'t want to do
                    794:                         * this before the bind above because the bind will
                    795:                         * fail if there already is a daemon, and this will
                    796:                         * overwrite any old pid in the file.
                    797:                         */
1.112     markus    798:                        f = fopen(options.pid_file, "w");
1.64      markus    799:                        if (f) {
                    800:                                fprintf(f, "%u\n", (unsigned int) getpid());
                    801:                                fclose(f);
                    802:                        }
                    803:                }
1.108     markus    804:                if (options.protocol & SSH_PROTO_1) {
                    805:                        public_key = RSA_new();
                    806:                        sensitive_data.private_key = RSA_new();
                    807:
                    808:                        log("Generating %d bit RSA key.", options.server_key_bits);
                    809:                        rsa_generate_key(sensitive_data.private_key, public_key,
                    810:                            options.server_key_bits);
                    811:                        arc4random_stir();
                    812:                        log("RSA key generation complete.");
1.64      markus    813:
1.108     markus    814:                        /* Schedule server key regeneration alarm. */
                    815:                        signal(SIGALRM, key_regeneration_alarm);
                    816:                        alarm(options.key_regeneration_time);
                    817:                }
1.64      markus    818:
                    819:                /* Arrange to restart on SIGHUP.  The handler needs listen_sock. */
                    820:                signal(SIGHUP, sighup_handler);
1.120     markus    821:
1.64      markus    822:                signal(SIGTERM, sigterm_handler);
                    823:                signal(SIGQUIT, sigterm_handler);
                    824:
                    825:                /* Arrange SIGCHLD to be caught. */
                    826:                signal(SIGCHLD, main_sigchld_handler);
                    827:
1.75      markus    828:                /* setup fd set for listen */
1.120     markus    829:                fdset = NULL;
1.75      markus    830:                maxfd = 0;
                    831:                for (i = 0; i < num_listen_socks; i++)
                    832:                        if (listen_socks[i] > maxfd)
                    833:                                maxfd = listen_socks[i];
1.120     markus    834:                /* pipes connected to unauthenticated childs */
                    835:                startup_pipes = xmalloc(options.max_startups * sizeof(int));
                    836:                for (i = 0; i < options.max_startups; i++)
                    837:                        startup_pipes[i] = -1;
1.75      markus    838:
1.66      markus    839:                /*
                    840:                 * Stay listening for connections until the system crashes or
                    841:                 * the daemon is killed with a signal.
                    842:                 */
1.64      markus    843:                for (;;) {
                    844:                        if (received_sighup)
                    845:                                sighup_restart();
1.120     markus    846:                        if (fdset != NULL)
                    847:                                xfree(fdset);
                    848:                        fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
                    849:                        fdset = (fd_set *)xmalloc(fdsetsz);
1.75      markus    850:                        memset(fdset, 0, fdsetsz);
1.120     markus    851:
1.75      markus    852:                        for (i = 0; i < num_listen_socks; i++)
                    853:                                FD_SET(listen_socks[i], fdset);
1.120     markus    854:                        for (i = 0; i < options.max_startups; i++)
                    855:                                if (startup_pipes[i] != -1)
                    856:                                        FD_SET(startup_pipes[i], fdset);
                    857:
                    858:                        /* Wait in select until there is a connection. */
1.75      markus    859:                        if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
                    860:                                if (errno != EINTR)
                    861:                                        error("select: %.100s", strerror(errno));
                    862:                                continue;
                    863:                        }
1.120     markus    864:                        for (i = 0; i < options.max_startups; i++)
                    865:                                if (startup_pipes[i] != -1 &&
                    866:                                    FD_ISSET(startup_pipes[i], fdset)) {
                    867:                                        /*
                    868:                                         * the read end of the pipe is ready
                    869:                                         * if the child has closed the pipe
                    870:                                         * after successfull authentication
                    871:                                         * or if the child has died
                    872:                                         */
                    873:                                        close(startup_pipes[i]);
                    874:                                        startup_pipes[i] = -1;
                    875:                                        startups--;
                    876:                                }
1.75      markus    877:                        for (i = 0; i < num_listen_socks; i++) {
                    878:                                if (!FD_ISSET(listen_socks[i], fdset))
1.70      provos    879:                                        continue;
1.120     markus    880:                                fromlen = sizeof(from);
                    881:                                newsock = accept(listen_socks[i], (struct sockaddr *)&from,
                    882:                                    &fromlen);
                    883:                                if (newsock < 0) {
                    884:                                        if (errno != EINTR && errno != EWOULDBLOCK)
                    885:                                                error("accept: %.100s", strerror(errno));
                    886:                                        continue;
                    887:                                }
                    888:                                if (fcntl(newsock, F_SETFL, 0) < 0) {
                    889:                                        error("newsock del O_NONBLOCK: %s", strerror(errno));
                    890:                                        continue;
                    891:                                }
1.124     markus    892:                                if (drop_connection(startups) == 1) {
                    893:                                        debug("drop connection #%d", startups);
1.120     markus    894:                                        close(newsock);
                    895:                                        continue;
                    896:                                }
                    897:                                if (pipe(startup_p) == -1) {
                    898:                                        close(newsock);
                    899:                                        continue;
                    900:                                }
                    901:
                    902:                                for (j = 0; j < options.max_startups; j++)
                    903:                                        if (startup_pipes[j] == -1) {
                    904:                                                startup_pipes[j] = startup_p[0];
                    905:                                                if (maxfd < startup_p[0])
                    906:                                                        maxfd = startup_p[0];
                    907:                                                startups++;
                    908:                                                break;
                    909:                                        }
                    910:
1.66      markus    911:                                /*
1.120     markus    912:                                 * Got connection.  Fork a child to handle it, unless
                    913:                                 * we are in debugging mode.
1.66      markus    914:                                 */
1.120     markus    915:                                if (debug_flag) {
1.66      markus    916:                                        /*
1.120     markus    917:                                         * In debugging mode.  Close the listening
                    918:                                         * socket, and start processing the
                    919:                                         * connection without forking.
1.66      markus    920:                                         */
1.120     markus    921:                                        debug("Server will not fork when running in debugging mode.");
1.75      markus    922:                                        close_listen_socks();
1.64      markus    923:                                        sock_in = newsock;
                    924:                                        sock_out = newsock;
1.122     deraadt   925:                                        startup_pipe = -1;
1.120     markus    926:                                        pid = getpid();
1.64      markus    927:                                        break;
1.120     markus    928:                                } else {
                    929:                                        /*
                    930:                                         * Normal production daemon.  Fork, and have
                    931:                                         * the child process the connection. The
                    932:                                         * parent continues listening.
                    933:                                         */
                    934:                                        if ((pid = fork()) == 0) {
                    935:                                                /*
                    936:                                                 * Child.  Close the listening and max_startup
                    937:                                                 * sockets.  Start using the accepted socket.
                    938:                                                 * Reinitialize logging (since our pid has
                    939:                                                 * changed).  We break out of the loop to handle
                    940:                                                 * the connection.
                    941:                                                 */
                    942:                                                startup_pipe = startup_p[1];
                    943:                                                for (j = 0; j < options.max_startups; j++)
                    944:                                                        if (startup_pipes[j] != -1)
                    945:                                                                close(startup_pipes[j]);
                    946:                                                close_listen_socks();
                    947:                                                sock_in = newsock;
                    948:                                                sock_out = newsock;
                    949:                                                log_init(av0, options.log_level, options.log_facility, log_stderr);
                    950:                                                break;
                    951:                                        }
1.64      markus    952:                                }
                    953:
1.120     markus    954:                                /* Parent.  Stay in the loop. */
                    955:                                if (pid < 0)
                    956:                                        error("fork: %.100s", strerror(errno));
                    957:                                else
                    958:                                        debug("Forked child %d.", pid);
                    959:
                    960:                                close(startup_p[1]);
1.1       deraadt   961:
1.120     markus    962:                                /* Mark that the key has been used (it was "given" to the child). */
                    963:                                key_used = 1;
1.1       deraadt   964:
1.120     markus    965:                                arc4random_stir();
1.1       deraadt   966:
1.120     markus    967:                                /* Close the new socket (the child is now taking care of it). */
                    968:                                close(newsock);
                    969:                        }
1.75      markus    970:                        /* child process check (or debug mode) */
                    971:                        if (num_listen_socks < 0)
                    972:                                break;
1.64      markus    973:                }
1.1       deraadt   974:        }
                    975:
1.64      markus    976:        /* This is the child processing a new connection. */
                    977:
1.66      markus    978:        /*
                    979:         * Disable the key regeneration alarm.  We will not regenerate the
                    980:         * key since we are no longer in a position to give it to anyone. We
                    981:         * will not restart on SIGHUP since it no longer makes sense.
                    982:         */
1.64      markus    983:        alarm(0);
                    984:        signal(SIGALRM, SIG_DFL);
                    985:        signal(SIGHUP, SIG_DFL);
                    986:        signal(SIGTERM, SIG_DFL);
                    987:        signal(SIGQUIT, SIG_DFL);
                    988:        signal(SIGCHLD, SIG_DFL);
                    989:
1.66      markus    990:        /*
                    991:         * Set socket options for the connection.  We want the socket to
                    992:         * close as fast as possible without waiting for anything.  If the
                    993:         * connection is not a socket, these will do nothing.
                    994:         */
                    995:        /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.64      markus    996:        linger.l_onoff = 1;
                    997:        linger.l_linger = 5;
                    998:        setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
                    999:
1.66      markus   1000:        /*
                   1001:         * Register our connection.  This turns encryption off because we do
                   1002:         * not have a key.
                   1003:         */
1.64      markus   1004:        packet_set_connection(sock_in, sock_out);
1.1       deraadt  1005:
1.64      markus   1006:        remote_port = get_remote_port();
                   1007:        remote_ip = get_remote_ipaddr();
1.52      markus   1008:
1.64      markus   1009:        /* Check whether logins are denied from this host. */
1.37      dugsong  1010: #ifdef LIBWRAP
1.75      markus   1011:        /* XXX LIBWRAP noes not know about IPv6 */
1.64      markus   1012:        {
                   1013:                struct request_info req;
1.37      dugsong  1014:
1.64      markus   1015:                request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
                   1016:                fromhost(&req);
1.37      dugsong  1017:
1.64      markus   1018:                if (!hosts_access(&req)) {
                   1019:                        close(sock_in);
                   1020:                        close(sock_out);
                   1021:                        refuse(&req);
                   1022:                }
1.75      markus   1023: /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
1.64      markus   1024:        }
1.75      markus   1025: #endif /* LIBWRAP */
1.64      markus   1026:        /* Log the connection. */
                   1027:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1       deraadt  1028:
1.66      markus   1029:        /*
                   1030:         * We don\'t want to listen forever unless the other side
                   1031:         * successfully authenticates itself.  So we set up an alarm which is
                   1032:         * cleared after successful authentication.  A limit of zero
                   1033:         * indicates no limit. Note that we don\'t set the alarm in debugging
                   1034:         * mode; it is just annoying to have the server exit just when you
                   1035:         * are about to discover the bug.
                   1036:         */
1.64      markus   1037:        signal(SIGALRM, grace_alarm_handler);
                   1038:        if (!debug_flag)
                   1039:                alarm(options.login_grace_time);
                   1040:
1.96      markus   1041:        sshd_exchange_identification(sock_in, sock_out);
1.66      markus   1042:        /*
                   1043:         * Check that the connection comes from a privileged port.  Rhosts-
                   1044:         * and Rhosts-RSA-Authentication only make sense from priviledged
                   1045:         * programs.  Of course, if the intruder has root access on his local
                   1046:         * machine, he can connect from any port.  So do not use these
                   1047:         * authentication methods from machines that you do not trust.
                   1048:         */
1.64      markus   1049:        if (remote_port >= IPPORT_RESERVED ||
                   1050:            remote_port < IPPORT_RESERVED / 2) {
                   1051:                options.rhosts_authentication = 0;
                   1052:                options.rhosts_rsa_authentication = 0;
                   1053:        }
1.76      markus   1054: #ifdef KRB4
                   1055:        if (!packet_connection_is_ipv4() &&
                   1056:            options.kerberos_authentication) {
                   1057:                debug("Kerberos Authentication disabled, only available for IPv4.");
                   1058:                options.kerberos_authentication = 0;
                   1059:        }
                   1060: #endif /* KRB4 */
                   1061:
1.64      markus   1062:        packet_set_nonblocking();
1.1       deraadt  1063:
1.77      markus   1064:        /* perform the key exchange */
                   1065:        /* authenticate user and start session */
1.98      markus   1066:        if (compat20) {
                   1067:                do_ssh2_kex();
                   1068:                do_authentication2();
                   1069:        } else {
                   1070:                do_ssh1_kex();
                   1071:                do_authentication();
                   1072:        }
1.1       deraadt  1073:
                   1074: #ifdef KRB4
1.64      markus   1075:        /* Cleanup user's ticket cache file. */
                   1076:        if (options.kerberos_ticket_cleanup)
                   1077:                (void) dest_tkt();
1.1       deraadt  1078: #endif /* KRB4 */
                   1079:
1.64      markus   1080:        /* The connection has been terminated. */
                   1081:        verbose("Closing connection to %.100s", remote_ip);
                   1082:        packet_close();
                   1083:        exit(0);
1.1       deraadt  1084: }
                   1085:
1.65      deraadt  1086: /*
1.77      markus   1087:  * SSH1 key exchange
1.65      deraadt  1088:  */
1.52      markus   1089: void
1.96      markus   1090: do_ssh1_kex()
1.1       deraadt  1091: {
1.64      markus   1092:        int i, len;
1.77      markus   1093:        int plen, slen;
1.64      markus   1094:        BIGNUM *session_key_int;
                   1095:        unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1.77      markus   1096:        unsigned char cookie[8];
1.64      markus   1097:        unsigned int cipher_type, auth_mask, protocol_flags;
                   1098:        u_int32_t rand = 0;
                   1099:
1.66      markus   1100:        /*
                   1101:         * Generate check bytes that the client must send back in the user
                   1102:         * packet in order for it to be accepted; this is used to defy ip
                   1103:         * spoofing attacks.  Note that this only works against somebody
                   1104:         * doing IP spoofing from a remote machine; any machine on the local
                   1105:         * network can still see outgoing packets and catch the random
                   1106:         * cookie.  This only affects rhosts authentication, and this is one
                   1107:         * of the reasons why it is inherently insecure.
                   1108:         */
1.64      markus   1109:        for (i = 0; i < 8; i++) {
                   1110:                if (i % 4 == 0)
                   1111:                        rand = arc4random();
1.77      markus   1112:                cookie[i] = rand & 0xff;
1.64      markus   1113:                rand >>= 8;
                   1114:        }
                   1115:
1.66      markus   1116:        /*
                   1117:         * Send our public key.  We include in the packet 64 bits of random
                   1118:         * data that must be matched in the reply in order to prevent IP
                   1119:         * spoofing.
                   1120:         */
1.64      markus   1121:        packet_start(SSH_SMSG_PUBLIC_KEY);
                   1122:        for (i = 0; i < 8; i++)
1.77      markus   1123:                packet_put_char(cookie[i]);
1.64      markus   1124:
                   1125:        /* Store our public server RSA key. */
                   1126:        packet_put_int(BN_num_bits(public_key->n));
                   1127:        packet_put_bignum(public_key->e);
                   1128:        packet_put_bignum(public_key->n);
                   1129:
                   1130:        /* Store our public host RSA key. */
                   1131:        packet_put_int(BN_num_bits(sensitive_data.host_key->n));
                   1132:        packet_put_bignum(sensitive_data.host_key->e);
                   1133:        packet_put_bignum(sensitive_data.host_key->n);
                   1134:
                   1135:        /* Put protocol flags. */
                   1136:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   1137:
                   1138:        /* Declare which ciphers we support. */
1.97      markus   1139:        packet_put_int(cipher_mask1());
1.64      markus   1140:
                   1141:        /* Declare supported authentication types. */
                   1142:        auth_mask = 0;
                   1143:        if (options.rhosts_authentication)
                   1144:                auth_mask |= 1 << SSH_AUTH_RHOSTS;
                   1145:        if (options.rhosts_rsa_authentication)
                   1146:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   1147:        if (options.rsa_authentication)
                   1148:                auth_mask |= 1 << SSH_AUTH_RSA;
1.1       deraadt  1149: #ifdef KRB4
1.64      markus   1150:        if (options.kerberos_authentication)
                   1151:                auth_mask |= 1 << SSH_AUTH_KERBEROS;
1.1       deraadt  1152: #endif
1.5       dugsong  1153: #ifdef AFS
1.64      markus   1154:        if (options.kerberos_tgt_passing)
                   1155:                auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
                   1156:        if (options.afs_token_passing)
                   1157:                auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1.1       deraadt  1158: #endif
1.63      markus   1159: #ifdef SKEY
1.64      markus   1160:        if (options.skey_authentication == 1)
                   1161:                auth_mask |= 1 << SSH_AUTH_TIS;
1.63      markus   1162: #endif
1.64      markus   1163:        if (options.password_authentication)
                   1164:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   1165:        packet_put_int(auth_mask);
                   1166:
                   1167:        /* Send the packet and wait for it to be sent. */
                   1168:        packet_send();
                   1169:        packet_write_wait();
                   1170:
                   1171:        debug("Sent %d bit public key and %d bit host key.",
                   1172:              BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
                   1173:
                   1174:        /* Read clients reply (cipher type and session key). */
                   1175:        packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
                   1176:
1.69      markus   1177:        /* Get cipher type and check whether we accept this. */
1.64      markus   1178:        cipher_type = packet_get_char();
1.69      markus   1179:
1.105     markus   1180:        if (!(cipher_mask() & (1 << cipher_type)))
1.69      markus   1181:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   1182:
                   1183:        /* Get check bytes from the packet.  These must match those we
                   1184:           sent earlier with the public key packet. */
                   1185:        for (i = 0; i < 8; i++)
1.77      markus   1186:                if (cookie[i] != packet_get_char())
1.64      markus   1187:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   1188:
                   1189:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   1190:
                   1191:        /* Get the encrypted integer. */
                   1192:        session_key_int = BN_new();
                   1193:        packet_get_bignum(session_key_int, &slen);
                   1194:
                   1195:        protocol_flags = packet_get_int();
                   1196:        packet_set_protocol_flags(protocol_flags);
                   1197:
                   1198:        packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
                   1199:
1.66      markus   1200:        /*
                   1201:         * Decrypt it using our private server key and private host key (key
                   1202:         * with larger modulus first).
                   1203:         */
1.64      markus   1204:        if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
                   1205:                /* Private key has bigger modulus. */
                   1206:                if (BN_num_bits(sensitive_data.private_key->n) <
                   1207:                    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                   1208:                        fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                   1209:                              get_remote_ipaddr(),
                   1210:                              BN_num_bits(sensitive_data.private_key->n),
                   1211:                              BN_num_bits(sensitive_data.host_key->n),
                   1212:                              SSH_KEY_BITS_RESERVED);
                   1213:                }
                   1214:                rsa_private_decrypt(session_key_int, session_key_int,
                   1215:                                    sensitive_data.private_key);
                   1216:                rsa_private_decrypt(session_key_int, session_key_int,
                   1217:                                    sensitive_data.host_key);
                   1218:        } else {
                   1219:                /* Host key has bigger modulus (or they are equal). */
                   1220:                if (BN_num_bits(sensitive_data.host_key->n) <
                   1221:                    BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
                   1222:                        fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
                   1223:                              get_remote_ipaddr(),
                   1224:                              BN_num_bits(sensitive_data.host_key->n),
                   1225:                              BN_num_bits(sensitive_data.private_key->n),
                   1226:                              SSH_KEY_BITS_RESERVED);
                   1227:                }
                   1228:                rsa_private_decrypt(session_key_int, session_key_int,
                   1229:                                    sensitive_data.host_key);
                   1230:                rsa_private_decrypt(session_key_int, session_key_int,
                   1231:                                    sensitive_data.private_key);
                   1232:        }
                   1233:
1.77      markus   1234:        compute_session_id(session_id, cookie,
1.64      markus   1235:                           sensitive_data.host_key->n,
                   1236:                           sensitive_data.private_key->n);
                   1237:
1.77      markus   1238:        /* Destroy the private and public keys.  They will no longer be needed. */
1.108     markus   1239:        destroy_sensitive_data();
1.77      markus   1240:
1.66      markus   1241:        /*
                   1242:         * Extract session key from the decrypted integer.  The key is in the
                   1243:         * least significant 256 bits of the integer; the first byte of the
                   1244:         * key is in the highest bits.
                   1245:         */
1.64      markus   1246:        BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   1247:        len = BN_num_bytes(session_key_int);
                   1248:        if (len < 0 || len > sizeof(session_key))
                   1249:                fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
                   1250:                      get_remote_ipaddr(),
                   1251:                      len, sizeof(session_key));
                   1252:        memset(session_key, 0, sizeof(session_key));
                   1253:        BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
                   1254:
1.77      markus   1255:        /* Destroy the decrypted integer.  It is no longer needed. */
                   1256:        BN_clear_free(session_key_int);
                   1257:
1.64      markus   1258:        /* Xor the first 16 bytes of the session key with the session id. */
                   1259:        for (i = 0; i < 16; i++)
                   1260:                session_key[i] ^= session_id[i];
                   1261:
                   1262:        /* Set the session key.  From this on all communications will be encrypted. */
                   1263:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   1264:
                   1265:        /* Destroy our copy of the session key.  It is no longer needed. */
                   1266:        memset(session_key, 0, sizeof(session_key));
                   1267:
                   1268:        debug("Received session key; encryption turned on.");
                   1269:
                   1270:        /* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
                   1271:        packet_start(SSH_SMSG_SUCCESS);
                   1272:        packet_send();
                   1273:        packet_write_wait();
1.98      markus   1274: }
                   1275:
                   1276: /*
                   1277:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   1278:  */
                   1279: void
                   1280: do_ssh2_kex()
                   1281: {
                   1282:        Buffer *server_kexinit;
                   1283:        Buffer *client_kexinit;
1.129   ! provos   1284:        int payload_len;
1.98      markus   1285:        int i;
                   1286:        Kex *kex;
                   1287:        char *cprop[PROPOSAL_MAX];
                   1288:
                   1289: /* KEXINIT */
1.102     markus   1290:
                   1291:        if (options.ciphers != NULL) {
1.105     markus   1292:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102     markus   1293:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
                   1294:        }
1.118     markus   1295:        server_kexinit = kex_init(myproposal);
1.98      markus   1296:        client_kexinit = xmalloc(sizeof(*client_kexinit));
                   1297:        buffer_init(client_kexinit);
                   1298:
1.118     markus   1299:        /* algorithm negotiation */
                   1300:        kex_exchange_kexinit(server_kexinit, client_kexinit, cprop);
                   1301:        kex = kex_choose_conf(cprop, myproposal, 1);
                   1302:        for (i = 0; i < PROPOSAL_MAX; i++)
                   1303:                xfree(cprop[i]);
1.98      markus   1304:
1.129   ! provos   1305:        switch (kex->kex_type) {
        !          1306:        case DH_GRP1_SHA1:
        !          1307:                ssh_dh1_server(kex, client_kexinit, server_kexinit);
        !          1308:                break;
        !          1309:        case DH_GEX_SHA1:
        !          1310:                ssh_dhgex_server(kex, client_kexinit, server_kexinit);
        !          1311:                break;
        !          1312:        default:
        !          1313:                fatal("Unsupported key exchange %d", kex->kex_type);
        !          1314:        }
        !          1315:
        !          1316:        debug("send SSH2_MSG_NEWKEYS.");
        !          1317:        packet_start(SSH2_MSG_NEWKEYS);
        !          1318:        packet_send();
        !          1319:        packet_write_wait();
        !          1320:        debug("done: send SSH2_MSG_NEWKEYS.");
        !          1321:
        !          1322:        debug("Wait SSH2_MSG_NEWKEYS.");
        !          1323:        packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
        !          1324:        debug("GOT SSH2_MSG_NEWKEYS.");
        !          1325:
        !          1326: #ifdef DEBUG_KEXDH
        !          1327:        /* send 1st encrypted/maced/compressed message */
        !          1328:        packet_start(SSH2_MSG_IGNORE);
        !          1329:        packet_put_cstring("markus");
        !          1330:        packet_send();
        !          1331:        packet_write_wait();
        !          1332: #endif
        !          1333:
        !          1334:        debug("done: KEX2.");
        !          1335: }
        !          1336:
        !          1337: /*
        !          1338:  * SSH2 key exchange
        !          1339:  */
        !          1340:
        !          1341: /* diffie-hellman-group1-sha1 */
        !          1342:
        !          1343: void
        !          1344: ssh_dh1_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
        !          1345: {
        !          1346:        int payload_len, dlen;
        !          1347:        int slen;
        !          1348:        unsigned char *signature = NULL;
        !          1349:        unsigned char *server_host_key_blob = NULL;
        !          1350:        unsigned int sbloblen;
        !          1351:        unsigned int klen, kout;
        !          1352:        unsigned char *kbuf;
        !          1353:        unsigned char *hash;
        !          1354:        BIGNUM *shared_secret = 0;
        !          1355:        DH *dh;
        !          1356:        BIGNUM *dh_client_pub = 0;
        !          1357:
1.98      markus   1358: /* KEXDH */
                   1359:        debug("Wait SSH2_MSG_KEXDH_INIT.");
                   1360:        packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
                   1361:
                   1362:        /* key, cert */
                   1363:        dh_client_pub = BN_new();
                   1364:        if (dh_client_pub == NULL)
                   1365:                fatal("dh_client_pub == NULL");
                   1366:        packet_get_bignum2(dh_client_pub, &dlen);
                   1367:
                   1368: #ifdef DEBUG_KEXDH
                   1369:        fprintf(stderr, "\ndh_client_pub= ");
1.128     markus   1370:        BN_print_fp(stderr, dh_client_pub);
1.98      markus   1371:        fprintf(stderr, "\n");
                   1372:        debug("bits %d", BN_num_bits(dh_client_pub));
                   1373: #endif
                   1374:
                   1375:        /* generate DH key */
1.101     markus   1376:        dh = dh_new_group1();                   /* XXX depends on 'kex' */
1.98      markus   1377:
                   1378: #ifdef DEBUG_KEXDH
                   1379:        fprintf(stderr, "\np= ");
1.128     markus   1380:        BN_print_fp(stderr, dh->p);
1.98      markus   1381:        fprintf(stderr, "\ng= ");
1.128     markus   1382:        bn_print(dh->g);
1.98      markus   1383:        fprintf(stderr, "\npub= ");
1.128     markus   1384:        BN_print_fp(stderr, dh->pub_key);
1.98      markus   1385:        fprintf(stderr, "\n");
1.128     markus   1386:         DHparams_print_fp(stderr, dh);
1.98      markus   1387: #endif
1.101     markus   1388:        if (!dh_pub_is_valid(dh, dh_client_pub))
                   1389:                packet_disconnect("bad client public DH value");
1.98      markus   1390:
                   1391:        klen = DH_size(dh);
                   1392:        kbuf = xmalloc(klen);
                   1393:        kout = DH_compute_key(kbuf, dh_client_pub, dh);
                   1394:
                   1395: #ifdef DEBUG_KEXDH
                   1396:        debug("shared secret: len %d/%d", klen, kout);
                   1397:        fprintf(stderr, "shared secret == ");
                   1398:        for (i = 0; i< kout; i++)
                   1399:                fprintf(stderr, "%02x", (kbuf[i])&0xff);
                   1400:        fprintf(stderr, "\n");
                   1401: #endif
                   1402:        shared_secret = BN_new();
                   1403:
                   1404:        BN_bin2bn(kbuf, kout, shared_secret);
                   1405:        memset(kbuf, 0, klen);
                   1406:        xfree(kbuf);
                   1407:
1.111     markus   1408:        /* XXX precompute? */
1.129   ! provos   1409:        dsa_make_key_blob(sensitive_data.dsa_host_key,
        !          1410:                          &server_host_key_blob, &sbloblen);
1.98      markus   1411:
                   1412:        /* calc H */                    /* XXX depends on 'kex' */
                   1413:        hash = kex_hash(
                   1414:            client_version_string,
                   1415:            server_version_string,
                   1416:            buffer_ptr(client_kexinit), buffer_len(client_kexinit),
                   1417:            buffer_ptr(server_kexinit), buffer_len(server_kexinit),
                   1418:            (char *)server_host_key_blob, sbloblen,
                   1419:            dh_client_pub,
                   1420:            dh->pub_key,
                   1421:            shared_secret
                   1422:        );
                   1423:        buffer_free(client_kexinit);
                   1424:        buffer_free(server_kexinit);
                   1425:        xfree(client_kexinit);
                   1426:        xfree(server_kexinit);
                   1427: #ifdef DEBUG_KEXDH
1.105     markus   1428:        fprintf(stderr, "hash == ");
                   1429:        for (i = 0; i< 20; i++)
                   1430:                fprintf(stderr, "%02x", (hash[i])&0xff);
                   1431:        fprintf(stderr, "\n");
1.98      markus   1432: #endif
1.108     markus   1433:        /* save session id := H */
                   1434:        /* XXX hashlen depends on KEX */
                   1435:        session_id2_len = 20;
                   1436:        session_id2 = xmalloc(session_id2_len);
                   1437:        memcpy(session_id2, hash, session_id2_len);
                   1438:
1.98      markus   1439:        /* sign H */
1.108     markus   1440:        /* XXX hashlen depends on KEX */
                   1441:        dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
                   1442:
                   1443:        destroy_sensitive_data();
1.98      markus   1444:
                   1445:        /* send server hostkey, DH pubkey 'f' and singed H */
                   1446:        packet_start(SSH2_MSG_KEXDH_REPLY);
                   1447:        packet_put_string((char *)server_host_key_blob, sbloblen);
1.114     markus   1448:        packet_put_bignum2(dh->pub_key);        /* f */
1.98      markus   1449:        packet_put_string((char *)signature, slen);
                   1450:        packet_send();
1.106     markus   1451:        xfree(signature);
1.111     markus   1452:        xfree(server_host_key_blob);
1.98      markus   1453:        packet_write_wait();
                   1454:
                   1455:        kex_derive_keys(kex, hash, shared_secret);
                   1456:        packet_set_kex(kex);
                   1457:
                   1458:        /* have keys, free DH */
                   1459:        DH_free(dh);
1.129   ! provos   1460: }
        !          1461:
        !          1462: /* diffie-hellman-group-exchange-sha1 */
1.98      markus   1463:
1.129   ! provos   1464: void
        !          1465: ssh_dhgex_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
        !          1466: {
        !          1467:        int payload_len, dlen;
        !          1468:        int slen, nbits;
        !          1469:        unsigned char *signature = NULL;
        !          1470:        unsigned char *server_host_key_blob = NULL;
        !          1471:        unsigned int sbloblen;
        !          1472:        unsigned int klen, kout;
        !          1473:        unsigned char *kbuf;
        !          1474:        unsigned char *hash;
        !          1475:        BIGNUM *shared_secret = 0;
        !          1476:        DH *dh;
        !          1477:        BIGNUM *dh_client_pub = 0;
        !          1478:
        !          1479: /* KEXDHGEX */
        !          1480:        debug("Wait SSH2_MSG_KEX_DH_GEX_REQUEST.");
        !          1481:        packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_REQUEST);
        !          1482:        nbits = packet_get_int();
        !          1483:        dh = choose_dh(nbits);
        !          1484:
        !          1485:        debug("Sending SSH2_MSG_KEX_DH_GEX_GROUP.");
        !          1486:        packet_start(SSH2_MSG_KEX_DH_GEX_GROUP);
        !          1487:        packet_put_bignum2(dh->p);
        !          1488:        packet_put_bignum2(dh->g);
1.98      markus   1489:        packet_send();
                   1490:        packet_write_wait();
                   1491:
1.129   ! provos   1492:        debug("Wait SSH2_MSG_KEX_DH_GEX_INIT.");
        !          1493:        packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_INIT);
        !          1494:
        !          1495:        /* key, cert */
        !          1496:        dh_client_pub = BN_new();
        !          1497:        if (dh_client_pub == NULL)
        !          1498:                fatal("dh_client_pub == NULL");
        !          1499:        packet_get_bignum2(dh_client_pub, &dlen);
        !          1500:
        !          1501: #ifdef DEBUG_KEXDH
        !          1502:        fprintf(stderr, "\ndh_client_pub= ");
        !          1503:        BN_print_fp(stderr, dh_client_pub);
        !          1504:        fprintf(stderr, "\n");
        !          1505:        debug("bits %d", BN_num_bits(dh_client_pub));
        !          1506: #endif
        !          1507:
        !          1508: #ifdef DEBUG_KEXDH
        !          1509:        fprintf(stderr, "\np= ");
        !          1510:        BN_print_fp(stderr, dh->p);
        !          1511:        fprintf(stderr, "\ng= ");
        !          1512:        bn_print(dh->g);
        !          1513:        fprintf(stderr, "\npub= ");
        !          1514:        BN_print_fp(stderr, dh->pub_key);
        !          1515:        fprintf(stderr, "\n");
        !          1516:         DHparams_print_fp(stderr, dh);
        !          1517: #endif
        !          1518:        if (!dh_pub_is_valid(dh, dh_client_pub))
        !          1519:                packet_disconnect("bad client public DH value");
        !          1520:
        !          1521:        klen = DH_size(dh);
        !          1522:        kbuf = xmalloc(klen);
        !          1523:        kout = DH_compute_key(kbuf, dh_client_pub, dh);
        !          1524:
        !          1525: #ifdef DEBUG_KEXDH
        !          1526:        debug("shared secret: len %d/%d", klen, kout);
        !          1527:        fprintf(stderr, "shared secret == ");
        !          1528:        for (i = 0; i< kout; i++)
        !          1529:                fprintf(stderr, "%02x", (kbuf[i])&0xff);
        !          1530:        fprintf(stderr, "\n");
        !          1531: #endif
        !          1532:        shared_secret = BN_new();
        !          1533:
        !          1534:        BN_bin2bn(kbuf, kout, shared_secret);
        !          1535:        memset(kbuf, 0, klen);
        !          1536:        xfree(kbuf);
        !          1537:
        !          1538:        /* XXX precompute? */
        !          1539:        dsa_make_key_blob(sensitive_data.dsa_host_key,
        !          1540:                          &server_host_key_blob, &sbloblen);
1.98      markus   1541:
1.129   ! provos   1542:        /* calc H */                    /* XXX depends on 'kex' */
        !          1543:        hash = kex_hash_gex(
        !          1544:            client_version_string,
        !          1545:            server_version_string,
        !          1546:            buffer_ptr(client_kexinit), buffer_len(client_kexinit),
        !          1547:            buffer_ptr(server_kexinit), buffer_len(server_kexinit),
        !          1548:            (char *)server_host_key_blob, sbloblen,
        !          1549:            nbits, dh->p, dh->g,
        !          1550:            dh_client_pub,
        !          1551:            dh->pub_key,
        !          1552:            shared_secret
        !          1553:        );
        !          1554:        buffer_free(client_kexinit);
        !          1555:        buffer_free(server_kexinit);
        !          1556:        xfree(client_kexinit);
        !          1557:        xfree(server_kexinit);
1.100     markus   1558: #ifdef DEBUG_KEXDH
1.129   ! provos   1559:        fprintf(stderr, "hash == ");
        !          1560:        for (i = 0; i< 20; i++)
        !          1561:                fprintf(stderr, "%02x", (hash[i])&0xff);
        !          1562:        fprintf(stderr, "\n");
        !          1563: #endif
        !          1564:        /* save session id := H */
        !          1565:        /* XXX hashlen depends on KEX */
        !          1566:        session_id2_len = 20;
        !          1567:        session_id2 = xmalloc(session_id2_len);
        !          1568:        memcpy(session_id2, hash, session_id2_len);
        !          1569:
        !          1570:        /* sign H */
        !          1571:        /* XXX hashlen depends on KEX */
        !          1572:        dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
        !          1573:
        !          1574:        destroy_sensitive_data();
        !          1575:
        !          1576:        /* send server hostkey, DH pubkey 'f' and singed H */
        !          1577:        packet_start(SSH2_MSG_KEX_DH_GEX_REPLY);
        !          1578:        packet_put_string((char *)server_host_key_blob, sbloblen);
        !          1579:        packet_put_bignum2(dh->pub_key);        /* f */
        !          1580:        packet_put_string((char *)signature, slen);
1.98      markus   1581:        packet_send();
1.129   ! provos   1582:        xfree(signature);
        !          1583:        xfree(server_host_key_blob);
1.98      markus   1584:        packet_write_wait();
1.129   ! provos   1585:
        !          1586:        kex_derive_keys(kex, hash, shared_secret);
        !          1587:        packet_set_kex(kex);
        !          1588:
        !          1589:        /* have keys, free DH */
        !          1590:        DH_free(dh);
1.1       deraadt  1591: }
1.129   ! provos   1592: