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

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