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

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