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

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