[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.290.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:
1.231     provos     18:  * Privilege Separation:
1.126     deraadt    19:  *
1.231     provos     20:  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
                     21:  * Copyright (c) 2002 Niels Provos.  All rights reserved.
1.126     deraadt    22:  *
                     23:  * Redistribution and use in source and binary forms, with or without
                     24:  * modification, are permitted provided that the following conditions
                     25:  * are met:
                     26:  * 1. Redistributions of source code must retain the above copyright
                     27:  *    notice, this list of conditions and the following disclaimer.
                     28:  * 2. Redistributions in binary form must reproduce the above copyright
                     29:  *    notice, this list of conditions and the following disclaimer in the
                     30:  *    documentation and/or other materials provided with the distribution.
                     31:  *
                     32:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     33:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     34:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     35:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     36:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     37:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     38:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     39:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     40:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     41:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.65      deraadt    42:  */
1.1       deraadt    43:
                     44: #include "includes.h"
1.290.2.2! brad       45: RCSID("$OpenBSD: sshd.c,v 1.308 2005/02/08 22:24:57 dtucker Exp $");
1.1       deraadt    46:
1.155     markus     47: #include <openssl/dh.h>
                     48: #include <openssl/bn.h>
1.226     markus     49: #include <openssl/md5.h>
1.231     provos     50: #include <openssl/rand.h>
1.155     markus     51:
                     52: #include "ssh.h"
                     53: #include "ssh1.h"
                     54: #include "ssh2.h"
1.1       deraadt    55: #include "xmalloc.h"
                     56: #include "rsa.h"
1.171     djm        57: #include "sshpty.h"
1.1       deraadt    58: #include "packet.h"
1.155     markus     59: #include "log.h"
1.1       deraadt    60: #include "servconf.h"
                     61: #include "uidswap.h"
1.33      markus     62: #include "compat.h"
1.96      markus     63: #include "buffer.h"
1.290.2.1  brad       64: #include "bufaux.h"
1.155     markus     65: #include "cipher.h"
1.98      markus     66: #include "kex.h"
1.96      markus     67: #include "key.h"
1.129     provos     68: #include "dh.h"
1.98      markus     69: #include "myproposal.h"
1.108     markus     70: #include "authfile.h"
1.154     markus     71: #include "pathnames.h"
1.155     markus     72: #include "atomicio.h"
                     73: #include "canohost.h"
                     74: #include "auth.h"
                     75: #include "misc.h"
1.290.2.1  brad       76: #include "msg.h"
1.186     markus     77: #include "dispatch.h"
1.206     stevesk    78: #include "channels.h"
1.230     provos     79: #include "session.h"
1.231     provos     80: #include "monitor_mm.h"
                     81: #include "monitor.h"
                     82: #include "monitor_wrap.h"
                     83: #include "monitor_fdpass.h"
1.1       deraadt    84:
                     85: #ifdef LIBWRAP
                     86: #include <tcpd.h>
                     87: #include <syslog.h>
                     88: int allow_severity = LOG_INFO;
                     89: int deny_severity = LOG_WARNING;
                     90: #endif /* LIBWRAP */
                     91:
                     92: #ifndef O_NOCTTY
                     93: #define O_NOCTTY       0
                     94: #endif
                     95:
1.290.2.1  brad       96: /* Re-exec fds */
                     97: #define REEXEC_DEVCRYPTO_RESERVED_FD   (STDERR_FILENO + 1)
                     98: #define REEXEC_STARTUP_PIPE_FD         (STDERR_FILENO + 2)
                     99: #define REEXEC_CONFIG_PASS_FD          (STDERR_FILENO + 3)
                    100: #define REEXEC_MIN_FREE_FD             (STDERR_FILENO + 4)
                    101:
1.138     markus    102: extern char *__progname;
                    103:
1.1       deraadt   104: /* Server configuration options. */
                    105: ServerOptions options;
                    106:
                    107: /* Name of the server configuration file. */
1.154     markus    108: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1       deraadt   109:
1.105     markus    110: /*
1.65      deraadt   111:  * Debug mode flag.  This can be set on the command line.  If debug
                    112:  * mode is enabled, extra debugging output will be sent to the system
                    113:  * log, the daemon will not go to background, and will exit after processing
                    114:  * the first connection.
                    115:  */
1.1       deraadt   116: int debug_flag = 0;
                    117:
1.203     stevesk   118: /* Flag indicating that the daemon should only test the configuration and keys. */
                    119: int test_flag = 0;
                    120:
1.1       deraadt   121: /* Flag indicating that the daemon is being started from inetd. */
                    122: int inetd_flag = 0;
                    123:
1.135     markus    124: /* Flag indicating that sshd should not detach and become a daemon. */
                    125: int no_daemon_flag = 0;
                    126:
1.47      markus    127: /* debug goes to stderr unless inetd_flag is set */
                    128: int log_stderr = 0;
                    129:
1.1       deraadt   130: /* Saved arguments to main(). */
                    131: char **saved_argv;
                    132:
1.290.2.1  brad      133: /* re-exec */
                    134: int rexeced_flag = 0;
                    135: int rexec_flag = 1;
                    136: int rexec_argc = 0;
                    137: char **rexec_argv;
                    138:
1.66      markus    139: /*
1.75      markus    140:  * The sockets that the server is listening; this is used in the SIGHUP
                    141:  * signal handler.
1.66      markus    142:  */
1.75      markus    143: #define        MAX_LISTEN_SOCKS        16
                    144: int listen_socks[MAX_LISTEN_SOCKS];
                    145: int num_listen_socks = 0;
1.1       deraadt   146:
1.66      markus    147: /*
                    148:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                    149:  * sshd will skip the version-number exchange
                    150:  */
1.61      markus    151: char *client_version_string = NULL;
1.96      markus    152: char *server_version_string = NULL;
1.1       deraadt   153:
1.189     markus    154: /* for rekeying XXX fixme */
                    155: Kex *xxx_kex;
                    156:
1.66      markus    157: /*
                    158:  * Any really sensitive data in the application is contained in this
                    159:  * structure. The idea is that this structure could be locked into memory so
                    160:  * that the pages do not get written into swap.  However, there are some
                    161:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    162:  * have access to the internals of them, and locking just the structure is
                    163:  * not very useful.  Currently, memory locking is not implemented.
                    164:  */
1.64      markus    165: struct {
1.174     deraadt   166:        Key     *server_key;            /* ephemeral server key */
1.134     markus    167:        Key     *ssh1_host_key;         /* ssh1 host key */
                    168:        Key     **host_keys;            /* all private host keys */
                    169:        int     have_ssh1_key;
                    170:        int     have_ssh2_key;
1.169     markus    171:        u_char  ssh1_cookie[SSH_SESSION_KEY_LENGTH];
1.1       deraadt   172: } sensitive_data;
                    173:
1.66      markus    174: /*
1.151     markus    175:  * Flag indicating whether the RSA server key needs to be regenerated.
                    176:  * Is set in the SIGALRM handler and cleared when the key is regenerated.
1.66      markus    177:  */
1.212     markus    178: static volatile sig_atomic_t key_do_regen = 0;
1.1       deraadt   179:
1.199     markus    180: /* This is set to true when a signal is received. */
1.212     markus    181: static volatile sig_atomic_t received_sighup = 0;
                    182: static volatile sig_atomic_t received_sigterm = 0;
1.1       deraadt   183:
1.96      markus    184: /* session identifier, used by RSA-auth */
1.140     markus    185: u_char session_id[16];
1.96      markus    186:
1.108     markus    187: /* same for ssh2 */
1.140     markus    188: u_char *session_id2 = NULL;
1.269     markus    189: u_int session_id2_len = 0;
1.108     markus    190:
1.125     markus    191: /* record remote hostname or ip */
1.140     markus    192: u_int utmp_len = MAXHOSTNAMELEN;
1.125     markus    193:
1.211     markus    194: /* options.max_startup sized array of fd ints */
                    195: int *startup_pipes = NULL;
                    196: int startup_pipe;              /* in child */
                    197:
1.231     provos    198: /* variables used for privilege separation */
1.263     markus    199: int use_privsep;
1.285     dtucker   200: struct monitor *pmonitor = NULL;
1.231     provos    201:
1.278     markus    202: /* global authentication context */
                    203: Authctxt *the_authctxt = NULL;
                    204:
1.290.2.1  brad      205: /* message to be displayed after login */
                    206: Buffer loginmsg;
                    207:
1.1       deraadt   208: /* Prototypes for various functions defined later in this file. */
1.200     itojun    209: void destroy_sensitive_data(void);
1.231     provos    210: void demote_sensitive_data(void);
1.87      markus    211:
1.200     itojun    212: static void do_ssh1_kex(void);
                    213: static void do_ssh2_kex(void);
1.129     provos    214:
1.87      markus    215: /*
1.75      markus    216:  * Close all listening sockets
                    217:  */
1.200     itojun    218: static void
1.75      markus    219: close_listen_socks(void)
                    220: {
                    221:        int i;
1.250     deraadt   222:
1.75      markus    223:        for (i = 0; i < num_listen_socks; i++)
                    224:                close(listen_socks[i]);
                    225:        num_listen_socks = -1;
                    226: }
                    227:
1.211     markus    228: static void
                    229: close_startup_pipes(void)
                    230: {
                    231:        int i;
1.250     deraadt   232:
1.211     markus    233:        if (startup_pipes)
                    234:                for (i = 0; i < options.max_startups; i++)
                    235:                        if (startup_pipes[i] != -1)
                    236:                                close(startup_pipes[i]);
                    237: }
                    238:
1.75      markus    239: /*
1.65      deraadt   240:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    241:  * the effect is to reread the configuration file (and to regenerate
                    242:  * the server key).
                    243:  */
1.200     itojun    244: static void
1.64      markus    245: sighup_handler(int sig)
1.1       deraadt   246: {
1.210     deraadt   247:        int save_errno = errno;
                    248:
1.64      markus    249:        received_sighup = 1;
                    250:        signal(SIGHUP, sighup_handler);
1.210     deraadt   251:        errno = save_errno;
1.1       deraadt   252: }
                    253:
1.65      deraadt   254: /*
                    255:  * Called from the main program after receiving SIGHUP.
                    256:  * Restarts the server.
                    257:  */
1.200     itojun    258: static void
1.165     itojun    259: sighup_restart(void)
1.1       deraadt   260: {
1.264     itojun    261:        logit("Received SIGHUP; restarting.");
1.75      markus    262:        close_listen_socks();
1.211     markus    263:        close_startup_pipes();
1.64      markus    264:        execv(saved_argv[0], saved_argv);
1.264     itojun    265:        logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
1.250     deraadt   266:            strerror(errno));
1.64      markus    267:        exit(1);
1.1       deraadt   268: }
                    269:
1.65      deraadt   270: /*
                    271:  * Generic signal handler for terminating signals in the master daemon.
                    272:  */
1.200     itojun    273: static void
1.64      markus    274: sigterm_handler(int sig)
1.1       deraadt   275: {
1.199     markus    276:        received_sigterm = sig;
1.1       deraadt   277: }
                    278:
1.65      deraadt   279: /*
                    280:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
1.199     markus    281:  * reap any zombies left by exited children.
1.65      deraadt   282:  */
1.200     itojun    283: static void
1.64      markus    284: main_sigchld_handler(int sig)
1.1       deraadt   285: {
1.250     deraadt   286:        int save_errno = errno;
1.239     markus    287:        pid_t pid;
1.64      markus    288:        int status;
1.60      deraadt   289:
1.239     markus    290:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
                    291:            (pid < 0 && errno == EINTR))
1.64      markus    292:                ;
1.60      deraadt   293:
1.64      markus    294:        signal(SIGCHLD, main_sigchld_handler);
                    295:        errno = save_errno;
1.1       deraadt   296: }
                    297:
1.65      deraadt   298: /*
                    299:  * Signal handler for the alarm after the login grace period has expired.
                    300:  */
1.200     itojun    301: static void
1.64      markus    302: grace_alarm_handler(int sig)
1.1       deraadt   303: {
1.199     markus    304:        /* XXX no idea how fix this signal handler */
                    305:
1.285     dtucker   306:        if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
                    307:                kill(pmonitor->m_pid, SIGALRM);
                    308:
1.64      markus    309:        /* Log error and exit. */
1.259     markus    310:        fatal("Timeout before authentication for %s", get_remote_ipaddr());
1.62      markus    311: }
                    312:
1.65      deraadt   313: /*
                    314:  * Signal handler for the key regeneration alarm.  Note that this
                    315:  * alarm only occurs in the daemon waiting for connections, and it does not
                    316:  * do anything with the private key or random state before forking.
                    317:  * Thus there should be no concurrency control/asynchronous execution
                    318:  * problems.
                    319:  */
1.200     itojun    320: static void
1.174     deraadt   321: generate_ephemeral_server_key(void)
1.134     markus    322: {
1.254     deraadt   323:        u_int32_t rnd = 0;
1.169     markus    324:        int i;
                    325:
1.191     markus    326:        verbose("Generating %s%d bit RSA key.",
1.185     djm       327:            sensitive_data.server_key ? "new " : "", options.server_key_bits);
1.134     markus    328:        if (sensitive_data.server_key != NULL)
                    329:                key_free(sensitive_data.server_key);
1.191     markus    330:        sensitive_data.server_key = key_generate(KEY_RSA1,
1.185     djm       331:            options.server_key_bits);
                    332:        verbose("RSA key generation complete.");
1.169     markus    333:
                    334:        for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
                    335:                if (i % 4 == 0)
1.254     deraadt   336:                        rnd = arc4random();
                    337:                sensitive_data.ssh1_cookie[i] = rnd & 0xff;
                    338:                rnd >>= 8;
1.169     markus    339:        }
1.134     markus    340:        arc4random_stir();
                    341: }
1.147     deraadt   342:
1.200     itojun    343: static void
1.64      markus    344: key_regeneration_alarm(int sig)
1.1       deraadt   345: {
1.64      markus    346:        int save_errno = errno;
1.250     deraadt   347:
1.151     markus    348:        signal(SIGALRM, SIG_DFL);
1.64      markus    349:        errno = save_errno;
1.151     markus    350:        key_do_regen = 1;
1.98      markus    351: }
                    352:
1.200     itojun    353: static void
1.96      markus    354: sshd_exchange_identification(int sock_in, int sock_out)
                    355: {
1.102     markus    356:        int i, mismatch;
1.96      markus    357:        int remote_major, remote_minor;
1.102     markus    358:        int major, minor;
1.96      markus    359:        char *s;
                    360:        char buf[256];                  /* Must not be larger than remote_version. */
                    361:        char remote_version[256];       /* Must be at least as big as buf. */
                    362:
1.103     markus    363:        if ((options.protocol & SSH_PROTO_1) &&
                    364:            (options.protocol & SSH_PROTO_2)) {
1.102     markus    365:                major = PROTOCOL_MAJOR_1;
                    366:                minor = 99;
                    367:        } else if (options.protocol & SSH_PROTO_2) {
                    368:                major = PROTOCOL_MAJOR_2;
                    369:                minor = PROTOCOL_MINOR_2;
                    370:        } else {
                    371:                major = PROTOCOL_MAJOR_1;
                    372:                minor = PROTOCOL_MINOR_1;
                    373:        }
                    374:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
1.96      markus    375:        server_version_string = xstrdup(buf);
                    376:
1.272     markus    377:        /* Send our protocol version identification. */
                    378:        if (atomicio(vwrite, sock_out, server_version_string,
                    379:            strlen(server_version_string))
                    380:            != strlen(server_version_string)) {
                    381:                logit("Could not write ident string to %s", get_remote_ipaddr());
1.278     markus    382:                cleanup_exit(255);
1.272     markus    383:        }
                    384:
                    385:        /* Read other sides version identification. */
                    386:        memset(buf, 0, sizeof(buf));
                    387:        for (i = 0; i < sizeof(buf) - 1; i++) {
                    388:                if (atomicio(read, sock_in, &buf[i], 1) != 1) {
                    389:                        logit("Did not receive identification string from %s",
                    390:                            get_remote_ipaddr());
1.278     markus    391:                        cleanup_exit(255);
1.96      markus    392:                }
1.272     markus    393:                if (buf[i] == '\r') {
                    394:                        buf[i] = 0;
                    395:                        /* Kludge for F-Secure Macintosh < 1.0.2 */
                    396:                        if (i == 12 &&
                    397:                            strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
1.96      markus    398:                                break;
1.272     markus    399:                        continue;
                    400:                }
                    401:                if (buf[i] == '\n') {
                    402:                        buf[i] = 0;
                    403:                        break;
1.96      markus    404:                }
                    405:        }
1.272     markus    406:        buf[sizeof(buf) - 1] = 0;
                    407:        client_version_string = xstrdup(buf);
1.96      markus    408:
                    409:        /*
                    410:         * Check that the versions match.  In future this might accept
                    411:         * several versions and set appropriate flags to handle them.
                    412:         */
                    413:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    414:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    415:                s = "Protocol mismatch.\n";
1.271     deraadt   416:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    417:                close(sock_in);
                    418:                close(sock_out);
1.264     itojun    419:                logit("Bad protocol version identification '%.100s' from %s",
1.96      markus    420:                    client_version_string, get_remote_ipaddr());
1.278     markus    421:                cleanup_exit(255);
1.96      markus    422:        }
                    423:        debug("Client protocol version %d.%d; client software version %.100s",
1.217     deraadt   424:            remote_major, remote_minor, remote_version);
1.96      markus    425:
1.98      markus    426:        compat_datafellows(remote_version);
1.260     mickey    427:
                    428:        if (datafellows & SSH_BUG_PROBE) {
1.264     itojun    429:                logit("probed from %s with %s.  Don't panic.",
1.260     mickey    430:                    get_remote_ipaddr(), client_version_string);
1.278     markus    431:                cleanup_exit(255);
1.260     mickey    432:        }
1.175     deraadt   433:
                    434:        if (datafellows & SSH_BUG_SCANNER) {
1.264     itojun    435:                logit("scanned from %s with %s.  Don't panic.",
1.175     deraadt   436:                    get_remote_ipaddr(), client_version_string);
1.278     markus    437:                cleanup_exit(255);
1.175     deraadt   438:        }
1.98      markus    439:
1.102     markus    440:        mismatch = 0;
1.214     deraadt   441:        switch (remote_major) {
1.96      markus    442:        case 1:
1.108     markus    443:                if (remote_minor == 99) {
                    444:                        if (options.protocol & SSH_PROTO_2)
                    445:                                enable_compat20();
                    446:                        else
                    447:                                mismatch = 1;
                    448:                        break;
                    449:                }
1.102     markus    450:                if (!(options.protocol & SSH_PROTO_1)) {
                    451:                        mismatch = 1;
                    452:                        break;
                    453:                }
1.96      markus    454:                if (remote_minor < 3) {
1.121     provos    455:                        packet_disconnect("Your ssh version is too old and "
1.96      markus    456:                            "is no longer supported.  Please install a newer version.");
                    457:                } else if (remote_minor == 3) {
                    458:                        /* note that this disables agent-forwarding */
                    459:                        enable_compat13();
                    460:                }
1.102     markus    461:                break;
1.98      markus    462:        case 2:
1.102     markus    463:                if (options.protocol & SSH_PROTO_2) {
1.98      markus    464:                        enable_compat20();
                    465:                        break;
                    466:                }
1.99      markus    467:                /* FALLTHROUGH */
1.105     markus    468:        default:
1.102     markus    469:                mismatch = 1;
                    470:                break;
                    471:        }
                    472:        chop(server_version_string);
                    473:        debug("Local version string %.200s", server_version_string);
                    474:
                    475:        if (mismatch) {
1.96      markus    476:                s = "Protocol major versions differ.\n";
1.271     deraadt   477:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    478:                close(sock_in);
                    479:                close(sock_out);
1.264     itojun    480:                logit("Protocol major versions differ for %s: %.200s vs. %.200s",
1.102     markus    481:                    get_remote_ipaddr(),
                    482:                    server_version_string, client_version_string);
1.278     markus    483:                cleanup_exit(255);
1.96      markus    484:        }
1.108     markus    485: }
                    486:
1.134     markus    487: /* Destroy the host and server keys.  They will no longer be needed. */
1.108     markus    488: void
                    489: destroy_sensitive_data(void)
                    490: {
1.134     markus    491:        int i;
                    492:
                    493:        if (sensitive_data.server_key) {
                    494:                key_free(sensitive_data.server_key);
                    495:                sensitive_data.server_key = NULL;
                    496:        }
1.217     deraadt   497:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    498:                if (sensitive_data.host_keys[i]) {
                    499:                        key_free(sensitive_data.host_keys[i]);
                    500:                        sensitive_data.host_keys[i] = NULL;
                    501:                }
                    502:        }
                    503:        sensitive_data.ssh1_host_key = NULL;
1.169     markus    504:        memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
1.134     markus    505: }
                    506:
1.231     provos    507: /* Demote private to public keys for network child */
                    508: void
                    509: demote_sensitive_data(void)
                    510: {
                    511:        Key *tmp;
                    512:        int i;
                    513:
                    514:        if (sensitive_data.server_key) {
                    515:                tmp = key_demote(sensitive_data.server_key);
                    516:                key_free(sensitive_data.server_key);
                    517:                sensitive_data.server_key = tmp;
                    518:        }
                    519:
                    520:        for (i = 0; i < options.num_host_key_files; i++) {
                    521:                if (sensitive_data.host_keys[i]) {
                    522:                        tmp = key_demote(sensitive_data.host_keys[i]);
                    523:                        key_free(sensitive_data.host_keys[i]);
                    524:                        sensitive_data.host_keys[i] = tmp;
                    525:                        if (tmp->type == KEY_RSA1)
                    526:                                sensitive_data.ssh1_host_key = tmp;
                    527:                }
                    528:        }
                    529:
                    530:        /* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
                    531: }
                    532:
1.233     markus    533: static void
1.231     provos    534: privsep_preauth_child(void)
                    535: {
1.254     deraadt   536:        u_int32_t rnd[256];
1.253     deraadt   537:        gid_t gidset[1];
1.250     deraadt   538:        struct passwd *pw;
1.231     provos    539:        int i;
                    540:
                    541:        /* Enable challenge-response authentication for privilege separation */
                    542:        privsep_challenge_enable();
                    543:
                    544:        for (i = 0; i < 256; i++)
1.254     deraadt   545:                rnd[i] = arc4random();
                    546:        RAND_seed(rnd, sizeof(rnd));
1.231     provos    547:
                    548:        /* Demote the private keys to public keys. */
                    549:        demote_sensitive_data();
                    550:
1.235     stevesk   551:        if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1.240     djm       552:                fatal("Privilege separation user %s does not exist",
                    553:                    SSH_PRIVSEP_USER);
1.235     stevesk   554:        memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
                    555:        endpwent();
                    556:
1.255     deraadt   557:        /* Change our root directory */
1.232     stevesk   558:        if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    559:                fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    560:                    strerror(errno));
1.231     provos    561:        if (chdir("/") == -1)
1.236     stevesk   562:                fatal("chdir(\"/\"): %s", strerror(errno));
1.234     markus    563:
1.231     provos    564:        /* Drop our privileges */
1.235     stevesk   565:        debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    566:            (u_int)pw->pw_gid);
1.251     markus    567: #if 0
1.287     djm       568:        /* XXX not ready, too heavy after chroot */
1.235     stevesk   569:        do_setusercontext(pw);
1.251     markus    570: #else
                    571:        gidset[0] = pw->pw_gid;
                    572:        if (setgroups(1, gidset) < 0)
                    573:                fatal("setgroups: %.100s", strerror(errno));
                    574:        permanently_set_uid(pw);
                    575: #endif
1.231     provos    576: }
                    577:
1.278     markus    578: static int
                    579: privsep_preauth(Authctxt *authctxt)
1.237     markus    580: {
                    581:        int status;
                    582:        pid_t pid;
                    583:
                    584:        /* Set up unprivileged child process to deal with network data */
1.242     mouring   585:        pmonitor = monitor_init();
1.237     markus    586:        /* Store a pointer to the kex for later rekeying */
1.242     mouring   587:        pmonitor->m_pkex = &xxx_kex;
1.237     markus    588:
                    589:        pid = fork();
                    590:        if (pid == -1) {
                    591:                fatal("fork of unprivileged child failed");
                    592:        } else if (pid != 0) {
1.245     mpech     593:                debug2("Network child is on pid %ld", (long)pid);
1.237     markus    594:
1.242     mouring   595:                close(pmonitor->m_recvfd);
1.285     dtucker   596:                pmonitor->m_pid = pid;
1.278     markus    597:                monitor_child_preauth(authctxt, pmonitor);
1.242     mouring   598:                close(pmonitor->m_sendfd);
1.237     markus    599:
                    600:                /* Sync memory */
1.242     mouring   601:                monitor_sync(pmonitor);
1.237     markus    602:
                    603:                /* Wait for the child's exit status */
1.239     markus    604:                while (waitpid(pid, &status, 0) < 0)
                    605:                        if (errno != EINTR)
                    606:                                break;
1.278     markus    607:                return (1);
1.237     markus    608:        } else {
                    609:                /* child */
                    610:
1.242     mouring   611:                close(pmonitor->m_sendfd);
1.237     markus    612:
                    613:                /* Demote the child */
                    614:                if (getuid() == 0 || geteuid() == 0)
                    615:                        privsep_preauth_child();
1.238     stevesk   616:                setproctitle("%s", "[net]");
1.237     markus    617:        }
1.278     markus    618:        return (0);
1.237     markus    619: }
                    620:
1.233     markus    621: static void
1.237     markus    622: privsep_postauth(Authctxt *authctxt)
1.231     provos    623: {
                    624:        if (authctxt->pw->pw_uid == 0 || options.use_login) {
                    625:                /* File descriptor passing is broken or root login */
1.242     mouring   626:                monitor_apply_keystate(pmonitor);
1.231     provos    627:                use_privsep = 0;
                    628:                return;
                    629:        }
1.234     markus    630:
1.231     provos    631:        /* Authentication complete */
                    632:        alarm(0);
                    633:        if (startup_pipe != -1) {
                    634:                close(startup_pipe);
                    635:                startup_pipe = -1;
                    636:        }
                    637:
                    638:        /* New socket pair */
1.242     mouring   639:        monitor_reinit(pmonitor);
1.231     provos    640:
1.242     mouring   641:        pmonitor->m_pid = fork();
                    642:        if (pmonitor->m_pid == -1)
1.231     provos    643:                fatal("fork of unprivileged child failed");
1.242     mouring   644:        else if (pmonitor->m_pid != 0) {
1.245     mpech     645:                debug2("User child is on pid %ld", (long)pmonitor->m_pid);
1.242     mouring   646:                close(pmonitor->m_recvfd);
1.290.2.2! brad      647:                buffer_clear(&loginmsg);
1.242     mouring   648:                monitor_child_postauth(pmonitor);
1.231     provos    649:
                    650:                /* NEVERREACHED */
                    651:                exit(0);
                    652:        }
                    653:
1.242     mouring   654:        close(pmonitor->m_sendfd);
1.231     provos    655:
                    656:        /* Demote the private keys to public keys. */
                    657:        demote_sensitive_data();
                    658:
                    659:        /* Drop privileges */
                    660:        do_setusercontext(authctxt->pw);
                    661:
                    662:        /* It is safe now to apply the key state */
1.242     mouring   663:        monitor_apply_keystate(pmonitor);
1.231     provos    664: }
                    665:
1.200     itojun    666: static char *
1.134     markus    667: list_hostkey_types(void)
                    668: {
1.223     markus    669:        Buffer b;
1.281     jakob     670:        const char *p;
                    671:        char *ret;
1.134     markus    672:        int i;
1.223     markus    673:
                    674:        buffer_init(&b);
1.217     deraadt   675:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    676:                Key *key = sensitive_data.host_keys[i];
                    677:                if (key == NULL)
                    678:                        continue;
1.214     deraadt   679:                switch (key->type) {
1.134     markus    680:                case KEY_RSA:
                    681:                case KEY_DSA:
1.223     markus    682:                        if (buffer_len(&b) > 0)
                    683:                                buffer_append(&b, ",", 1);
                    684:                        p = key_ssh_name(key);
                    685:                        buffer_append(&b, p, strlen(p));
1.134     markus    686:                        break;
                    687:                }
                    688:        }
1.223     markus    689:        buffer_append(&b, "\0", 1);
1.281     jakob     690:        ret = xstrdup(buffer_ptr(&b));
1.223     markus    691:        buffer_free(&b);
1.281     jakob     692:        debug("list_hostkey_types: %s", ret);
                    693:        return ret;
1.134     markus    694: }
                    695:
1.231     provos    696: Key *
1.134     markus    697: get_hostkey_by_type(int type)
                    698: {
                    699:        int i;
1.250     deraadt   700:
1.217     deraadt   701:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    702:                Key *key = sensitive_data.host_keys[i];
                    703:                if (key != NULL && key->type == type)
                    704:                        return key;
                    705:        }
                    706:        return NULL;
1.96      markus    707: }
                    708:
1.231     provos    709: Key *
                    710: get_hostkey_by_index(int ind)
                    711: {
                    712:        if (ind < 0 || ind >= options.num_host_key_files)
                    713:                return (NULL);
                    714:        return (sensitive_data.host_keys[ind]);
                    715: }
                    716:
                    717: int
                    718: get_hostkey_index(Key *key)
                    719: {
                    720:        int i;
1.250     deraadt   721:
1.231     provos    722:        for (i = 0; i < options.num_host_key_files; i++) {
                    723:                if (key == sensitive_data.host_keys[i])
                    724:                        return (i);
                    725:        }
                    726:        return (-1);
                    727: }
                    728:
1.124     markus    729: /*
                    730:  * returns 1 if connection should be dropped, 0 otherwise.
                    731:  * dropping starts at connection #max_startups_begin with a probability
                    732:  * of (max_startups_rate/100). the probability increases linearly until
                    733:  * all connections are dropped for startups > max_startups
                    734:  */
1.200     itojun    735: static int
1.124     markus    736: drop_connection(int startups)
                    737: {
1.290.2.2! brad      738:        int p, r;
1.124     markus    739:
                    740:        if (startups < options.max_startups_begin)
                    741:                return 0;
                    742:        if (startups >= options.max_startups)
                    743:                return 1;
                    744:        if (options.max_startups_rate == 100)
                    745:                return 1;
                    746:
                    747:        p  = 100 - options.max_startups_rate;
                    748:        p *= startups - options.max_startups_begin;
1.290.2.2! brad      749:        p /= options.max_startups - options.max_startups_begin;
1.124     markus    750:        p += options.max_startups_rate;
1.290.2.2! brad      751:        r = arc4random() % 100;
1.124     markus    752:
1.290.2.2! brad      753:        debug("drop_connection: p %d, r %d", p, r);
1.124     markus    754:        return (r < p) ? 1 : 0;
                    755: }
                    756:
1.215     markus    757: static void
                    758: usage(void)
                    759: {
1.290     markus    760:        fprintf(stderr, "%s, %s\n",
1.280     markus    761:            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.289     markus    762:        fprintf(stderr,
                    763: "usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
                    764: "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
                    765:        );
1.215     markus    766:        exit(1);
                    767: }
                    768:
1.290.2.1  brad      769: static void
                    770: send_rexec_state(int fd, Buffer *conf)
                    771: {
                    772:        Buffer m;
                    773:
                    774:        debug3("%s: entering fd = %d config len %d", __func__, fd,
                    775:            buffer_len(conf));
                    776:
                    777:        /*
                    778:         * Protocol from reexec master to child:
                    779:         *      string  configuration
                    780:         *      u_int   ephemeral_key_follows
                    781:         *      bignum  e               (only if ephemeral_key_follows == 1)
                    782:         *      bignum  n                       "
                    783:         *      bignum  d                       "
                    784:         *      bignum  iqmp                    "
                    785:         *      bignum  p                       "
                    786:         *      bignum  q                       "
                    787:         */
                    788:        buffer_init(&m);
                    789:        buffer_put_cstring(&m, buffer_ptr(conf));
                    790:
                    791:        if (sensitive_data.server_key != NULL &&
                    792:            sensitive_data.server_key->type == KEY_RSA1) {
                    793:                buffer_put_int(&m, 1);
                    794:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
                    795:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
                    796:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
                    797:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                    798:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
                    799:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
                    800:        } else
                    801:                buffer_put_int(&m, 0);
                    802:
                    803:        if (ssh_msg_send(fd, 0, &m) == -1)
                    804:                fatal("%s: ssh_msg_send failed", __func__);
                    805:
                    806:        buffer_free(&m);
                    807:
                    808:        debug3("%s: done", __func__);
                    809: }
                    810:
                    811: static void
                    812: recv_rexec_state(int fd, Buffer *conf)
                    813: {
                    814:        Buffer m;
                    815:        char *cp;
                    816:        u_int len;
                    817:
                    818:        debug3("%s: entering fd = %d", __func__, fd);
                    819:
                    820:        buffer_init(&m);
                    821:
                    822:        if (ssh_msg_recv(fd, &m) == -1)
                    823:                fatal("%s: ssh_msg_recv failed", __func__);
                    824:        if (buffer_get_char(&m) != 0)
                    825:                fatal("%s: rexec version mismatch", __func__);
                    826:
                    827:        cp = buffer_get_string(&m, &len);
                    828:        if (conf != NULL)
                    829:                buffer_append(conf, cp, len + 1);
                    830:        xfree(cp);
                    831:
                    832:        if (buffer_get_int(&m)) {
                    833:                if (sensitive_data.server_key != NULL)
                    834:                        key_free(sensitive_data.server_key);
                    835:                sensitive_data.server_key = key_new_private(KEY_RSA1);
                    836:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
                    837:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
                    838:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
                    839:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                    840:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
                    841:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
                    842:                rsa_generate_additional_parameters(
                    843:                    sensitive_data.server_key->rsa);
                    844:        }
                    845:        buffer_free(&m);
                    846:
                    847:        debug3("%s: done", __func__);
                    848: }
                    849:
1.65      deraadt   850: /*
                    851:  * Main program for the daemon.
                    852:  */
1.2       provos    853: int
                    854: main(int ac, char **av)
1.1       deraadt   855: {
1.64      markus    856:        extern char *optarg;
                    857:        extern int optind;
1.290.2.1  brad      858:        int opt, j, i, fdsetsz, on = 1;
                    859:        int sock_in = -1, sock_out = -1, newsock = -1;
1.107     deraadt   860:        pid_t pid;
1.75      markus    861:        socklen_t fromlen;
                    862:        fd_set *fdset;
                    863:        struct sockaddr_storage from;
1.64      markus    864:        const char *remote_ip;
                    865:        int remote_port;
                    866:        FILE *f;
1.75      markus    867:        struct addrinfo *ai;
                    868:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.283     markus    869:        char *line;
1.75      markus    870:        int listen_sock, maxfd;
1.290.2.2! brad      871:        int startup_p[2] = { -1 , -1 }, config_s[2] = { -1 , -1 };
1.120     markus    872:        int startups = 0;
1.278     markus    873:        Key *key;
1.230     provos    874:        Authctxt *authctxt;
1.151     markus    875:        int ret, key_used = 0;
1.290.2.1  brad      876:        Buffer cfg;
1.64      markus    877:
1.138     markus    878:        /* Save argv. */
1.64      markus    879:        saved_argv = av;
1.290.2.1  brad      880:        rexec_argc = ac;
1.64      markus    881:
                    882:        /* Initialize configuration options to their default values. */
                    883:        initialize_server_options(&options);
                    884:
                    885:        /* Parse command-line arguments. */
1.290.2.1  brad      886:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
1.64      markus    887:                switch (opt) {
1.75      markus    888:                case '4':
1.290.2.2! brad      889:                        options.address_family = AF_INET;
1.75      markus    890:                        break;
                    891:                case '6':
1.290.2.2! brad      892:                        options.address_family = AF_INET6;
1.75      markus    893:                        break;
1.64      markus    894:                case 'f':
                    895:                        config_file_name = optarg;
                    896:                        break;
                    897:                case 'd':
1.273     markus    898:                        if (debug_flag == 0) {
1.127     markus    899:                                debug_flag = 1;
                    900:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273     markus    901:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127     markus    902:                                options.log_level++;
1.64      markus    903:                        break;
1.135     markus    904:                case 'D':
                    905:                        no_daemon_flag = 1;
1.192     lebel     906:                        break;
                    907:                case 'e':
                    908:                        log_stderr = 1;
1.135     markus    909:                        break;
1.64      markus    910:                case 'i':
                    911:                        inetd_flag = 1;
                    912:                        break;
1.290.2.1  brad      913:                case 'r':
                    914:                        rexec_flag = 0;
                    915:                        break;
                    916:                case 'R':
                    917:                        rexeced_flag = 1;
                    918:                        inetd_flag = 1;
                    919:                        break;
1.64      markus    920:                case 'Q':
1.158     markus    921:                        /* ignored */
1.64      markus    922:                        break;
                    923:                case 'q':
                    924:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    925:                        break;
                    926:                case 'b':
                    927:                        options.server_key_bits = atoi(optarg);
                    928:                        break;
                    929:                case 'p':
1.75      markus    930:                        options.ports_from_cmdline = 1;
1.127     markus    931:                        if (options.num_ports >= MAX_PORTS) {
                    932:                                fprintf(stderr, "too many ports.\n");
                    933:                                exit(1);
                    934:                        }
1.193     stevesk   935:                        options.ports[options.num_ports++] = a2port(optarg);
                    936:                        if (options.ports[options.num_ports-1] == 0) {
                    937:                                fprintf(stderr, "Bad port number.\n");
                    938:                                exit(1);
                    939:                        }
1.64      markus    940:                        break;
                    941:                case 'g':
1.197     stevesk   942:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                    943:                                fprintf(stderr, "Invalid login grace time.\n");
                    944:                                exit(1);
                    945:                        }
1.64      markus    946:                        break;
                    947:                case 'k':
1.197     stevesk   948:                        if ((options.key_regeneration_time = convtime(optarg)) == -1) {
                    949:                                fprintf(stderr, "Invalid key regeneration interval.\n");
                    950:                                exit(1);
                    951:                        }
1.64      markus    952:                        break;
                    953:                case 'h':
1.134     markus    954:                        if (options.num_host_key_files >= MAX_HOSTKEYS) {
                    955:                                fprintf(stderr, "too many host keys.\n");
                    956:                                exit(1);
                    957:                        }
                    958:                        options.host_key_files[options.num_host_key_files++] = optarg;
1.64      markus    959:                        break;
1.203     stevesk   960:                case 't':
                    961:                        test_flag = 1;
                    962:                        break;
1.125     markus    963:                case 'u':
                    964:                        utmp_len = atoi(optarg);
1.257     stevesk   965:                        if (utmp_len > MAXHOSTNAMELEN) {
                    966:                                fprintf(stderr, "Invalid utmp length.\n");
                    967:                                exit(1);
                    968:                        }
1.125     markus    969:                        break;
1.215     markus    970:                case 'o':
1.283     markus    971:                        line = xstrdup(optarg);
                    972:                        if (process_server_config_line(&options, line,
1.215     markus    973:                            "command-line", 0) != 0)
1.217     deraadt   974:                                exit(1);
1.283     markus    975:                        xfree(line);
1.215     markus    976:                        break;
1.64      markus    977:                case '?':
                    978:                default:
1.215     markus    979:                        usage();
                    980:                        break;
1.64      markus    981:                }
                    982:        }
1.290.2.1  brad      983:        if (rexeced_flag || inetd_flag)
                    984:                rexec_flag = 0;
                    985:        if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
                    986:                fatal("sshd re-exec requires execution with an absolute path");
                    987:        if (rexeced_flag)
                    988:                closefrom(REEXEC_MIN_FREE_FD);
                    989:        else
                    990:                closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
                    991:
1.180     markus    992:        SSLeay_add_all_algorithms();
1.64      markus    993:
1.75      markus    994:        /*
                    995:         * Force logging to stderr until we have loaded the private host
                    996:         * key (unless started from inetd)
                    997:         */
1.138     markus    998:        log_init(__progname,
1.224     markus    999:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                   1000:            SYSLOG_LEVEL_INFO : options.log_level,
                   1001:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                   1002:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.261     markus   1003:            log_stderr || !inetd_flag);
1.75      markus   1004:
1.290.2.1  brad     1005:        sensitive_data.server_key = NULL;
                   1006:        sensitive_data.ssh1_host_key = NULL;
                   1007:        sensitive_data.have_ssh1_key = 0;
                   1008:        sensitive_data.have_ssh2_key = 0;
                   1009:
                   1010:        /* Fetch our configuration */
                   1011:        buffer_init(&cfg);
                   1012:        if (rexeced_flag)
                   1013:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
                   1014:        else
                   1015:                load_server_config(config_file_name, &cfg);
                   1016:
                   1017:        parse_server_config(&options,
                   1018:            rexeced_flag ? "rexec" : config_file_name, &cfg);
                   1019:
                   1020:        if (!rexec_flag)
                   1021:                buffer_free(&cfg);
1.64      markus   1022:
                   1023:        /* Fill in default values for those options not explicitly set. */
                   1024:        fill_default_server_options(&options);
                   1025:
1.290.2.2! brad     1026:        /* set default channel AF */
        !          1027:        channel_set_af(options.address_family);
        !          1028:
1.64      markus   1029:        /* Check that there are no remaining arguments. */
                   1030:        if (optind < ac) {
                   1031:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                   1032:                exit(1);
                   1033:        }
                   1034:
                   1035:        debug("sshd version %.100s", SSH_VERSION);
                   1036:
1.134     markus   1037:        /* load private host keys */
1.255     deraadt  1038:        sensitive_data.host_keys = xmalloc(options.num_host_key_files *
                   1039:            sizeof(Key *));
1.217     deraadt  1040:        for (i = 0; i < options.num_host_key_files; i++)
1.141     markus   1041:                sensitive_data.host_keys[i] = NULL;
1.134     markus   1042:
1.217     deraadt  1043:        for (i = 0; i < options.num_host_key_files; i++) {
1.179     markus   1044:                key = key_load_private(options.host_key_files[i], "", NULL);
                   1045:                sensitive_data.host_keys[i] = key;
1.134     markus   1046:                if (key == NULL) {
1.195     markus   1047:                        error("Could not load host key: %s",
                   1048:                            options.host_key_files[i]);
1.179     markus   1049:                        sensitive_data.host_keys[i] = NULL;
1.134     markus   1050:                        continue;
                   1051:                }
1.214     deraadt  1052:                switch (key->type) {
1.134     markus   1053:                case KEY_RSA1:
                   1054:                        sensitive_data.ssh1_host_key = key;
                   1055:                        sensitive_data.have_ssh1_key = 1;
                   1056:                        break;
                   1057:                case KEY_RSA:
                   1058:                case KEY_DSA:
                   1059:                        sensitive_data.have_ssh2_key = 1;
                   1060:                        break;
                   1061:                }
1.179     markus   1062:                debug("private host key: #%d type %d %s", i, key->type,
                   1063:                    key_type(key));
1.134     markus   1064:        }
                   1065:        if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1.264     itojun   1066:                logit("Disabling protocol version 1. Could not load host key");
1.108     markus   1067:                options.protocol &= ~SSH_PROTO_1;
                   1068:        }
1.134     markus   1069:        if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1.264     itojun   1070:                logit("Disabling protocol version 2. Could not load host key");
1.134     markus   1071:                options.protocol &= ~SSH_PROTO_2;
1.108     markus   1072:        }
1.162     stevesk  1073:        if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.264     itojun   1074:                logit("sshd: no hostkeys available -- exiting.");
1.64      markus   1075:                exit(1);
                   1076:        }
                   1077:
1.108     markus   1078:        /* Check certain values for sanity. */
                   1079:        if (options.protocol & SSH_PROTO_1) {
                   1080:                if (options.server_key_bits < 512 ||
                   1081:                    options.server_key_bits > 32768) {
                   1082:                        fprintf(stderr, "Bad server key size.\n");
                   1083:                        exit(1);
                   1084:                }
                   1085:                /*
                   1086:                 * Check that server and host key lengths differ sufficiently. This
                   1087:                 * is necessary to make double encryption work with rsaref. Oh, I
                   1088:                 * hate software patents. I dont know if this can go? Niels
                   1089:                 */
                   1090:                if (options.server_key_bits >
1.250     deraadt  1091:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
                   1092:                    SSH_KEY_BITS_RESERVED && options.server_key_bits <
                   1093:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1094:                    SSH_KEY_BITS_RESERVED) {
1.108     markus   1095:                        options.server_key_bits =
1.250     deraadt  1096:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1097:                            SSH_KEY_BITS_RESERVED;
1.108     markus   1098:                        debug("Forcing server key to %d bits to make it differ from host key.",
                   1099:                            options.server_key_bits);
                   1100:                }
1.244     markus   1101:        }
                   1102:
                   1103:        if (use_privsep) {
                   1104:                struct passwd *pw;
                   1105:                struct stat st;
                   1106:
                   1107:                if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
                   1108:                        fatal("Privilege separation user %s does not exist",
                   1109:                            SSH_PRIVSEP_USER);
                   1110:                if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
                   1111:                    (S_ISDIR(st.st_mode) == 0))
                   1112:                        fatal("Missing privilege separation directory: %s",
1.247     stevesk  1113:                            _PATH_PRIVSEP_CHROOT_DIR);
                   1114:                if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262     markus   1115:                        fatal("%s must be owned by root and not group or "
                   1116:                            "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.108     markus   1117:        }
1.203     stevesk  1118:
                   1119:        /* Configuration looks good, so exit if in test mode. */
                   1120:        if (test_flag)
                   1121:                exit(0);
1.108     markus   1122:
1.290.2.1  brad     1123:        if (rexec_flag) {
                   1124:                rexec_argv = xmalloc(sizeof(char *) * (rexec_argc + 2));
                   1125:                for (i = 0; i < rexec_argc; i++) {
                   1126:                        debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
                   1127:                        rexec_argv[i] = saved_argv[i];
                   1128:                }
                   1129:                rexec_argv[rexec_argc] = "-R";
                   1130:                rexec_argv[rexec_argc + 1] = NULL;
                   1131:        }
                   1132:
1.108     markus   1133:        /* Initialize the log (it is reinitialized below in case we forked). */
1.290.2.2! brad     1134:        if (debug_flag && (!inetd_flag || rexeced_flag))
1.64      markus   1135:                log_stderr = 1;
1.138     markus   1136:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1137:
1.108     markus   1138:        /*
                   1139:         * If not in debugging mode, and not started from inetd, disconnect
                   1140:         * from the controlling terminal, and fork.  The original process
                   1141:         * exits.
                   1142:         */
1.135     markus   1143:        if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.1       deraadt  1144: #ifdef TIOCNOTTY
1.64      markus   1145:                int fd;
1.1       deraadt  1146: #endif /* TIOCNOTTY */
1.64      markus   1147:                if (daemon(0, 0) < 0)
                   1148:                        fatal("daemon() failed: %.200s", strerror(errno));
                   1149:
                   1150:                /* Disconnect from the controlling tty. */
1.1       deraadt  1151: #ifdef TIOCNOTTY
1.165     itojun   1152:                fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64      markus   1153:                if (fd >= 0) {
                   1154:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                   1155:                        close(fd);
                   1156:                }
                   1157: #endif /* TIOCNOTTY */
                   1158:        }
                   1159:        /* Reinitialize the log (because of the fork above). */
1.138     markus   1160:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1161:
                   1162:        /* Initialize the random number generator. */
                   1163:        arc4random_stir();
                   1164:
                   1165:        /* Chdir to the root directory so that the current disk can be
                   1166:           unmounted if desired. */
                   1167:        chdir("/");
1.217     deraadt  1168:
1.178     markus   1169:        /* ignore SIGPIPE */
                   1170:        signal(SIGPIPE, SIG_IGN);
1.64      markus   1171:
                   1172:        /* Start listening for a socket, unless started from inetd. */
                   1173:        if (inetd_flag) {
1.290.2.1  brad     1174:                int fd;
                   1175:
1.123     djm      1176:                startup_pipe = -1;
1.290.2.1  brad     1177:                if (rexeced_flag) {
                   1178:                        close(REEXEC_CONFIG_PASS_FD);
                   1179:                        sock_in = sock_out = dup(STDIN_FILENO);
                   1180:                        if (!debug_flag) {
                   1181:                                startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
                   1182:                                close(REEXEC_STARTUP_PIPE_FD);
                   1183:                        }
                   1184:                } else {
                   1185:                        sock_in = dup(STDIN_FILENO);
                   1186:                        sock_out = dup(STDOUT_FILENO);
                   1187:                }
1.108     markus   1188:                /*
                   1189:                 * We intentionally do not close the descriptors 0, 1, and 2
1.290.2.1  brad     1190:                 * as our code for setting the descriptors won't work if
1.108     markus   1191:                 * ttyfd happens to be one of those.
                   1192:                 */
1.290.2.1  brad     1193:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1194:                        dup2(fd, STDIN_FILENO);
                   1195:                        dup2(fd, STDOUT_FILENO);
                   1196:                        if (fd > STDOUT_FILENO)
                   1197:                                close(fd);
                   1198:                }
1.64      markus   1199:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1.290.2.1  brad     1200:                if ((options.protocol & SSH_PROTO_1) &&
                   1201:                    sensitive_data.server_key == NULL)
1.174     deraadt  1202:                        generate_ephemeral_server_key();
1.64      markus   1203:        } else {
1.75      markus   1204:                for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                   1205:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1206:                                continue;
                   1207:                        if (num_listen_socks >= MAX_LISTEN_SOCKS)
                   1208:                                fatal("Too many listen sockets. "
                   1209:                                    "Enlarge MAX_LISTEN_SOCKS");
1.290.2.2! brad     1210:                        if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1.75      markus   1211:                            ntop, sizeof(ntop), strport, sizeof(strport),
1.290.2.2! brad     1212:                            NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
        !          1213:                                error("getnameinfo failed: %.100s",
        !          1214:                                    (ret != EAI_SYSTEM) ? gai_strerror(ret) :
        !          1215:                                    strerror(errno));
1.75      markus   1216:                                continue;
                   1217:                        }
                   1218:                        /* Create socket for listening. */
1.265     markus   1219:                        listen_sock = socket(ai->ai_family, ai->ai_socktype,
                   1220:                            ai->ai_protocol);
1.75      markus   1221:                        if (listen_sock < 0) {
                   1222:                                /* kernel may not support ipv6 */
                   1223:                                verbose("socket: %.100s", strerror(errno));
                   1224:                                continue;
                   1225:                        }
1.290.2.1  brad     1226:                        if (set_nonblock(listen_sock) == -1) {
1.286     markus   1227:                                close(listen_sock);
                   1228:                                continue;
                   1229:                        }
1.75      markus   1230:                        /*
1.258     stevesk  1231:                         * Set socket options.
                   1232:                         * Allow local port reuse in TIME_WAIT.
1.75      markus   1233:                         */
1.258     stevesk  1234:                        if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                   1235:                            &on, sizeof(on)) == -1)
                   1236:                                error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1.75      markus   1237:
                   1238:                        debug("Bind to port %s on %s.", strport, ntop);
                   1239:
                   1240:                        /* Bind the socket to the desired port. */
                   1241:                        if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1242:                                error("Bind to port %s on %s failed: %.200s.",
                   1243:                                    strport, ntop, strerror(errno));
                   1244:                                close(listen_sock);
                   1245:                                continue;
                   1246:                        }
                   1247:                        listen_socks[num_listen_socks] = listen_sock;
                   1248:                        num_listen_socks++;
                   1249:
                   1250:                        /* Start listening on the port. */
1.264     itojun   1251:                        logit("Server listening on %s port %s.", ntop, strport);
1.282     markus   1252:                        if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1.75      markus   1253:                                fatal("listen: %.100s", strerror(errno));
                   1254:
1.64      markus   1255:                }
1.75      markus   1256:                freeaddrinfo(options.listen_addrs);
                   1257:
                   1258:                if (!num_listen_socks)
                   1259:                        fatal("Cannot bind any address.");
                   1260:
1.201     markus   1261:                if (options.protocol & SSH_PROTO_1)
                   1262:                        generate_ephemeral_server_key();
                   1263:
                   1264:                /*
                   1265:                 * Arrange to restart on SIGHUP.  The handler needs
                   1266:                 * listen_sock.
                   1267:                 */
                   1268:                signal(SIGHUP, sighup_handler);
                   1269:
                   1270:                signal(SIGTERM, sigterm_handler);
                   1271:                signal(SIGQUIT, sigterm_handler);
                   1272:
                   1273:                /* Arrange SIGCHLD to be caught. */
                   1274:                signal(SIGCHLD, main_sigchld_handler);
                   1275:
                   1276:                /* Write out the pid file after the sigterm handler is setup */
1.64      markus   1277:                if (!debug_flag) {
1.66      markus   1278:                        /*
1.136     todd     1279:                         * Record our pid in /var/run/sshd.pid to make it
                   1280:                         * easier to kill the correct sshd.  We don't want to
                   1281:                         * do this before the bind above because the bind will
1.66      markus   1282:                         * fail if there already is a daemon, and this will
                   1283:                         * overwrite any old pid in the file.
                   1284:                         */
1.112     markus   1285:                        f = fopen(options.pid_file, "w");
1.270     djm      1286:                        if (f == NULL) {
                   1287:                                error("Couldn't create pid file \"%s\": %s",
                   1288:                                    options.pid_file, strerror(errno));
                   1289:                        } else {
1.245     mpech    1290:                                fprintf(f, "%ld\n", (long) getpid());
1.64      markus   1291:                                fclose(f);
                   1292:                        }
                   1293:                }
                   1294:
1.75      markus   1295:                /* setup fd set for listen */
1.120     markus   1296:                fdset = NULL;
1.75      markus   1297:                maxfd = 0;
                   1298:                for (i = 0; i < num_listen_socks; i++)
                   1299:                        if (listen_socks[i] > maxfd)
                   1300:                                maxfd = listen_socks[i];
1.120     markus   1301:                /* pipes connected to unauthenticated childs */
                   1302:                startup_pipes = xmalloc(options.max_startups * sizeof(int));
                   1303:                for (i = 0; i < options.max_startups; i++)
                   1304:                        startup_pipes[i] = -1;
1.75      markus   1305:
1.66      markus   1306:                /*
                   1307:                 * Stay listening for connections until the system crashes or
                   1308:                 * the daemon is killed with a signal.
                   1309:                 */
1.64      markus   1310:                for (;;) {
                   1311:                        if (received_sighup)
                   1312:                                sighup_restart();
1.120     markus   1313:                        if (fdset != NULL)
                   1314:                                xfree(fdset);
1.148     markus   1315:                        fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1.120     markus   1316:                        fdset = (fd_set *)xmalloc(fdsetsz);
1.75      markus   1317:                        memset(fdset, 0, fdsetsz);
1.120     markus   1318:
1.75      markus   1319:                        for (i = 0; i < num_listen_socks; i++)
                   1320:                                FD_SET(listen_socks[i], fdset);
1.120     markus   1321:                        for (i = 0; i < options.max_startups; i++)
                   1322:                                if (startup_pipes[i] != -1)
                   1323:                                        FD_SET(startup_pipes[i], fdset);
                   1324:
                   1325:                        /* Wait in select until there is a connection. */
1.151     markus   1326:                        ret = select(maxfd+1, fdset, NULL, NULL, NULL);
                   1327:                        if (ret < 0 && errno != EINTR)
                   1328:                                error("select: %.100s", strerror(errno));
1.199     markus   1329:                        if (received_sigterm) {
1.264     itojun   1330:                                logit("Received signal %d; terminating.",
1.213     itojun   1331:                                    (int) received_sigterm);
1.199     markus   1332:                                close_listen_socks();
                   1333:                                unlink(options.pid_file);
                   1334:                                exit(255);
                   1335:                        }
1.151     markus   1336:                        if (key_used && key_do_regen) {
1.174     deraadt  1337:                                generate_ephemeral_server_key();
1.151     markus   1338:                                key_used = 0;
                   1339:                                key_do_regen = 0;
                   1340:                        }
                   1341:                        if (ret < 0)
1.75      markus   1342:                                continue;
1.151     markus   1343:
1.120     markus   1344:                        for (i = 0; i < options.max_startups; i++)
                   1345:                                if (startup_pipes[i] != -1 &&
                   1346:                                    FD_ISSET(startup_pipes[i], fdset)) {
                   1347:                                        /*
                   1348:                                         * the read end of the pipe is ready
                   1349:                                         * if the child has closed the pipe
1.143     markus   1350:                                         * after successful authentication
1.120     markus   1351:                                         * or if the child has died
                   1352:                                         */
                   1353:                                        close(startup_pipes[i]);
                   1354:                                        startup_pipes[i] = -1;
                   1355:                                        startups--;
                   1356:                                }
1.75      markus   1357:                        for (i = 0; i < num_listen_socks; i++) {
                   1358:                                if (!FD_ISSET(listen_socks[i], fdset))
1.70      provos   1359:                                        continue;
1.120     markus   1360:                                fromlen = sizeof(from);
                   1361:                                newsock = accept(listen_socks[i], (struct sockaddr *)&from,
                   1362:                                    &fromlen);
                   1363:                                if (newsock < 0) {
                   1364:                                        if (errno != EINTR && errno != EWOULDBLOCK)
                   1365:                                                error("accept: %.100s", strerror(errno));
1.286     markus   1366:                                        continue;
                   1367:                                }
1.290.2.1  brad     1368:                                if (unset_nonblock(newsock) == -1) {
1.286     markus   1369:                                        close(newsock);
1.120     markus   1370:                                        continue;
                   1371:                                }
1.124     markus   1372:                                if (drop_connection(startups) == 1) {
                   1373:                                        debug("drop connection #%d", startups);
1.120     markus   1374:                                        close(newsock);
                   1375:                                        continue;
                   1376:                                }
                   1377:                                if (pipe(startup_p) == -1) {
                   1378:                                        close(newsock);
                   1379:                                        continue;
                   1380:                                }
                   1381:
1.290.2.1  brad     1382:                                if (rexec_flag && socketpair(AF_UNIX,
                   1383:                                    SOCK_STREAM, 0, config_s) == -1) {
                   1384:                                        error("reexec socketpair: %s",
                   1385:                                            strerror(errno));
                   1386:                                        close(newsock);
                   1387:                                        close(startup_p[0]);
                   1388:                                        close(startup_p[1]);
                   1389:                                        continue;
                   1390:                                }
                   1391:
1.120     markus   1392:                                for (j = 0; j < options.max_startups; j++)
                   1393:                                        if (startup_pipes[j] == -1) {
                   1394:                                                startup_pipes[j] = startup_p[0];
                   1395:                                                if (maxfd < startup_p[0])
                   1396:                                                        maxfd = startup_p[0];
                   1397:                                                startups++;
                   1398:                                                break;
                   1399:                                        }
1.161     stevesk  1400:
1.66      markus   1401:                                /*
1.120     markus   1402:                                 * Got connection.  Fork a child to handle it, unless
                   1403:                                 * we are in debugging mode.
1.66      markus   1404:                                 */
1.120     markus   1405:                                if (debug_flag) {
1.66      markus   1406:                                        /*
1.120     markus   1407:                                         * In debugging mode.  Close the listening
                   1408:                                         * socket, and start processing the
                   1409:                                         * connection without forking.
1.66      markus   1410:                                         */
1.120     markus   1411:                                        debug("Server will not fork when running in debugging mode.");
1.75      markus   1412:                                        close_listen_socks();
1.64      markus   1413:                                        sock_in = newsock;
                   1414:                                        sock_out = newsock;
1.290.2.1  brad     1415:                                        close(startup_p[0]);
                   1416:                                        close(startup_p[1]);
1.122     deraadt  1417:                                        startup_pipe = -1;
1.120     markus   1418:                                        pid = getpid();
1.290.2.1  brad     1419:                                        if (rexec_flag) {
                   1420:                                                send_rexec_state(config_s[0],
                   1421:                                                    &cfg);
                   1422:                                                close(config_s[0]);
                   1423:                                        }
1.64      markus   1424:                                        break;
1.120     markus   1425:                                } else {
                   1426:                                        /*
                   1427:                                         * Normal production daemon.  Fork, and have
                   1428:                                         * the child process the connection. The
                   1429:                                         * parent continues listening.
                   1430:                                         */
                   1431:                                        if ((pid = fork()) == 0) {
                   1432:                                                /*
                   1433:                                                 * Child.  Close the listening and max_startup
                   1434:                                                 * sockets.  Start using the accepted socket.
                   1435:                                                 * Reinitialize logging (since our pid has
                   1436:                                                 * changed).  We break out of the loop to handle
                   1437:                                                 * the connection.
                   1438:                                                 */
                   1439:                                                startup_pipe = startup_p[1];
1.211     markus   1440:                                                close_startup_pipes();
1.120     markus   1441:                                                close_listen_socks();
                   1442:                                                sock_in = newsock;
                   1443:                                                sock_out = newsock;
1.138     markus   1444:                                                log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.290.2.2! brad     1445:                                                if (rexec_flag)
        !          1446:                                                        close(config_s[0]);
1.120     markus   1447:                                                break;
                   1448:                                        }
1.64      markus   1449:                                }
                   1450:
1.120     markus   1451:                                /* Parent.  Stay in the loop. */
                   1452:                                if (pid < 0)
                   1453:                                        error("fork: %.100s", strerror(errno));
                   1454:                                else
1.245     mpech    1455:                                        debug("Forked child %ld.", (long)pid);
1.120     markus   1456:
                   1457:                                close(startup_p[1]);
1.1       deraadt  1458:
1.290.2.1  brad     1459:                                if (rexec_flag) {
                   1460:                                        send_rexec_state(config_s[0], &cfg);
                   1461:                                        close(config_s[0]);
                   1462:                                        close(config_s[1]);
                   1463:                                }
                   1464:
1.120     markus   1465:                                /* Mark that the key has been used (it was "given" to the child). */
1.151     markus   1466:                                if ((options.protocol & SSH_PROTO_1) &&
                   1467:                                    key_used == 0) {
                   1468:                                        /* Schedule server key regeneration alarm. */
                   1469:                                        signal(SIGALRM, key_regeneration_alarm);
                   1470:                                        alarm(options.key_regeneration_time);
                   1471:                                        key_used = 1;
                   1472:                                }
1.1       deraadt  1473:
1.120     markus   1474:                                arc4random_stir();
1.1       deraadt  1475:
1.120     markus   1476:                                /* Close the new socket (the child is now taking care of it). */
                   1477:                                close(newsock);
                   1478:                        }
1.75      markus   1479:                        /* child process check (or debug mode) */
                   1480:                        if (num_listen_socks < 0)
                   1481:                                break;
1.64      markus   1482:                }
1.1       deraadt  1483:        }
                   1484:
1.64      markus   1485:        /* This is the child processing a new connection. */
1.288     markus   1486:        setproctitle("%s", "[accepted]");
1.241     millert  1487:
                   1488:        /*
                   1489:         * Create a new session and process group since the 4.4BSD
                   1490:         * setlogin() affects the entire process group.  We don't
                   1491:         * want the child to be able to affect the parent.
                   1492:         */
1.248     stevesk  1493:        if (!debug_flag && !inetd_flag && setsid() < 0)
1.241     millert  1494:                error("setsid: %.100s", strerror(errno));
1.64      markus   1495:
1.290.2.1  brad     1496:        if (rexec_flag) {
                   1497:                int fd;
                   1498:
                   1499:                debug("rexec start in %d out %d newsock %d pipe %d sock %d",
                   1500:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
                   1501:                dup2(newsock, STDIN_FILENO);
                   1502:                dup2(STDIN_FILENO, STDOUT_FILENO);
                   1503:                if (startup_pipe == -1)
                   1504:                        close(REEXEC_STARTUP_PIPE_FD);
                   1505:                else
                   1506:                        dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
                   1507:
                   1508:                dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
                   1509:                close(config_s[1]);
                   1510:                if (startup_pipe != -1)
                   1511:                        close(startup_pipe);
                   1512:
                   1513:                execv(rexec_argv[0], rexec_argv);
                   1514:
                   1515:                /* Reexec has failed, fall back and continue */
                   1516:                error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
                   1517:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
                   1518:                log_init(__progname, options.log_level,
                   1519:                    options.log_facility, log_stderr);
                   1520:
                   1521:                /* Clean up fds */
                   1522:                startup_pipe = REEXEC_STARTUP_PIPE_FD;
                   1523:                close(config_s[1]);
                   1524:                close(REEXEC_CONFIG_PASS_FD);
                   1525:                newsock = sock_out = sock_in = dup(STDIN_FILENO);
                   1526:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1527:                        dup2(fd, STDIN_FILENO);
                   1528:                        dup2(fd, STDOUT_FILENO);
                   1529:                        if (fd > STDERR_FILENO)
                   1530:                                close(fd);
                   1531:                }
                   1532:                debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
                   1533:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
                   1534:        }
                   1535:
1.66      markus   1536:        /*
                   1537:         * Disable the key regeneration alarm.  We will not regenerate the
                   1538:         * key since we are no longer in a position to give it to anyone. We
                   1539:         * will not restart on SIGHUP since it no longer makes sense.
                   1540:         */
1.64      markus   1541:        alarm(0);
                   1542:        signal(SIGALRM, SIG_DFL);
                   1543:        signal(SIGHUP, SIG_DFL);
                   1544:        signal(SIGTERM, SIG_DFL);
                   1545:        signal(SIGQUIT, SIG_DFL);
                   1546:        signal(SIGCHLD, SIG_DFL);
1.150     markus   1547:
1.284     markus   1548:        /* Set SO_KEEPALIVE if requested. */
                   1549:        if (options.tcp_keep_alive &&
1.228     stevesk  1550:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1.150     markus   1551:            sizeof(on)) < 0)
                   1552:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.64      markus   1553:
1.66      markus   1554:        /*
                   1555:         * Register our connection.  This turns encryption off because we do
                   1556:         * not have a key.
                   1557:         */
1.64      markus   1558:        packet_set_connection(sock_in, sock_out);
1.1       deraadt  1559:
1.64      markus   1560:        remote_port = get_remote_port();
                   1561:        remote_ip = get_remote_ipaddr();
1.52      markus   1562:
1.209     markus   1563: #ifdef LIBWRAP
1.64      markus   1564:        /* Check whether logins are denied from this host. */
1.290.2.1  brad     1565:        if (packet_connection_is_on_socket()) {
1.64      markus   1566:                struct request_info req;
1.37      dugsong  1567:
1.204     camield  1568:                request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1.64      markus   1569:                fromhost(&req);
1.37      dugsong  1570:
1.64      markus   1571:                if (!hosts_access(&req)) {
1.209     markus   1572:                        debug("Connection refused by tcp wrapper");
1.182     markus   1573:                        refuse(&req);
1.209     markus   1574:                        /* NOTREACHED */
                   1575:                        fatal("libwrap refuse returns");
1.64      markus   1576:                }
                   1577:        }
1.75      markus   1578: #endif /* LIBWRAP */
1.209     markus   1579:
1.64      markus   1580:        /* Log the connection. */
                   1581:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1       deraadt  1582:
1.66      markus   1583:        /*
                   1584:         * We don\'t want to listen forever unless the other side
                   1585:         * successfully authenticates itself.  So we set up an alarm which is
                   1586:         * cleared after successful authentication.  A limit of zero
                   1587:         * indicates no limit. Note that we don\'t set the alarm in debugging
                   1588:         * mode; it is just annoying to have the server exit just when you
                   1589:         * are about to discover the bug.
                   1590:         */
1.64      markus   1591:        signal(SIGALRM, grace_alarm_handler);
                   1592:        if (!debug_flag)
                   1593:                alarm(options.login_grace_time);
                   1594:
1.96      markus   1595:        sshd_exchange_identification(sock_in, sock_out);
1.275     markus   1596:
1.64      markus   1597:        packet_set_nonblocking();
1.1       deraadt  1598:
1.278     markus   1599:        /* allocate authentication context */
                   1600:        authctxt = xmalloc(sizeof(*authctxt));
                   1601:        memset(authctxt, 0, sizeof(*authctxt));
                   1602:
                   1603:        /* XXX global for cleanup, access from other modules */
                   1604:        the_authctxt = authctxt;
                   1605:
1.290.2.2! brad     1606:        /* prepare buffer to collect messages to display to user after login */
        !          1607:        buffer_init(&loginmsg);
        !          1608:
1.237     markus   1609:        if (use_privsep)
1.278     markus   1610:                if (privsep_preauth(authctxt) == 1)
1.237     markus   1611:                        goto authenticated;
1.290.2.1  brad     1612:
1.77      markus   1613:        /* perform the key exchange */
                   1614:        /* authenticate user and start session */
1.98      markus   1615:        if (compat20) {
                   1616:                do_ssh2_kex();
1.278     markus   1617:                do_authentication2(authctxt);
1.98      markus   1618:        } else {
                   1619:                do_ssh1_kex();
1.278     markus   1620:                do_authentication(authctxt);
1.98      markus   1621:        }
1.237     markus   1622:        /*
                   1623:         * If we use privilege separation, the unprivileged child transfers
                   1624:         * the current keystate and exits
                   1625:         */
                   1626:        if (use_privsep) {
1.242     mouring  1627:                mm_send_keystate(pmonitor);
1.231     provos   1628:                exit(0);
1.237     markus   1629:        }
1.231     provos   1630:
                   1631:  authenticated:
1.234     markus   1632:        /*
1.231     provos   1633:         * In privilege separation, we fork another child and prepare
                   1634:         * file descriptor passing.
                   1635:         */
                   1636:        if (use_privsep) {
1.237     markus   1637:                privsep_postauth(authctxt);
                   1638:                /* the monitor process [priv] will not return */
1.231     provos   1639:                if (!compat20)
                   1640:                        destroy_sensitive_data();
                   1641:        }
1.230     provos   1642:
1.278     markus   1643:        /* Start session. */
1.230     provos   1644:        do_authenticated(authctxt);
                   1645:
1.64      markus   1646:        /* The connection has been terminated. */
                   1647:        verbose("Closing connection to %.100s", remote_ip);
                   1648:        packet_close();
1.231     provos   1649:
                   1650:        if (use_privsep)
                   1651:                mm_terminate();
                   1652:
1.64      markus   1653:        exit(0);
1.1       deraadt  1654: }
                   1655:
1.65      deraadt  1656: /*
1.229     markus   1657:  * Decrypt session_key_int using our private server key and private host key
                   1658:  * (key with larger modulus first).
                   1659:  */
1.231     provos   1660: int
1.229     markus   1661: ssh1_session_key(BIGNUM *session_key_int)
                   1662: {
                   1663:        int rsafail = 0;
                   1664:
                   1665:        if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
                   1666:                /* Server key has bigger modulus. */
                   1667:                if (BN_num_bits(sensitive_data.server_key->rsa->n) <
                   1668:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1669:                        fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                   1670:                            get_remote_ipaddr(),
                   1671:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1672:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1673:                            SSH_KEY_BITS_RESERVED);
                   1674:                }
                   1675:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1676:                    sensitive_data.server_key->rsa) <= 0)
                   1677:                        rsafail++;
                   1678:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1679:                    sensitive_data.ssh1_host_key->rsa) <= 0)
                   1680:                        rsafail++;
                   1681:        } else {
                   1682:                /* Host key has bigger modulus (or they are equal). */
                   1683:                if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
                   1684:                    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1685:                        fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
                   1686:                            get_remote_ipaddr(),
                   1687:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1688:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1689:                            SSH_KEY_BITS_RESERVED);
                   1690:                }
                   1691:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1692:                    sensitive_data.ssh1_host_key->rsa) < 0)
                   1693:                        rsafail++;
                   1694:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1695:                    sensitive_data.server_key->rsa) < 0)
                   1696:                        rsafail++;
                   1697:        }
                   1698:        return (rsafail);
                   1699: }
                   1700: /*
1.77      markus   1701:  * SSH1 key exchange
1.65      deraadt  1702:  */
1.200     itojun   1703: static void
1.142     markus   1704: do_ssh1_kex(void)
1.1       deraadt  1705: {
1.64      markus   1706:        int i, len;
1.159     markus   1707:        int rsafail = 0;
1.64      markus   1708:        BIGNUM *session_key_int;
1.140     markus   1709:        u_char session_key[SSH_SESSION_KEY_LENGTH];
                   1710:        u_char cookie[8];
                   1711:        u_int cipher_type, auth_mask, protocol_flags;
1.254     deraadt  1712:        u_int32_t rnd = 0;
1.64      markus   1713:
1.66      markus   1714:        /*
                   1715:         * Generate check bytes that the client must send back in the user
                   1716:         * packet in order for it to be accepted; this is used to defy ip
                   1717:         * spoofing attacks.  Note that this only works against somebody
                   1718:         * doing IP spoofing from a remote machine; any machine on the local
                   1719:         * network can still see outgoing packets and catch the random
                   1720:         * cookie.  This only affects rhosts authentication, and this is one
                   1721:         * of the reasons why it is inherently insecure.
                   1722:         */
1.64      markus   1723:        for (i = 0; i < 8; i++) {
                   1724:                if (i % 4 == 0)
1.254     deraadt  1725:                        rnd = arc4random();
                   1726:                cookie[i] = rnd & 0xff;
                   1727:                rnd >>= 8;
1.64      markus   1728:        }
                   1729:
1.66      markus   1730:        /*
                   1731:         * Send our public key.  We include in the packet 64 bits of random
                   1732:         * data that must be matched in the reply in order to prevent IP
                   1733:         * spoofing.
                   1734:         */
1.64      markus   1735:        packet_start(SSH_SMSG_PUBLIC_KEY);
                   1736:        for (i = 0; i < 8; i++)
1.77      markus   1737:                packet_put_char(cookie[i]);
1.64      markus   1738:
                   1739:        /* Store our public server RSA key. */
1.134     markus   1740:        packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
                   1741:        packet_put_bignum(sensitive_data.server_key->rsa->e);
                   1742:        packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64      markus   1743:
                   1744:        /* Store our public host RSA key. */
1.134     markus   1745:        packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
                   1746:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
                   1747:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64      markus   1748:
                   1749:        /* Put protocol flags. */
                   1750:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   1751:
                   1752:        /* Declare which ciphers we support. */
1.131     markus   1753:        packet_put_int(cipher_mask_ssh1(0));
1.64      markus   1754:
                   1755:        /* Declare supported authentication types. */
                   1756:        auth_mask = 0;
                   1757:        if (options.rhosts_rsa_authentication)
                   1758:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   1759:        if (options.rsa_authentication)
                   1760:                auth_mask |= 1 << SSH_AUTH_RSA;
1.196     markus   1761:        if (options.challenge_response_authentication == 1)
1.64      markus   1762:                auth_mask |= 1 << SSH_AUTH_TIS;
                   1763:        if (options.password_authentication)
                   1764:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   1765:        packet_put_int(auth_mask);
                   1766:
                   1767:        /* Send the packet and wait for it to be sent. */
                   1768:        packet_send();
                   1769:        packet_write_wait();
                   1770:
1.134     markus   1771:        debug("Sent %d bit server key and %d bit host key.",
                   1772:            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1773:            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64      markus   1774:
                   1775:        /* Read clients reply (cipher type and session key). */
1.222     markus   1776:        packet_read_expect(SSH_CMSG_SESSION_KEY);
1.64      markus   1777:
1.69      markus   1778:        /* Get cipher type and check whether we accept this. */
1.64      markus   1779:        cipher_type = packet_get_char();
1.69      markus   1780:
1.131     markus   1781:        if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69      markus   1782:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   1783:
                   1784:        /* Get check bytes from the packet.  These must match those we
                   1785:           sent earlier with the public key packet. */
                   1786:        for (i = 0; i < 8; i++)
1.77      markus   1787:                if (cookie[i] != packet_get_char())
1.64      markus   1788:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   1789:
                   1790:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   1791:
                   1792:        /* Get the encrypted integer. */
1.218     markus   1793:        if ((session_key_int = BN_new()) == NULL)
                   1794:                fatal("do_ssh1_kex: BN_new failed");
1.221     markus   1795:        packet_get_bignum(session_key_int);
1.64      markus   1796:
                   1797:        protocol_flags = packet_get_int();
                   1798:        packet_set_protocol_flags(protocol_flags);
1.220     markus   1799:        packet_check_eom();
1.64      markus   1800:
1.229     markus   1801:        /* Decrypt session_key_int using host/server keys */
1.231     provos   1802:        rsafail = PRIVSEP(ssh1_session_key(session_key_int));
                   1803:
1.66      markus   1804:        /*
                   1805:         * Extract session key from the decrypted integer.  The key is in the
                   1806:         * least significant 256 bits of the integer; the first byte of the
                   1807:         * key is in the highest bits.
                   1808:         */
1.159     markus   1809:        if (!rsafail) {
                   1810:                BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   1811:                len = BN_num_bytes(session_key_int);
                   1812:                if (len < 0 || len > sizeof(session_key)) {
                   1813:                        error("do_connection: bad session key len from %s: "
1.165     itojun   1814:                            "session_key_int %d > sizeof(session_key) %lu",
                   1815:                            get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1.159     markus   1816:                        rsafail++;
                   1817:                } else {
                   1818:                        memset(session_key, 0, sizeof(session_key));
                   1819:                        BN_bn2bin(session_key_int,
                   1820:                            session_key + sizeof(session_key) - len);
1.169     markus   1821:
1.290.2.1  brad     1822:                        derive_ssh1_session_id(
1.169     markus   1823:                            sensitive_data.ssh1_host_key->rsa->n,
1.290.2.1  brad     1824:                            sensitive_data.server_key->rsa->n,
                   1825:                            cookie, session_id);
1.169     markus   1826:                        /*
                   1827:                         * Xor the first 16 bytes of the session key with the
                   1828:                         * session id.
                   1829:                         */
                   1830:                        for (i = 0; i < 16; i++)
                   1831:                                session_key[i] ^= session_id[i];
1.159     markus   1832:                }
                   1833:        }
                   1834:        if (rsafail) {
1.169     markus   1835:                int bytes = BN_num_bytes(session_key_int);
1.227     stevesk  1836:                u_char *buf = xmalloc(bytes);
1.169     markus   1837:                MD5_CTX md;
                   1838:
1.264     itojun   1839:                logit("do_connection: generating a fake encryption key");
1.169     markus   1840:                BN_bn2bin(session_key_int, buf);
                   1841:                MD5_Init(&md);
                   1842:                MD5_Update(&md, buf, bytes);
                   1843:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1844:                MD5_Final(session_key, &md);
                   1845:                MD5_Init(&md);
                   1846:                MD5_Update(&md, session_key, 16);
                   1847:                MD5_Update(&md, buf, bytes);
                   1848:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1849:                MD5_Final(session_key + 16, &md);
                   1850:                memset(buf, 0, bytes);
                   1851:                xfree(buf);
1.170     markus   1852:                for (i = 0; i < 16; i++)
                   1853:                        session_id[i] = session_key[i] ^ session_key[i + 16];
1.159     markus   1854:        }
1.231     provos   1855:        /* Destroy the private and public keys. No longer. */
1.169     markus   1856:        destroy_sensitive_data();
                   1857:
1.231     provos   1858:        if (use_privsep)
                   1859:                mm_ssh1_session_id(session_id);
                   1860:
1.77      markus   1861:        /* Destroy the decrypted integer.  It is no longer needed. */
                   1862:        BN_clear_free(session_key_int);
1.64      markus   1863:
                   1864:        /* Set the session key.  From this on all communications will be encrypted. */
                   1865:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   1866:
                   1867:        /* Destroy our copy of the session key.  It is no longer needed. */
                   1868:        memset(session_key, 0, sizeof(session_key));
                   1869:
                   1870:        debug("Received session key; encryption turned on.");
                   1871:
1.243     deraadt  1872:        /* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
1.64      markus   1873:        packet_start(SSH_SMSG_SUCCESS);
                   1874:        packet_send();
                   1875:        packet_write_wait();
1.98      markus   1876: }
                   1877:
                   1878: /*
                   1879:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   1880:  */
1.200     itojun   1881: static void
1.142     markus   1882: do_ssh2_kex(void)
1.98      markus   1883: {
                   1884:        Kex *kex;
1.102     markus   1885:
                   1886:        if (options.ciphers != NULL) {
1.105     markus   1887:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102     markus   1888:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1.166     markus   1889:        }
1.184     stevesk  1890:        myproposal[PROPOSAL_ENC_ALGS_CTOS] =
                   1891:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
                   1892:        myproposal[PROPOSAL_ENC_ALGS_STOC] =
                   1893:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
                   1894:
1.166     markus   1895:        if (options.macs != NULL) {
                   1896:                myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   1897:                myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1.246     markus   1898:        }
                   1899:        if (!options.compression) {
                   1900:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   1901:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.102     markus   1902:        }
1.134     markus   1903:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
                   1904:
1.189     markus   1905:        /* start key exchange */
1.188     markus   1906:        kex = kex_setup(myproposal);
1.263     markus   1907:        kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.290.2.1  brad     1908:        kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.263     markus   1909:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.186     markus   1910:        kex->server = 1;
                   1911:        kex->client_version_string=client_version_string;
                   1912:        kex->server_version_string=server_version_string;
                   1913:        kex->load_host_key=&get_hostkey_by_type;
1.231     provos   1914:        kex->host_key_index=&get_hostkey_index;
1.129     provos   1915:
1.189     markus   1916:        xxx_kex = kex;
                   1917:
1.190     markus   1918:        dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1.187     markus   1919:
                   1920:        session_id2 = kex->session_id;
                   1921:        session_id2_len = kex->session_id_len;
1.129     provos   1922:
                   1923: #ifdef DEBUG_KEXDH
                   1924:        /* send 1st encrypted/maced/compressed message */
                   1925:        packet_start(SSH2_MSG_IGNORE);
                   1926:        packet_put_cstring("markus");
                   1927:        packet_send();
                   1928:        packet_write_wait();
                   1929: #endif
1.186     markus   1930:        debug("KEX done");
1.278     markus   1931: }
                   1932:
                   1933: /* server specific fatal cleanup */
                   1934: void
                   1935: cleanup_exit(int i)
                   1936: {
                   1937:        if (the_authctxt)
                   1938:                do_cleanup(the_authctxt);
                   1939:        _exit(i);
1.1       deraadt  1940: }