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

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