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

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.317   ! djm        45: RCSID("$OpenBSD: sshd.c,v 1.316 2005/10/30 08:29:29 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.294     djm        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.294     djm        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.296     djm        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.294     djm       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.299     dtucker   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.311     djm       356:        u_int i;
                    357:        int mismatch;
1.96      markus    358:        int remote_major, remote_minor;
1.102     markus    359:        int major, minor;
1.96      markus    360:        char *s;
                    361:        char buf[256];                  /* Must not be larger than remote_version. */
                    362:        char remote_version[256];       /* Must be at least as big as buf. */
                    363:
1.103     markus    364:        if ((options.protocol & SSH_PROTO_1) &&
                    365:            (options.protocol & SSH_PROTO_2)) {
1.102     markus    366:                major = PROTOCOL_MAJOR_1;
                    367:                minor = 99;
                    368:        } else if (options.protocol & SSH_PROTO_2) {
                    369:                major = PROTOCOL_MAJOR_2;
                    370:                minor = PROTOCOL_MINOR_2;
                    371:        } else {
                    372:                major = PROTOCOL_MAJOR_1;
                    373:                minor = PROTOCOL_MINOR_1;
                    374:        }
                    375:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
1.96      markus    376:        server_version_string = xstrdup(buf);
                    377:
1.272     markus    378:        /* Send our protocol version identification. */
                    379:        if (atomicio(vwrite, sock_out, server_version_string,
                    380:            strlen(server_version_string))
                    381:            != strlen(server_version_string)) {
                    382:                logit("Could not write ident string to %s", get_remote_ipaddr());
1.278     markus    383:                cleanup_exit(255);
1.272     markus    384:        }
                    385:
                    386:        /* Read other sides version identification. */
                    387:        memset(buf, 0, sizeof(buf));
                    388:        for (i = 0; i < sizeof(buf) - 1; i++) {
                    389:                if (atomicio(read, sock_in, &buf[i], 1) != 1) {
                    390:                        logit("Did not receive identification string from %s",
                    391:                            get_remote_ipaddr());
1.278     markus    392:                        cleanup_exit(255);
1.96      markus    393:                }
1.272     markus    394:                if (buf[i] == '\r') {
                    395:                        buf[i] = 0;
                    396:                        /* Kludge for F-Secure Macintosh < 1.0.2 */
                    397:                        if (i == 12 &&
                    398:                            strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
1.96      markus    399:                                break;
1.272     markus    400:                        continue;
                    401:                }
                    402:                if (buf[i] == '\n') {
                    403:                        buf[i] = 0;
                    404:                        break;
1.96      markus    405:                }
                    406:        }
1.272     markus    407:        buf[sizeof(buf) - 1] = 0;
                    408:        client_version_string = xstrdup(buf);
1.96      markus    409:
                    410:        /*
                    411:         * Check that the versions match.  In future this might accept
                    412:         * several versions and set appropriate flags to handle them.
                    413:         */
                    414:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    415:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    416:                s = "Protocol mismatch.\n";
1.271     deraadt   417:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    418:                close(sock_in);
                    419:                close(sock_out);
1.264     itojun    420:                logit("Bad protocol version identification '%.100s' from %s",
1.96      markus    421:                    client_version_string, get_remote_ipaddr());
1.278     markus    422:                cleanup_exit(255);
1.96      markus    423:        }
                    424:        debug("Client protocol version %d.%d; client software version %.100s",
1.217     deraadt   425:            remote_major, remote_minor, remote_version);
1.96      markus    426:
1.98      markus    427:        compat_datafellows(remote_version);
1.260     mickey    428:
                    429:        if (datafellows & SSH_BUG_PROBE) {
1.264     itojun    430:                logit("probed from %s with %s.  Don't panic.",
1.260     mickey    431:                    get_remote_ipaddr(), client_version_string);
1.278     markus    432:                cleanup_exit(255);
1.260     mickey    433:        }
1.175     deraadt   434:
                    435:        if (datafellows & SSH_BUG_SCANNER) {
1.264     itojun    436:                logit("scanned from %s with %s.  Don't panic.",
1.175     deraadt   437:                    get_remote_ipaddr(), client_version_string);
1.278     markus    438:                cleanup_exit(255);
1.175     deraadt   439:        }
1.98      markus    440:
1.102     markus    441:        mismatch = 0;
1.214     deraadt   442:        switch (remote_major) {
1.96      markus    443:        case 1:
1.108     markus    444:                if (remote_minor == 99) {
                    445:                        if (options.protocol & SSH_PROTO_2)
                    446:                                enable_compat20();
                    447:                        else
                    448:                                mismatch = 1;
                    449:                        break;
                    450:                }
1.102     markus    451:                if (!(options.protocol & SSH_PROTO_1)) {
                    452:                        mismatch = 1;
                    453:                        break;
                    454:                }
1.96      markus    455:                if (remote_minor < 3) {
1.121     provos    456:                        packet_disconnect("Your ssh version is too old and "
1.96      markus    457:                            "is no longer supported.  Please install a newer version.");
                    458:                } else if (remote_minor == 3) {
                    459:                        /* note that this disables agent-forwarding */
                    460:                        enable_compat13();
                    461:                }
1.102     markus    462:                break;
1.98      markus    463:        case 2:
1.102     markus    464:                if (options.protocol & SSH_PROTO_2) {
1.98      markus    465:                        enable_compat20();
                    466:                        break;
                    467:                }
1.99      markus    468:                /* FALLTHROUGH */
1.105     markus    469:        default:
1.102     markus    470:                mismatch = 1;
                    471:                break;
                    472:        }
                    473:        chop(server_version_string);
                    474:        debug("Local version string %.200s", server_version_string);
                    475:
                    476:        if (mismatch) {
1.96      markus    477:                s = "Protocol major versions differ.\n";
1.271     deraadt   478:                (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96      markus    479:                close(sock_in);
                    480:                close(sock_out);
1.264     itojun    481:                logit("Protocol major versions differ for %s: %.200s vs. %.200s",
1.102     markus    482:                    get_remote_ipaddr(),
                    483:                    server_version_string, client_version_string);
1.278     markus    484:                cleanup_exit(255);
1.96      markus    485:        }
1.108     markus    486: }
                    487:
1.134     markus    488: /* Destroy the host and server keys.  They will no longer be needed. */
1.108     markus    489: void
                    490: destroy_sensitive_data(void)
                    491: {
1.134     markus    492:        int i;
                    493:
                    494:        if (sensitive_data.server_key) {
                    495:                key_free(sensitive_data.server_key);
                    496:                sensitive_data.server_key = NULL;
                    497:        }
1.217     deraadt   498:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    499:                if (sensitive_data.host_keys[i]) {
                    500:                        key_free(sensitive_data.host_keys[i]);
                    501:                        sensitive_data.host_keys[i] = NULL;
                    502:                }
                    503:        }
                    504:        sensitive_data.ssh1_host_key = NULL;
1.169     markus    505:        memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
1.134     markus    506: }
                    507:
1.231     provos    508: /* Demote private to public keys for network child */
                    509: void
                    510: demote_sensitive_data(void)
                    511: {
                    512:        Key *tmp;
                    513:        int i;
                    514:
                    515:        if (sensitive_data.server_key) {
                    516:                tmp = key_demote(sensitive_data.server_key);
                    517:                key_free(sensitive_data.server_key);
                    518:                sensitive_data.server_key = tmp;
                    519:        }
                    520:
                    521:        for (i = 0; i < options.num_host_key_files; i++) {
                    522:                if (sensitive_data.host_keys[i]) {
                    523:                        tmp = key_demote(sensitive_data.host_keys[i]);
                    524:                        key_free(sensitive_data.host_keys[i]);
                    525:                        sensitive_data.host_keys[i] = tmp;
                    526:                        if (tmp->type == KEY_RSA1)
                    527:                                sensitive_data.ssh1_host_key = tmp;
                    528:                }
                    529:        }
                    530:
                    531:        /* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
                    532: }
                    533:
1.233     markus    534: static void
1.231     provos    535: privsep_preauth_child(void)
                    536: {
1.254     deraadt   537:        u_int32_t rnd[256];
1.253     deraadt   538:        gid_t gidset[1];
1.250     deraadt   539:        struct passwd *pw;
1.231     provos    540:        int i;
                    541:
                    542:        /* Enable challenge-response authentication for privilege separation */
                    543:        privsep_challenge_enable();
                    544:
                    545:        for (i = 0; i < 256; i++)
1.254     deraadt   546:                rnd[i] = arc4random();
                    547:        RAND_seed(rnd, sizeof(rnd));
1.231     provos    548:
                    549:        /* Demote the private keys to public keys. */
                    550:        demote_sensitive_data();
                    551:
1.235     stevesk   552:        if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1.240     djm       553:                fatal("Privilege separation user %s does not exist",
                    554:                    SSH_PRIVSEP_USER);
1.235     stevesk   555:        memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
                    556:        endpwent();
                    557:
1.255     deraadt   558:        /* Change our root directory */
1.232     stevesk   559:        if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
                    560:                fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
                    561:                    strerror(errno));
1.231     provos    562:        if (chdir("/") == -1)
1.236     stevesk   563:                fatal("chdir(\"/\"): %s", strerror(errno));
1.234     markus    564:
1.231     provos    565:        /* Drop our privileges */
1.235     stevesk   566:        debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
                    567:            (u_int)pw->pw_gid);
1.251     markus    568: #if 0
1.287     djm       569:        /* XXX not ready, too heavy after chroot */
1.235     stevesk   570:        do_setusercontext(pw);
1.251     markus    571: #else
                    572:        gidset[0] = pw->pw_gid;
                    573:        if (setgroups(1, gidset) < 0)
                    574:                fatal("setgroups: %.100s", strerror(errno));
                    575:        permanently_set_uid(pw);
                    576: #endif
1.231     provos    577: }
                    578:
1.278     markus    579: static int
                    580: privsep_preauth(Authctxt *authctxt)
1.237     markus    581: {
                    582:        int status;
                    583:        pid_t pid;
                    584:
                    585:        /* Set up unprivileged child process to deal with network data */
1.242     mouring   586:        pmonitor = monitor_init();
1.237     markus    587:        /* Store a pointer to the kex for later rekeying */
1.242     mouring   588:        pmonitor->m_pkex = &xxx_kex;
1.237     markus    589:
                    590:        pid = fork();
                    591:        if (pid == -1) {
                    592:                fatal("fork of unprivileged child failed");
                    593:        } else if (pid != 0) {
1.245     mpech     594:                debug2("Network child is on pid %ld", (long)pid);
1.237     markus    595:
1.242     mouring   596:                close(pmonitor->m_recvfd);
1.285     dtucker   597:                pmonitor->m_pid = pid;
1.278     markus    598:                monitor_child_preauth(authctxt, pmonitor);
1.242     mouring   599:                close(pmonitor->m_sendfd);
1.237     markus    600:
                    601:                /* Sync memory */
1.242     mouring   602:                monitor_sync(pmonitor);
1.237     markus    603:
                    604:                /* Wait for the child's exit status */
1.239     markus    605:                while (waitpid(pid, &status, 0) < 0)
                    606:                        if (errno != EINTR)
                    607:                                break;
1.278     markus    608:                return (1);
1.237     markus    609:        } else {
                    610:                /* child */
                    611:
1.242     mouring   612:                close(pmonitor->m_sendfd);
1.237     markus    613:
                    614:                /* Demote the child */
                    615:                if (getuid() == 0 || geteuid() == 0)
                    616:                        privsep_preauth_child();
1.238     stevesk   617:                setproctitle("%s", "[net]");
1.237     markus    618:        }
1.278     markus    619:        return (0);
1.237     markus    620: }
                    621:
1.233     markus    622: static void
1.237     markus    623: privsep_postauth(Authctxt *authctxt)
1.231     provos    624: {
                    625:        if (authctxt->pw->pw_uid == 0 || options.use_login) {
                    626:                /* File descriptor passing is broken or root login */
                    627:                use_privsep = 0;
1.315     djm       628:                goto skip;
1.231     provos    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.307     otto      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:
1.315     djm       662:  skip:
1.231     provos    663:        /* It is safe now to apply the key state */
1.242     mouring   664:        monitor_apply_keystate(pmonitor);
1.312     markus    665:
                    666:        /*
                    667:         * Tell the packet layer that authentication was successful, since
                    668:         * this information is not part of the key state.
                    669:         */
                    670:        packet_set_authenticated();
1.231     provos    671: }
                    672:
1.200     itojun    673: static char *
1.134     markus    674: list_hostkey_types(void)
                    675: {
1.223     markus    676:        Buffer b;
1.281     jakob     677:        const char *p;
                    678:        char *ret;
1.134     markus    679:        int i;
1.223     markus    680:
                    681:        buffer_init(&b);
1.217     deraadt   682:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    683:                Key *key = sensitive_data.host_keys[i];
                    684:                if (key == NULL)
                    685:                        continue;
1.214     deraadt   686:                switch (key->type) {
1.134     markus    687:                case KEY_RSA:
                    688:                case KEY_DSA:
1.223     markus    689:                        if (buffer_len(&b) > 0)
                    690:                                buffer_append(&b, ",", 1);
                    691:                        p = key_ssh_name(key);
                    692:                        buffer_append(&b, p, strlen(p));
1.134     markus    693:                        break;
                    694:                }
                    695:        }
1.223     markus    696:        buffer_append(&b, "\0", 1);
1.281     jakob     697:        ret = xstrdup(buffer_ptr(&b));
1.223     markus    698:        buffer_free(&b);
1.281     jakob     699:        debug("list_hostkey_types: %s", ret);
                    700:        return ret;
1.134     markus    701: }
                    702:
1.231     provos    703: Key *
1.134     markus    704: get_hostkey_by_type(int type)
                    705: {
                    706:        int i;
1.250     deraadt   707:
1.217     deraadt   708:        for (i = 0; i < options.num_host_key_files; i++) {
1.134     markus    709:                Key *key = sensitive_data.host_keys[i];
                    710:                if (key != NULL && key->type == type)
                    711:                        return key;
                    712:        }
                    713:        return NULL;
1.96      markus    714: }
                    715:
1.231     provos    716: Key *
                    717: get_hostkey_by_index(int ind)
                    718: {
                    719:        if (ind < 0 || ind >= options.num_host_key_files)
                    720:                return (NULL);
                    721:        return (sensitive_data.host_keys[ind]);
                    722: }
                    723:
                    724: int
                    725: get_hostkey_index(Key *key)
                    726: {
                    727:        int i;
1.250     deraadt   728:
1.231     provos    729:        for (i = 0; i < options.num_host_key_files; i++) {
                    730:                if (key == sensitive_data.host_keys[i])
                    731:                        return (i);
                    732:        }
                    733:        return (-1);
                    734: }
                    735:
1.124     markus    736: /*
                    737:  * returns 1 if connection should be dropped, 0 otherwise.
                    738:  * dropping starts at connection #max_startups_begin with a probability
                    739:  * of (max_startups_rate/100). the probability increases linearly until
                    740:  * all connections are dropped for startups > max_startups
                    741:  */
1.200     itojun    742: static int
1.124     markus    743: drop_connection(int startups)
                    744: {
1.303     mickey    745:        int p, r;
1.124     markus    746:
                    747:        if (startups < options.max_startups_begin)
                    748:                return 0;
                    749:        if (startups >= options.max_startups)
                    750:                return 1;
                    751:        if (options.max_startups_rate == 100)
                    752:                return 1;
                    753:
                    754:        p  = 100 - options.max_startups_rate;
                    755:        p *= startups - options.max_startups_begin;
1.303     mickey    756:        p /= options.max_startups - options.max_startups_begin;
1.124     markus    757:        p += options.max_startups_rate;
1.303     mickey    758:        r = arc4random() % 100;
1.124     markus    759:
1.304     djm       760:        debug("drop_connection: p %d, r %d", p, r);
1.124     markus    761:        return (r < p) ? 1 : 0;
                    762: }
                    763:
1.215     markus    764: static void
                    765: usage(void)
                    766: {
1.290     markus    767:        fprintf(stderr, "%s, %s\n",
1.280     markus    768:            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.289     markus    769:        fprintf(stderr,
                    770: "usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
                    771: "            [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
                    772:        );
1.215     markus    773:        exit(1);
                    774: }
                    775:
1.294     djm       776: static void
                    777: send_rexec_state(int fd, Buffer *conf)
                    778: {
                    779:        Buffer m;
                    780:
                    781:        debug3("%s: entering fd = %d config len %d", __func__, fd,
                    782:            buffer_len(conf));
                    783:
                    784:        /*
                    785:         * Protocol from reexec master to child:
                    786:         *      string  configuration
                    787:         *      u_int   ephemeral_key_follows
                    788:         *      bignum  e               (only if ephemeral_key_follows == 1)
                    789:         *      bignum  n                       "
                    790:         *      bignum  d                       "
                    791:         *      bignum  iqmp                    "
                    792:         *      bignum  p                       "
                    793:         *      bignum  q                       "
                    794:         */
                    795:        buffer_init(&m);
                    796:        buffer_put_cstring(&m, buffer_ptr(conf));
                    797:
1.298     deraadt   798:        if (sensitive_data.server_key != NULL &&
1.294     djm       799:            sensitive_data.server_key->type == KEY_RSA1) {
                    800:                buffer_put_int(&m, 1);
                    801:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
                    802:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
                    803:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
                    804:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                    805:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
                    806:                buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
                    807:        } else
                    808:                buffer_put_int(&m, 0);
                    809:
                    810:        if (ssh_msg_send(fd, 0, &m) == -1)
                    811:                fatal("%s: ssh_msg_send failed", __func__);
                    812:
                    813:        buffer_free(&m);
                    814:
                    815:        debug3("%s: done", __func__);
                    816: }
                    817:
                    818: static void
                    819: recv_rexec_state(int fd, Buffer *conf)
                    820: {
                    821:        Buffer m;
                    822:        char *cp;
                    823:        u_int len;
                    824:
                    825:        debug3("%s: entering fd = %d", __func__, fd);
                    826:
                    827:        buffer_init(&m);
                    828:
                    829:        if (ssh_msg_recv(fd, &m) == -1)
                    830:                fatal("%s: ssh_msg_recv failed", __func__);
                    831:        if (buffer_get_char(&m) != 0)
                    832:                fatal("%s: rexec version mismatch", __func__);
                    833:
                    834:        cp = buffer_get_string(&m, &len);
                    835:        if (conf != NULL)
                    836:                buffer_append(conf, cp, len + 1);
                    837:        xfree(cp);
                    838:
                    839:        if (buffer_get_int(&m)) {
                    840:                if (sensitive_data.server_key != NULL)
                    841:                        key_free(sensitive_data.server_key);
                    842:                sensitive_data.server_key = key_new_private(KEY_RSA1);
                    843:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
                    844:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
                    845:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
                    846:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
                    847:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
                    848:                buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
                    849:                rsa_generate_additional_parameters(
                    850:                    sensitive_data.server_key->rsa);
                    851:        }
                    852:        buffer_free(&m);
                    853:
                    854:        debug3("%s: done", __func__);
                    855: }
                    856:
1.65      deraadt   857: /*
                    858:  * Main program for the daemon.
                    859:  */
1.2       provos    860: int
                    861: main(int ac, char **av)
1.1       deraadt   862: {
1.64      markus    863:        extern char *optarg;
                    864:        extern int optind;
1.297     avsm      865:        int opt, j, i, fdsetsz, on = 1;
                    866:        int sock_in = -1, sock_out = -1, newsock = -1;
1.107     deraadt   867:        pid_t pid;
1.75      markus    868:        socklen_t fromlen;
                    869:        fd_set *fdset;
                    870:        struct sockaddr_storage from;
1.64      markus    871:        const char *remote_ip;
                    872:        int remote_port;
                    873:        FILE *f;
1.75      markus    874:        struct addrinfo *ai;
                    875:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1.283     markus    876:        char *line;
1.75      markus    877:        int listen_sock, maxfd;
1.302     djm       878:        int startup_p[2] = { -1 , -1 }, config_s[2] = { -1 , -1 };
1.120     markus    879:        int startups = 0;
1.278     markus    880:        Key *key;
1.230     provos    881:        Authctxt *authctxt;
1.151     markus    882:        int ret, key_used = 0;
1.294     djm       883:        Buffer cfg;
1.64      markus    884:
1.138     markus    885:        /* Save argv. */
1.64      markus    886:        saved_argv = av;
1.294     djm       887:        rexec_argc = ac;
1.313     djm       888:
                    889:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    890:        sanitise_stdfd();
1.64      markus    891:
                    892:        /* Initialize configuration options to their default values. */
                    893:        initialize_server_options(&options);
                    894:
                    895:        /* Parse command-line arguments. */
1.294     djm       896:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
1.64      markus    897:                switch (opt) {
1.75      markus    898:                case '4':
1.305     djm       899:                        options.address_family = AF_INET;
1.75      markus    900:                        break;
                    901:                case '6':
1.305     djm       902:                        options.address_family = AF_INET6;
1.75      markus    903:                        break;
1.64      markus    904:                case 'f':
                    905:                        config_file_name = optarg;
                    906:                        break;
                    907:                case 'd':
1.273     markus    908:                        if (debug_flag == 0) {
1.127     markus    909:                                debug_flag = 1;
                    910:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273     markus    911:                        } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127     markus    912:                                options.log_level++;
1.64      markus    913:                        break;
1.135     markus    914:                case 'D':
                    915:                        no_daemon_flag = 1;
1.192     lebel     916:                        break;
                    917:                case 'e':
                    918:                        log_stderr = 1;
1.135     markus    919:                        break;
1.64      markus    920:                case 'i':
                    921:                        inetd_flag = 1;
                    922:                        break;
1.294     djm       923:                case 'r':
                    924:                        rexec_flag = 0;
                    925:                        break;
                    926:                case 'R':
                    927:                        rexeced_flag = 1;
                    928:                        inetd_flag = 1;
                    929:                        break;
1.64      markus    930:                case 'Q':
1.158     markus    931:                        /* ignored */
1.64      markus    932:                        break;
                    933:                case 'q':
                    934:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    935:                        break;
                    936:                case 'b':
                    937:                        options.server_key_bits = atoi(optarg);
                    938:                        break;
                    939:                case 'p':
1.75      markus    940:                        options.ports_from_cmdline = 1;
1.127     markus    941:                        if (options.num_ports >= MAX_PORTS) {
                    942:                                fprintf(stderr, "too many ports.\n");
                    943:                                exit(1);
                    944:                        }
1.193     stevesk   945:                        options.ports[options.num_ports++] = a2port(optarg);
                    946:                        if (options.ports[options.num_ports-1] == 0) {
                    947:                                fprintf(stderr, "Bad port number.\n");
                    948:                                exit(1);
                    949:                        }
1.64      markus    950:                        break;
                    951:                case 'g':
1.197     stevesk   952:                        if ((options.login_grace_time = convtime(optarg)) == -1) {
                    953:                                fprintf(stderr, "Invalid login grace time.\n");
                    954:                                exit(1);
                    955:                        }
1.64      markus    956:                        break;
                    957:                case 'k':
1.197     stevesk   958:                        if ((options.key_regeneration_time = convtime(optarg)) == -1) {
                    959:                                fprintf(stderr, "Invalid key regeneration interval.\n");
                    960:                                exit(1);
                    961:                        }
1.64      markus    962:                        break;
                    963:                case 'h':
1.134     markus    964:                        if (options.num_host_key_files >= MAX_HOSTKEYS) {
                    965:                                fprintf(stderr, "too many host keys.\n");
                    966:                                exit(1);
                    967:                        }
                    968:                        options.host_key_files[options.num_host_key_files++] = optarg;
1.64      markus    969:                        break;
1.203     stevesk   970:                case 't':
                    971:                        test_flag = 1;
                    972:                        break;
1.125     markus    973:                case 'u':
                    974:                        utmp_len = atoi(optarg);
1.257     stevesk   975:                        if (utmp_len > MAXHOSTNAMELEN) {
                    976:                                fprintf(stderr, "Invalid utmp length.\n");
                    977:                                exit(1);
                    978:                        }
1.125     markus    979:                        break;
1.215     markus    980:                case 'o':
1.283     markus    981:                        line = xstrdup(optarg);
                    982:                        if (process_server_config_line(&options, line,
1.215     markus    983:                            "command-line", 0) != 0)
1.217     deraadt   984:                                exit(1);
1.283     markus    985:                        xfree(line);
1.215     markus    986:                        break;
1.64      markus    987:                case '?':
                    988:                default:
1.215     markus    989:                        usage();
                    990:                        break;
1.64      markus    991:                }
                    992:        }
1.294     djm       993:        if (rexeced_flag || inetd_flag)
                    994:                rexec_flag = 0;
                    995:        if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
                    996:                fatal("sshd re-exec requires execution with an absolute path");
                    997:        if (rexeced_flag)
1.296     djm       998:                closefrom(REEXEC_MIN_FREE_FD);
                    999:        else
                   1000:                closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1.294     djm      1001:
1.180     markus   1002:        SSLeay_add_all_algorithms();
1.64      markus   1003:
1.75      markus   1004:        /*
                   1005:         * Force logging to stderr until we have loaded the private host
                   1006:         * key (unless started from inetd)
                   1007:         */
1.138     markus   1008:        log_init(__progname,
1.224     markus   1009:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
                   1010:            SYSLOG_LEVEL_INFO : options.log_level,
                   1011:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
                   1012:            SYSLOG_FACILITY_AUTH : options.log_facility,
1.261     markus   1013:            log_stderr || !inetd_flag);
1.75      markus   1014:
1.294     djm      1015:        sensitive_data.server_key = NULL;
                   1016:        sensitive_data.ssh1_host_key = NULL;
                   1017:        sensitive_data.have_ssh1_key = 0;
                   1018:        sensitive_data.have_ssh2_key = 0;
                   1019:
                   1020:        /* Fetch our configuration */
                   1021:        buffer_init(&cfg);
                   1022:        if (rexeced_flag)
1.296     djm      1023:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1.294     djm      1024:        else
                   1025:                load_server_config(config_file_name, &cfg);
                   1026:
                   1027:        parse_server_config(&options,
                   1028:            rexeced_flag ? "rexec" : config_file_name, &cfg);
                   1029:
                   1030:        if (!rexec_flag)
                   1031:                buffer_free(&cfg);
1.64      markus   1032:
                   1033:        /* Fill in default values for those options not explicitly set. */
                   1034:        fill_default_server_options(&options);
1.305     djm      1035:
                   1036:        /* set default channel AF */
                   1037:        channel_set_af(options.address_family);
1.64      markus   1038:
                   1039:        /* Check that there are no remaining arguments. */
                   1040:        if (optind < ac) {
                   1041:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                   1042:                exit(1);
                   1043:        }
                   1044:
                   1045:        debug("sshd version %.100s", SSH_VERSION);
                   1046:
1.134     markus   1047:        /* load private host keys */
1.255     deraadt  1048:        sensitive_data.host_keys = xmalloc(options.num_host_key_files *
                   1049:            sizeof(Key *));
1.217     deraadt  1050:        for (i = 0; i < options.num_host_key_files; i++)
1.141     markus   1051:                sensitive_data.host_keys[i] = NULL;
1.134     markus   1052:
1.217     deraadt  1053:        for (i = 0; i < options.num_host_key_files; i++) {
1.179     markus   1054:                key = key_load_private(options.host_key_files[i], "", NULL);
                   1055:                sensitive_data.host_keys[i] = key;
1.134     markus   1056:                if (key == NULL) {
1.195     markus   1057:                        error("Could not load host key: %s",
                   1058:                            options.host_key_files[i]);
1.179     markus   1059:                        sensitive_data.host_keys[i] = NULL;
1.134     markus   1060:                        continue;
                   1061:                }
1.214     deraadt  1062:                switch (key->type) {
1.134     markus   1063:                case KEY_RSA1:
                   1064:                        sensitive_data.ssh1_host_key = key;
                   1065:                        sensitive_data.have_ssh1_key = 1;
                   1066:                        break;
                   1067:                case KEY_RSA:
                   1068:                case KEY_DSA:
                   1069:                        sensitive_data.have_ssh2_key = 1;
                   1070:                        break;
                   1071:                }
1.179     markus   1072:                debug("private host key: #%d type %d %s", i, key->type,
                   1073:                    key_type(key));
1.134     markus   1074:        }
                   1075:        if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1.264     itojun   1076:                logit("Disabling protocol version 1. Could not load host key");
1.108     markus   1077:                options.protocol &= ~SSH_PROTO_1;
                   1078:        }
1.134     markus   1079:        if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1.264     itojun   1080:                logit("Disabling protocol version 2. Could not load host key");
1.134     markus   1081:                options.protocol &= ~SSH_PROTO_2;
1.108     markus   1082:        }
1.162     stevesk  1083:        if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.264     itojun   1084:                logit("sshd: no hostkeys available -- exiting.");
1.64      markus   1085:                exit(1);
                   1086:        }
                   1087:
1.108     markus   1088:        /* Check certain values for sanity. */
                   1089:        if (options.protocol & SSH_PROTO_1) {
                   1090:                if (options.server_key_bits < 512 ||
                   1091:                    options.server_key_bits > 32768) {
                   1092:                        fprintf(stderr, "Bad server key size.\n");
                   1093:                        exit(1);
                   1094:                }
                   1095:                /*
                   1096:                 * Check that server and host key lengths differ sufficiently. This
                   1097:                 * is necessary to make double encryption work with rsaref. Oh, I
                   1098:                 * hate software patents. I dont know if this can go? Niels
                   1099:                 */
                   1100:                if (options.server_key_bits >
1.250     deraadt  1101:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
                   1102:                    SSH_KEY_BITS_RESERVED && options.server_key_bits <
                   1103:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1104:                    SSH_KEY_BITS_RESERVED) {
1.108     markus   1105:                        options.server_key_bits =
1.250     deraadt  1106:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
                   1107:                            SSH_KEY_BITS_RESERVED;
1.108     markus   1108:                        debug("Forcing server key to %d bits to make it differ from host key.",
                   1109:                            options.server_key_bits);
                   1110:                }
1.244     markus   1111:        }
                   1112:
                   1113:        if (use_privsep) {
                   1114:                struct passwd *pw;
                   1115:                struct stat st;
                   1116:
                   1117:                if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
                   1118:                        fatal("Privilege separation user %s does not exist",
                   1119:                            SSH_PRIVSEP_USER);
                   1120:                if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
                   1121:                    (S_ISDIR(st.st_mode) == 0))
                   1122:                        fatal("Missing privilege separation directory: %s",
1.247     stevesk  1123:                            _PATH_PRIVSEP_CHROOT_DIR);
                   1124:                if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262     markus   1125:                        fatal("%s must be owned by root and not group or "
                   1126:                            "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.108     markus   1127:        }
1.203     stevesk  1128:
                   1129:        /* Configuration looks good, so exit if in test mode. */
                   1130:        if (test_flag)
                   1131:                exit(0);
1.108     markus   1132:
1.294     djm      1133:        if (rexec_flag) {
                   1134:                rexec_argv = xmalloc(sizeof(char *) * (rexec_argc + 2));
                   1135:                for (i = 0; i < rexec_argc; i++) {
                   1136:                        debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
                   1137:                        rexec_argv[i] = saved_argv[i];
                   1138:                }
                   1139:                rexec_argv[rexec_argc] = "-R";
                   1140:                rexec_argv[rexec_argc + 1] = NULL;
                   1141:        }
                   1142:
1.108     markus   1143:        /* Initialize the log (it is reinitialized below in case we forked). */
1.306     dtucker  1144:        if (debug_flag && (!inetd_flag || rexeced_flag))
1.64      markus   1145:                log_stderr = 1;
1.138     markus   1146:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1147:
1.108     markus   1148:        /*
                   1149:         * If not in debugging mode, and not started from inetd, disconnect
                   1150:         * from the controlling terminal, and fork.  The original process
                   1151:         * exits.
                   1152:         */
1.135     markus   1153:        if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.1       deraadt  1154: #ifdef TIOCNOTTY
1.64      markus   1155:                int fd;
1.1       deraadt  1156: #endif /* TIOCNOTTY */
1.64      markus   1157:                if (daemon(0, 0) < 0)
                   1158:                        fatal("daemon() failed: %.200s", strerror(errno));
                   1159:
                   1160:                /* Disconnect from the controlling tty. */
1.1       deraadt  1161: #ifdef TIOCNOTTY
1.165     itojun   1162:                fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64      markus   1163:                if (fd >= 0) {
                   1164:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                   1165:                        close(fd);
                   1166:                }
                   1167: #endif /* TIOCNOTTY */
                   1168:        }
                   1169:        /* Reinitialize the log (because of the fork above). */
1.138     markus   1170:        log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64      markus   1171:
                   1172:        /* Initialize the random number generator. */
                   1173:        arc4random_stir();
                   1174:
                   1175:        /* Chdir to the root directory so that the current disk can be
                   1176:           unmounted if desired. */
                   1177:        chdir("/");
1.217     deraadt  1178:
1.178     markus   1179:        /* ignore SIGPIPE */
                   1180:        signal(SIGPIPE, SIG_IGN);
1.64      markus   1181:
                   1182:        /* Start listening for a socket, unless started from inetd. */
                   1183:        if (inetd_flag) {
1.294     djm      1184:                int fd;
                   1185:
1.123     djm      1186:                startup_pipe = -1;
1.294     djm      1187:                if (rexeced_flag) {
1.296     djm      1188:                        close(REEXEC_CONFIG_PASS_FD);
1.294     djm      1189:                        sock_in = sock_out = dup(STDIN_FILENO);
                   1190:                        if (!debug_flag) {
1.296     djm      1191:                                startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
                   1192:                                close(REEXEC_STARTUP_PIPE_FD);
1.294     djm      1193:                        }
                   1194:                } else {
                   1195:                        sock_in = dup(STDIN_FILENO);
                   1196:                        sock_out = dup(STDOUT_FILENO);
                   1197:                }
1.108     markus   1198:                /*
                   1199:                 * We intentionally do not close the descriptors 0, 1, and 2
1.294     djm      1200:                 * as our code for setting the descriptors won't work if
1.108     markus   1201:                 * ttyfd happens to be one of those.
                   1202:                 */
1.294     djm      1203:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1204:                        dup2(fd, STDIN_FILENO);
                   1205:                        dup2(fd, STDOUT_FILENO);
                   1206:                        if (fd > STDOUT_FILENO)
                   1207:                                close(fd);
                   1208:                }
1.64      markus   1209:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1.294     djm      1210:                if ((options.protocol & SSH_PROTO_1) &&
                   1211:                    sensitive_data.server_key == NULL)
1.174     deraadt  1212:                        generate_ephemeral_server_key();
1.64      markus   1213:        } else {
1.75      markus   1214:                for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                   1215:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                   1216:                                continue;
                   1217:                        if (num_listen_socks >= MAX_LISTEN_SOCKS)
                   1218:                                fatal("Too many listen sockets. "
                   1219:                                    "Enlarge MAX_LISTEN_SOCKS");
1.308     dtucker  1220:                        if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1.75      markus   1221:                            ntop, sizeof(ntop), strport, sizeof(strport),
1.308     dtucker  1222:                            NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
                   1223:                                error("getnameinfo failed: %.100s",
                   1224:                                    (ret != EAI_SYSTEM) ? gai_strerror(ret) :
                   1225:                                    strerror(errno));
1.75      markus   1226:                                continue;
                   1227:                        }
                   1228:                        /* Create socket for listening. */
1.265     markus   1229:                        listen_sock = socket(ai->ai_family, ai->ai_socktype,
                   1230:                            ai->ai_protocol);
1.75      markus   1231:                        if (listen_sock < 0) {
                   1232:                                /* kernel may not support ipv6 */
                   1233:                                verbose("socket: %.100s", strerror(errno));
                   1234:                                continue;
                   1235:                        }
1.293     djm      1236:                        if (set_nonblock(listen_sock) == -1) {
1.286     markus   1237:                                close(listen_sock);
                   1238:                                continue;
                   1239:                        }
1.75      markus   1240:                        /*
1.258     stevesk  1241:                         * Set socket options.
                   1242:                         * Allow local port reuse in TIME_WAIT.
1.75      markus   1243:                         */
1.258     stevesk  1244:                        if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                   1245:                            &on, sizeof(on)) == -1)
                   1246:                                error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1.75      markus   1247:
                   1248:                        debug("Bind to port %s on %s.", strport, ntop);
                   1249:
                   1250:                        /* Bind the socket to the desired port. */
                   1251:                        if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                   1252:                                error("Bind to port %s on %s failed: %.200s.",
                   1253:                                    strport, ntop, strerror(errno));
                   1254:                                close(listen_sock);
                   1255:                                continue;
                   1256:                        }
                   1257:                        listen_socks[num_listen_socks] = listen_sock;
                   1258:                        num_listen_socks++;
                   1259:
                   1260:                        /* Start listening on the port. */
1.264     itojun   1261:                        logit("Server listening on %s port %s.", ntop, strport);
1.282     markus   1262:                        if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1.75      markus   1263:                                fatal("listen: %.100s", strerror(errno));
                   1264:
1.64      markus   1265:                }
1.75      markus   1266:                freeaddrinfo(options.listen_addrs);
                   1267:
                   1268:                if (!num_listen_socks)
                   1269:                        fatal("Cannot bind any address.");
                   1270:
1.201     markus   1271:                if (options.protocol & SSH_PROTO_1)
                   1272:                        generate_ephemeral_server_key();
                   1273:
                   1274:                /*
                   1275:                 * Arrange to restart on SIGHUP.  The handler needs
                   1276:                 * listen_sock.
                   1277:                 */
                   1278:                signal(SIGHUP, sighup_handler);
                   1279:
                   1280:                signal(SIGTERM, sigterm_handler);
                   1281:                signal(SIGQUIT, sigterm_handler);
                   1282:
                   1283:                /* Arrange SIGCHLD to be caught. */
                   1284:                signal(SIGCHLD, main_sigchld_handler);
                   1285:
                   1286:                /* Write out the pid file after the sigterm handler is setup */
1.64      markus   1287:                if (!debug_flag) {
1.66      markus   1288:                        /*
1.136     todd     1289:                         * Record our pid in /var/run/sshd.pid to make it
                   1290:                         * easier to kill the correct sshd.  We don't want to
                   1291:                         * do this before the bind above because the bind will
1.66      markus   1292:                         * fail if there already is a daemon, and this will
                   1293:                         * overwrite any old pid in the file.
                   1294:                         */
1.112     markus   1295:                        f = fopen(options.pid_file, "w");
1.270     djm      1296:                        if (f == NULL) {
                   1297:                                error("Couldn't create pid file \"%s\": %s",
                   1298:                                    options.pid_file, strerror(errno));
                   1299:                        } else {
1.245     mpech    1300:                                fprintf(f, "%ld\n", (long) getpid());
1.64      markus   1301:                                fclose(f);
                   1302:                        }
                   1303:                }
                   1304:
1.75      markus   1305:                /* setup fd set for listen */
1.120     markus   1306:                fdset = NULL;
1.75      markus   1307:                maxfd = 0;
                   1308:                for (i = 0; i < num_listen_socks; i++)
                   1309:                        if (listen_socks[i] > maxfd)
                   1310:                                maxfd = listen_socks[i];
1.120     markus   1311:                /* pipes connected to unauthenticated childs */
                   1312:                startup_pipes = xmalloc(options.max_startups * sizeof(int));
                   1313:                for (i = 0; i < options.max_startups; i++)
                   1314:                        startup_pipes[i] = -1;
1.75      markus   1315:
1.66      markus   1316:                /*
                   1317:                 * Stay listening for connections until the system crashes or
                   1318:                 * the daemon is killed with a signal.
                   1319:                 */
1.64      markus   1320:                for (;;) {
                   1321:                        if (received_sighup)
                   1322:                                sighup_restart();
1.120     markus   1323:                        if (fdset != NULL)
                   1324:                                xfree(fdset);
1.148     markus   1325:                        fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1.120     markus   1326:                        fdset = (fd_set *)xmalloc(fdsetsz);
1.75      markus   1327:                        memset(fdset, 0, fdsetsz);
1.120     markus   1328:
1.75      markus   1329:                        for (i = 0; i < num_listen_socks; i++)
                   1330:                                FD_SET(listen_socks[i], fdset);
1.120     markus   1331:                        for (i = 0; i < options.max_startups; i++)
                   1332:                                if (startup_pipes[i] != -1)
                   1333:                                        FD_SET(startup_pipes[i], fdset);
                   1334:
                   1335:                        /* Wait in select until there is a connection. */
1.151     markus   1336:                        ret = select(maxfd+1, fdset, NULL, NULL, NULL);
                   1337:                        if (ret < 0 && errno != EINTR)
                   1338:                                error("select: %.100s", strerror(errno));
1.199     markus   1339:                        if (received_sigterm) {
1.264     itojun   1340:                                logit("Received signal %d; terminating.",
1.213     itojun   1341:                                    (int) received_sigterm);
1.199     markus   1342:                                close_listen_socks();
                   1343:                                unlink(options.pid_file);
                   1344:                                exit(255);
                   1345:                        }
1.151     markus   1346:                        if (key_used && key_do_regen) {
1.174     deraadt  1347:                                generate_ephemeral_server_key();
1.151     markus   1348:                                key_used = 0;
                   1349:                                key_do_regen = 0;
                   1350:                        }
                   1351:                        if (ret < 0)
1.75      markus   1352:                                continue;
1.151     markus   1353:
1.120     markus   1354:                        for (i = 0; i < options.max_startups; i++)
                   1355:                                if (startup_pipes[i] != -1 &&
                   1356:                                    FD_ISSET(startup_pipes[i], fdset)) {
                   1357:                                        /*
                   1358:                                         * the read end of the pipe is ready
                   1359:                                         * if the child has closed the pipe
1.143     markus   1360:                                         * after successful authentication
1.120     markus   1361:                                         * or if the child has died
                   1362:                                         */
                   1363:                                        close(startup_pipes[i]);
                   1364:                                        startup_pipes[i] = -1;
                   1365:                                        startups--;
                   1366:                                }
1.75      markus   1367:                        for (i = 0; i < num_listen_socks; i++) {
                   1368:                                if (!FD_ISSET(listen_socks[i], fdset))
1.70      provos   1369:                                        continue;
1.120     markus   1370:                                fromlen = sizeof(from);
                   1371:                                newsock = accept(listen_socks[i], (struct sockaddr *)&from,
                   1372:                                    &fromlen);
                   1373:                                if (newsock < 0) {
                   1374:                                        if (errno != EINTR && errno != EWOULDBLOCK)
                   1375:                                                error("accept: %.100s", strerror(errno));
1.286     markus   1376:                                        continue;
                   1377:                                }
1.293     djm      1378:                                if (unset_nonblock(newsock) == -1) {
1.286     markus   1379:                                        close(newsock);
1.120     markus   1380:                                        continue;
                   1381:                                }
1.124     markus   1382:                                if (drop_connection(startups) == 1) {
                   1383:                                        debug("drop connection #%d", startups);
1.120     markus   1384:                                        close(newsock);
                   1385:                                        continue;
                   1386:                                }
                   1387:                                if (pipe(startup_p) == -1) {
                   1388:                                        close(newsock);
                   1389:                                        continue;
                   1390:                                }
                   1391:
1.294     djm      1392:                                if (rexec_flag && socketpair(AF_UNIX,
                   1393:                                    SOCK_STREAM, 0, config_s) == -1) {
                   1394:                                        error("reexec socketpair: %s",
                   1395:                                            strerror(errno));
                   1396:                                        close(newsock);
                   1397:                                        close(startup_p[0]);
                   1398:                                        close(startup_p[1]);
                   1399:                                        continue;
                   1400:                                }
                   1401:
1.120     markus   1402:                                for (j = 0; j < options.max_startups; j++)
                   1403:                                        if (startup_pipes[j] == -1) {
                   1404:                                                startup_pipes[j] = startup_p[0];
                   1405:                                                if (maxfd < startup_p[0])
                   1406:                                                        maxfd = startup_p[0];
                   1407:                                                startups++;
                   1408:                                                break;
                   1409:                                        }
1.161     stevesk  1410:
1.66      markus   1411:                                /*
1.120     markus   1412:                                 * Got connection.  Fork a child to handle it, unless
                   1413:                                 * we are in debugging mode.
1.66      markus   1414:                                 */
1.120     markus   1415:                                if (debug_flag) {
1.66      markus   1416:                                        /*
1.120     markus   1417:                                         * In debugging mode.  Close the listening
                   1418:                                         * socket, and start processing the
                   1419:                                         * connection without forking.
1.66      markus   1420:                                         */
1.120     markus   1421:                                        debug("Server will not fork when running in debugging mode.");
1.75      markus   1422:                                        close_listen_socks();
1.64      markus   1423:                                        sock_in = newsock;
                   1424:                                        sock_out = newsock;
1.294     djm      1425:                                        close(startup_p[0]);
                   1426:                                        close(startup_p[1]);
1.122     deraadt  1427:                                        startup_pipe = -1;
1.120     markus   1428:                                        pid = getpid();
1.294     djm      1429:                                        if (rexec_flag) {
                   1430:                                                send_rexec_state(config_s[0],
                   1431:                                                    &cfg);
                   1432:                                                close(config_s[0]);
                   1433:                                        }
1.64      markus   1434:                                        break;
1.120     markus   1435:                                } else {
                   1436:                                        /*
                   1437:                                         * Normal production daemon.  Fork, and have
                   1438:                                         * the child process the connection. The
                   1439:                                         * parent continues listening.
                   1440:                                         */
                   1441:                                        if ((pid = fork()) == 0) {
                   1442:                                                /*
                   1443:                                                 * Child.  Close the listening and max_startup
                   1444:                                                 * sockets.  Start using the accepted socket.
                   1445:                                                 * Reinitialize logging (since our pid has
                   1446:                                                 * changed).  We break out of the loop to handle
                   1447:                                                 * the connection.
                   1448:                                                 */
                   1449:                                                startup_pipe = startup_p[1];
1.211     markus   1450:                                                close_startup_pipes();
1.120     markus   1451:                                                close_listen_socks();
                   1452:                                                sock_in = newsock;
                   1453:                                                sock_out = newsock;
1.138     markus   1454:                                                log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.302     djm      1455:                                                if (rexec_flag)
                   1456:                                                        close(config_s[0]);
1.120     markus   1457:                                                break;
                   1458:                                        }
1.64      markus   1459:                                }
                   1460:
1.120     markus   1461:                                /* Parent.  Stay in the loop. */
                   1462:                                if (pid < 0)
                   1463:                                        error("fork: %.100s", strerror(errno));
                   1464:                                else
1.245     mpech    1465:                                        debug("Forked child %ld.", (long)pid);
1.120     markus   1466:
                   1467:                                close(startup_p[1]);
1.1       deraadt  1468:
1.294     djm      1469:                                if (rexec_flag) {
                   1470:                                        send_rexec_state(config_s[0], &cfg);
                   1471:                                        close(config_s[0]);
                   1472:                                        close(config_s[1]);
                   1473:                                }
                   1474:
1.120     markus   1475:                                /* Mark that the key has been used (it was "given" to the child). */
1.151     markus   1476:                                if ((options.protocol & SSH_PROTO_1) &&
                   1477:                                    key_used == 0) {
                   1478:                                        /* Schedule server key regeneration alarm. */
                   1479:                                        signal(SIGALRM, key_regeneration_alarm);
                   1480:                                        alarm(options.key_regeneration_time);
                   1481:                                        key_used = 1;
                   1482:                                }
1.1       deraadt  1483:
1.120     markus   1484:                                arc4random_stir();
1.1       deraadt  1485:
1.120     markus   1486:                                /* Close the new socket (the child is now taking care of it). */
                   1487:                                close(newsock);
                   1488:                        }
1.75      markus   1489:                        /* child process check (or debug mode) */
                   1490:                        if (num_listen_socks < 0)
                   1491:                                break;
1.64      markus   1492:                }
1.1       deraadt  1493:        }
                   1494:
1.64      markus   1495:        /* This is the child processing a new connection. */
1.288     markus   1496:        setproctitle("%s", "[accepted]");
1.294     djm      1497:
1.300     markus   1498:        /*
                   1499:         * Create a new session and process group since the 4.4BSD
                   1500:         * setlogin() affects the entire process group.  We don't
                   1501:         * want the child to be able to affect the parent.
                   1502:         */
                   1503:        if (!debug_flag && !inetd_flag && setsid() < 0)
                   1504:                error("setsid: %.100s", strerror(errno));
                   1505:
1.294     djm      1506:        if (rexec_flag) {
                   1507:                int fd;
                   1508:
1.296     djm      1509:                debug("rexec start in %d out %d newsock %d pipe %d sock %d",
                   1510:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1511:                dup2(newsock, STDIN_FILENO);
                   1512:                dup2(STDIN_FILENO, STDOUT_FILENO);
                   1513:                if (startup_pipe == -1)
1.296     djm      1514:                        close(REEXEC_STARTUP_PIPE_FD);
1.294     djm      1515:                else
1.296     djm      1516:                        dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1.294     djm      1517:
1.296     djm      1518:                dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1.294     djm      1519:                close(config_s[1]);
1.301     dtucker  1520:                if (startup_pipe != -1)
                   1521:                        close(startup_pipe);
1.296     djm      1522:
1.294     djm      1523:                execv(rexec_argv[0], rexec_argv);
                   1524:
                   1525:                /* Reexec has failed, fall back and continue */
                   1526:                error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1.296     djm      1527:                recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1.294     djm      1528:                log_init(__progname, options.log_level,
                   1529:                    options.log_facility, log_stderr);
                   1530:
                   1531:                /* Clean up fds */
1.296     djm      1532:                startup_pipe = REEXEC_STARTUP_PIPE_FD;
1.294     djm      1533:                close(config_s[1]);
1.296     djm      1534:                close(REEXEC_CONFIG_PASS_FD);
                   1535:                newsock = sock_out = sock_in = dup(STDIN_FILENO);
1.294     djm      1536:                if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
                   1537:                        dup2(fd, STDIN_FILENO);
                   1538:                        dup2(fd, STDOUT_FILENO);
                   1539:                        if (fd > STDERR_FILENO)
                   1540:                                close(fd);
                   1541:                }
1.296     djm      1542:                debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
                   1543:                    sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294     djm      1544:        }
1.64      markus   1545:
1.66      markus   1546:        /*
                   1547:         * Disable the key regeneration alarm.  We will not regenerate the
                   1548:         * key since we are no longer in a position to give it to anyone. We
                   1549:         * will not restart on SIGHUP since it no longer makes sense.
                   1550:         */
1.64      markus   1551:        alarm(0);
                   1552:        signal(SIGALRM, SIG_DFL);
                   1553:        signal(SIGHUP, SIG_DFL);
                   1554:        signal(SIGTERM, SIG_DFL);
                   1555:        signal(SIGQUIT, SIG_DFL);
                   1556:        signal(SIGCHLD, SIG_DFL);
1.150     markus   1557:
1.66      markus   1558:        /*
                   1559:         * Register our connection.  This turns encryption off because we do
                   1560:         * not have a key.
                   1561:         */
1.64      markus   1562:        packet_set_connection(sock_in, sock_out);
1.312     markus   1563:        packet_set_server();
1.309     djm      1564:
                   1565:        /* Set SO_KEEPALIVE if requested. */
                   1566:        if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
                   1567:            setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
                   1568:                error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.1       deraadt  1569:
1.310     markus   1570:        if ((remote_port = get_remote_port()) < 0) {
                   1571:                debug("get_remote_port failed");
                   1572:                cleanup_exit(255);
                   1573:        }
1.316     dtucker  1574:
                   1575:        /*
                   1576:         * We use get_canonical_hostname with usedns = 0 instead of
                   1577:         * get_remote_ipaddr here so IP options will be checked.
                   1578:         */
                   1579:        remote_ip = get_canonical_hostname(0);
1.52      markus   1580:
1.209     markus   1581: #ifdef LIBWRAP
1.64      markus   1582:        /* Check whether logins are denied from this host. */
1.295     djm      1583:        if (packet_connection_is_on_socket()) {
1.64      markus   1584:                struct request_info req;
1.37      dugsong  1585:
1.204     camield  1586:                request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1.64      markus   1587:                fromhost(&req);
1.37      dugsong  1588:
1.64      markus   1589:                if (!hosts_access(&req)) {
1.209     markus   1590:                        debug("Connection refused by tcp wrapper");
1.182     markus   1591:                        refuse(&req);
1.209     markus   1592:                        /* NOTREACHED */
                   1593:                        fatal("libwrap refuse returns");
1.64      markus   1594:                }
                   1595:        }
1.75      markus   1596: #endif /* LIBWRAP */
1.209     markus   1597:
1.64      markus   1598:        /* Log the connection. */
                   1599:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1       deraadt  1600:
1.66      markus   1601:        /*
1.317   ! djm      1602:         * We don't want to listen forever unless the other side
1.66      markus   1603:         * successfully authenticates itself.  So we set up an alarm which is
                   1604:         * cleared after successful authentication.  A limit of zero
1.317   ! djm      1605:         * indicates no limit. Note that we don't set the alarm in debugging
1.66      markus   1606:         * mode; it is just annoying to have the server exit just when you
                   1607:         * are about to discover the bug.
                   1608:         */
1.64      markus   1609:        signal(SIGALRM, grace_alarm_handler);
                   1610:        if (!debug_flag)
                   1611:                alarm(options.login_grace_time);
                   1612:
1.96      markus   1613:        sshd_exchange_identification(sock_in, sock_out);
1.275     markus   1614:
1.64      markus   1615:        packet_set_nonblocking();
1.1       deraadt  1616:
1.278     markus   1617:        /* allocate authentication context */
                   1618:        authctxt = xmalloc(sizeof(*authctxt));
                   1619:        memset(authctxt, 0, sizeof(*authctxt));
                   1620:
                   1621:        /* XXX global for cleanup, access from other modules */
                   1622:        the_authctxt = authctxt;
                   1623:
1.307     otto     1624:        /* prepare buffer to collect messages to display to user after login */
                   1625:        buffer_init(&loginmsg);
                   1626:
1.237     markus   1627:        if (use_privsep)
1.278     markus   1628:                if (privsep_preauth(authctxt) == 1)
1.237     markus   1629:                        goto authenticated;
1.231     provos   1630:
1.77      markus   1631:        /* perform the key exchange */
                   1632:        /* authenticate user and start session */
1.98      markus   1633:        if (compat20) {
                   1634:                do_ssh2_kex();
1.278     markus   1635:                do_authentication2(authctxt);
1.98      markus   1636:        } else {
                   1637:                do_ssh1_kex();
1.278     markus   1638:                do_authentication(authctxt);
1.98      markus   1639:        }
1.237     markus   1640:        /*
                   1641:         * If we use privilege separation, the unprivileged child transfers
                   1642:         * the current keystate and exits
                   1643:         */
                   1644:        if (use_privsep) {
1.242     mouring  1645:                mm_send_keystate(pmonitor);
1.231     provos   1646:                exit(0);
1.237     markus   1647:        }
1.231     provos   1648:
                   1649:  authenticated:
1.234     markus   1650:        /*
1.231     provos   1651:         * In privilege separation, we fork another child and prepare
                   1652:         * file descriptor passing.
                   1653:         */
                   1654:        if (use_privsep) {
1.237     markus   1655:                privsep_postauth(authctxt);
                   1656:                /* the monitor process [priv] will not return */
1.231     provos   1657:                if (!compat20)
                   1658:                        destroy_sensitive_data();
                   1659:        }
1.230     provos   1660:
1.278     markus   1661:        /* Start session. */
1.230     provos   1662:        do_authenticated(authctxt);
                   1663:
1.64      markus   1664:        /* The connection has been terminated. */
                   1665:        verbose("Closing connection to %.100s", remote_ip);
                   1666:        packet_close();
1.231     provos   1667:
                   1668:        if (use_privsep)
                   1669:                mm_terminate();
                   1670:
1.64      markus   1671:        exit(0);
1.1       deraadt  1672: }
                   1673:
1.65      deraadt  1674: /*
1.229     markus   1675:  * Decrypt session_key_int using our private server key and private host key
                   1676:  * (key with larger modulus first).
                   1677:  */
1.231     provos   1678: int
1.229     markus   1679: ssh1_session_key(BIGNUM *session_key_int)
                   1680: {
                   1681:        int rsafail = 0;
                   1682:
                   1683:        if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
                   1684:                /* Server key has bigger modulus. */
                   1685:                if (BN_num_bits(sensitive_data.server_key->rsa->n) <
                   1686:                    BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1687:                        fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                   1688:                            get_remote_ipaddr(),
                   1689:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1690:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1691:                            SSH_KEY_BITS_RESERVED);
                   1692:                }
                   1693:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1694:                    sensitive_data.server_key->rsa) <= 0)
                   1695:                        rsafail++;
                   1696:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1697:                    sensitive_data.ssh1_host_key->rsa) <= 0)
                   1698:                        rsafail++;
                   1699:        } else {
                   1700:                /* Host key has bigger modulus (or they are equal). */
                   1701:                if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
                   1702:                    BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
                   1703:                        fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
                   1704:                            get_remote_ipaddr(),
                   1705:                            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
                   1706:                            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1707:                            SSH_KEY_BITS_RESERVED);
                   1708:                }
                   1709:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1710:                    sensitive_data.ssh1_host_key->rsa) < 0)
                   1711:                        rsafail++;
                   1712:                if (rsa_private_decrypt(session_key_int, session_key_int,
                   1713:                    sensitive_data.server_key->rsa) < 0)
                   1714:                        rsafail++;
                   1715:        }
                   1716:        return (rsafail);
                   1717: }
                   1718: /*
1.77      markus   1719:  * SSH1 key exchange
1.65      deraadt  1720:  */
1.200     itojun   1721: static void
1.142     markus   1722: do_ssh1_kex(void)
1.1       deraadt  1723: {
1.64      markus   1724:        int i, len;
1.159     markus   1725:        int rsafail = 0;
1.64      markus   1726:        BIGNUM *session_key_int;
1.140     markus   1727:        u_char session_key[SSH_SESSION_KEY_LENGTH];
                   1728:        u_char cookie[8];
                   1729:        u_int cipher_type, auth_mask, protocol_flags;
1.254     deraadt  1730:        u_int32_t rnd = 0;
1.64      markus   1731:
1.66      markus   1732:        /*
                   1733:         * Generate check bytes that the client must send back in the user
                   1734:         * packet in order for it to be accepted; this is used to defy ip
                   1735:         * spoofing attacks.  Note that this only works against somebody
                   1736:         * doing IP spoofing from a remote machine; any machine on the local
                   1737:         * network can still see outgoing packets and catch the random
                   1738:         * cookie.  This only affects rhosts authentication, and this is one
                   1739:         * of the reasons why it is inherently insecure.
                   1740:         */
1.64      markus   1741:        for (i = 0; i < 8; i++) {
                   1742:                if (i % 4 == 0)
1.254     deraadt  1743:                        rnd = arc4random();
                   1744:                cookie[i] = rnd & 0xff;
                   1745:                rnd >>= 8;
1.64      markus   1746:        }
                   1747:
1.66      markus   1748:        /*
                   1749:         * Send our public key.  We include in the packet 64 bits of random
                   1750:         * data that must be matched in the reply in order to prevent IP
                   1751:         * spoofing.
                   1752:         */
1.64      markus   1753:        packet_start(SSH_SMSG_PUBLIC_KEY);
                   1754:        for (i = 0; i < 8; i++)
1.77      markus   1755:                packet_put_char(cookie[i]);
1.64      markus   1756:
                   1757:        /* Store our public server RSA key. */
1.134     markus   1758:        packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
                   1759:        packet_put_bignum(sensitive_data.server_key->rsa->e);
                   1760:        packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64      markus   1761:
                   1762:        /* Store our public host RSA key. */
1.134     markus   1763:        packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
                   1764:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
                   1765:        packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64      markus   1766:
                   1767:        /* Put protocol flags. */
                   1768:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   1769:
                   1770:        /* Declare which ciphers we support. */
1.131     markus   1771:        packet_put_int(cipher_mask_ssh1(0));
1.64      markus   1772:
                   1773:        /* Declare supported authentication types. */
                   1774:        auth_mask = 0;
                   1775:        if (options.rhosts_rsa_authentication)
                   1776:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   1777:        if (options.rsa_authentication)
                   1778:                auth_mask |= 1 << SSH_AUTH_RSA;
1.196     markus   1779:        if (options.challenge_response_authentication == 1)
1.64      markus   1780:                auth_mask |= 1 << SSH_AUTH_TIS;
                   1781:        if (options.password_authentication)
                   1782:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   1783:        packet_put_int(auth_mask);
                   1784:
                   1785:        /* Send the packet and wait for it to be sent. */
                   1786:        packet_send();
                   1787:        packet_write_wait();
                   1788:
1.134     markus   1789:        debug("Sent %d bit server key and %d bit host key.",
                   1790:            BN_num_bits(sensitive_data.server_key->rsa->n),
                   1791:            BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64      markus   1792:
                   1793:        /* Read clients reply (cipher type and session key). */
1.222     markus   1794:        packet_read_expect(SSH_CMSG_SESSION_KEY);
1.64      markus   1795:
1.69      markus   1796:        /* Get cipher type and check whether we accept this. */
1.64      markus   1797:        cipher_type = packet_get_char();
1.69      markus   1798:
1.131     markus   1799:        if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69      markus   1800:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   1801:
                   1802:        /* Get check bytes from the packet.  These must match those we
                   1803:           sent earlier with the public key packet. */
                   1804:        for (i = 0; i < 8; i++)
1.77      markus   1805:                if (cookie[i] != packet_get_char())
1.64      markus   1806:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   1807:
                   1808:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   1809:
                   1810:        /* Get the encrypted integer. */
1.218     markus   1811:        if ((session_key_int = BN_new()) == NULL)
                   1812:                fatal("do_ssh1_kex: BN_new failed");
1.221     markus   1813:        packet_get_bignum(session_key_int);
1.64      markus   1814:
                   1815:        protocol_flags = packet_get_int();
                   1816:        packet_set_protocol_flags(protocol_flags);
1.220     markus   1817:        packet_check_eom();
1.64      markus   1818:
1.229     markus   1819:        /* Decrypt session_key_int using host/server keys */
1.231     provos   1820:        rsafail = PRIVSEP(ssh1_session_key(session_key_int));
                   1821:
1.66      markus   1822:        /*
                   1823:         * Extract session key from the decrypted integer.  The key is in the
                   1824:         * least significant 256 bits of the integer; the first byte of the
                   1825:         * key is in the highest bits.
                   1826:         */
1.159     markus   1827:        if (!rsafail) {
                   1828:                BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   1829:                len = BN_num_bytes(session_key_int);
1.311     djm      1830:                if (len < 0 || (u_int)len > sizeof(session_key)) {
1.159     markus   1831:                        error("do_connection: bad session key len from %s: "
1.165     itojun   1832:                            "session_key_int %d > sizeof(session_key) %lu",
                   1833:                            get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1.159     markus   1834:                        rsafail++;
                   1835:                } else {
                   1836:                        memset(session_key, 0, sizeof(session_key));
                   1837:                        BN_bn2bin(session_key_int,
                   1838:                            session_key + sizeof(session_key) - len);
1.169     markus   1839:
1.291     djm      1840:                        derive_ssh1_session_id(
1.298     deraadt  1841:                            sensitive_data.ssh1_host_key->rsa->n,
1.291     djm      1842:                            sensitive_data.server_key->rsa->n,
                   1843:                            cookie, session_id);
1.169     markus   1844:                        /*
                   1845:                         * Xor the first 16 bytes of the session key with the
                   1846:                         * session id.
                   1847:                         */
                   1848:                        for (i = 0; i < 16; i++)
                   1849:                                session_key[i] ^= session_id[i];
1.159     markus   1850:                }
                   1851:        }
                   1852:        if (rsafail) {
1.169     markus   1853:                int bytes = BN_num_bytes(session_key_int);
1.227     stevesk  1854:                u_char *buf = xmalloc(bytes);
1.169     markus   1855:                MD5_CTX md;
                   1856:
1.264     itojun   1857:                logit("do_connection: generating a fake encryption key");
1.169     markus   1858:                BN_bn2bin(session_key_int, buf);
                   1859:                MD5_Init(&md);
                   1860:                MD5_Update(&md, buf, bytes);
                   1861:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1862:                MD5_Final(session_key, &md);
                   1863:                MD5_Init(&md);
                   1864:                MD5_Update(&md, session_key, 16);
                   1865:                MD5_Update(&md, buf, bytes);
                   1866:                MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
                   1867:                MD5_Final(session_key + 16, &md);
                   1868:                memset(buf, 0, bytes);
                   1869:                xfree(buf);
1.170     markus   1870:                for (i = 0; i < 16; i++)
                   1871:                        session_id[i] = session_key[i] ^ session_key[i + 16];
1.159     markus   1872:        }
1.231     provos   1873:        /* Destroy the private and public keys. No longer. */
1.169     markus   1874:        destroy_sensitive_data();
                   1875:
1.231     provos   1876:        if (use_privsep)
                   1877:                mm_ssh1_session_id(session_id);
                   1878:
1.77      markus   1879:        /* Destroy the decrypted integer.  It is no longer needed. */
                   1880:        BN_clear_free(session_key_int);
1.64      markus   1881:
                   1882:        /* Set the session key.  From this on all communications will be encrypted. */
                   1883:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   1884:
                   1885:        /* Destroy our copy of the session key.  It is no longer needed. */
                   1886:        memset(session_key, 0, sizeof(session_key));
                   1887:
                   1888:        debug("Received session key; encryption turned on.");
                   1889:
1.243     deraadt  1890:        /* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
1.64      markus   1891:        packet_start(SSH_SMSG_SUCCESS);
                   1892:        packet_send();
                   1893:        packet_write_wait();
1.98      markus   1894: }
                   1895:
                   1896: /*
                   1897:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   1898:  */
1.200     itojun   1899: static void
1.142     markus   1900: do_ssh2_kex(void)
1.98      markus   1901: {
                   1902:        Kex *kex;
1.102     markus   1903:
                   1904:        if (options.ciphers != NULL) {
1.105     markus   1905:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102     markus   1906:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1.166     markus   1907:        }
1.184     stevesk  1908:        myproposal[PROPOSAL_ENC_ALGS_CTOS] =
                   1909:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
                   1910:        myproposal[PROPOSAL_ENC_ALGS_STOC] =
                   1911:            compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
                   1912:
1.166     markus   1913:        if (options.macs != NULL) {
                   1914:                myproposal[PROPOSAL_MAC_ALGS_CTOS] =
                   1915:                myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1.246     markus   1916:        }
1.312     markus   1917:        if (options.compression == COMP_NONE) {
1.246     markus   1918:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   1919:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.312     markus   1920:        } else if (options.compression == COMP_DELAYED) {
                   1921:                myproposal[PROPOSAL_COMP_ALGS_CTOS] =
                   1922:                myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
1.102     markus   1923:        }
1.312     markus   1924:
1.134     markus   1925:        myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
                   1926:
1.189     markus   1927:        /* start key exchange */
1.188     markus   1928:        kex = kex_setup(myproposal);
1.263     markus   1929:        kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.292     djm      1930:        kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.263     markus   1931:        kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.186     markus   1932:        kex->server = 1;
                   1933:        kex->client_version_string=client_version_string;
                   1934:        kex->server_version_string=server_version_string;
                   1935:        kex->load_host_key=&get_hostkey_by_type;
1.231     provos   1936:        kex->host_key_index=&get_hostkey_index;
1.129     provos   1937:
1.189     markus   1938:        xxx_kex = kex;
                   1939:
1.190     markus   1940:        dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1.187     markus   1941:
                   1942:        session_id2 = kex->session_id;
                   1943:        session_id2_len = kex->session_id_len;
1.129     provos   1944:
                   1945: #ifdef DEBUG_KEXDH
                   1946:        /* send 1st encrypted/maced/compressed message */
                   1947:        packet_start(SSH2_MSG_IGNORE);
                   1948:        packet_put_cstring("markus");
                   1949:        packet_send();
                   1950:        packet_write_wait();
                   1951: #endif
1.186     markus   1952:        debug("KEX done");
1.278     markus   1953: }
                   1954:
                   1955: /* server specific fatal cleanup */
                   1956: void
                   1957: cleanup_exit(int i)
                   1958: {
                   1959:        if (the_authctxt)
                   1960:                do_cleanup(the_authctxt);
                   1961:        _exit(i);
1.1       deraadt  1962: }