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

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