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

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