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

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