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

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