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

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