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

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