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

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