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

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