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

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